Push a studio stream of any codec over RTMP, in H.264
Classic RTMP carries H.264 only, and the RTMP output refused a stream encoding anything else. Since TeamSpeak streams now prefer the codecs every client decodes before H.264, that refusal hit the usual case. An output may now name a video codec of its own. The streamer then runs an encoder of that codec for the layer the output takes, as it does for a viewer that chose another codec, and hands those packets to the outputs that asked for it only; recordings and the replay buffer keep the stream's codec, which a studio now always encodes for them even when every viewer chose another one. Only the output's layer gets the extra encoder, not every simulcast layer. Tested end to end: a VP8 studio stream pushed to FFmpeg's own RTMP server arrives as H.264 and AAC (ffprobe), starting at a keyframe, while a recording of the same stream stays VP8 and Opus. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7c3baf95e8
commit
49cd9a3f12
8 files changed
+266
-97
No files matched your search
@@ -1854,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,
|
||||
@@ -1880,7 +1891,7 @@ impl LayerEncoder {
|
||||
shared: &Shared,
|
||||
layer: &Layer,
|
||||
sink: &dyn MediaSink,
|
||||
studio: Option<&Studio>,
|
||||
studio: ToStudio<'_>,
|
||||
picture: &Picture,
|
||||
requested: bool,
|
||||
target: u64,
|
||||
@@ -1909,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,
|
||||
@@ -2009,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;
|
||||
@@ -2070,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);
|
||||
|
||||
@@ -194,6 +194,21 @@ fn rtmp_server(port: u16, out: &Path) -> std::process::Child {
|
||||
.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;
|
||||
@@ -248,7 +263,9 @@ fn starts_with_keyframe(path: &Path) -> bool {
|
||||
.arg(path)
|
||||
.output()
|
||||
.unwrap();
|
||||
String::from_utf8_lossy(&out.stdout).lines().next() == Some("1")
|
||||
// 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
|
||||
@@ -299,18 +316,7 @@ async fn a_studio_stream_goes_out_over_rtmp_and_comes_back_after_the_server_did(
|
||||
url: format!("rtmp://127.0.0.1:{port}/live"),
|
||||
token: Some("test-key".into()),
|
||||
};
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
loop {
|
||||
match studio.apply(Command::AddOutput(spec.clone())).await {
|
||||
Ok(()) => break,
|
||||
// The server is still starting.
|
||||
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}"),
|
||||
}
|
||||
}
|
||||
add_rtmp(&studio, &spec).await;
|
||||
studio.apply(Command::GoLive).await.unwrap();
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
|
||||
@@ -350,6 +356,74 @@ async fn a_studio_stream_goes_out_over_rtmp_and_comes_back_after_the_server_did(
|
||||
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();
|
||||
|
||||
@@ -726,8 +726,7 @@ impl Studio {
|
||||
(Box::new(output::record::Recorder::start(path, layer, 2)?), false)
|
||||
}
|
||||
OutputSpec::Url { url, token } if output::rtmp::Rtmp::handles(url) => {
|
||||
let codec = *lock(&self.shared.codec);
|
||||
let rtmp = output::rtmp::Rtmp::start(url, token.as_deref(), layer, codec).await?;
|
||||
let rtmp = output::rtmp::Rtmp::start(url, token.as_deref(), layer).await?;
|
||||
(Box::new(rtmp), true)
|
||||
}
|
||||
OutputSpec::Url { url, token } => {
|
||||
@@ -837,12 +836,33 @@ impl Studio {
|
||||
self.shared.state_changed();
|
||||
}
|
||||
|
||||
/// Hand one encoded packet to every output. Called on the streamer's
|
||||
/// encoder threads.
|
||||
/// Hand one encoded packet of the stream's codec to every output.
|
||||
/// Called on the streamer's encoder threads.
|
||||
pub fn write_packet(&self, packet: &Packet<'_>) {
|
||||
self.shared.write_packet(packet);
|
||||
}
|
||||
|
||||
/// Adds to `out` the video codecs the outputs taking `layer` need besides
|
||||
/// the stream's ([`OutputSink::video_codec`]), which the streamer then
|
||||
/// encodes too, for that layer only.
|
||||
pub fn output_codecs(&self, layer: u32, out: &mut Vec<Codec>) {
|
||||
for output in lock(&self.shared.outputs).iter() {
|
||||
let Some(codec) = output.sink.video_codec() else { continue };
|
||||
if !out.contains(&codec) && output.sink.wants(Track::Video { codec, layer }) {
|
||||
out.push(codec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hand a video packet of a codec an output asked for
|
||||
/// ([`Studio::output_codecs`]) to the outputs that need that codec only:
|
||||
/// the replay buffer and recordings keep the stream's.
|
||||
pub fn write_output_packet(&self, packet: &Packet<'_>) {
|
||||
if let Track::Video { codec, .. } = packet.track {
|
||||
self.shared.to_outputs(packet, Some(codec));
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether an output needs a keyframe of `layer` now (a recording that
|
||||
/// just started, a WHIP session that just connected, the replay buffer's
|
||||
/// next clip start). Only the layer the outputs take
|
||||
@@ -924,11 +944,18 @@ impl Shared {
|
||||
if let Err(e) = lock(&self.replay).write(packet) {
|
||||
self.fail("replay", e);
|
||||
}
|
||||
self.to_outputs(packet, None);
|
||||
}
|
||||
|
||||
/// Write `packet` to the outputs that want it; with `codec`, only to
|
||||
/// those that need that codec of their own.
|
||||
fn to_outputs(&self, packet: &Packet<'_>, codec: Option<Codec>) {
|
||||
let mut failed = Vec::new();
|
||||
{
|
||||
let mut outputs = lock(&self.outputs);
|
||||
for output in outputs.iter_mut() {
|
||||
if !output.sink.wants(packet.track) {
|
||||
let own = codec.is_none_or(|c| output.sink.video_codec() == Some(c));
|
||||
if !own || !output.sink.wants(packet.track) {
|
||||
continue;
|
||||
}
|
||||
if let Err(e) = output.sink.write(packet) {
|
||||
@@ -1295,15 +1322,16 @@ mod tests {
|
||||
.await
|
||||
.unwrap();
|
||||
studio.apply(Command::SetReplay { seconds: 2, memory_mb: 4 }).await.unwrap();
|
||||
let vp8 = |n: u64| Packet {
|
||||
track: Track::Video { codec: Codec::Vp8, layer: 0 },
|
||||
pts_90khz: n * 3000,
|
||||
keyframe: n.is_multiple_of(15),
|
||||
width: 64,
|
||||
height: 48,
|
||||
data: &[1, 2, 3, 4],
|
||||
};
|
||||
for n in 0..30u64 {
|
||||
studio.write_packet(&Packet {
|
||||
track: Track::Video { codec: Codec::Vp8, layer: 0 },
|
||||
pts_90khz: n * 3000,
|
||||
keyframe: n.is_multiple_of(15),
|
||||
width: 64,
|
||||
height: 48,
|
||||
data: &[1, 2, 3, 4],
|
||||
});
|
||||
studio.write_packet(&vp8(n));
|
||||
}
|
||||
{
|
||||
let outputs = lock(&studio.shared.outputs);
|
||||
@@ -1311,17 +1339,60 @@ mod tests {
|
||||
assert!(outputs[0].sink.bytes() > 0);
|
||||
}
|
||||
assert!(lock(&studio.shared.replay).stats().packets > 0);
|
||||
// RTMP carries H.264: with VP8 as the stream codec it is refused
|
||||
// with that reason, before anything connects.
|
||||
let e = studio
|
||||
.apply(Command::AddOutput(OutputSpec::Url {
|
||||
url: "rtmp://live.example/app".into(),
|
||||
token: None,
|
||||
}))
|
||||
.await
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert!(e.contains("H.264") && e.contains("VP8"), "{e}");
|
||||
|
||||
// An output that needs H.264 of layer 0 (as RTMP does) while the
|
||||
// stream is VP8: the streamer is asked for H.264 of that layer only,
|
||||
// and those packets reach that output only.
|
||||
struct NeedsH264(Arc<AtomicU64>);
|
||||
impl OutputSink for NeedsH264 {
|
||||
fn name(&self) -> &str {
|
||||
"h264"
|
||||
}
|
||||
|
||||
fn wants(&self, track: Track) -> bool {
|
||||
track == Track::Video { codec: Codec::H264, layer: 0 }
|
||||
}
|
||||
|
||||
fn video_codec(&self) -> Option<Codec> {
|
||||
Some(Codec::H264)
|
||||
}
|
||||
|
||||
fn write(&mut self, packet: &Packet<'_>) -> Result<()> {
|
||||
self.0.fetch_add(packet.data.len() as u64, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let got = Arc::new(AtomicU64::new(0));
|
||||
lock(&studio.shared.outputs).push(Output {
|
||||
id: 7,
|
||||
sink: Box::new(NeedsH264(got.clone())),
|
||||
path: None,
|
||||
started: Instant::now(),
|
||||
kbps: 0.0,
|
||||
last_bytes: 0,
|
||||
pushes: true,
|
||||
error: None,
|
||||
});
|
||||
let mut codecs = vec![Codec::Vp8];
|
||||
studio.output_codecs(0, &mut codecs);
|
||||
assert_eq!(codecs, [Codec::Vp8, Codec::H264]);
|
||||
let mut codecs = vec![Codec::Vp8];
|
||||
studio.output_codecs(1, &mut codecs);
|
||||
assert_eq!(codecs, [Codec::Vp8], "no H.264 for a layer nothing takes");
|
||||
let (recorded, replayed) = {
|
||||
let outputs = lock(&studio.shared.outputs);
|
||||
(outputs[0].sink.bytes(), lock(&studio.shared.replay).stats().packets)
|
||||
};
|
||||
let h264 = Packet { track: Track::Video { codec: Codec::H264, layer: 0 }, ..vp8(30) };
|
||||
studio.write_output_packet(&h264);
|
||||
assert_eq!(got.load(Ordering::Relaxed), 4);
|
||||
// The recording and the replay buffer keep the stream's codec.
|
||||
assert_eq!(lock(&studio.shared.outputs)[0].sink.bytes(), recorded);
|
||||
assert_eq!(lock(&studio.shared.replay).stats().packets, replayed);
|
||||
// And the stream's own packets do not reach it.
|
||||
studio.write_packet(&vp8(31));
|
||||
assert_eq!(got.load(Ordering::Relaxed), 4);
|
||||
lock(&studio.shared.outputs).retain(|o| o.id != 7);
|
||||
|
||||
// The studio is a capture backend the streamer can use unchanged.
|
||||
let mut capture = studio.capture();
|
||||
|
||||
@@ -91,6 +91,14 @@ pub trait OutputSink: Send {
|
||||
false
|
||||
}
|
||||
|
||||
/// The video codec this sink needs whatever the stream encodes (RTMP:
|
||||
/// H.264). The streamer then encodes it too, as for a viewer that chose
|
||||
/// it ([`Studio::output_codecs`](crate::studio::Studio::output_codecs)).
|
||||
/// `None`: the stream's own codec.
|
||||
fn video_codec(&self) -> Option<Codec> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Take one packet.
|
||||
fn write(&mut self, packet: &Packet<'_>) -> Result<()>;
|
||||
|
||||
|
||||
@@ -8,9 +8,11 @@
|
||||
//! libavformat struct is touched; the one field read is where a failed
|
||||
//! write lands, found at load.
|
||||
//!
|
||||
//! - Video: the studio's H.264 packets of one layer, as they are (no second
|
||||
//! encode). Another stream codec is refused with the reason: classic RTMP
|
||||
//! carries H.264 only.
|
||||
//! - Video: H.264 of one layer (classic RTMP carries nothing else): the
|
||||
//! stream's packets as they are when it encodes H.264, else those of an
|
||||
//! H.264 encoder the streamer runs for this output beside the stream's
|
||||
//! ([`OutputSink::video_codec`]), as it does for a viewer of another
|
||||
//! codec.
|
||||
//! - Audio: the studio's Opus, decoded and encoded as AAC-LC by FFmpeg's own
|
||||
//! codecs ([`crate::ffmpeg::audio`]) on the output's thread.
|
||||
//! - The stream key: in the URL (`rtmp://host/app/key`) or given apart (the
|
||||
@@ -61,14 +63,6 @@ fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Why `codec` cannot go out over RTMP.
|
||||
fn unsupported(codec: Codec) -> Error {
|
||||
error(format!(
|
||||
"RTMP carries H.264 video; the stream encodes {codec}. Choose H.264 as the stream codec \
|
||||
for this output"
|
||||
))
|
||||
}
|
||||
|
||||
/// Where to connect: the URL libavformat opens, its protocol options and a
|
||||
/// name for the UI that does not show the stream key.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -176,22 +170,13 @@ impl Rtmp {
|
||||
url.starts_with("rtmp://") || url.starts_with("rtmps://")
|
||||
}
|
||||
|
||||
/// Connect to `url` and push `layer` of the studio and its audio. The
|
||||
/// stream key is the last part of the URL's path, or `key` if given.
|
||||
/// `codec` is what the studio encodes, if known: anything but H.264 is
|
||||
/// refused (also later, when its first packet comes).
|
||||
/// Connect to `url` and push `layer` of the studio (in H.264) and its
|
||||
/// audio. The stream key is the last part of the URL's path, or `key` if
|
||||
/// given.
|
||||
///
|
||||
/// Fails when there is no FFmpeg with libavformat, or the first
|
||||
/// connection does (a wrong address, a refused key).
|
||||
pub async fn start(
|
||||
url: &str,
|
||||
key: Option<&str>,
|
||||
layer: u32,
|
||||
codec: Option<Codec>,
|
||||
) -> Result<Self> {
|
||||
if let Some(codec) = codec.filter(|c| *c != Codec::H264) {
|
||||
return Err(unsupported(codec));
|
||||
}
|
||||
pub async fn start(url: &str, key: Option<&str>, layer: u32) -> Result<Self> {
|
||||
let target = Target::new(url, key)?;
|
||||
#[cfg(not(feature = "ffmpeg"))]
|
||||
{
|
||||
@@ -245,7 +230,7 @@ impl OutputSink for Rtmp {
|
||||
|
||||
fn wants(&self, track: Track) -> bool {
|
||||
match track {
|
||||
Track::Video { layer, .. } => layer == self.layer,
|
||||
Track::Video { codec, layer } => codec == Codec::H264 && layer == self.layer,
|
||||
Track::Audio { .. } => true,
|
||||
}
|
||||
}
|
||||
@@ -254,15 +239,16 @@ impl OutputSink for Rtmp {
|
||||
self.shared.keyframe.swap(false, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn video_codec(&self) -> Option<Codec> {
|
||||
Some(Codec::H264)
|
||||
}
|
||||
|
||||
fn write(&mut self, packet: &Packet<'_>) -> Result<()> {
|
||||
let Some(queue) = &self.queue else { return Ok(()) };
|
||||
if let Track::Video { codec, layer } = packet.track {
|
||||
if layer != self.layer {
|
||||
if packet.track.is_video() {
|
||||
if !self.wants(packet.track) {
|
||||
return Ok(());
|
||||
}
|
||||
if codec != Codec::H264 {
|
||||
return Err(unsupported(codec));
|
||||
}
|
||||
if self.skip_video {
|
||||
if !packet.keyframe {
|
||||
return Ok(());
|
||||
@@ -630,16 +616,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn other_codecs_and_dead_servers_are_refused() {
|
||||
let e = Rtmp::start("rtmp://127.0.0.1:1/app", Some("k"), 0, Some(Codec::Vp8))
|
||||
.await
|
||||
.err()
|
||||
.expect("VP8 refused")
|
||||
.to_string();
|
||||
assert!(e.contains("H.264"), "{e}");
|
||||
async fn dead_servers_are_refused() {
|
||||
// Port 1 on loopback: nothing listens.
|
||||
if crate::ffmpeg::avio::Connection::available().is_ok() {
|
||||
let e = Rtmp::start("rtmp://127.0.0.1:1/app", Some("k"), 0, Some(Codec::H264))
|
||||
let e = Rtmp::start("rtmp://127.0.0.1:1/app", Some("k"), 0)
|
||||
.await
|
||||
.err()
|
||||
.expect("nothing listens")
|
||||
|
||||
@@ -145,6 +145,11 @@ viewer: Engine::subscribe_frames ─ VideoPipeline (thread) ─ VideoDecoder
|
||||
go out through `MediaSink::send_video(frame, codec)`. Sinks that do not
|
||||
tell codecs apart (`EncodedSource`, a `FrameSource`) get the stream codec
|
||||
only, so their offers must list it alone (`voelinctl stream start` does).
|
||||
A studio's outputs count as viewers too: the stream codec always runs
|
||||
for its recordings and replay buffer, and an output that needs a codec of
|
||||
its own (RTMP: H.264) gets an encoder of the layer it takes
|
||||
(`Studio::output_codecs`), whose packets reach only such outputs
|
||||
(`Studio::write_output_packet`).
|
||||
- `stats()`: `StreamerStats` with capture fps, convert time and threads,
|
||||
the GPU path (`gpu_frames`, `gpu_convert_time`, `gpu_error`),
|
||||
dropped frames, codec, and per layer (`LayerStats`) size, frames,
|
||||
|
||||
+17
-9
@@ -194,12 +194,17 @@ fails is removed and reported, and the rest go on.
|
||||
`rtmp://` and `rtmps://` protocols do the handshake, `connect`, `publish`
|
||||
and TLS and take an FLV byte stream; the FLV is ours (`flv`: `onMetaData`,
|
||||
AVC and AAC sequence headers, then one tag per frame), as the recordings'
|
||||
Matroska is, so no libavformat struct is touched. Video is the studio's
|
||||
H.264 of the output's layer as encoded; another stream codec is refused
|
||||
with the reason (classic RTMP carries H.264; Enhanced RTMP's HEVC, AV1,
|
||||
VP9 and Opus are not written). Audio is the studio's Opus decoded and
|
||||
encoded as AAC-LC (160 kbit/s, 48 kHz stereo) by FFmpeg's own `opus`
|
||||
decoder and `aac` encoder, on the output's thread. The stream key is the
|
||||
Matroska is, so no libavformat struct is touched. Video is H.264 of the
|
||||
output's layer (classic RTMP carries nothing else; Enhanced RTMP's HEVC,
|
||||
AV1, VP9 and Opus are not written): the stream's packets as they are
|
||||
when it encodes H.264; with another stream codec the streamer runs an
|
||||
H.264 encoder for that layer beside it, as for a viewer that chose
|
||||
another codec (`OutputSink::video_codec`, `Studio::output_codecs`), and
|
||||
its packets go to the outputs that asked for H.264 only, while the
|
||||
recordings and the replay buffer keep the stream's codec. Audio is the
|
||||
studio's Opus decoded and encoded as AAC-LC (160 kbit/s, 48 kHz stereo)
|
||||
by FFmpeg's own `opus` decoder and `aac` encoder, on the output's
|
||||
thread. The stream key is the
|
||||
last part of the URL's path (`rtmp://host/app/key`) or the output's token
|
||||
(sent as the play path, the URL's path as the application); the output's
|
||||
name never shows it. The first connection is made when the output is
|
||||
@@ -297,8 +302,9 @@ voelinctl studio run scenes.json --seconds 10 --switch-to 2 \
|
||||
--preview preview.png --record rec.webm --clip clip.mkv --replay 30 --tone 440 --codec vp8
|
||||
# Push to a WHIP endpoint (token also from VOELIN_WHIP_TOKEN).
|
||||
voelinctl studio run scenes.json --seconds 60 --whip https://ingest.example/whip --token ...
|
||||
# Push over RTMP(S) (H.264; the key in the URL or in --token).
|
||||
voelinctl studio run scenes.json --seconds 60 --codec h264 --tone 440 \
|
||||
# Push over RTMP(S) (H.264, encoded besides the stream's unless --codec h264;
|
||||
# the key in the URL or in --token).
|
||||
voelinctl studio run scenes.json --seconds 60 --tone 440 \
|
||||
--rtmp rtmps://live.example/app --token <stream key>
|
||||
# The compositor alone: compose time and heap allocations per frame.
|
||||
voelinctl studio bench --sources 4 --res 1920x1080 --fps 60
|
||||
@@ -344,6 +350,8 @@ two threads) takes about 3 ms at its own rate (15 fps by default).
|
||||
| Background blur, image and colour backdrops on the oval mask | `segment::tests` | tested; **no person segmentation model** (see above) |
|
||||
| Windows cameras (Media Foundation: listing, the native format nearest the wanted size, NV12 through the source reader, MJPEG decoded by it) | `cargo clippy --target x86_64-pc-windows-gnu -p voelin-media` | type-checked only, never run |
|
||||
| Android cameras | – | not implemented: `camera::list()` has only the test pattern there |
|
||||
| RTMP: the FLV tags (sizes, times past 24 bits, AVC from Annex B, `onMetaData` in AMF0), URL and key handling (the name hides the key), codecs other than H.264 and dead servers refused | `flv::tests`, `rtmp::tests` | tested |
|
||||
| RTMP: the FLV tags (sizes, times past 24 bits, AVC from Annex B, `onMetaData` in AMF0), URL and key handling (the name hides the key), dead servers refused | `flv::tests`, `rtmp::tests` | tested |
|
||||
| RTMP beside another stream codec: an output asks for H.264 of its layer only, its packets reach it alone, the recording and the replay buffer keep the stream's | `studio::tests::packets_reach_the_outputs_and_the_studio_is_a_capture_backend` | tested |
|
||||
| RTMP: write errors seen (`AVIOContext.error`, found at load), an abort ends a stuck connect, the sample format field of the AAC encoder, Opus → AAC (frames back to back from the packets' clock, priming, a gap restarts the clock) | `ffmpeg::avio::tests`, `ffmpeg::audio::tests`, `ffmpeg::tests` | tested with FFmpeg 9.0.1 (libavformat 63: `error` at 84, `sample_fmt` at 348) and FFmpeg 4.4.8 (58: 120 and 408) |
|
||||
| RTMP end to end: a studio stream (H.264 through the hardware encoder, a 440 Hz tone) pushed to FFmpeg's own RTMP server (`ffmpeg -listen 1`) with the key apart from the URL; the server killed and another started on its port; `EndStream` | `voelin-core/tests/studio.rs` `a_studio_stream_goes_out_over_rtmp_and_comes_back_after_the_server_did` | tested: ffprobe reads `h264` 320x180 and `aac` 48000 Hz stereo in both servers' files, each starting at a keyframe, every picture decodes (red), the audio decodes to 440 Hz; the key arrived as the stream name; the second server finished its file and exited by itself. No public service (Twitch, YouTube) tried; RTMPS only through FFmpeg's TLS, untried here |
|
||||
| RTMP from a VP8 stream: the same server, the key in the URL, a recording at the same time | `voelin-core/tests/studio.rs` `a_vp8_stream_goes_out_over_rtmp_as_h264` | tested: the streamer's layer encodes VP8 and H.264; ffprobe reads `h264` 320x180 and `aac` 48000 Hz stereo, starting at a keyframe, every picture decodes (red), 440 Hz; the recording is VP8 and Opus |
|
||||
@@ -74,7 +74,7 @@ struct RunArgs {
|
||||
#[arg(long)]
|
||||
whip: Option<String>,
|
||||
/// Push to this RTMP(S) server (`rtmp://host/app/key`, or the key in
|
||||
/// --token). Needs --codec h264 unless H.264 is the first codec.
|
||||
/// --token), in H.264: encoded besides the stream's unless --codec h264.
|
||||
#[arg(long)]
|
||||
rtmp: Option<String>,
|
||||
/// Bearer token for --whip, stream key for --rtmp.
|
||||
|
||||
Reference in new issue
Block a user