Encode each layer once per codec its viewers chose (WIP)
Offers list the stream codec first, then the codecs of hardware encoders, VP8 through libvpx and HEVC last; software encoders other than VP8 are only ever the stream codec, so no answer starts an expensive one. The streamer's peer reports the codec each answer chose, the session sends video only to viewers of its codec and tells the encoders through LayerFeedback which codecs are needed. Each layer's encoder thread keeps one encoder per such codec, made when a viewer needs it and dropped when none does; the stream codec is skipped while nobody takes it. The H.264 profile-level-id is computed from macroblocks per second, frame size and bitrate (Table A-1), at least 3.1 as before. Streamer takes an encoder preference (hardware on/off, auto / software / a named backend) that reconfigure can change live. HEVC is negotiable (str0m packetizes it) and only offered when a hardware encoder has it. Work in progress: committed early so it cannot be lost. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G
This commit is contained in:
1 parent
1b1d662fef
commit
40f6bb4ca6
10 files changed
+799
-97
No files matched your search
@@ -1,5 +1,6 @@
|
||||
//! Feedback from the stream sessions to the encoders of our stream's layers:
|
||||
//! keyframe requests and bitrate targets per [`LayerId`].
|
||||
//! keyframe requests and bitrate targets per [`LayerId`], and the video
|
||||
//! codecs the viewers negotiated.
|
||||
//!
|
||||
//! [`LayerFeedback`] is shared between the stream session (which writes) and
|
||||
//! encoder threads (which read every frame). Both sides only use atomics;
|
||||
@@ -9,9 +10,10 @@
|
||||
|
||||
use std::array;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::atomic::{AtomicU16, AtomicU64, Ordering};
|
||||
use std::sync::atomic::{AtomicU8, AtomicU16, AtomicU64, Ordering};
|
||||
|
||||
use crate::layer::{LayerId, LayerSet};
|
||||
use crate::peer::VideoCodec;
|
||||
|
||||
/// Words of the keyframe bitmap: one bit per layer id.
|
||||
const WORDS: usize = (LayerId::MAX as usize + 1) / 64;
|
||||
@@ -30,6 +32,8 @@ pub struct LayerFeedback {
|
||||
top: AtomicU16,
|
||||
/// Bitrate targets (bit/s, 0: none) in chunks of [`CHUNK`] layer ids.
|
||||
bitrates: Box<[OnceLock<Box<[AtomicU64]>>]>,
|
||||
/// [`VideoCodec::bit`]s of the codecs connected viewers negotiated.
|
||||
codecs: AtomicU8,
|
||||
}
|
||||
|
||||
impl Default for LayerFeedback {
|
||||
@@ -51,6 +55,7 @@ impl LayerFeedback {
|
||||
summary: array::from_fn(|_| AtomicU64::new(0)),
|
||||
top: AtomicU16::new(0),
|
||||
bitrates: (0..=LayerId::MAX as usize / CHUNK).map(|_| OnceLock::new()).collect(),
|
||||
codecs: AtomicU8::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -122,6 +127,22 @@ impl LayerFeedback {
|
||||
let bitrate = chunk[usize::from(layer) % CHUNK].load(Ordering::Relaxed);
|
||||
(bitrate != 0).then_some(bitrate)
|
||||
}
|
||||
|
||||
/// The video codecs the viewers negotiated.
|
||||
pub fn set_codecs(&self, codecs: impl IntoIterator<Item = VideoCodec>) {
|
||||
let bits = codecs.into_iter().fold(0, |bits, c| bits | c.bit());
|
||||
self.codecs.store(bits, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Whether a viewer negotiated `codec`.
|
||||
pub fn has_codec(&self, codec: VideoCodec) -> bool {
|
||||
self.codecs.load(Ordering::Relaxed) & codec.bit() != 0
|
||||
}
|
||||
|
||||
/// Whether any viewer negotiated a codec yet.
|
||||
pub fn has_codecs(&self) -> bool {
|
||||
self.codecs.load(Ordering::Relaxed) != 0
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -160,4 +181,15 @@ mod tests {
|
||||
f.set_bitrate(3, None);
|
||||
assert_eq!(f.bitrate(3), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codecs() {
|
||||
let f = LayerFeedback::new();
|
||||
assert!(!f.has_codecs());
|
||||
f.set_codecs([VideoCodec::Vp8, VideoCodec::H265, VideoCodec::Vp8]);
|
||||
assert!(f.has_codec(VideoCodec::Vp8) && f.has_codec(VideoCodec::H265));
|
||||
assert!(!f.has_codec(VideoCodec::H264));
|
||||
f.set_codecs([]);
|
||||
assert!(!f.has_codecs());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! H.264 `profile-level-id` for the offer: the profile our encoders produce
|
||||
//! and the level the stream's size, frame rate and bitrate need (ITU-T
|
||||
//! H.264 Table A-1), instead of a fixed level.
|
||||
|
||||
/// Profile of our H.264 streams.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum H264Profile {
|
||||
/// Constrained High (`profile_idc` 100, `constraint_set4` and `5`): what
|
||||
/// TeamSpeak clients decode.
|
||||
#[default]
|
||||
ConstrainedHigh,
|
||||
/// Constrained Baseline (`profile_idc` 66, `constraint_set0` and `1`).
|
||||
ConstrainedBaseline,
|
||||
}
|
||||
|
||||
/// Level limits: `level_idc`, macroblocks per second, macroblocks per frame,
|
||||
/// bitrate in kbit/s (Baseline; High allows 1.25 times that).
|
||||
const LEVELS: [(u8, u64, u64, u64); 19] = [
|
||||
(10, 1_485, 99, 64),
|
||||
(11, 3_000, 396, 192),
|
||||
(12, 6_000, 396, 384),
|
||||
(13, 11_880, 396, 768),
|
||||
(20, 11_880, 396, 2_000),
|
||||
(21, 19_800, 792, 4_000),
|
||||
(22, 20_250, 1_620, 4_000),
|
||||
(30, 40_500, 1_620, 10_000),
|
||||
(31, 108_000, 3_600, 14_000),
|
||||
(32, 216_000, 5_120, 20_000),
|
||||
(40, 245_760, 8_192, 20_000),
|
||||
(41, 245_760, 8_192, 50_000),
|
||||
(42, 522_240, 8_704, 50_000),
|
||||
(50, 589_824, 22_080, 135_000),
|
||||
(51, 983_040, 36_864, 240_000),
|
||||
(52, 2_073_600, 36_864, 240_000),
|
||||
(60, 4_177_920, 139_264, 240_000),
|
||||
(61, 8_355_840, 139_264, 480_000),
|
||||
(62, 16_711_680, 139_264, 800_000),
|
||||
];
|
||||
|
||||
/// The lowest level (`level_idc`, e.g. 31 for 3.1) whose limits hold
|
||||
/// `width` x `height` at `fps` and `bitrate` bit/s; the highest level
|
||||
/// defined if none does (the stream is sent anyway: decoders mostly take
|
||||
/// more than their level).
|
||||
pub fn level_idc(profile: H264Profile, width: u32, height: u32, fps: u32, bitrate: u64) -> u8 {
|
||||
let (mbs_w, mbs_h) = (u64::from(width.div_ceil(16)), u64::from(height.div_ceil(16)));
|
||||
let frame = mbs_w * mbs_h;
|
||||
let rate = frame * u64::from(fps.max(1));
|
||||
let factor = match profile {
|
||||
H264Profile::ConstrainedHigh => 1250,
|
||||
H264Profile::ConstrainedBaseline => 1000,
|
||||
};
|
||||
LEVELS
|
||||
.iter()
|
||||
.find(|&&(_, max_rate, max_frame, max_kbps)| {
|
||||
rate <= max_rate
|
||||
&& frame <= max_frame
|
||||
// Neither side may exceed sqrt(8 * MaxFS) macroblocks.
|
||||
&& mbs_w * mbs_w <= 8 * max_frame
|
||||
&& mbs_h * mbs_h <= 8 * max_frame
|
||||
&& bitrate <= max_kbps * factor
|
||||
})
|
||||
.map_or(LEVELS[LEVELS.len() - 1].0, |l| l.0)
|
||||
}
|
||||
|
||||
/// `profile-level-id` (`a=fmtp`, three bytes: `profile_idc`,
|
||||
/// `profile-iop`, `level_idc`) for `profile` at `level_idc`.
|
||||
pub fn profile_level_id(profile: H264Profile, level_idc: u8) -> u32 {
|
||||
let (profile_idc, iop) = match profile {
|
||||
H264Profile::ConstrainedHigh => (0x64, 0x0c),
|
||||
H264Profile::ConstrainedBaseline => (0x42, 0xe0),
|
||||
};
|
||||
(profile_idc << 16) | (iop << 8) | u32::from(level_idc)
|
||||
}
|
||||
|
||||
/// The level TeamSpeak offers (3.1): our offers never go below it, so the
|
||||
/// offer official clients know stays the same for small streams.
|
||||
pub const MIN_OFFER_LEVEL: u8 = 31;
|
||||
|
||||
/// `profile-level-id` for a stream of this size, frame rate and bitrate,
|
||||
/// at least level 3.1.
|
||||
pub fn offer_profile_level_id(
|
||||
profile: H264Profile,
|
||||
width: u32,
|
||||
height: u32,
|
||||
fps: u32,
|
||||
bitrate: u64,
|
||||
) -> u32 {
|
||||
let level = level_idc(profile, width, height, fps, bitrate).max(MIN_OFFER_LEVEL);
|
||||
profile_level_id(profile, level)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const HIGH: H264Profile = H264Profile::ConstrainedHigh;
|
||||
|
||||
#[test]
|
||||
fn levels_from_macroblocks_per_second() {
|
||||
// 720p30: 3600 MBs per frame, 108000 per second: exactly 3.1.
|
||||
assert_eq!(level_idc(HIGH, 1280, 720, 30, 4_000_000), 31);
|
||||
// 720p60 needs 3.2, 1080p30 4.0, 1080p60 4.2.
|
||||
assert_eq!(level_idc(HIGH, 1280, 720, 60, 4_000_000), 32);
|
||||
assert_eq!(level_idc(HIGH, 1920, 1080, 30, 8_000_000), 40);
|
||||
assert_eq!(level_idc(HIGH, 1920, 1080, 60, 8_000_000), 42);
|
||||
// 1440p60: 14400 MBs per frame, more than 4.2's 8704: 5.1.
|
||||
assert_eq!(level_idc(HIGH, 2560, 1440, 60, 10_000_000), 51);
|
||||
// 4K120 needs 6.0 (and any size or rate beyond all: the top level).
|
||||
assert_eq!(level_idc(HIGH, 3840, 2160, 120, 10_000_000), 60);
|
||||
assert_eq!(level_idc(HIGH, 16384, 16384, 240, 10_000_000), 62);
|
||||
// Small streams: low levels.
|
||||
assert_eq!(level_idc(HIGH, 320, 240, 15, 200_000), 12);
|
||||
// The bitrate counts too: 1080p30 at 30 Mbit/s is beyond 4.0 (25
|
||||
// Mbit/s in High).
|
||||
assert_eq!(level_idc(HIGH, 1920, 1080, 30, 30_000_000), 41);
|
||||
// Baseline has the lower bitrate limit.
|
||||
let baseline = H264Profile::ConstrainedBaseline;
|
||||
assert_eq!(level_idc(baseline, 1920, 1080, 30, 22_000_000), 41);
|
||||
assert_eq!(level_idc(HIGH, 1920, 1080, 30, 22_000_000), 40);
|
||||
// A very wide frame is limited by sqrt(8 * MaxFS).
|
||||
assert_eq!(level_idc(HIGH, 4096, 64, 1, 100_000), 40);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_level_ids() {
|
||||
assert_eq!(profile_level_id(HIGH, 31), 0x640c1f);
|
||||
assert_eq!(profile_level_id(H264Profile::ConstrainedBaseline, 31), 0x42e01f);
|
||||
assert_eq!(offer_profile_level_id(HIGH, 320, 240, 15, 200_000), 0x640c1f);
|
||||
assert_eq!(offer_profile_level_id(HIGH, 1920, 1080, 60, 8_000_000), 0x640c2a);
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,7 @@
|
||||
pub mod discovery;
|
||||
pub mod dtls;
|
||||
pub mod feedback;
|
||||
pub mod h264;
|
||||
pub mod layer;
|
||||
pub mod peer;
|
||||
pub mod proto;
|
||||
@@ -23,6 +24,7 @@ pub mod stun;
|
||||
pub use discovery::{ClientState, StreamLookup};
|
||||
pub use dtls::SrtpProfile;
|
||||
pub use feedback::LayerFeedback;
|
||||
pub use h264::H264Profile;
|
||||
pub use layer::{LayerId, LayerSet, LayerSpec};
|
||||
pub use peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerError, PeerEvent, VideoCodec};
|
||||
pub use proto::{LeaveReason, StreamInfo, StreamKind, StreamNotification, StreamSetup};
|
||||
|
||||
@@ -32,6 +32,7 @@ use tokio::sync::{mpsc, oneshot};
|
||||
use tracing::{debug, trace, warn};
|
||||
|
||||
use crate::dtls::{self, NegotiatedProfile, SrtpProfile};
|
||||
use crate::h264::{self, H264Profile};
|
||||
use crate::layer::LayerSpec;
|
||||
use crate::stun;
|
||||
|
||||
@@ -46,10 +47,12 @@ pub enum VideoCodec {
|
||||
Vp9,
|
||||
H264,
|
||||
Av1,
|
||||
/// HEVC: offered last, for peers that take nothing else.
|
||||
H265,
|
||||
}
|
||||
|
||||
impl VideoCodec {
|
||||
pub const ALL: [Self; 4] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1];
|
||||
pub const ALL: [Self; 5] = [Self::Vp8, Self::Vp9, Self::H264, Self::Av1, Self::H265];
|
||||
|
||||
pub fn from_codec(c: Codec) -> Option<Self> {
|
||||
match c {
|
||||
@@ -57,6 +60,7 @@ impl VideoCodec {
|
||||
Codec::Vp9 => Some(Self::Vp9),
|
||||
Codec::H264 => Some(Self::H264),
|
||||
Codec::Av1 => Some(Self::Av1),
|
||||
Codec::H265 => Some(Self::H265),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
@@ -72,8 +76,20 @@ impl VideoCodec {
|
||||
Self::Vp9 => "VP9",
|
||||
Self::H264 => "H264",
|
||||
Self::Av1 => "AV1",
|
||||
Self::H265 => "H265",
|
||||
}
|
||||
}
|
||||
|
||||
/// Bit of this codec in a set of codecs ([`crate::LayerFeedback`]).
|
||||
pub fn bit(self) -> u8 {
|
||||
1 << Self::ALL.iter().position(|c| *c == self).unwrap_or(0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for VideoCodec {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.write_str(self.sdp_name())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
@@ -107,6 +123,10 @@ pub struct PeerConfig {
|
||||
/// simulcast leaves the peer unable to send video. Official TeamSpeak
|
||||
/// viewers get a plain offer and one layer at a time.
|
||||
pub simulcast: bool,
|
||||
/// H.264 `profile-level-id` of the offer: Constrained High at the level
|
||||
/// the stream needs ([`set_h264_format`](Self::set_h264_format)); level
|
||||
/// 3.1 by default.
|
||||
pub h264_profile_level_id: u32,
|
||||
}
|
||||
|
||||
impl Default for PeerConfig {
|
||||
@@ -121,6 +141,7 @@ impl Default for PeerConfig {
|
||||
srtp_profiles: SrtpProfile::DEFAULT_ORDER.to_vec(),
|
||||
bandwidth_estimation: true,
|
||||
simulcast: false,
|
||||
h264_profile_level_id: H264_CONSTRAINED_HIGH,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -134,6 +155,21 @@ impl PeerConfig {
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// Offer H.264 in `profile` at the level a `width` x `height` stream at
|
||||
/// `fps` and `bitrate` bit/s needs (at least 3.1, see
|
||||
/// [`crate::h264::offer_profile_level_id`]).
|
||||
pub fn set_h264_format(
|
||||
&mut self,
|
||||
profile: H264Profile,
|
||||
width: u32,
|
||||
height: u32,
|
||||
fps: u32,
|
||||
bitrate: u64,
|
||||
) {
|
||||
self.h264_profile_level_id =
|
||||
h264::offer_profile_level_id(profile, width, height, fps, bitrate);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
@@ -190,6 +226,9 @@ pub enum PeerEvent {
|
||||
/// The answer accepted RID simulcast: video goes out per layer with
|
||||
/// these RIDs ([`Peer::write_rid`]).
|
||||
Simulcast(Vec<Rid>),
|
||||
/// The video codec the answer chose (streamer side): the viewer's first
|
||||
/// one. Video written to this peer must be in it.
|
||||
VideoCodec(VideoCodec),
|
||||
/// The connection is gone.
|
||||
Closed,
|
||||
}
|
||||
@@ -422,11 +461,12 @@ fn build_rtc(
|
||||
112.into(),
|
||||
Some(113.into()),
|
||||
true,
|
||||
H264_CONSTRAINED_HIGH,
|
||||
config.h264_profile_level_id,
|
||||
);
|
||||
c
|
||||
}
|
||||
VideoCodec::Av1 => rtc_config.enable_av1(true),
|
||||
VideoCodec::H265 => rtc_config.enable_h265(true),
|
||||
};
|
||||
}
|
||||
dtls::build_rtc(rtc_config, &config.srtp_profiles)
|
||||
@@ -798,6 +838,18 @@ impl Task {
|
||||
let _ = self.events.send(PeerEvent::Simulcast(rids.clone()));
|
||||
}
|
||||
}
|
||||
// The codec video is written in (see `find_writer`).
|
||||
if let Some((mid, pt)) = self.find_writer(MediaKind::Video) {
|
||||
self.writers.insert(MediaKind::Video, (mid, pt));
|
||||
let codec = self.rtc.writer(mid).and_then(|w| {
|
||||
let params = w.payload_params().find(|p| p.pt() == pt)?;
|
||||
VideoCodec::from_codec(params.spec().codec)
|
||||
});
|
||||
if let Some(codec) = codec {
|
||||
debug!(%codec, "the answer chose");
|
||||
let _ = self.events.send(PeerEvent::VideoCodec(codec));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -872,6 +924,41 @@ mod tests {
|
||||
assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}");
|
||||
}
|
||||
|
||||
/// Several codecs offered: the streamer learns which one each viewer's
|
||||
/// answer chose; H.264 carries the level the stream needs.
|
||||
#[tokio::test]
|
||||
async fn streamer_learns_the_answered_codec() {
|
||||
let mut streamer = PeerConfig {
|
||||
video_codecs: vec![VideoCodec::Vp8, VideoCodec::H264, VideoCodec::H265],
|
||||
..PeerConfig::loopback()
|
||||
};
|
||||
streamer.set_h264_format(H264Profile::ConstrainedHigh, 1920, 1080, 60, 8_000_000);
|
||||
let (mut peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
|
||||
assert!(offer.contains("profile-level-id=640c2a"), "{offer}");
|
||||
assert!(offer.contains("H265/90000"), "{offer}");
|
||||
let viewers = [
|
||||
(vec![VideoCodec::Vp8, VideoCodec::H264], VideoCodec::Vp8),
|
||||
(vec![VideoCodec::H264], VideoCodec::H264),
|
||||
(vec![VideoCodec::H265], VideoCodec::H265),
|
||||
];
|
||||
for (accept, expected) in viewers {
|
||||
let (mut streamer_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
|
||||
let config = PeerConfig { accept_video_codecs: accept, ..PeerConfig::loopback() };
|
||||
let (_viewer, answer) = Peer::answer(&config, &offer).await.unwrap();
|
||||
streamer_peer.accept_answer(&answer).await.unwrap();
|
||||
let codec = loop {
|
||||
match streamer_peer.next_event().await.unwrap() {
|
||||
PeerEvent::VideoCodec(codec) => break codec,
|
||||
PeerEvent::Closed => panic!("closed"),
|
||||
_ => {}
|
||||
}
|
||||
};
|
||||
assert_eq!(codec, expected);
|
||||
}
|
||||
peer.close();
|
||||
while peer.next_event().await.is_some() {}
|
||||
}
|
||||
|
||||
/// The SDP lines that make up the media description (not the random ids,
|
||||
/// ports, credentials and fingerprints).
|
||||
fn media_lines(sdp: &str) -> Vec<&str> {
|
||||
|
||||
@@ -40,7 +40,7 @@ use crate::discovery::{ClientState, Discovery, StreamLookup};
|
||||
use crate::dtls::SrtpProfile;
|
||||
use crate::feedback::LayerFeedback;
|
||||
use crate::layer::{LayerId, LayerSet, LayerSpec};
|
||||
use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent};
|
||||
use crate::peer::{MediaFrame, OfferOptions, Peer, PeerConfig, PeerEvent, VideoCodec};
|
||||
use crate::proto::{self, LeaveReason, StreamInfo, StreamNotification, StreamSetup};
|
||||
use crate::signal::Signal;
|
||||
use crate::source::EncodedFrame;
|
||||
@@ -146,6 +146,9 @@ pub struct ViewerInfo {
|
||||
pub estimate: Option<u64>,
|
||||
/// The SRTP profile of the connection, once DTLS is done.
|
||||
pub srtp_profile: Option<SrtpProfile>,
|
||||
/// The video codec the viewer's answer chose (it gets video in that
|
||||
/// codec).
|
||||
pub codec: Option<VideoCodec>,
|
||||
}
|
||||
|
||||
/// What happens to our own stream.
|
||||
@@ -542,6 +545,8 @@ struct ViewerSlot {
|
||||
/// The latest bandwidth estimate of the connection (bit/s).
|
||||
estimate: Option<u64>,
|
||||
srtp_profile: Option<SrtpProfile>,
|
||||
/// The video codec its answer chose.
|
||||
codec: Option<VideoCodec>,
|
||||
}
|
||||
|
||||
impl ViewerSlot {
|
||||
@@ -554,6 +559,7 @@ impl ViewerSlot {
|
||||
rids: None,
|
||||
estimate: None,
|
||||
srtp_profile: None,
|
||||
codec: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -648,6 +654,7 @@ impl StreamerSession {
|
||||
layer: (v.peer.is_some() && v.rids.is_none()).then_some(v.choice.layer),
|
||||
estimate: v.estimate,
|
||||
srtp_profile: v.srtp_profile,
|
||||
codec: v.codec,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
@@ -792,6 +799,7 @@ impl StreamerSession {
|
||||
slot.peer = Some(peer);
|
||||
slot.state = ViewerState::Connecting;
|
||||
slot.choice = LayerChoice::new(layer);
|
||||
slot.codec = None;
|
||||
slot.rids = None;
|
||||
slot.estimate = None;
|
||||
slot.srtp_profile = None;
|
||||
@@ -930,6 +938,18 @@ impl StreamerSession {
|
||||
/// Send an encoded frame: audio to every connected viewer, video to the
|
||||
/// viewers of its layer (with its RID to peers with RID simulcast).
|
||||
pub fn write_frame(&mut self, frame: &EncodedFrame, out: &mut Outbox) {
|
||||
self.write_frame_in(frame, None, out);
|
||||
}
|
||||
|
||||
/// [`write_frame`](Self::write_frame) for video encoded in `codec`
|
||||
/// (`None`: whatever the viewers negotiated): only viewers whose answer
|
||||
/// chose that codec get it.
|
||||
pub fn write_frame_in(
|
||||
&mut self,
|
||||
frame: &EncodedFrame,
|
||||
codec: Option<VideoCodec>,
|
||||
out: &mut Outbox,
|
||||
) {
|
||||
let (kind, time, layer) = (frame.kind, frame.time, frame.layer);
|
||||
let rid = match kind {
|
||||
MediaKind::Video => self.layers.index(layer).and_then(|i| self.layers.rids[i]),
|
||||
@@ -944,6 +964,11 @@ impl StreamerSession {
|
||||
peer.write(kind, time, frame.data.clone());
|
||||
continue;
|
||||
}
|
||||
if let (Some(codec), Some(negotiated)) = (codec, slot.codec)
|
||||
&& codec != negotiated
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match &slot.rids {
|
||||
Some(rids) => {
|
||||
if let Some(rid) = rid
|
||||
@@ -1062,6 +1087,11 @@ impl StreamerSession {
|
||||
slot.rids = Some(rids);
|
||||
}
|
||||
}
|
||||
PeerEvent::VideoCodec(codec) => {
|
||||
debug!(viewer = viewer.0, %codec, "viewer's video codec");
|
||||
slot.codec = Some(codec);
|
||||
self.emit_viewers(out);
|
||||
}
|
||||
PeerEvent::Media(_) | PeerEvent::LayerMedia { .. } => {}
|
||||
PeerEvent::Closed => {
|
||||
// The viewer may ask for a new offer (`reconnect`); it stays
|
||||
@@ -1173,6 +1203,11 @@ impl StreamerSession {
|
||||
}
|
||||
|
||||
fn emit_viewers(&mut self, out: &mut Outbox) {
|
||||
// Every change of the viewers comes through here: the encoders learn
|
||||
// which codecs are needed now.
|
||||
self.feedback.set_codecs(
|
||||
self.viewers.values().filter(|v| v.peer.is_some()).filter_map(|v| v.codec),
|
||||
);
|
||||
self.last_viewers_event = Some(Instant::now());
|
||||
out.event(StreamEvent::Streamer(StreamerEvent::Viewers(self.viewers())));
|
||||
}
|
||||
@@ -1409,7 +1444,8 @@ impl ViewerSession {
|
||||
PeerEvent::KeyframeRequest
|
||||
| PeerEvent::LayerKeyframeRequest(_)
|
||||
| PeerEvent::BitrateEstimate(_)
|
||||
| PeerEvent::Simulcast(_) => {}
|
||||
| PeerEvent::Simulcast(_)
|
||||
| PeerEvent::VideoCodec(_) => {}
|
||||
PeerEvent::Closed => {
|
||||
if self.peer.take().is_none() {
|
||||
return;
|
||||
@@ -1524,8 +1560,15 @@ impl Streams {
|
||||
/// Send an encoded frame of our stream: audio to every connected viewer,
|
||||
/// video to the viewers of its layer.
|
||||
pub fn write_frame(&mut self, frame: &EncodedFrame) {
|
||||
self.write_frame_in(frame, None);
|
||||
}
|
||||
|
||||
/// [`write_frame`](Self::write_frame) of video encoded in `codec`: to
|
||||
/// the viewers that negotiated it (see
|
||||
/// [`StreamerSession::write_frame_in`]).
|
||||
pub fn write_frame_in(&mut self, frame: &EncodedFrame, codec: Option<VideoCodec>) {
|
||||
if let Some(s) = self.streamer.as_mut().filter(|s| !s.is_ended()) {
|
||||
s.write_frame(frame, &mut self.out);
|
||||
s.write_frame_in(frame, codec, &mut self.out);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user