fix(calling): scale the screen share once its frame size is known
- The mixer limit (max-fs 8160) arrived before the first share frame, so it was applied unscaled and never again - 1920x1200 then exceeded max-fs and Teams web showed no share; limits are now reapplied when the frame size changes - call-e2e: guest camera toggles by its observed state, failed scenarios keep per-stream guest stats Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -2259,6 +2259,13 @@ async fn drive(
2259
2259
}
2260
2260
});
2261
2261
}
2262
for (source, refreshed) in local_video.refresh_send_limits() {
2263
match refreshed {
2264
Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?} after a frame size change")),
2265
Ok(None) => {}
2266
Err(error) => timeline.record("send limits failed", error.to_string()),
2267
}
2268
}
2262
2269
if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)
2263
2270
&& let Some(average_ms) = local_video.blur_average_ms()
2264
2271
{
@@ -2259,6 +2259,13 @@ async fn drive(2259
}2259
}2260
});2260
});2261
}2261
}2262
for (source, refreshed) in local_video.refresh_send_limits() {2263
match refreshed {2264
Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?} after a frame size change")),2265
Ok(None) => {}2266
Err(error) => timeline.record("send limits failed", error.to_string()),2267
}2268
}2262
if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)2269
if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)2263
&& let Some(average_ms) = local_video.blur_average_ms()2270
&& let Some(average_ms) = local_video.blur_average_ms()2264
{2271
{@@ -264,6 +264,8 @@ mod tests {
264
264
let scale = scale_for(960, 720, 920);
265
265
assert!(macroblocks(960.0 / scale, 720.0 / scale) <= 920);
266
266
assert_eq!(scale_for(1280, 720, 0), 1.0);
267
let screen = scale_for(1920, 1200, 8160);
268
assert!(screen > 1.0 && macroblocks(1920.0 / screen, 1200.0 / screen) <= 8160, "{screen}");
267
269
}
268
270
269
271
#[test]
@@ -264,6 +264,8 @@ mod tests {264
let scale = scale_for(960, 720, 920);264
let scale = scale_for(960, 720, 920);265
assert!(macroblocks(960.0 / scale, 720.0 / scale) <= 920);265
assert!(macroblocks(960.0 / scale, 720.0 / scale) <= 920);266
assert_eq!(scale_for(1280, 720, 0), 1.0);266
assert_eq!(scale_for(1280, 720, 0), 1.0);267
let screen = scale_for(1920, 1200, 8160);268
assert!(screen > 1.0 && macroblocks(1920.0 / screen, 1200.0 / screen) <= 8160, "{screen}");267
}269
}268
270
269
#[test]271
#[test]@@ -133,7 +133,12 @@ struct Outgoing {
133
133
track: RtcVideoTrack,
134
134
capture: Option<Capture>,
135
135
frame_size: Arc<AtomicU64>,
136
limits: Option<EncoderLimits>,
136
requested: Option<RequestedLimits>,
137
}
138
139
struct RequestedLimits {
140
limits: Vec<SendLimit>,
141
applied_for: Option<(u32, u32)>,
137
142
}
138
143
139
144
impl Outgoing {
@@ -141,7 +146,7 @@ impl Outgoing {
141
146
let (width, height) = kind.size();
142
147
let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
143
148
let track = factory.create_video_track(label, source.clone());
144
Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), limits: None }
149
Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), requested: None }
145
150
}
146
151
}
147
152
@@ -218,6 +223,7 @@ impl LocalVideo {
218
223
SendSource::Screen => &mut self.screen,
219
224
};
220
225
let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
226
outgoing.requested = Some(RequestedLimits { limits: limits.to_vec(), applied_for: frame });
221
227
let rids: Vec<String> = sender.parameters().encodings.into_iter().map(|encoding| encoding.rid).collect();
222
228
if rids.len() > 1 {
223
229
let plans = plan_layers(limits, frame, &rids);
@@ -229,7 +235,6 @@ impl LocalVideo {
229
235
}
230
236
let Some(limit) = limits.first() else { return Ok(None) };
231
237
let encoder = encoder_limits(limit, frame);
232
outgoing.limits = Some(encoder);
233
238
if limit.keyframe {
234
239
Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
235
240
}
@@ -237,6 +242,24 @@ impl LocalVideo {
237
242
Ok(Some(vec![LayerPlan { rid: rids.into_iter().next().unwrap_or_default(), active: true, limits: Some(encoder), keyframe: limit.keyframe }]))
238
243
}
239
244
245
/// The mixer sends its limits once, often before the first frame tells the size to scale from.
246
pub fn refresh_send_limits(&mut self) -> Vec<(SendSource, Result<Option<Vec<LayerPlan>>>)> {
247
let mut refreshed = Vec::new();
248
for source in [SendSource::Camera, SendSource::Screen] {
249
let outgoing = match source {
250
SendSource::Camera => &self.camera,
251
SendSource::Screen => &self.screen,
252
};
253
let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
254
let Some(requested) = outgoing.requested.as_ref().filter(|requested| frame.is_some() && requested.applied_for != frame) else {
255
continue;
256
};
257
let limits = requested.limits.clone();
258
refreshed.push((source, self.apply_send_limit(source, &limits)));
259
}
260
refreshed
261
}
262
240
263
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
241
264
let mut parameters = sender.parameters();
242
265
for encoding in &mut parameters.encodings {
@@ -133,7 +133,12 @@ struct Outgoing {133
track: RtcVideoTrack,133
track: RtcVideoTrack,134
capture: Option<Capture>,134
capture: Option<Capture>,135
frame_size: Arc<AtomicU64>,135
frame_size: Arc<AtomicU64>,136
limits: Option<EncoderLimits>,136
requested: Option<RequestedLimits>,137
}138
139
struct RequestedLimits {140
limits: Vec<SendLimit>,141
applied_for: Option<(u32, u32)>,137
}142
}138
143
139
impl Outgoing {144
impl Outgoing {@@ -141,7 +146,7 @@ impl Outgoing {141
let (width, height) = kind.size();146
let (width, height) = kind.size();142
let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);147
let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);143
let track = factory.create_video_track(label, source.clone());148
let track = factory.create_video_track(label, source.clone());144
Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), limits: None }149
Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), requested: None }145
}150
}146
}151
}147
152
@@ -218,6 +223,7 @@ impl LocalVideo {218
SendSource::Screen => &mut self.screen,223
SendSource::Screen => &mut self.screen,219
};224
};220
let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));225
let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));226
outgoing.requested = Some(RequestedLimits { limits: limits.to_vec(), applied_for: frame });221
let rids: Vec<String> = sender.parameters().encodings.into_iter().map(|encoding| encoding.rid).collect();227
let rids: Vec<String> = sender.parameters().encodings.into_iter().map(|encoding| encoding.rid).collect();222
if rids.len() > 1 {228
if rids.len() > 1 {223
let plans = plan_layers(limits, frame, &rids);229
let plans = plan_layers(limits, frame, &rids);@@ -229,7 +235,6 @@ impl LocalVideo {229
}235
}230
let Some(limit) = limits.first() else { return Ok(None) };236
let Some(limit) = limits.first() else { return Ok(None) };231
let encoder = encoder_limits(limit, frame);237
let encoder = encoder_limits(limit, frame);232
outgoing.limits = Some(encoder);233
if limit.keyframe {238
if limit.keyframe {234
Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;239
Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;235
}240
}@@ -237,6 +242,24 @@ impl LocalVideo {237
Ok(Some(vec![LayerPlan { rid: rids.into_iter().next().unwrap_or_default(), active: true, limits: Some(encoder), keyframe: limit.keyframe }]))242
Ok(Some(vec![LayerPlan { rid: rids.into_iter().next().unwrap_or_default(), active: true, limits: Some(encoder), keyframe: limit.keyframe }]))238
}243
}239
244
245
/// The mixer sends its limits once, often before the first frame tells the size to scale from.246
pub fn refresh_send_limits(&mut self) -> Vec<(SendSource, Result<Option<Vec<LayerPlan>>>)> {247
let mut refreshed = Vec::new();248
for source in [SendSource::Camera, SendSource::Screen] {249
let outgoing = match source {250
SendSource::Camera => &self.camera,251
SendSource::Screen => &self.screen,252
};253
let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));254
let Some(requested) = outgoing.requested.as_ref().filter(|requested| frame.is_some() && requested.applied_for != frame) else {255
continue;256
};257
let limits = requested.limits.clone();258
refreshed.push((source, self.apply_send_limit(source, &limits)));259
}260
refreshed261
}262
240
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {263
fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {241
let mut parameters = sender.parameters();264
let mut parameters = sender.parameters();242
for encoding in &mut parameters.encodings {265
for encoding in &mut parameters.encodings {@@ -267,7 +267,10 @@ async function measure(tab, workDir) {
267
267
};
268
268
}
269
269
270
const ONLY = process.env.SCENARIOS?.split(',');
271
270
272
async function scenario(name, report, tab, workDir, act, check) {
273
if (ONLY && !ONLY.includes(name)) return;
271
274
log(`scenario: ${name}`);
272
275
try {
273
276
await act();
@@ -276,7 +279,10 @@ async function scenario(name, report, tab, workDir, act, check) {
276
279
const pass = Boolean(check(measured));
277
280
report.scenarios[name] = { pass, ...measured, app: undefined, appState: measured.app };
278
281
log(`scenario ${name}: ${pass ? 'PASS' : 'FAIL'}`);
279
if (!pass) await tab.shot(`${workDir}/${name}.png`).catch(() => {});
282
if (!pass) {
283
await tab.shot(`${workDir}/${name}.png`).catch(() => {});
284
report.scenarios[name].guestVideoStreams = (await tab.evaluate(PEER_STATS).catch(() => ({}))).videoIn;
285
}
280
286
} catch (error) {
281
287
report.scenarios[name] = { pass: false, error: error.message };
282
288
log(`scenario ${name}: ERROR ${error.message}`);
@@ -290,15 +296,22 @@ async function guestClick(tab, labels) {
290
296
throw new Error(`guest found none of ${labels.join(', ')}`);
291
297
}
292
298
299
async function guestCamera(tab, on) {
300
const sending = (await guestVideo(tab)).sentFrames;
301
await delay(2_000);
302
const isOn = (await guestVideo(tab)).sentFrames > sending;
303
if (isOn !== on) await guestClick(tab, [on ? '=Turn camera on' : '=Turn camera off', '=Camera']);
304
}
305
293
306
async function runScenarios(report, tab, workDir) {
294
307
report.scenarios = {};
295
308
await scenario('app-camera-on', report, tab, workDir, () => runTeams('--call', 'camera on'),
296
309
(m) => m.app.cameraOn && m.appVideoOut >= MIN_FRAMES && m.guestVideoIn >= MIN_FRAMES);
297
await scenario('guest-camera-on', report, tab, workDir, () => guestClick(tab, ['=Turn camera on', 'Turn camera on', '=Camera']),
310
await scenario('guest-camera-on', report, tab, workDir, () => guestCamera(tab, true),
298
311
(m) => m.guestVideoOut >= MIN_FRAMES && m.appVideoIn >= MIN_FRAMES && m.appVideoShown >= MIN_FRAMES);
299
312
await scenario('app-camera-off', report, tab, workDir, () => runTeams('--call', 'camera off'),
300
313
(m) => !m.app.cameraOn && m.appVideoOut < MIN_FRAMES && m.appVideoIn >= MIN_FRAMES);
301
await scenario('guest-camera-off', report, tab, workDir, () => guestClick(tab, ['=Turn camera off', 'Turn camera off', '=Camera']),
314
await scenario('guest-camera-off', report, tab, workDir, () => guestCamera(tab, false),
302
315
(m) => m.appVideoIn < MIN_FRAMES);
303
316
await scenario('app-share', report, tab, workDir, async () => {
304
317
runTeams('--call', 'share-sources');
@@ -267,7 +267,10 @@ async function measure(tab, workDir) {267
};267
};268
}268
}269
269
270
const ONLY = process.env.SCENARIOS?.split(',');271
270
async function scenario(name, report, tab, workDir, act, check) {272
async function scenario(name, report, tab, workDir, act, check) {273
if (ONLY && !ONLY.includes(name)) return;271
log(`scenario: ${name}`);274
log(`scenario: ${name}`);272
try {275
try {273
await act();276
await act();@@ -276,7 +279,10 @@ async function scenario(name, report, tab, workDir, act, check) {276
const pass = Boolean(check(measured));279
const pass = Boolean(check(measured));277
report.scenarios[name] = { pass, ...measured, app: undefined, appState: measured.app };280
report.scenarios[name] = { pass, ...measured, app: undefined, appState: measured.app };278
log(`scenario ${name}: ${pass ? 'PASS' : 'FAIL'}`);281
log(`scenario ${name}: ${pass ? 'PASS' : 'FAIL'}`);279
if (!pass) await tab.shot(`${workDir}/${name}.png`).catch(() => {});282
if (!pass) {283
await tab.shot(`${workDir}/${name}.png`).catch(() => {});284
report.scenarios[name].guestVideoStreams = (await tab.evaluate(PEER_STATS).catch(() => ({}))).videoIn;285
}280
} catch (error) {286
} catch (error) {281
report.scenarios[name] = { pass: false, error: error.message };287
report.scenarios[name] = { pass: false, error: error.message };282
log(`scenario ${name}: ERROR ${error.message}`);288
log(`scenario ${name}: ERROR ${error.message}`);@@ -290,15 +296,22 @@ async function guestClick(tab, labels) {290
throw new Error(`guest found none of ${labels.join(', ')}`);296
throw new Error(`guest found none of ${labels.join(', ')}`);291
}297
}292
298
299
async function guestCamera(tab, on) {300
const sending = (await guestVideo(tab)).sentFrames;301
await delay(2_000);302
const isOn = (await guestVideo(tab)).sentFrames > sending;303
if (isOn !== on) await guestClick(tab, [on ? '=Turn camera on' : '=Turn camera off', '=Camera']);304
}305
293
async function runScenarios(report, tab, workDir) {306
async function runScenarios(report, tab, workDir) {294
report.scenarios = {};307
report.scenarios = {};295
await scenario('app-camera-on', report, tab, workDir, () => runTeams('--call', 'camera on'),308
await scenario('app-camera-on', report, tab, workDir, () => runTeams('--call', 'camera on'),296
(m) => m.app.cameraOn && m.appVideoOut >= MIN_FRAMES && m.guestVideoIn >= MIN_FRAMES);309
(m) => m.app.cameraOn && m.appVideoOut >= MIN_FRAMES && m.guestVideoIn >= MIN_FRAMES);297
await scenario('guest-camera-on', report, tab, workDir, () => guestClick(tab, ['=Turn camera on', 'Turn camera on', '=Camera']),310
await scenario('guest-camera-on', report, tab, workDir, () => guestCamera(tab, true),298
(m) => m.guestVideoOut >= MIN_FRAMES && m.appVideoIn >= MIN_FRAMES && m.appVideoShown >= MIN_FRAMES);311
(m) => m.guestVideoOut >= MIN_FRAMES && m.appVideoIn >= MIN_FRAMES && m.appVideoShown >= MIN_FRAMES);299
await scenario('app-camera-off', report, tab, workDir, () => runTeams('--call', 'camera off'),312
await scenario('app-camera-off', report, tab, workDir, () => runTeams('--call', 'camera off'),300
(m) => !m.app.cameraOn && m.appVideoOut < MIN_FRAMES && m.appVideoIn >= MIN_FRAMES);313
(m) => !m.app.cameraOn && m.appVideoOut < MIN_FRAMES && m.appVideoIn >= MIN_FRAMES);301
await scenario('guest-camera-off', report, tab, workDir, () => guestClick(tab, ['=Turn camera off', 'Turn camera off', '=Camera']),314
await scenario('guest-camera-off', report, tab, workDir, () => guestCamera(tab, false),302
(m) => m.appVideoIn < MIN_FRAMES);315
(m) => m.appVideoIn < MIN_FRAMES);303
await scenario('app-share', report, tab, workDir, async () => {316
await scenario('app-share', report, tab, workDir, async () => {304
runTeams('--call', 'share-sources');317
runTeams('--call', 'share-sources');@@ -63,7 +63,7 @@ export const PEER_STATS = `(async () => {
63
63
report.peers++;
64
64
(await peer.getStats()).forEach((entry) => {
65
65
if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived });
66
if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight });
66
if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight, packets: entry.packetsReceived, received: entry.framesReceived, keyFrames: entry.keyFramesDecoded, ssrc: entry.ssrc, codec: entry.codecId, pli: entry.pliCount, nack: entry.nackCount, lost: entry.packetsLost });
67
67
if (entry.type === 'outbound-rtp') report[entry.kind + 'Out'].push({ mid: entry.mid, packets: entry.packetsSent, frames: entry.framesEncoded, width: entry.frameWidth, height: entry.frameHeight });
68
68
});
69
69
}
@@ -63,7 +63,7 @@ export const PEER_STATS = `(async () => {63
report.peers++;63
report.peers++;64
(await peer.getStats()).forEach((entry) => {64
(await peer.getStats()).forEach((entry) => {65
if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived });65
if (entry.type === 'inbound-rtp' && entry.kind === 'audio') report.audioIn.push({ energy: entry.totalAudioEnergy, level: entry.audioLevel, packets: entry.packetsReceived });66
if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight });66
if (entry.type === 'inbound-rtp' && entry.kind === 'video') report.videoIn.push({ mid: entry.mid, decoded: entry.framesDecoded || 0, width: entry.frameWidth, height: entry.frameHeight, packets: entry.packetsReceived, received: entry.framesReceived, keyFrames: entry.keyFramesDecoded, ssrc: entry.ssrc, codec: entry.codecId, pli: entry.pliCount, nack: entry.nackCount, lost: entry.packetsLost });67
if (entry.type === 'outbound-rtp') report[entry.kind + 'Out'].push({ mid: entry.mid, packets: entry.packetsSent, frames: entry.framesEncoded, width: entry.frameWidth, height: entry.frameHeight });67
if (entry.type === 'outbound-rtp') report[entry.kind + 'Out'].push({ mid: entry.mid, packets: entry.packetsSent, frames: entry.framesEncoded, width: entry.frameWidth, height: entry.frameHeight });68
});68
});69
}69
}