Merge the development branch: share menu, codec order, segmentation

Brings in the Share button's menu (Share screen / Stream Studio) and the
removal of the separate Stream Studio button from the headers, the
codecs every TeamSpeak client decodes ahead of H.264, the portal fix
and person segmentation.

The phone header keeps this branch's voice-channel button and hides the
bell on the voice screen, and loses the Stream Studio button as the
development branch wants. The studio's test table takes the
segmentation rows and the Android camera row. MediaCodec follows the new
codec order with no code change (Codecs orders every hardware factory's
codecs); its description and docs/media.md now say so, including what
that means on a phone without a hardware VP8, VP9 or AV1 encoder.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
selikhovandClaude Opus 5.5 committed 2026-10-03 20:02:47 +03:00
commit 698e5f911e
35 files changed
+24436 -224

No files matched your search

+2 -1
View File
@@ -51,7 +51,8 @@ tsproto-packets = { path = "../proto/tsproto-packets" }
tsproto-types = { path = "../proto/tsproto-types" }
[dev-dependencies]
tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "test-util"] }
# `process`: the browser interop test drives Chromium through Node.js.
tokio = { version = "1", features = ["macros", "net", "process", "rt-multi-thread", "test-util"] }
[lints]
workspace = true
+41 -16
View File
@@ -142,29 +142,37 @@ pub fn peer_config(codecs: &Codecs, mut config: PeerConfig) -> PeerConfig {
config
}
/// Whether every official TeamSpeak client decodes `codec`: their WebRTC
/// stack has VP8, VP9 and AV1 decoders built in. H.264 needs an OpenH264
/// library the official client downloads at start-up and may not get; it
/// still answers H.264 then, and decodes nothing (libwebrtc's
/// `NullVideoDecoder`). HEVC needs a hardware decoder.
pub fn decoded_everywhere(codec: Codec) -> bool {
matches!(codec, Codec::Vp8 | Codec::Vp9 | Codec::Av1)
}
/// What a streamer with `primary` as its stream codec offers, in order:
/// `primary`, the codecs of hardware encoders, VP8 through libvpx (every
/// TeamSpeak client decodes it), and HEVC last (for peers that take nothing
/// else). Other software encoders are only ever the stream codec, so no
/// viewer's answer starts one of them on top of it.
/// `primary`; the codecs of hardware encoders and VP8 through libvpx that
/// every TeamSpeak client decodes ([`decoded_everywhere`]), so that a
/// viewer, which answers with the first codec it supports, never picks
/// H.264 while one of them is there; H.264 from hardware; HEVC last (for
/// peers that take nothing else). Other software encoders are only ever the
/// stream codec, so no viewer's answer starts one of them on top of it.
pub fn offer_codecs(codecs: &Codecs, primary: Codec) -> Vec<Codec> {
let mut offer = vec![primary];
let mut hevc = false;
for (codec, backend) in codecs.encoders() {
let cheap = codecs.is_hardware(backend)
|| (codec == Codec::Vp8 && backend == voelin_media::EncoderBackend::Libvpx);
if !cheap || offer.contains(&codec) {
continue;
}
if codec == Codec::H265 {
hevc = true;
} else {
if cheap && !offer.contains(&codec) {
offer.push(codec);
}
}
if hevc && primary != Codec::H265 {
offer.push(Codec::H265);
}
// Stable: the encoder preference orders codecs of the same rank.
offer[1..].sort_by_key(|&codec| match codec {
_ if decoded_everywhere(codec) => 0,
Codec::H265 => 2,
_ => 1,
});
offer
}
@@ -180,12 +188,14 @@ pub fn encoder_preference(settings: &crate::settings::Settings) -> voelin_media:
/// The stream codec: `configured` if we can encode it, else the first codec
/// of the encoder preference (hardware first when enabled; VP8 through
/// libvpx without hardware), never HEVC (offered last only). Put it first in
/// `PeerConfig::video_codecs` before [`peer_config`].
/// libvpx without hardware) that every TeamSpeak client decodes
/// ([`decoded_everywhere`]), else any but HEVC (offered last only). Put it
/// first in `PeerConfig::video_codecs` before [`peer_config`].
pub fn preferred_codec(codecs: &Codecs, configured: Option<Codec>) -> Option<Codec> {
let encodable = codecs.encoder_codecs();
configured
.filter(|c| encodable.contains(c))
.or_else(|| encodable.iter().copied().find(|&c| decoded_everywhere(c)))
.or_else(|| encodable.into_iter().find(|c| *c != Codec::H265))
}
@@ -2870,6 +2880,21 @@ mod tests {
if all.encoder_codecs().contains(&Codec::H264) && !offer.contains(&Codec::H264) {
assert_eq!(offer_codecs(&all, Codec::H264)[..2], [Codec::H264, Codec::Vp8]);
}
// Whatever this machine has: codecs every TeamSpeak client decodes
// come before H.264, HEVC last, and the automatic stream codec is
// one of the first.
let rank = |c: &Codec| match c {
_ if decoded_everywhere(*c) => 0,
Codec::H265 => 2,
_ => 1,
};
let ranks: Vec<_> = offer[1..].iter().map(rank).collect();
assert!(ranks.is_sorted(), "{offer:?}");
assert!(preferred_codec(&all, None).is_some_and(decoded_everywhere), "{all:?}");
assert_eq!(
preferred_codec(&all, Some(Codec::H264)).is_some(),
all.encoder_codecs().contains(&Codec::H264)
);
}
/// A sink whose viewers chose `codecs`; keeps every video frame with its
+2 -1
View File
@@ -964,7 +964,8 @@ pub enum CodecChoice {
pub static STREAM_CODEC: Key<CodecChoice> = Key::new(
"stream.codec",
Kind::Choice(&["auto", "vp8", "vp9", "h264", "av1"]),
"Video codec of our stream.",
"Video codec of our stream. Official TeamSpeak clients always decode VP8, VP9 and AV1; \
H.264 only when they could download OpenH264.",
CodecChoice::default,
);
+187
View File
@@ -0,0 +1,187 @@
//! The stream's real encoders against a browser's WebRTC stack: the test
//! pattern, encoded by each encoder this machine has as a share encodes the
//! screen, sent by our streamer peer offering just that codec, must decode
//! at its size in headless Chromium (libwebrtc, the stack the official
//! TeamSpeak 6 client is built on).
//!
//! Runs only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`). Codecs
//! the browser does not decode (H.264 in Playwright's Chromium, HEVC) are
//! skipped; `VOELIN_CHROMIUM=/usr/bin/chromium` tests a system Chromium that
//! decodes H.264.
#![cfg(feature = "media-desktop")]
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use tokio::time::timeout;
use voelin_core::media::voelin_media::capture::SourceId;
use voelin_core::media::voelin_media::{Codec, Codecs};
use voelin_core::media::{
EncodedSource, EncoderPreference, Streamer, StreamerConfig, decoded_everywhere, media_codec,
peer_config, preferred_codec, video_codec,
};
use voelin_core::stream::{FrameSource, PeerConfig, VideoCodec};
use voelin_stream::{Peer, PeerEvent};
#[path = "../../../tests/interop/browser.rs"]
mod browser;
use browser::{Browser, enabled};
const SIZE: (u32, u32) = (1280, 720);
/// The test pattern encoded with `codec` by the encoders `preference` picks
/// (from DMA-BUFs with `dmabuf`, as the ScreenCast portal hands over the
/// screen).
async fn test_pattern(preference: EncoderPreference, codec: Codec, dmabuf: bool) -> EncodedSource {
let codecs = Codecs::new().with_preference(preference.clone());
let config = StreamerConfig {
source: SourceId::Synthetic,
synthetic_size: SIZE,
synthetic_dmabuf: dmabuf,
fps: 30,
bitrate_kbps: 3000,
audio: false,
codec,
encoder: preference,
..StreamerConfig::default()
};
EncodedSource::new(Streamer::start(&codecs, config).await.unwrap())
}
/// Our streamer peer with `config`'s offer, answered by the browser and
/// connected; the codec the answer chose, `None` if it took no video.
async fn connect(browser: &mut Browser, config: &PeerConfig) -> Option<(Peer, VideoCodec)> {
let (mut peer, offer) = Peer::offer(config, "interop").await.unwrap();
let answer = browser.call(json!({ "op": "answer", "sdp": offer })).await;
peer.accept_answer(answer["sdp"].as_str().unwrap()).await.ok()?;
let mut chosen = None;
timeout(Duration::from_secs(15), async {
loop {
match peer.next_event().await {
Some(PeerEvent::VideoCodec(codec)) => chosen = Some(codec),
Some(PeerEvent::Connected) => return,
Some(PeerEvent::Closed) | None => panic!("closed before connecting"),
_ => {}
}
}
})
.await
.expect("no connection with the browser");
Some((peer, chosen?))
}
/// Three seconds of `source` to `peer`; the browser's `inbound-rtp` video
/// stats.
async fn send(browser: &mut Browser, peer: &mut Peer, source: &mut EncodedSource) -> Value {
source.request_keyframe();
let mut frames = Vec::new();
let end = Instant::now() + Duration::from_secs(3);
while Instant::now() < end {
source.poll_frames(Instant::now(), &mut frames);
for f in frames.drain(..) {
peer.write(f.kind, f.time, f.data);
}
while let Some(event) = peer.try_next_event() {
if matches!(event, PeerEvent::KeyframeRequest) {
source.request_keyframe();
}
}
tokio::time::sleep(Duration::from_millis(5)).await;
}
let stats = browser.call(json!({ "op": "stats" })).await;
peer.close();
stats["inbound"]["video"].clone()
}
/// Whether the browser decoded most of three seconds at the stream's size.
fn decoded(video: &Value) -> Result<(), String> {
let frames = video["framesDecoded"].as_u64().unwrap_or(0);
let size = (video["frameWidth"].as_u64(), video["frameHeight"].as_u64());
let expected = (Some(u64::from(SIZE.0)), Some(u64::from(SIZE.1)));
if frames < 60 || size != expected {
return Err(format!("{frames} frames decoded at {size:?}"));
}
Ok(())
}
/// Every encoder of this machine (hardware ones from memory and from
/// DMA-BUFs) decodes in the browser: most frames decoded, at the stream's
/// size.
#[tokio::test(flavor = "multi_thread")]
async fn real_encoders_decode_in_browser() {
if !enabled() {
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
return;
}
let mut browser = Browser::start().await;
let codecs = Codecs::new();
let udmabuf = std::path::Path::new("/dev/udmabuf").exists();
let mut failed = Vec::new();
for (codec, backend) in codecs.encoders() {
let gpu = codecs.is_hardware(backend) && backend.name().ends_with("_vaapi") && udmabuf;
for dmabuf in [false, true].into_iter().filter(|d| !d || gpu) {
let what =
format!("{codec} {}{}", backend.name(), if dmabuf { " (DMA-BUF)" } else { "" });
let config = PeerConfig {
video_codecs: vec![video_codec(codec)],
audio: false,
// Headless Chromium lists only the H.264 profiles of
// libwebrtc's software decoder (Baseline, Constrained
// Baseline, Main), not the Constrained High we offer; its
// FFmpeg decoder takes our High profile streams all the same.
h264_profile_level_id: 0x42e01f,
..PeerConfig::loopback()
};
let Some((mut peer, _)) = connect(&mut browser, &config).await else {
eprintln!("{what}: the browser does not decode it, skipped");
continue;
};
let preference =
EncoderPreference { hardware: true, backend: backend.name().parse().unwrap() };
let mut source = test_pattern(preference, codec, dmabuf).await;
let video = send(&mut browser, &mut peer, &mut source).await;
eprintln!("{what}: {video}");
if let Err(e) = decoded(&video) {
failed.push(format!("{what}: {e}"));
}
}
}
browser.quit().await;
assert!(failed.is_empty(), "not decoded in the browser:\n{}", failed.join("\n"));
}
/// The offer a share makes on this machine (`preferred_codec`,
/// `peer_config`): the browser, which answers like the official client with
/// the first codec of the offer it lists, picks one every TeamSpeak client
/// decodes, never H.264 ahead of them (the official client may list H.264
/// without being able to decode it), and decodes it.
#[tokio::test(flavor = "multi_thread")]
async fn share_offer_picks_a_codec_every_client_decodes() {
if !enabled() {
eprintln!("skipped: set VOELIN_INTEROP=1 (needs node, Playwright and Chromium)");
return;
}
let mut browser = Browser::start().await;
let codecs = Codecs::new();
let primary = preferred_codec(&codecs, None).expect("an encoder");
let config = PeerConfig {
video_codecs: vec![video_codec(primary)],
audio: false,
..PeerConfig::loopback()
};
let config = peer_config(&codecs, config);
eprintln!("offer: {:?}", config.video_codecs);
let (mut peer, chosen) = connect(&mut browser, &config).await.expect("video answered");
let chosen = media_codec(chosen);
assert!(
decoded_everywhere(chosen),
"the browser chose {chosen} from {:?}",
config.video_codecs
);
let mut source = test_pattern(codecs.preference().clone(), chosen, false).await;
let video = send(&mut browser, &mut peer, &mut source).await;
eprintln!("{chosen}: {video}");
browser.quit().await;
decoded(&video).unwrap();
}
+6 -1
View File
@@ -9,7 +9,7 @@ repository.workspace = true
publish.workspace = true
[features]
default = ["vpx", "openh264", "openh264-download", "ffmpeg", "x11", "pipewire", "wlroots"]
default = ["vpx", "openh264", "openh264-download", "ffmpeg", "x11", "pipewire", "wlroots", "segment"]
# VP8 and VP9 through the system libvpx (pkg-config `vpx`).
vpx = ["dep:libvpx-native-sys"]
# H.264 through Cisco's prebuilt OpenH264 library, loaded at runtime. The
@@ -31,6 +31,10 @@ pipewire = ["dep:ashpd", "dep:pipewire", "dep:memmap2", "dep:rustix"]
# Screen capture on wlroots compositors (Sway, Hyprland, river, ...) without
# the portal: ext-image-copy-capture-v1 or wlr-screencopy-unstable-v1 (Linux).
wlroots = ["dep:wayland-client", "dep:wayland-protocols", "dep:wayland-protocols-wlr", "dep:memmap2", "dep:rustix"]
# The studio's background replacement finds the person with a segmentation
# model (PP-HumanSeg, ONNX, bundled in `models/`) run on the CPU by tract.
# Without it the background is cut around a centred oval.
segment = ["dep:tract-onnx"]
# Conversion between `Codec` and `str0m::format::Codec`.
str0m = ["dep:str0m"]
# The studio's WHIP output: a WebRTC session (str0m) set up over HTTP. Needs
@@ -54,6 +58,7 @@ image = { version = "0.25.10", default-features = false, features = ["jpeg", "pn
sha2 = { version = "0.10.9", optional = true }
str0m = { version = "0.23.1", default-features = false, optional = true }
thiserror = "2.0.21"
tract-onnx = { version = "0.23.8", optional = true }
tokio = { version = "1", features = ["sync"] }
tracing = "0.1.44"
yuv = "0.8.19"
@@ -0,0 +1,203 @@
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+13
View File
@@ -0,0 +1,13 @@
# Models
`pphumanseg-2023mar.onnx`: PP-HumanSeg, PaddleSeg's portrait segmentation
model, as OpenCV Zoo ships it
(`models/human_segmentation_pphumanseg/human_segmentation_pphumanseg_2023mar.onnx`
in https://github.com/opencv/opencv_zoo, ported from PaddleHub). Copyright (c)
2021 PaddlePaddle Authors, under the Apache License 2.0
(`LICENSE-PP-HumanSeg`). Unchanged; SHA-256
`552d8a984054e59b5d773d24b9b12022b22046ceb2bbc4c9aaeaceb36a9ddf24`.
Input `x`: 1x3x192x192 RGB, `(value / 255 - 0.5) / 0.5`. Output: 1x2x192x192
probabilities, channel 1 the person. The studio's background replacement
(`src/studio/segment.rs`, feature `segment`) runs it with tract.
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -9,7 +9,9 @@
//! disable it (see docs/media.md).
//!
//! TeamSpeak clients only decode H.264 Constrained High; OpenH264 encodes
//! without B-frames, so its High profile output qualifies.
//! without B-frames, so its High profile output qualifies. The official
//! client decodes H.264 only once it downloaded OpenH264 itself, so streams
//! prefer codecs it always decodes (`voelin_core::media::decoded_everywhere`).
use std::path::{Path, PathBuf};
+3 -2
View File
@@ -178,8 +178,9 @@ pub fn check_decoder(codec: Codec) -> Result<()> {
}
}
/// Encoders of this device: hardware ones first (H.264, VP9, VP8), then
/// Google's software VP8 and H.264. Software VP9 and AV1 are too slow.
/// Encoders of this device: the hardware ones (H.264, VP9, VP8, AV1) and
/// Google's software VP8 and H.264; software VP9 and AV1 are too slow.
/// `Codecs` orders them by codec, as every hardware factory.
pub fn probe() -> Option<MediaCodecFactory> {
let encoders = &available().encoders;
let name = |codec| encoders.iter().find(|(c, _)| *c == codec).map(|(_, n)| n.as_str());
+9 -7
View File
@@ -406,10 +406,12 @@ fn unavailable(codec: Codec, reason: impl Into<String>) -> Error {
Error::CodecUnavailable { codec, reason: reason.into() }
}
/// Order of codecs among hardware encoders: H.264 (every viewer decodes
/// it), AV1, VP9, VP8, and HEVC last (only for peers that take nothing
/// else).
const HARDWARE_ORDER: [Codec; 5] = [Codec::H264, Codec::Av1, Codec::Vp9, Codec::Vp8, Codec::H265];
/// Order of codecs among hardware encoders: the ones every TeamSpeak
/// client decodes first (AV1, VP9, VP8: the official client's WebRTC stack
/// has their decoders built in), then H.264 (the official client decodes it
/// only with an OpenH264 library it downloads at start-up and may not get),
/// and HEVC last (only for peers that take nothing else).
const HARDWARE_ORDER: [Codec; 5] = [Codec::Av1, Codec::Vp9, Codec::Vp8, Codec::H264, Codec::H265];
/// An encoder backend in the base order (before the preference applies).
struct Candidate {
@@ -868,8 +870,8 @@ mod tests {
codecs.encoders_for(&preference).iter().map(|(_, b)| b.name()).collect()
};
let auto = names(EncoderPreference::default());
// Hardware in codec order (HEVC last), then software.
assert_eq!(auto[..3], ["h264_gpu", "vp8_gpu", "hevc_gpu"]);
// Hardware in codec order (H.264 after VP8, HEVC last), then software.
assert_eq!(auto[..3], ["vp8_gpu", "h264_gpu", "hevc_gpu"]);
let position = |list: &[&str], name| list.iter().position(|n| *n == name).unwrap();
assert!(position(&auto, "x264") < position(&auto, "av1_sw"));
#[cfg(feature = "vpx")]
@@ -886,7 +888,7 @@ mod tests {
assert!(!named[1..].iter().any(|n| n.ends_with("_gpu")));
// The codecs follow the preference.
codecs.set_preference(EncoderPreference::default());
assert_eq!(codecs.encoder_codecs()[..3], [Codec::H264, Codec::Vp8, Codec::H265]);
assert_eq!(codecs.encoder_codecs()[..3], [Codec::Vp8, Codec::H264, Codec::H265]);
// The report ranks what the preference uses.
let report = codecs.report();
let openh264 = report.encoders.iter().find(|e| e.name == "openh264").unwrap();
+2
View File
@@ -76,6 +76,8 @@ pub enum Error {
Cancelled,
#[error("download failed: {0}")]
Download(String),
#[error("segmentation: {0}")]
Segmentation(String),
#[error("I/O: {0}")]
Io(#[from] std::io::Error),
}
+175 -15
View File
@@ -20,13 +20,12 @@
//! a placeholder — it exercises the mask path and the tests, and gives a
//! usable "blur everything but the middle" — but it does not find a person.
//!
//! A real segmenter is a small neural network (the MediaPipe-style selfie
//! segmentation models are what this is sized for: one 256x144 or 256x256
//! input, one mask output). That is not in this build: nothing here loads an
//! ONNX model yet, so [`Background::Blur`](crate::studio::scene::Background)
//! blurs around an oval rather than around a person. The seam is
//! [`Segmenter`]; a model-backed implementation drops in behind it without
//! touching the frame path.
//! [`HumanSeg`] (feature `segment`, on by default) finds the person:
//! PP-HumanSeg, PaddleSeg's portrait segmentation network (bundled in
//! `models/`, Apache-2.0), run on the CPU by tract. It is the default
//! segmenter when built in; if its model cannot be loaded, [`Ellipse`] stands
//! in. Other models drop in behind [`Segmenter`] without touching the frame
//! path.
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
@@ -96,6 +95,137 @@ pub trait Segmenter: Send {
fn mask(&mut self, frame: &VideoFrame, mask: &mut Mask) -> Result<()>;
}
/// PP-HumanSeg, PaddleSeg's portrait segmentation model, as OpenCV Zoo ships
/// it (`models/pphumanseg-2023mar.onnx`, Apache-2.0, see `models/README.md`),
/// run on the CPU by tract: the frame squeezed to 192x192 RGB in, the
/// probability of a person per pixel out, as a 192x192 mask the frame path
/// stretches back over the frame. The model is loaded once per process, on
/// the segmentation thread the first time it runs; if that fails,
/// [`Ellipse`] stands in.
#[cfg(feature = "segment")]
pub struct HumanSeg {
plan: Option<std::sync::Arc<tract_onnx::prelude::TypedSimplePlan>>,
/// The input tensor, filled in place for each mask.
input: tract_onnx::prelude::Tensor,
fallback: Option<Ellipse>,
}
#[cfg(feature = "segment")]
mod model {
use std::sync::{Arc, OnceLock};
use tract_onnx::prelude::*;
/// Width and height of the model's input and output.
pub const SIZE: usize = 192;
static ONNX: &[u8] = include_bytes!("../../models/pphumanseg-2023mar.onnx");
/// The optimised model, made once.
pub fn plan() -> Result<Arc<TypedSimplePlan>, String> {
static PLAN: OnceLock<Result<Arc<TypedSimplePlan>, String>> = OnceLock::new();
PLAN.get_or_init(|| {
tract_onnx::onnx()
.model_for_read(&mut &ONNX[..])
.and_then(|m| m.with_input_fact(0, f32::fact([1, 3, SIZE, SIZE]).into()))
.and_then(|m| m.into_optimized())
.and_then(|m| m.into_runnable())
.map_err(|e| format!("{e:#}"))
})
.clone()
}
}
#[cfg(feature = "segment")]
impl HumanSeg {
pub fn new() -> Self {
let size = model::SIZE;
Self {
plan: None,
input: tract_onnx::prelude::Tensor::zero::<f32>(&[1, 3, size, size])
.expect("a small tensor"),
fallback: None,
}
}
/// Fill the input from `frame` (packed RGBA): nearest sample per input
/// pixel, planar RGB, `value / 127.5 - 1`.
fn fill_input(&mut self, frame: &VideoFrame) -> Result<()> {
let FrameData::Rgba(plane) = &frame.data else {
return Err(Error::InvalidFrame("segmentation needs RGBA frames".into()));
};
let size = model::SIZE;
let (width, height) = (frame.width.max(1) as usize, frame.height.max(1) as usize);
let mut input =
self.input.try_as_plain_ram_mut().map_err(|e| Error::Segmentation(e.to_string()))?;
let input = input.as_slice_mut::<f32>().map_err(|e| Error::Segmentation(e.to_string()))?;
let (red, rest) = input.split_at_mut(size * size);
let (green, blue) = rest.split_at_mut(size * size);
for y in 0..size {
let row = plane.row(y * height / size, width * 4);
for x in 0..size {
let px = &row[x * width / size * 4..][..3];
let i = y * size + x;
red[i] = f32::from(px[0]) / 127.5 - 1.0;
green[i] = f32::from(px[1]) / 127.5 - 1.0;
blue[i] = f32::from(px[2]) / 127.5 - 1.0;
}
}
Ok(())
}
}
#[cfg(feature = "segment")]
impl Default for HumanSeg {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "segment")]
impl Segmenter for HumanSeg {
fn name(&self) -> &'static str {
"pp-humanseg"
}
fn mask(&mut self, frame: &VideoFrame, mask: &mut Mask) -> Result<()> {
use tract_onnx::prelude::{IntoTValue, tvec};
if let Some(fallback) = &mut self.fallback {
return fallback.mask(frame, mask);
}
if self.plan.is_none() {
match model::plan() {
Ok(plan) => self.plan = Some(plan),
Err(e) => {
warn!("the segmentation model does not load, using an oval: {e}");
return self.fallback.insert(Ellipse::person()).mask(frame, mask);
}
}
}
self.fill_input(frame)?;
let plan = self.plan.as_ref().expect("loaded above");
// ponytail: tract takes the input by value; a 442 KiB copy per mask
// (a few a second) next to its own intermediates.
let outputs = plan
.run(tvec![self.input.clone().into_tvalue()])
.map_err(|e| Error::Segmentation(format!("{e:#}")))?;
let output =
outputs[0].try_as_plain_ram().map_err(|e| Error::Segmentation(e.to_string()))?;
let person = output.as_slice::<f32>().map_err(|e| Error::Segmentation(e.to_string()))?;
let size = model::SIZE;
// Channel 1 of the 1x2xHxW probabilities is the person.
let person = person
.get(size * size..2 * size * size)
.ok_or_else(|| Error::Segmentation(format!("an output of {} values", person.len())))?;
mask.resize(size as u32, size as u32);
for (m, p) in mask.data.iter_mut().zip(person) {
*m = (p.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
Ok(())
}
}
/// The segmenter that is always available: a centred oval covering most of
/// the frame. See the [module docs](self) for what it is and is not.
#[derive(Clone, Copy, Debug, Default)]
@@ -340,8 +470,12 @@ impl BackgroundFilter {
}
}
/// A filter with the built-in [`Ellipse`] segmenter.
/// A filter with the default segmenter: [`HumanSeg`] when built in, else
/// [`Ellipse`].
pub fn with_default_segmenter(mode: Background) -> Self {
#[cfg(feature = "segment")]
return Self::new(mode, Box::new(HumanSeg::new()));
#[cfg(not(feature = "segment"))]
Self::new(mode, Box::new(Ellipse::person()))
}
@@ -598,6 +732,36 @@ fn flat_rgba(width: u32, height: u32, rgba: [u8; 4]) -> VideoFrame {
mod tests {
use super::*;
/// A filter with the oval: these tests check the frame path, which
/// needs a mask that is known in advance.
fn oval_filter(mode: Background) -> BackgroundFilter {
BackgroundFilter::new(mode, Box::new(Ellipse::person()))
}
/// The bundled model loads and runs: a 192x192 mask of probabilities,
/// next to nothing in an empty, evenly lit room, and fast enough for a
/// few masks a second on one core.
#[cfg(feature = "segment")]
#[test]
fn the_model_finds_nobody_in_an_empty_room() {
let mut segmenter = HumanSeg::new();
let frame = flat_rgba(256, 144, [128, 120, 110, 255]);
let mut mask = Mask::default();
segmenter.mask(&frame, &mut mask).unwrap();
assert!(segmenter.fallback.is_none(), "the model did not load");
assert_eq!((mask.width, mask.height), (192, 192));
let mean = mask.data.iter().map(|&v| u64::from(v)).sum::<u64>() / mask.data.len() as u64;
assert!(mean < 64, "a person in an empty room: mean {mean}");
let start = Instant::now();
for _ in 0..5 {
segmenter.mask(&frame, &mut mask).unwrap();
}
let each = start.elapsed() / 5;
eprintln!("one mask in {each:?}");
// Debug builds run tract unoptimised; release is several times faster.
assert!(each < Duration::from_secs(2), "{each:?} per mask");
}
fn pixel(frame: &VideoFrame, x: u32, y: u32) -> [u8; 4] {
let FrameData::Rgba(p) = &frame.data else { panic!("not RGBA") };
p.row(y as usize, frame.width as usize * 4)[x as usize * 4..][..4].try_into().unwrap()
@@ -657,9 +821,7 @@ mod tests {
#[test]
fn a_colour_background_replaces_everything_but_the_subject() {
let mut filter = BackgroundFilter::with_default_segmenter(Background::Colour {
colour: Colour::rgb(200, 0, 0),
});
let mut filter = oval_filter(Background::Colour { colour: Colour::rgb(200, 0, 0) });
assert_eq!(filter.segmenter(), "ellipse");
let mut frame = flat_rgba(64, 64, [0, 255, 0, 255]);
// Wait for the first mask.
@@ -699,8 +861,7 @@ mod tests {
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("behind.png");
image::RgbaImage::from_pixel(16, 16, image::Rgba([0, 0, 220, 255])).save(&path).unwrap();
let mut filter =
BackgroundFilter::with_default_segmenter(Background::Image { path: path.clone() });
let mut filter = oval_filter(Background::Image { path: path.clone() });
let started = Instant::now();
let mut frame = flat_rgba(64, 64, [0, 255, 0, 255]);
while pixel(&frame, 0, 0) != [0, 0, 220, 255] {
@@ -715,8 +876,7 @@ mod tests {
#[test]
fn a_blurred_background_keeps_the_subject_sharp() {
let mut filter =
BackgroundFilter::with_default_segmenter(Background::Blur { strength: 0.1 });
let mut filter = oval_filter(Background::Blur { strength: 0.1 });
filter.set_mask_fps(60);
// A checkerboard, so blurring is visible.
let mut frame = flat_rgba(64, 64, [0, 0, 0, 255]);
+7 -4
View File
@@ -2,8 +2,10 @@
//! (MIT-SHM and GetImage), checks pixels, and sends a window capture through
//! VP8 and back.
//!
//! Needs `DISPLAY` (e.g. `Xvfb :101 -screen 0 1280x720x24 & DISPLAY=:101
//! cargo test -p voelin-media --test x11_capture`); skipped without it.
//! Needs a test X server in `VOELIN_X11_TEST_DISPLAY`, never the desktop's
//! `DISPLAY` (it maps windows and moves the pointer): e.g. `xvfb-run -a bash
//! -c 'VOELIN_X11_TEST_DISPLAY=$DISPLAY cargo test -p voelin-media --test
//! x11_capture'`, as CI does; skipped without it.
#![cfg(all(target_os = "linux", feature = "x11", feature = "vpx"))]
use std::time::Duration;
@@ -150,8 +152,9 @@ async fn check_monitor(capture: &mut X11Capture, scene: &Scene) {
#[tokio::test(flavor = "multi_thread")]
async fn x11_capture_end_to_end() {
let Some(display) = std::env::var("DISPLAY").ok().filter(|d| !d.is_empty()) else {
eprintln!("skipped: DISPLAY is not set");
let Some(display) = std::env::var("VOELIN_X11_TEST_DISPLAY").ok().filter(|d| !d.is_empty())
else {
eprintln!("skipped: VOELIN_X11_TEST_DISPLAY is not set");
return;
};
let scene = Scene::create(&display);
+12 -4
View File
@@ -282,7 +282,7 @@ impl Peer {
) -> Result<(Self, String), PeerError> {
let start = options.start_bitrate.unwrap_or(DEFAULT_START_BITRATE).max(1);
let bwe = config.bandwidth_estimation.then_some(start);
let (mut rtc, srtp_profile) = build_rtc(config, &config.video_codecs, bwe);
let (mut rtc, srtp_profile) = build_rtc(config, &config.video_codecs, true, bwe);
if bwe.is_some() {
let desired = options.desired_bitrate.unwrap_or(start);
rtc.bwe().set_desired_bitrate(Bitrate::bps(desired));
@@ -333,7 +333,7 @@ impl Peer {
}
}
let offer = SdpOffer::from_sdp_string(offer).map_err(|e| PeerError::Sdp(e.to_string()))?;
let (mut rtc, srtp_profile) = build_rtc(config, &codecs, None);
let (mut rtc, srtp_profile) = build_rtc(config, &codecs, false, None);
let net = Net::bind(config, &mut rtc).await?;
let answer = rtc.sdp_api().accept_offer(offer)?;
let peer = Self::spawn(rtc, net, config, None, Vec::new(), srtp_profile);
@@ -462,10 +462,15 @@ fn simulcast_offer(layers: &[LayerSpec]) -> Option<Simulcast> {
}
/// An RTC with Opus and `video` codecs, in this order of preference, our
/// DTLS, and bandwidth estimation starting at `bwe` bit/s if given.
/// DTLS, and bandwidth estimation starting at `bwe` bit/s if given. An
/// offer lists H.264 only as our encoders produce it (`profile-level-id`
/// [`PeerConfig::h264_profile_level_id`], packetization mode 1): with
/// str0m's other variants offered too, a viewer may answer a profile we
/// never send. An answer takes every variant the offer has.
fn build_rtc(
config: &PeerConfig,
video: &[VideoCodec],
offer: bool,
bwe: Option<u64>,
) -> (Rtc, NegotiatedProfile) {
let mut rtc_config =
@@ -475,7 +480,7 @@ fn build_rtc(
VideoCodec::Vp8 => rtc_config.enable_vp8(true),
VideoCodec::Vp9 => rtc_config.enable_vp9(true),
VideoCodec::H264 => {
let mut c = rtc_config.enable_h264(true);
let mut c = if offer { rtc_config } else { rtc_config.enable_h264(true) };
c.codec_config().add_h264(
112.into(),
Some(113.into()),
@@ -935,6 +940,9 @@ mod tests {
};
let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
assert!(offer.contains("profile-level-id=640c1f"), "{offer}");
// Only the profile we encode: a viewer must not answer another.
let h264 = offer.lines().filter(|l| l.contains(" H264/90000")).count();
assert_eq!(h264, 1, "{offer}");
let (_peer, answer) = Peer::answer(&PeerConfig::loopback(), &offer).await.unwrap();
assert_eq!(offered_video_codecs(&answer)[0], VideoCodec::H264, "{answer}");
let vp8_only =
+10 -69
View File
@@ -4,82 +4,23 @@
//!
//! Runs only with `VOELIN_INTEROP=1` (see `tests/interop/README.md`).
use std::path::PathBuf;
use std::process::Stdio;
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use serde_json::json;
use tokio::time::timeout;
use voelin_stream::{
Codec, FrameSource, MediaKind, Peer, PeerConfig, PeerEvent, Signal, SrtpProfile,
SyntheticSource,
};
fn enabled() -> bool {
std::env::var("VOELIN_INTEROP").is_ok_and(|v| v == "1")
}
#[path = "../../../tests/interop/browser.rs"]
mod browser;
use browser::{Browser, enabled};
/// The Node.js side (headless Chromium).
struct Browser {
_child: Child,
stdin: ChildStdin,
stdout: Lines<BufReader<ChildStdout>>,
}
impl Browser {
async fn start() -> Self {
let script = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("../../tests/interop/browser-peer.cjs")
.canonicalize()
.expect("tests/interop/browser-peer.cjs");
let node = std::env::var("VOELIN_NODE").unwrap_or_else(|_| "node".into());
let mut command = Command::new(node);
command
.arg(script)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
// Playwright is usually installed globally.
if std::env::var_os("NODE_PATH").is_none()
&& let Ok(out) = std::process::Command::new("npm").args(["root", "-g"]).output()
{
command.env("NODE_PATH", String::from_utf8_lossy(&out.stdout).trim());
}
let mut child = command.spawn().expect("cannot start node (set VOELIN_NODE)");
let stdin = child.stdin.take().unwrap();
let stdout = BufReader::new(child.stdout.take().unwrap()).lines();
let mut browser = Self { _child: child, stdin, stdout };
let ready = browser.read().await;
eprintln!("browser: {}", ready["userAgent"]);
browser
}
async fn read(&mut self) -> Value {
let line = timeout(Duration::from_secs(60), self.stdout.next_line())
.await
.expect("browser did not answer")
.unwrap()
.expect("browser exited");
let value: Value = serde_json::from_str(&line).unwrap();
if let Some(error) = value.get("error") {
panic!("browser: {error}");
}
value
}
async fn call(&mut self, command: Value) -> Value {
let mut line = command.to_string();
line.push('\n');
self.stdin.write_all(line.as_bytes()).await.unwrap();
self.read().await
}
async fn quit(mut self) {
let _ = self.call(json!({ "op": "quit" })).await;
}
/// The `srtpCipher` of `getStats()` for AES_CM_128_HMAC_SHA1_80, as Chromium
/// 141 and 152 name it.
fn aes_cm_128_sha1_80(cipher: &serde_json::Value) -> bool {
["AES_CM_128_HMAC_SHA1_80", "SRTP_AES128_CM_HMAC_SHA1_80"].iter().any(|name| cipher == name)
}
async fn wait_connected(peer: &mut Peer) {
@@ -139,7 +80,7 @@ async fn rust_streams_to_browser() {
eprintln!("browser stats: {stats:#}\nkeyframe requests from the browser: {keyframe_requests}");
eprintln!("bandwidth estimates (bit/s): {estimates:?}");
assert_eq!(stats["connectionState"], "connected");
assert_eq!(stats["transport"]["srtpCipher"], "AES_CM_128_HMAC_SHA1_80", "{stats:#}");
assert!(aes_cm_128_sha1_80(&stats["transport"]["srtpCipher"]), "{stats:#}");
assert_eq!(peer.srtp_profile(), Some(SrtpProfile::Aes128CmSha1_80));
assert!(!estimates.is_empty(), "no bandwidth estimate from the browser's feedback");
let video = &stats["inbound"]["video"];
@@ -329,6 +270,6 @@ async fn browser_streams_to_rust() {
}
assert!(tested.contains(&"VP8") && tested.contains(&"VP9"), "tested {tested:?}");
let stats = browser.call(json!({ "op": "stats" })).await;
assert_eq!(stats["transport"]["srtpCipher"], "AES_CM_128_HMAC_SHA1_80", "{stats:#}");
assert!(aes_cm_128_sha1_80(&stats["transport"]["srtpCipher"]), "{stats:#}");
browser.quit().await;
}
+2 -1
View File
@@ -420,7 +420,8 @@ impl App {
let test_pattern = cfg!(debug_assertions)
|| self.demo
|| std::env::var("VOELIN_TEST_PATTERN").is_ok_and(|v| v == "1");
let sources = match self.video.sources(test_pattern) {
let restorable = self.settings.portal_restore_token.is_some();
let sources = match self.video.sources(test_pattern, restorable) {
Ok(sources) => {
if self.share.is_none() {
self.share_error.clear();
+77 -26
View File
@@ -10,7 +10,7 @@ use std::sync::Arc;
use slint::{Image, Rgba8Pixel, SharedPixelBuffer};
use tokio::runtime::Handle;
use tracing::warn;
use voelin_core::media::voelin_media::capture::SourceId;
use voelin_core::media::voelin_media::capture::{CaptureSource, SourceId};
use voelin_core::media::voelin_media::{Codec, Codecs, EncoderReport, VideoFrame, convert};
use voelin_core::media::{
self, AudioSourceSpec, EncoderPreference, Latest, LocalPreview, Streamer, StreamerConfig,
@@ -63,7 +63,7 @@ pub(crate) struct Video {
encoder: EncoderPreference,
codec: Option<Codec>,
/// Sources of the share dialog, by index.
sources: Vec<(SourceId, String)>,
sources: Vec<ShareEntry>,
}
impl Video {
@@ -199,8 +199,14 @@ impl Video {
}
/// Screens and windows to share, as (name, detail); the test pattern too
/// when asked for.
pub fn sources(&mut self, test_pattern: bool) -> Result<Vec<(String, String)>, String> {
/// when asked for. With `restorable` (a portal restore token from an
/// earlier share) the portal comes twice: its dialog, which always asks,
/// and the last choice again without the dialog.
pub fn sources(
&mut self,
test_pattern: bool,
restorable: bool,
) -> Result<Vec<(String, String)>, String> {
let mut error = None;
let mut sources = match media::screen_sources() {
Ok(list) => list,
@@ -215,26 +221,9 @@ impl Video {
if sources.is_empty() {
return Err(error.unwrap_or_else(|| "Nothing to share was found.".into()));
}
self.sources = sources.iter().map(|s| (s.id.clone(), s.name.clone())).collect();
Ok(sources
.iter()
.map(|s| {
let name = match s.id {
SourceId::Portal => "Choose via system dialog".to_owned(),
_ => s.name.clone(),
};
let detail = match (&s.id, s.primary) {
(SourceId::Monitor(_), true) => {
format!("{} · primary", size_text(s.width, s.height))
}
(SourceId::Window(_), _) => {
format!("window {}", size_text(s.width, s.height)).trim().to_owned()
}
_ => size_text(s.width, s.height),
};
(name, detail)
})
.collect())
let (rows, entries) = share_rows(&sources, restorable);
self.sources = entries;
Ok(rows)
}
/// Start capturing source `index` of [`Video::sources`]; `done` runs on
@@ -246,7 +235,7 @@ impl Video {
options: CaptureRequest,
done: impl FnOnce(Result<Capture, String>) + Send + 'static,
) {
let Some((source, name)) = self.sources.get(index).cloned() else {
let Some((source, name, restore)) = self.sources.get(index).cloned() else {
done(Err("Pick something to share.".into()));
return;
};
@@ -264,7 +253,8 @@ impl Video {
encoder: self.encoder.clone(),
audio: options.audio,
audio_sources: options.audio_sources,
restore_token: options.restore_token,
// The portal skips its dialog with a token: only when asked to.
restore_token: options.restore_token.filter(|_| restore),
..StreamerConfig::default()
};
runtime.spawn(async move {
@@ -368,6 +358,40 @@ fn deliver(
}
}
/// What a row of the share dialog starts: the source, its name, and whether
/// to restore the portal's last choice instead of asking.
type ShareEntry = (SourceId, String, bool);
/// The share dialog's rows (name, detail) for `sources`, and what each row
/// starts (restoring only in the extra portal row with `restorable`).
fn share_rows(
sources: &[CaptureSource],
restorable: bool,
) -> (Vec<(String, String)>, Vec<ShareEntry>) {
let mut rows = Vec::with_capacity(sources.len() + 1);
let mut entries = Vec::with_capacity(sources.len() + 1);
for s in sources {
let name = match s.id {
SourceId::Portal => "Choose via system dialog".to_owned(),
_ => s.name.clone(),
};
let detail = match (&s.id, s.primary) {
(SourceId::Monitor(_), true) => format!("{} · primary", size_text(s.width, s.height)),
(SourceId::Window(_), _) => {
format!("window {}", size_text(s.width, s.height)).trim().to_owned()
}
_ => size_text(s.width, s.height),
};
rows.push((name, detail));
entries.push((s.id.clone(), s.name.clone(), false));
if s.id == SourceId::Portal && restorable {
rows.push(("Same as last time".to_owned(), "without the dialog".to_owned()));
entries.push((s.id.clone(), s.name.clone(), true));
}
}
(rows, entries)
}
/// Share settings from the dialog.
pub(crate) struct CaptureRequest {
pub fps: u32,
@@ -473,3 +497,30 @@ impl Decoder {
stats.error.filter(|_| stats.decoded == 0)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// "Choose via system dialog" never passes the restore token, so the
/// portal always asks; with a token the last choice gets its own row.
#[test]
fn the_portal_dialog_always_asks() {
let portal = CaptureSource {
id: SourceId::Portal,
name: "Screen".into(),
width: 0,
height: 0,
primary: false,
};
let (rows, entries) = share_rows(std::slice::from_ref(&portal), false);
assert_eq!(rows.len(), 1);
assert_eq!(rows[0].0, "Choose via system dialog");
assert!(!entries[0].2);
let (rows, entries) = share_rows(&[portal], true);
let names: Vec<_> = rows.iter().map(|(name, _)| name.as_str()).collect();
assert_eq!(names, ["Choose via system dialog", "Same as last time"]);
let restore: Vec<_> = entries.iter().map(|e| e.2).collect();
assert_eq!(restore, [false, true]);
}
}
+11 -5
View File
@@ -12,6 +12,8 @@ import { StreamsPanel } from "streams.slint";
import { PinsDrawer, TopicsDrawer } from "drawers.slint";
import { MembersPanel } from "members.slint";
import { VoiceCard, VoiceButtons } from "../shells/common.slint";
import { StudioBridge } from "../studio-bridge.slint";
import { ShareMenu } from "../share-menu.slint";
// Servers as a horizontal strip, the current server, its channels.
export component MobileServers inherits VerticalLayout {
@@ -169,11 +171,15 @@ export component YouPage inherits ScrollView {
enabled: Bridge.voice-connected;
clicked => { Bridge.set-output-muted(!Bridge.output-muted); }
}
if Bridge.streams-available && Bridge.can-share: ActionButton {
icon: Icons.radio;
text: Bridge.share-state == "live" ? @tr("Live") : @tr("Go Live");
checked: Bridge.share-state == "live";
clicked => { Nav.open-share(); }
// A screen or the Stream Studio (ShareMenu).
if Bridge.streams-available && Bridge.can-share: VerticalLayout {
live := ActionButton {
icon: Icons.radio;
text: Bridge.share-state == "live" || StudioBridge.status.live ? @tr("Live") : @tr("Go Live");
checked: Bridge.share-state == "live" || StudioBridge.status.live;
clicked => { share-menu.open(0, - live.height - share-menu.menu-height - 4px); }
}
share-menu := ShareMenu { }
}
ActionButton {
icon: Icons.phone-off;
+42
View File
@@ -0,0 +1,42 @@
// What a Share button opens: a quick share of a screen or a window (the
// share dialog) or the Stream Studio. While a share runs it opens the share
// dialog right away, to manage it.
import { Theme } from "theme.slint";
import { Icons } from "icons.slint";
import { PopupMenu } from "components/index.slint";
import { Bridge } from "bridge.slint";
import { StudioBridge } from "studio-bridge.slint";
import { Nav } from "nav.slint";
export component ShareMenu inherits Rectangle {
// The menu's height, to open it above a button.
out property <length> menu-height: 2 * Theme.control-height + 2 * Theme.space-2 + 2px;
width: 0;
height: 0;
// Open at (x, y), relative to this element.
public function open(x: length, y: length) {
if Bridge.share-state == "live" || Bridge.share-state == "starting" {
Nav.open-share();
} else {
menu.show(x, y);
}
}
menu := PopupMenu {
menu-width: 220px;
entries: [
// The studio's stream takes the place of a simple share.
{ text: @tr("Share screen"), icon: Icons.monitor-up, enabled: !StudioBridge.status.live },
{ text: @tr("Stream Studio"), icon: Icons.radio, enabled: true },
];
activated(i) => {
if i == 0 {
Nav.open-share();
} else {
Nav.open-studio();
}
}
}
}
+12 -6
View File
@@ -4,6 +4,8 @@ import { Theme } from "../theme.slint";
import { Icons } from "../icons.slint";
import { Bridge } from "../bridge.slint";
import { Nav, SettingsSection } from "../nav.slint";
import { StudioBridge } from "../studio-bridge.slint";
import { ShareMenu } from "../share-menu.slint";
import { Icon, IconButton, Avatar, Status } from "../components/index.slint";
// A rounded panel of the frame (sidebar, main area, right panel).
@@ -143,12 +145,16 @@ export component VoiceButtons inherits HorizontalLayout {
enabled: Bridge.voice-connected;
clicked => { Bridge.set-output-muted(!Bridge.output-muted); }
}
if Bridge.streams-available && Bridge.can-share: IconButton {
icon: Icons.monitor-up;
label: Bridge.share-state == "live" ? @tr("Sharing") : @tr("Share screen");
checked: Bridge.share-state == "live";
size: root.size;
clicked => { Nav.open-share(); }
// A screen or window, or the Stream Studio (ShareMenu).
if Bridge.streams-available && Bridge.can-share: VerticalLayout {
IconButton {
icon: Icons.monitor-up;
label: Bridge.share-state == "live" ? @tr("Sharing") : StudioBridge.status.live ? @tr("Live in the Stream Studio") : @tr("Share or go live");
checked: Bridge.share-state == "live" || StudioBridge.status.live;
size: root.size;
clicked => { share-menu.open(0, - root.size - share-menu.menu-height - 4px); }
}
share-menu := ShareMenu { }
}
IconButton {
icon: Icons.settings;
-7
View File
@@ -218,13 +218,6 @@ export component TopBar inherits Rectangle {
}
}
}
IconButton {
icon: Icons.radio;
label: @tr("Stream Studio");
checked: Nav.page == Page.studio;
y: (parent.height - self.height) / 2;
clicked => { Nav.open-studio(); }
}
IconButton {
icon: Icons.users;
label: @tr("Members");
-9
View File
@@ -172,15 +172,6 @@ export component MobileShell inherits Rectangle {
Nav.show-voice(true);
}
}
if !root.voice: IconButton {
icon: Icons.radio;
label: @tr("Stream Studio");
round: true;
filled: true;
checked: Nav.page == Page.studio;
y: (parent.height - self.height) / 2;
clicked => { Nav.open-studio(); }
}
if !root.voice: IconButton {
icon: Icons.bell;
label: @tr("Notifications");