Merge the server screens into the Stream Studio branch
Both sides added to Nav (the studio's open-studio next to the drawers and the voice view), to App (the studio's state next to the uploads) and to the development switches (studio[:...] next to voice, pins, topics, watch); all of them are kept. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
No files matched your search
@@ -9194,6 +9194,7 @@ dependencies = [
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"voelin-stream",
|
||||
"wasapi",
|
||||
"wayland-client",
|
||||
"wayland-protocols",
|
||||
@@ -9303,6 +9304,7 @@ dependencies = [
|
||||
"unicode-segmentation",
|
||||
"voelin-audio",
|
||||
"voelin-core",
|
||||
"voelin-gateway-proto",
|
||||
"voelin-model",
|
||||
"voelin-platform",
|
||||
"voelin-query",
|
||||
|
||||
@@ -78,3 +78,7 @@ against or offered back to upstream.
|
||||
"Voelin patch"). TeamSpeak 6 sends some times, e.g. `datetime` of `notifyfilelist`,
|
||||
in milliseconds, which failed to parse and dropped the whole message (empty file
|
||||
lists). Values from 10^11 on (year 5138 in seconds) are taken as milliseconds.
|
||||
10. **Test logger** (`tsclientlib/src/tests.rs`, "Voelin patch"). The tests' shared
|
||||
tracing setup used `init`, which panics when quickcheck (`use_logging`) has
|
||||
already installed a `log` logger; the panic poisoned the `Lazy` and failed every
|
||||
later test of the binary, depending on test order. It uses `try_init` now.
|
||||
@@ -2,7 +2,11 @@ use once_cell::sync::Lazy;
|
||||
use ts_bookkeeping::messages::s2c::InMessage;
|
||||
use tsproto_packets::packets::{Direction, Flags, OutPacket, PacketType};
|
||||
|
||||
static TRACING: Lazy<()> = Lazy::new(|| tracing_subscriber::fmt().with_test_writer().init());
|
||||
// Voelin patch: `try_init`. quickcheck's logging installs a `log` logger, after
|
||||
// which `init` panics, poisons this `Lazy` and fails every test that follows.
|
||||
static TRACING: Lazy<()> = Lazy::new(|| {
|
||||
let _ = tracing_subscriber::fmt().with_test_writer().try_init();
|
||||
});
|
||||
|
||||
pub(crate) fn create_logger() { Lazy::force(&TRACING); }
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ openh264-download = ["openh264", "dep:reqwest", "dep:bzip2", "dep:sha2"]
|
||||
# Video encoders through FFmpeg loaded at runtime (never linked or shipped):
|
||||
# VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox, x264,
|
||||
# SVT-AV1, ... whatever the installed FFmpeg has (see docs/media.md).
|
||||
ffmpeg = ["dep:libloading"]
|
||||
ffmpeg = ["dep:libloading", "dep:rustix"]
|
||||
# AV1 decoding through the system libdav1d (pkg-config `dav1d` >= 1.3).
|
||||
av1 = ["dep:dav1d"]
|
||||
# X11 screen capture (Linux).
|
||||
@@ -62,7 +62,7 @@ yuv = "0.8.19"
|
||||
ashpd = { version = "0.13.13", default-features = false, features = ["camera", "screencast", "tokio"], optional = true }
|
||||
memmap2 = { version = "0.9.11", optional = true }
|
||||
pipewire = { version = "0.10.1", optional = true }
|
||||
rustix = { version = "1.1.5", features = ["event", "fs"], optional = true }
|
||||
rustix = { version = "1.1.5", features = ["event", "fs", "stdio"], optional = true }
|
||||
wayland-client = { version = "0.31.15", optional = true }
|
||||
wayland-protocols = { version = "0.32.13", features = ["client", "staging"], optional = true }
|
||||
wayland-protocols-wlr = { version = "0.3.12", features = ["client"], optional = true }
|
||||
@@ -80,6 +80,10 @@ windows-capture = "2.0.1"
|
||||
[dev-dependencies]
|
||||
criterion = "0.8"
|
||||
serde_json = "1"
|
||||
# The H.264 `profile-level-id` the signalling offers, to check it against the
|
||||
# SPS the encoders really emit (`tests/ffmpeg.rs`). No cycle: voelin-stream
|
||||
# does not depend on this crate.
|
||||
voelin-stream = { path = "../voelin-stream" }
|
||||
# Logs of integration tests (`RUST_LOG`).
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tokio = { version = "1", features = ["macros", "rt", "rt-multi-thread", "time"] }
|
||||
|
||||
@@ -21,6 +21,18 @@ const DMA_BUF_SYNC_END: u64 = 1 << 2;
|
||||
/// `DMA_BUF_IOCTL_SYNC`: `_IOW('b', 0, struct dma_buf_sync)`.
|
||||
const SYNC: rustix::ioctl::Opcode = rustix::ioctl::opcode::write::<DmaBufSync>(b'b', 0);
|
||||
|
||||
/// The size of DMA-BUF `fd` in bytes (`lseek(fd, 0, SEEK_END)`, which a
|
||||
/// DMA-BUF answers with its buffer object's size without moving anything).
|
||||
pub(crate) fn size_of(fd: RawFd) -> Option<usize> {
|
||||
if fd < 0 {
|
||||
return None;
|
||||
}
|
||||
// SAFETY: borrowed for the call from a caller that holds it open.
|
||||
let fd = unsafe { BorrowedFd::borrow_raw(fd) };
|
||||
let end = rustix::fs::seek(fd, rustix::fs::SeekFrom::End(0)).ok()?;
|
||||
usize::try_from(end).ok().filter(|&size| size > 0)
|
||||
}
|
||||
|
||||
/// A read-only mapping of a DMA-BUF.
|
||||
pub(crate) struct DmaBufMap {
|
||||
fd: RawFd,
|
||||
@@ -97,5 +109,7 @@ mod tests {
|
||||
assert_eq!(map.fd(), file.as_raw_fd());
|
||||
assert_eq!(map.read(|b| b.iter().map(|&x| u64::from(x)).sum::<u64>()), 7 * 8192);
|
||||
assert!(DmaBufMap::new(-1, 10).is_err());
|
||||
assert_eq!(size_of(file.as_raw_fd()), Some(8192));
|
||||
assert_eq!(size_of(-1), None);
|
||||
}
|
||||
}
|
||||
@@ -11,9 +11,13 @@
|
||||
//! (`BGRx` / `BGRA` / `RGBx` / `RGBA`) second, so compositors without
|
||||
//! DMA-BUF support use shared memory. When reading DMA-BUFs turns out slow
|
||||
//! (buffers in memory the CPU reads uncached, e.g. a discrete GPU's VRAM),
|
||||
//! the stream switches to shared memory. Tiled DMA-BUFs would need a GPU
|
||||
//! import and are not offered. Frames go to the [`FrameSink`] while the
|
||||
//! buffer is dequeued; nothing is copied before conversion. The frame rate
|
||||
//! the stream switches to shared memory. A sink that
|
||||
//! [accepts DMA-BUFs](FrameSink::accepts_dmabuf) (a VA-API encoder, which
|
||||
//! converts and encodes them on the GPU) gets them before anything is
|
||||
//! mapped, and then the CPU never reads them. Tiled DMA-BUFs are not
|
||||
//! offered: the modifiers the encoder's driver imports are not known here.
|
||||
//! Frames go to the [`FrameSink`] while the buffer is dequeued; nothing is
|
||||
//! copied before conversion. The frame rate
|
||||
//! follows the sink's cap: the compositor is asked for up to that rate and
|
||||
//! sends frames when the screen changes.
|
||||
|
||||
@@ -31,7 +35,7 @@ use pw::spa::pod::{
|
||||
use pw::spa::utils::{Choice, ChoiceEnum, ChoiceFlags, Fraction, Id, Rectangle, SpaTypes};
|
||||
use tracing::{debug, warn};
|
||||
|
||||
use crate::capture::dmabuf::DmaBufMap;
|
||||
use crate::capture::dmabuf::{self, DmaBufMap};
|
||||
use crate::capture::pw::{PwThread, pod, serialize};
|
||||
use crate::capture::{
|
||||
BoxFuture, CaptureOptions, CaptureSource, DRM_MOD_LINEAR, DmaBufRef, FrameSink, QueueSink,
|
||||
@@ -248,9 +252,23 @@ const MODIFIER_LINEAR: i64 = 0;
|
||||
/// Reading DMA-BUFs slower than this (per pixel, conversion included) means
|
||||
/// the buffers live in memory the CPU reads uncached (e.g. a discrete GPU's
|
||||
/// VRAM); shared memory is faster then.
|
||||
const SLOW_DMABUF_NS_PER_PIXEL: f64 = 6.0;
|
||||
///
|
||||
/// Measured on a Radeon RX 7900 GRE capturing a 2560x1440 desktop at 60 fps,
|
||||
/// the same run through both paths: a LINEAR DMA-BUF took 11.95 ms per frame
|
||||
/// (3.24 ns per pixel) and 19.5 CPU cores, shared memory 0.27 ms (0.07 ns
|
||||
/// per pixel) and 0.41 cores — 44 times the time and 48 times the CPU. The
|
||||
/// threshold was 6.0, which that does not reach, so the switch never
|
||||
/// happened and a discrete GPU burned twenty cores on screen sharing. It
|
||||
/// sits between the two figures, an order of magnitude above the fast path,
|
||||
/// so a GPU whose buffers the CPU can read (anything with unified memory)
|
||||
/// keeps them.
|
||||
const SLOW_DMABUF_NS_PER_PIXEL: f64 = 1.0;
|
||||
/// DMA-BUF frames timed before deciding.
|
||||
const DMABUF_PROBE_FRAMES: u32 = 30;
|
||||
/// DMA-BUFs that failed to map before shared memory is offered instead. A
|
||||
/// few failures can be a buffer being replaced; more means this compositor's
|
||||
/// buffers cannot be read this way at all.
|
||||
const DMABUF_FAILURES_BEFORE_SHM: u32 = 5;
|
||||
|
||||
/// What was negotiated.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
@@ -275,6 +293,9 @@ struct VideoState {
|
||||
/// Time spent handing DMA-BUF frames to the sink, and how many.
|
||||
dmabuf_time: Duration,
|
||||
dmabuf_frames: u32,
|
||||
/// DMA-BUFs that could not be mapped (see
|
||||
/// [`DMABUF_FAILURES_BEFORE_SHM`]).
|
||||
dmabuf_failures: u32,
|
||||
logged: Option<bool>,
|
||||
mainloop: pw::main_loop::MainLoopWeak,
|
||||
}
|
||||
@@ -303,6 +324,7 @@ fn video_stream(
|
||||
maps: Vec::new(),
|
||||
dmabuf_time: Duration::ZERO,
|
||||
dmabuf_frames: 0,
|
||||
dmabuf_failures: 0,
|
||||
logged: None,
|
||||
mainloop: mainloop.downgrade(),
|
||||
};
|
||||
@@ -582,7 +604,12 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
|
||||
fourcc,
|
||||
modifier: format.modifier.map_or(DRM_MOD_LINEAR, |m| m as u64),
|
||||
fd: data.fd(),
|
||||
size: (raw.mapoffset + raw.maxsize) as usize,
|
||||
// As for the mapping below: compositors leave `maxsize` 0 for
|
||||
// a DMA-BUF, whose size is its buffer object's.
|
||||
size: match (raw.mapoffset + raw.maxsize) as usize {
|
||||
0 => dmabuf::size_of(data.fd()).unwrap_or(raw.mapoffset as usize + needed),
|
||||
size => size,
|
||||
},
|
||||
planes: [(raw.mapoffset as usize + offset, stride), (0, 0), (0, 0), (0, 0)],
|
||||
plane_count: 1,
|
||||
};
|
||||
@@ -600,14 +627,42 @@ fn process(stream: &pw::stream::Stream, state: &mut VideoState) {
|
||||
let started = Instant::now();
|
||||
let more = if is_dmabuf {
|
||||
let raw = data.as_raw();
|
||||
let len = (raw.mapoffset + raw.maxsize) as usize;
|
||||
// A DMA-BUF's size lives in its buffer object, not in `maxsize`:
|
||||
// `maxsize` describes a mapping, which only shared memory has, and
|
||||
// compositors leave it 0 (measured on a 2560x1440 Wayland desktop:
|
||||
// fd valid, stride 10240, `mapoffset` and `maxsize` both 0). Mapping
|
||||
// `mapoffset + maxsize` bytes then asks for a zero-length mapping
|
||||
// and every frame is dropped, so fall back to the rows the
|
||||
// negotiated format describes, which is exactly what is read below.
|
||||
let len = match (raw.mapoffset + raw.maxsize) as usize {
|
||||
0 => raw.mapoffset as usize + needed,
|
||||
size => size,
|
||||
};
|
||||
let fd = data.fd();
|
||||
if !state.maps.iter().any(|m| m.fd() == fd && m.len() >= len) {
|
||||
state.maps.retain(|m| m.fd() != fd);
|
||||
match DmaBufMap::new(fd, len) {
|
||||
Ok(map) => state.maps.push(map),
|
||||
Err(e) => {
|
||||
warn!("cannot map a screen capture DMA-BUF: {e}");
|
||||
warn!(
|
||||
fd,
|
||||
len,
|
||||
mapoffset = raw.mapoffset,
|
||||
maxsize = raw.maxsize,
|
||||
stride,
|
||||
height = format.height,
|
||||
"cannot map a screen capture DMA-BUF: {e}"
|
||||
);
|
||||
// Dropping every frame would leave the viewer a black
|
||||
// screen; shared memory always works.
|
||||
state.dmabuf_failures += 1;
|
||||
if state.dmabuf_failures >= DMABUF_FAILURES_BEFORE_SHM && state.dmabuf {
|
||||
tracing::info!(
|
||||
"screen capture DMA-BUFs cannot be mapped; switching to shared memory"
|
||||
);
|
||||
state.dmabuf = false;
|
||||
renegotiate(stream, state.fps, false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,11 +13,15 @@
|
||||
//! | `AVFrame.pict_type`, `AVFrame.pts` | forcing a keyframe, timestamps | right after the leading fields: `key_frame` (removed in libavutil 60), `pict_type`, `sample_aspect_ratio`, `pts` | a fresh frame must read `pict_type` 0, `sample_aspect_ratio` {0, 1}, `pts` `AV_NOPTS_VALUE` in exactly one of the two layouts |
|
||||
//! | `AVCodecContext.hw_frames_ctx` | VA-API input frames | next to fields that have AVOptions, whose offsets `av_opt_find` reports: before `hw_device_ctx`, `hwaccel_flags` (libavcodec 61 and later, after `err_recognition`), or two fields before `max_pixels` (up to 60) | the neighbours' option offsets must match the layout, and the field must be NULL in a new context |
|
||||
//! | `AVHWFramesContext` `initial_pool_size`, `format`, `sw_format`, `width`, `height` | creating a frame pool | after seven pointers (eight up to libavutil 58: `internal`) | `device_ctx` must equal the device and both formats must be `AV_PIX_FMT_NONE` in a new context |
|
||||
//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-60, 64-bit only) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool |
|
||||
//! | `AVFrame.buf[0]`, `AVFrame.hw_frames_ctx` | importing DMA-BUFs (zero-copy) | a table per libavutil major (56-61, 64-bit only; an unlisted major disables the import) | `buf[0]` of a frame from `av_frame_get_buffer` must hold that frame's `data[0]`; `hw_frames_ctx` of a frame from `av_hwframe_get_buffer` must reference the pool |
|
||||
//! | `AVHWDeviceContext.hwctx` | the `VADisplay`, for the GPU colour conversion of RGB DMA-BUFs | right after `type`, after one pointer (two up to libavutil 58: `internal`) | `type` must be the device's type in exactly that layout |
|
||||
//!
|
||||
//! A check that fails disables only what needs the field (VA-API, or the
|
||||
//! DMA-BUF import), with the reason in the probe results; a new major whose
|
||||
//! layout matches keeps working without a change here.
|
||||
//! DMA-BUF import), with the reason in the probe results. The first three
|
||||
//! rows are found by searching, so a new major whose layout matches keeps
|
||||
//! working without a change here; the last one is a table, because there is
|
||||
//! nothing to anchor those offsets to, and an unlisted major turns the
|
||||
//! DMA-BUF import off rather than guess (see [`frame_refs_table`]).
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::ffi::c_int;
|
||||
@@ -316,6 +320,51 @@ pub unsafe fn hw_frames_fields(frames: Ptr, device: Ptr) -> Result<HwFramesField
|
||||
}
|
||||
}
|
||||
|
||||
/// `AVHWDeviceContext` up to libavutil 58.
|
||||
#[repr(C)]
|
||||
struct DeviceWithInternal {
|
||||
av_class: Ptr,
|
||||
internal: Ptr,
|
||||
kind: c_int,
|
||||
hwctx: Ptr,
|
||||
}
|
||||
|
||||
/// `AVHWDeviceContext` from libavutil 59 (`internal` removed).
|
||||
#[repr(C)]
|
||||
struct DevicePublic {
|
||||
av_class: Ptr,
|
||||
kind: c_int,
|
||||
hwctx: Ptr,
|
||||
}
|
||||
|
||||
/// `AVHWDeviceContext.hwctx` of `device`, a device of type `kind`: the
|
||||
/// API's own context (`AVVAAPIDeviceContext` for VA-API, whose first field
|
||||
/// is the `VADisplay`).
|
||||
///
|
||||
/// Found by `type`, which comes right before it: in the old layout the
|
||||
/// same offset holds the low half of the `internal` pointer, which is
|
||||
/// aligned and so never a small device type.
|
||||
///
|
||||
/// # Safety
|
||||
/// `device` must be a live buffer reference of an `AVHWDeviceContext`.
|
||||
pub unsafe fn device_hwctx(device: Ptr, kind: c_int) -> Result<Ptr, String> {
|
||||
// SAFETY: guaranteed by the caller; `data` is the leading field pair,
|
||||
// and both layouts lie within the smaller one (the current struct).
|
||||
unsafe {
|
||||
let ctx = (*device.cast::<BufferRefHead>()).data.cast::<std::ffi::c_void>();
|
||||
for (kind_at, hwctx_at) in [
|
||||
(offset_of!(DevicePublic, kind), offset_of!(DevicePublic, hwctx)),
|
||||
(offset_of!(DeviceWithInternal, kind), offset_of!(DeviceWithInternal, hwctx)),
|
||||
] {
|
||||
if read::<c_int>(ctx, kind_at) == kind {
|
||||
let hwctx: Ptr = read(ctx, hwctx_at);
|
||||
return if hwctx.is_null() { Err("no device context".into()) } else { Ok(hwctx) };
|
||||
}
|
||||
}
|
||||
}
|
||||
Err("unknown AVHWDeviceContext layout".into())
|
||||
}
|
||||
|
||||
/// Offsets of `buf[0]` and `hw_frames_ctx` in `AVFrame`, for importing
|
||||
/// DMA-BUFs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
@@ -324,8 +373,19 @@ pub struct FrameRefs {
|
||||
pub hw_frames_ctx: usize,
|
||||
}
|
||||
|
||||
/// The table of [`FrameRefs`] per libavutil major (64-bit targets). A newer
|
||||
/// major is tried with the newest entry and must pass the checks.
|
||||
/// The table of [`FrameRefs`] per libavutil major (64-bit targets).
|
||||
///
|
||||
/// Every entry is `offsetof` compiled from that release's own
|
||||
/// `libavutil/frame.h`; libavutil 61's was measured against the headers
|
||||
/// installed next to the library it describes (FFmpeg 9.0.1: `buf` 184,
|
||||
/// `hw_frames_ctx` 328, `sizeof(AVFrame)` 424).
|
||||
///
|
||||
/// A major that is not listed returns `None`, which disables the DMA-BUF
|
||||
/// import (and nothing else) with the reason in the probe results. It
|
||||
/// deliberately does not fall back to the newest entry: `AVFrame` has both
|
||||
/// grown and shrunk between majors (424 bytes in 61 against 536 in 56), so
|
||||
/// an offset guessed for an unknown layout could read past the end of the
|
||||
/// struct. Adding a major here needs its `offsetof` values, not a guess.
|
||||
fn frame_refs_table(avutil_major: u32) -> Option<FrameRefs> {
|
||||
if size_of::<Ptr>() != 8 {
|
||||
return None;
|
||||
@@ -334,7 +394,7 @@ fn frame_refs_table(avutil_major: u32) -> Option<FrameRefs> {
|
||||
56 => (288, 480),
|
||||
57 | 58 => (224, 392),
|
||||
59 => (200, 352),
|
||||
60.. => (184, 328),
|
||||
60 | 61 => (184, 328),
|
||||
_ => return None,
|
||||
};
|
||||
Some(FrameRefs { buf, hw_frames_ctx })
|
||||
@@ -346,8 +406,12 @@ fn frame_refs_table(avutil_major: u32) -> Option<FrameRefs> {
|
||||
pub fn frame_refs(api: &Api, yuv420p: c_int) -> Result<FrameRefs, String> {
|
||||
// SAFETY: no arguments.
|
||||
let major = unsafe { (api.avutil_version)() } >> 16;
|
||||
let refs = frame_refs_table(major)
|
||||
.ok_or_else(|| format!("AVFrame references not known for libavutil {major} here"))?;
|
||||
let refs = frame_refs_table(major).ok_or_else(|| {
|
||||
format!(
|
||||
"AVFrame.buf / hw_frames_ctx offsets are not recorded for libavutil {major} (see \
|
||||
frame_refs_table); the import stays off until they are measured"
|
||||
)
|
||||
})?;
|
||||
// SAFETY: a frame of 16x16 yuv420p pixels; the head fields are set
|
||||
// before av_frame_get_buffer as its documentation asks; the offsets are
|
||||
// inside AVFrame for this major (the table), pointer-aligned.
|
||||
@@ -410,4 +474,35 @@ mod tests {
|
||||
assert_eq!(frame_refs_table(58), Some(FrameRefs { buf: 224, hw_frames_ctx: 392 }));
|
||||
assert_eq!(frame_refs_table(55), None);
|
||||
}
|
||||
|
||||
/// libavutil 61 (FFmpeg 9), compiled from the installed headers on
|
||||
/// x86-64: `AVFrame` `pict_type` 120, `pts` 136, `buf` 184,
|
||||
/// `hw_frames_ctx` 328, `sizeof` 424; `AVCodecContext`
|
||||
/// `err_recognition` 528, `hw_frames_ctx` 552, `hw_device_ctx` 560,
|
||||
/// `hwaccel_flags` 568, `extra_hw_frames` 572; `AVHWFramesContext`
|
||||
/// `pool` 48, `initial_pool_size` 56, `format` 60, `sw_format` 64,
|
||||
/// `width` 68, `height` 72; `AVHWDeviceContext` `type` 8, `hwctx` 16.
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
#[test]
|
||||
fn libavutil_61_matches_the_headers() {
|
||||
assert_eq!(frame_refs_table(61), Some(FrameRefs { buf: 184, hw_frames_ctx: 328 }));
|
||||
assert_eq!(offset_of!(FrameWithoutKeyFrame, pict_type), 120);
|
||||
assert_eq!(offset_of!(FrameWithoutKeyFrame, pts), 136);
|
||||
let base = 528;
|
||||
assert_eq!(base + offset_of!(HwFieldsNew, hw_frames_ctx), 552);
|
||||
assert_eq!(base + offset_of!(HwFieldsNew, hw_device_ctx), 560);
|
||||
assert_eq!(base + offset_of!(HwFieldsNew, hwaccel_flags), 568);
|
||||
assert_eq!(base + offset_of!(HwFieldsNew, extra_hw_frames), 572);
|
||||
assert_eq!(offset_of!(HwFramesPublic, pool), 48);
|
||||
assert_eq!(offset_of!(HwFramesPublic, initial_pool_size), 56);
|
||||
assert_eq!(offset_of!(HwFramesPublic, sw_format), 64);
|
||||
assert_eq!(offset_of!(HwFramesPublic, height), 72);
|
||||
assert_eq!(offset_of!(DevicePublic, kind), 8);
|
||||
assert_eq!(offset_of!(DevicePublic, hwctx), 16);
|
||||
// A major nobody measured must disable the import, not reuse 61's
|
||||
// offsets: AVFrame has shrunk between majors (424 bytes in 61
|
||||
// against 536 in 56), so reading at a guessed offset could leave
|
||||
// the struct.
|
||||
assert_eq!(frame_refs_table(62), None);
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ use std::sync::{Mutex, OnceLock};
|
||||
pub mod encoder;
|
||||
mod layout;
|
||||
pub mod sys;
|
||||
mod vpp;
|
||||
|
||||
pub use encoder::{
|
||||
BACKENDS, BackendKind, BackendSpec, BackendStatus, FfmpegEncoder, FfmpegFactory, Input, probe,
|
||||
@@ -37,6 +38,8 @@ pub(crate) struct PixFmts {
|
||||
pub nv12: c_int,
|
||||
pub vaapi: Option<c_int>,
|
||||
pub drm_prime: Option<c_int>,
|
||||
/// `bgr0`: B, G, R, x in memory, the DRM `XR24` of captured screens.
|
||||
pub bgr0: Option<c_int>,
|
||||
}
|
||||
|
||||
/// What was loaded, for logs and the UI.
|
||||
@@ -98,6 +101,7 @@ impl Ffmpeg {
|
||||
nv12,
|
||||
vaapi: api.pix_fmt("vaapi").or_else(|| api.pix_fmt("vaapi_vld")),
|
||||
drm_prime: api.pix_fmt("drm_prime"),
|
||||
bgr0: api.pix_fmt("bgr0"),
|
||||
};
|
||||
let codec_hw_frames = layout::codec_hw_frames(&api);
|
||||
let frame_refs = layout::frame_refs(&api, yuv420p);
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
//! RGB to NV12 on the GPU (VA-API video processing), so that a captured
|
||||
//! RGB DMA-BUF reaches a VA-API encoder without the CPU reading a pixel.
|
||||
//!
|
||||
//! libva is what FFmpeg's VA-API support is built on, not one of FFmpeg's
|
||||
//! libraries: it is opened at runtime (`libva.so.2`, which libavutil has
|
||||
//! already loaded once a VA-API device exists) and driven on FFmpeg's own
|
||||
//! `VADisplay`, so FFmpeg's surfaces (`AVFrame.data[3]`) are used as they
|
||||
//! are. FFmpeg does the same conversion only in libavfilter (`scale_vaapi`),
|
||||
//! which would be one more library to find and a filter graph to drive for
|
||||
//! what is one call here. libva 2 has kept its ABI since 2017: structs are
|
||||
//! padded to a fixed size and new fields take reserved space.
|
||||
#![allow(unsafe_code)]
|
||||
|
||||
use std::ffi::{CStr, c_char, c_int, c_uint, c_void};
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use libloading::Library;
|
||||
|
||||
/// `VADisplay`.
|
||||
pub type Display = *mut c_void;
|
||||
|
||||
/// `VAProfileNone`, `VAEntrypointVideoProc`, `VA_PROGRESSIVE`,
|
||||
/// `VAProcPipelineParameterBufferType`.
|
||||
const PROFILE_NONE: c_int = -1;
|
||||
const ENTRYPOINT_VIDEO_PROC: c_int = 10;
|
||||
const PROGRESSIVE: c_int = 1;
|
||||
const PROC_PIPELINE_PARAMETER_BUFFER: c_int = 41;
|
||||
/// `VAProcColorStandardBT601`, `VAProcColorStandardExplicit`,
|
||||
/// `VA_SOURCE_RANGE_REDUCED` / `_FULL`.
|
||||
const COLOR_STANDARD_BT601: c_int = 1;
|
||||
const COLOR_STANDARD_EXPLICIT: c_int = 13;
|
||||
const RANGE_REDUCED: u8 = 1;
|
||||
const RANGE_FULL: u8 = 2;
|
||||
/// ISO/IEC 23091-2 code points: SMPTE 170M (BT.601) primaries and transfer,
|
||||
/// and the identity matrix (RGB).
|
||||
const SMPTE170M: u8 = 6;
|
||||
const MATRIX_IDENTITY: u8 = 0;
|
||||
|
||||
/// `VARectangle`.
|
||||
#[repr(C)]
|
||||
struct Rectangle {
|
||||
x: i16,
|
||||
y: i16,
|
||||
width: u16,
|
||||
height: u16,
|
||||
}
|
||||
|
||||
/// `VAProcColorProperties`.
|
||||
#[repr(C)]
|
||||
#[derive(Default)]
|
||||
struct ColorProperties {
|
||||
chroma_sample_location: u8,
|
||||
color_range: u8,
|
||||
colour_primaries: u8,
|
||||
transfer_characteristics: u8,
|
||||
matrix_coefficients: u8,
|
||||
reserved: [u8; 3],
|
||||
}
|
||||
|
||||
/// `VAProcPipelineParameterBuffer` of libva 2 (224 bytes on 64-bit
|
||||
/// targets).
|
||||
#[repr(C)]
|
||||
struct PipelineParameters {
|
||||
surface: c_uint,
|
||||
surface_region: *const Rectangle,
|
||||
surface_color_standard: c_int,
|
||||
output_region: *const Rectangle,
|
||||
output_background_color: u32,
|
||||
output_color_standard: c_int,
|
||||
pipeline_flags: u32,
|
||||
filter_flags: u32,
|
||||
filters: *mut c_uint,
|
||||
num_filters: u32,
|
||||
forward_references: *mut c_uint,
|
||||
num_forward_references: u32,
|
||||
backward_references: *mut c_uint,
|
||||
num_backward_references: u32,
|
||||
rotation_state: u32,
|
||||
blend_state: *const c_void,
|
||||
mirror_state: u32,
|
||||
additional_outputs: *mut c_uint,
|
||||
num_additional_outputs: u32,
|
||||
input_surface_flag: u32,
|
||||
output_surface_flag: u32,
|
||||
input_color_properties: ColorProperties,
|
||||
output_color_properties: ColorProperties,
|
||||
processing_mode: c_int,
|
||||
output_hdr_metadata: *mut c_void,
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
reserved: [u32; 16],
|
||||
#[cfg(not(target_pointer_width = "64"))]
|
||||
reserved: [u32; 19],
|
||||
}
|
||||
|
||||
/// The libva functions used, with their `va.h` signatures.
|
||||
struct Va {
|
||||
create_config:
|
||||
unsafe extern "C" fn(Display, c_int, c_int, *mut c_void, c_int, *mut c_uint) -> c_int,
|
||||
destroy_config: unsafe extern "C" fn(Display, c_uint) -> c_int,
|
||||
create_context: unsafe extern "C" fn(
|
||||
Display,
|
||||
c_uint,
|
||||
c_int,
|
||||
c_int,
|
||||
c_int,
|
||||
*mut c_uint,
|
||||
c_int,
|
||||
*mut c_uint,
|
||||
) -> c_int,
|
||||
destroy_context: unsafe extern "C" fn(Display, c_uint) -> c_int,
|
||||
create_buffer: unsafe extern "C" fn(
|
||||
Display,
|
||||
c_uint,
|
||||
c_int,
|
||||
c_uint,
|
||||
c_uint,
|
||||
*mut c_void,
|
||||
*mut c_uint,
|
||||
) -> c_int,
|
||||
destroy_buffer: unsafe extern "C" fn(Display, c_uint) -> c_int,
|
||||
begin_picture: unsafe extern "C" fn(Display, c_uint, c_uint) -> c_int,
|
||||
render_picture: unsafe extern "C" fn(Display, c_uint, *mut c_uint, c_int) -> c_int,
|
||||
end_picture: unsafe extern "C" fn(Display, c_uint) -> c_int,
|
||||
sync_surface: unsafe extern "C" fn(Display, c_uint) -> c_int,
|
||||
error_str: unsafe extern "C" fn(c_int) -> *const c_char,
|
||||
_lib: Library,
|
||||
}
|
||||
|
||||
impl Va {
|
||||
fn get() -> Result<&'static Va, String> {
|
||||
static VA: OnceLock<Result<Va, String>> = OnceLock::new();
|
||||
VA.get_or_init(|| {
|
||||
// SAFETY: libva has no initialisers with requirements; once a
|
||||
// VA-API device exists this is the copy libavutil loaded.
|
||||
let lib = unsafe { Library::new("libva.so.2") }.map_err(|e| format!("libva: {e}"))?;
|
||||
macro_rules! symbol {
|
||||
($name:literal) => {
|
||||
// SAFETY: looked up with its C signature from va.h; the
|
||||
// library stays loaded as long as the pointers (`_lib`).
|
||||
*unsafe { lib.get($name) }.map_err(|e| format!("libva: {e}"))?
|
||||
};
|
||||
}
|
||||
Ok(Va {
|
||||
create_config: symbol!(b"vaCreateConfig\0"),
|
||||
destroy_config: symbol!(b"vaDestroyConfig\0"),
|
||||
create_context: symbol!(b"vaCreateContext\0"),
|
||||
destroy_context: symbol!(b"vaDestroyContext\0"),
|
||||
create_buffer: symbol!(b"vaCreateBuffer\0"),
|
||||
destroy_buffer: symbol!(b"vaDestroyBuffer\0"),
|
||||
begin_picture: symbol!(b"vaBeginPicture\0"),
|
||||
render_picture: symbol!(b"vaRenderPicture\0"),
|
||||
end_picture: symbol!(b"vaEndPicture\0"),
|
||||
sync_surface: symbol!(b"vaSyncSurface\0"),
|
||||
error_str: symbol!(b"vaErrorStr\0"),
|
||||
_lib: lib,
|
||||
})
|
||||
})
|
||||
.as_ref()
|
||||
.map_err(Clone::clone)
|
||||
}
|
||||
|
||||
/// `Err` with libva's text for a status other than `VA_STATUS_SUCCESS`.
|
||||
fn check(&self, what: &str, status: c_int) -> Result<(), String> {
|
||||
if status == 0 {
|
||||
return Ok(());
|
||||
}
|
||||
// SAFETY: returns a static string for any status.
|
||||
let text = unsafe { CStr::from_ptr((self.error_str)(status)) };
|
||||
Err(format!("{what}: {}", text.to_string_lossy()))
|
||||
}
|
||||
}
|
||||
|
||||
/// A VA-API video processing context that converts RGB surfaces into NV12
|
||||
/// ones of `width` x `height`.
|
||||
pub struct Converter {
|
||||
va: &'static Va,
|
||||
display: Display,
|
||||
config: c_uint,
|
||||
context: c_uint,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
|
||||
// SAFETY: libva serialises calls per display; the context is used from one
|
||||
// thread at a time (`&self` of a session behind `&mut`).
|
||||
unsafe impl Send for Converter {}
|
||||
|
||||
impl Converter {
|
||||
/// A context on `display` (FFmpeg's, see
|
||||
/// [`layout::device_hwctx`](super::layout::device_hwctx)) for output
|
||||
/// surfaces of `width` x `height`.
|
||||
pub fn new(display: Display, width: u32, height: u32) -> Result<Self, String> {
|
||||
let va = Va::get()?;
|
||||
let mut config = 0;
|
||||
// SAFETY: a live display; no attributes; out pointer.
|
||||
let status = unsafe {
|
||||
(va.create_config)(
|
||||
display,
|
||||
PROFILE_NONE,
|
||||
ENTRYPOINT_VIDEO_PROC,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut config,
|
||||
)
|
||||
};
|
||||
va.check("no VA-API video processing", status)?;
|
||||
let mut context = 0;
|
||||
// SAFETY: the config just made; no render targets (surfaces are
|
||||
// named per picture); out pointer.
|
||||
let status = unsafe {
|
||||
(va.create_context)(
|
||||
display,
|
||||
config,
|
||||
width as c_int,
|
||||
height as c_int,
|
||||
PROGRESSIVE,
|
||||
std::ptr::null_mut(),
|
||||
0,
|
||||
&mut context,
|
||||
)
|
||||
};
|
||||
if let Err(e) = va.check("VA-API video processing context", status) {
|
||||
// SAFETY: made above.
|
||||
unsafe { (va.destroy_config)(display, config) };
|
||||
return Err(e);
|
||||
}
|
||||
Ok(Self { va, display, config, context, width, height })
|
||||
}
|
||||
|
||||
/// Convert the top-left `width` x `height` of RGB surface `input` into
|
||||
/// NV12 surface `output` (both of this display): BT.601, limited range,
|
||||
/// what the encoders signal and the CPU path ([`crate::convert`])
|
||||
/// produces.
|
||||
///
|
||||
/// Returns once the GPU has read `input`, so a captured buffer can go
|
||||
/// back to the compositor; `output` is ready for an encoder of the same
|
||||
/// display, which orders its reads after this.
|
||||
pub fn convert(&self, input: c_uint, output: c_uint) -> Result<(), String> {
|
||||
let va = self.va;
|
||||
let region = Rectangle { x: 0, y: 0, width: self.width as u16, height: self.height as u16 };
|
||||
let mut parameters = PipelineParameters {
|
||||
surface: input,
|
||||
surface_region: ®ion,
|
||||
output_region: ®ion,
|
||||
output_background_color: 0xff00_0000,
|
||||
output_color_standard: COLOR_STANDARD_BT601,
|
||||
pipeline_flags: 0,
|
||||
filter_flags: 0,
|
||||
filters: std::ptr::null_mut(),
|
||||
num_filters: 0,
|
||||
forward_references: std::ptr::null_mut(),
|
||||
num_forward_references: 0,
|
||||
backward_references: std::ptr::null_mut(),
|
||||
num_backward_references: 0,
|
||||
rotation_state: 0,
|
||||
blend_state: std::ptr::null(),
|
||||
mirror_state: 0,
|
||||
additional_outputs: std::ptr::null_mut(),
|
||||
num_additional_outputs: 0,
|
||||
input_surface_flag: 0,
|
||||
output_surface_flag: 0,
|
||||
// The input is described with the output's primaries and transfer,
|
||||
// so the driver applies the matrix and nothing else, as the CPU
|
||||
// path does. Left to itself (no standard, or sRGB) Mesa also
|
||||
// converts the transfer function: measured on an RX 7900 GRE,
|
||||
// grey 30 came out as Y 47 instead of 42, every dark pixel about
|
||||
// 5 levels too bright.
|
||||
surface_color_standard: COLOR_STANDARD_EXPLICIT,
|
||||
input_color_properties: ColorProperties {
|
||||
color_range: RANGE_FULL,
|
||||
colour_primaries: SMPTE170M,
|
||||
transfer_characteristics: SMPTE170M,
|
||||
matrix_coefficients: MATRIX_IDENTITY,
|
||||
..Default::default()
|
||||
},
|
||||
output_color_properties: ColorProperties {
|
||||
color_range: RANGE_REDUCED,
|
||||
..Default::default()
|
||||
},
|
||||
processing_mode: 0,
|
||||
output_hdr_metadata: std::ptr::null_mut(),
|
||||
reserved: Default::default(),
|
||||
};
|
||||
let (display, context) = (self.display, self.context);
|
||||
// SAFETY: surfaces and context of this display; the parameters are
|
||||
// copied by vaCreateBuffer (and the regions they point to live until
|
||||
// vaEndPicture returns); the buffer is ours to destroy afterwards.
|
||||
unsafe {
|
||||
va.check("vaBeginPicture", (va.begin_picture)(display, context, output))?;
|
||||
let mut buffer = 0;
|
||||
let status = (va.create_buffer)(
|
||||
display,
|
||||
context,
|
||||
PROC_PIPELINE_PARAMETER_BUFFER,
|
||||
size_of::<PipelineParameters>() as c_uint,
|
||||
1,
|
||||
(&raw mut parameters).cast(),
|
||||
&mut buffer,
|
||||
);
|
||||
let rendered = va.check("vaCreateBuffer", status).and_then(|()| {
|
||||
va.check("vaRenderPicture", (va.render_picture)(display, context, &mut buffer, 1))
|
||||
});
|
||||
// A picture that was begun has to end, rendered or not.
|
||||
let ended = va.check("vaEndPicture", (va.end_picture)(display, context));
|
||||
if status == 0 {
|
||||
(va.destroy_buffer)(display, buffer);
|
||||
}
|
||||
rendered?;
|
||||
ended?;
|
||||
va.check("vaSyncSurface", (va.sync_surface)(display, output))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Converter {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: made in `new` on this display, no longer used.
|
||||
unsafe {
|
||||
(self.va.destroy_context)(self.display, self.context);
|
||||
(self.va.destroy_config)(self.display, self.config);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::mem::offset_of;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// The mirror against `va/va_vpp.h` of libva 2.24 (x86-64), compiled.
|
||||
#[cfg(target_pointer_width = "64")]
|
||||
#[test]
|
||||
fn pipeline_parameters_match_the_header() {
|
||||
assert_eq!(size_of::<PipelineParameters>(), 224);
|
||||
assert_eq!(offset_of!(PipelineParameters, output_color_standard), 36);
|
||||
assert_eq!(offset_of!(PipelineParameters, rotation_state), 92);
|
||||
assert_eq!(offset_of!(PipelineParameters, input_surface_flag), 124);
|
||||
assert_eq!(offset_of!(PipelineParameters, input_color_properties), 132);
|
||||
assert_eq!(offset_of!(PipelineParameters, output_color_properties), 140);
|
||||
assert_eq!(offset_of!(PipelineParameters, processing_mode), 148);
|
||||
assert_eq!(offset_of!(ColorProperties, color_range), 1);
|
||||
}
|
||||
}
|
||||
@@ -41,19 +41,21 @@ fn decoder(codec: Codec) -> Option<Box<dyn VideoDecoder>> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Twelve frames of the moving test pattern, a keyframe forced at 8, a
|
||||
/// bitrate change at 5: keyframes where asked, timestamps kept, and (with a
|
||||
/// decoder) every picture decodable at PSNR > 28 dB.
|
||||
fn roundtrip(name: &'static str) {
|
||||
let screen = SyntheticScreen::new(W, H);
|
||||
/// Twelve frames of the moving test pattern at `w` x `h`, a keyframe forced
|
||||
/// at 8, a bitrate change at 5: keyframes where asked, timestamps kept, and
|
||||
/// (with a decoder) every picture decodable at its own size, PSNR > 28 dB.
|
||||
fn roundtrip(name: &'static str, w: u32, h: u32) {
|
||||
let screen = SyntheticScreen::new(w, h);
|
||||
let config = EncoderConfig { fps: 30, bitrate_bps: 1_500_000, ..EncoderConfig::default() };
|
||||
let mut encoder = FfmpegEncoder::new(name, config).unwrap();
|
||||
assert_eq!(encoder.backend(), EncoderBackend::Ffmpeg(name));
|
||||
let (aw, ah) = probe().iter().find(|s| s.spec.name == name).unwrap().alignment;
|
||||
let codec = encoder.codec();
|
||||
let mut decoder = decoder(codec);
|
||||
let mut keyframes = Vec::new();
|
||||
let mut sent = Vec::new();
|
||||
let mut decoded = 0;
|
||||
let mut worst = f64::INFINITY;
|
||||
let mut sources = Vec::new();
|
||||
// Frames in until the first packet came out (the encoder's delay).
|
||||
let mut delay = None;
|
||||
@@ -81,15 +83,25 @@ fn roundtrip(name: &'static str) {
|
||||
if let Some(decoder) = &mut decoder
|
||||
&& let Some(picture) = decoder.decode(&f.data).unwrap()
|
||||
{
|
||||
assert_eq!((picture.width, picture.height), (W, H));
|
||||
let psnr = convert::psnr(&sources[index], &picture).unwrap();
|
||||
assert!(psnr > 28.0, "{name} frame {index}: PSNR {psnr:.1} dB");
|
||||
// The top-left part the encoder's alignment allows, never
|
||||
// padding (which the viewer would see).
|
||||
let (pw, ph) = (picture.width, picture.height);
|
||||
assert!(
|
||||
pw <= w && ph <= h && w - pw < aw && h - ph < ah,
|
||||
"{name}: {w}x{h} decoded as {pw}x{ph} (alignment {aw}x{ah})"
|
||||
);
|
||||
let mut source = sources[index].view();
|
||||
(source.width, source.height) = (pw, ph);
|
||||
let psnr = convert::psnr(&source.to_frame(), &picture).unwrap();
|
||||
assert!(psnr > 28.0, "{name} {w}x{h} frame {index}: PSNR {psnr:.1} dB");
|
||||
worst = worst.min(psnr);
|
||||
decoded += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
eprintln!(
|
||||
"{name}: {} packets from {} frames (first after {delay:?}), keyframes at {keyframes:?}, decoded {decoded}",
|
||||
"{name} {w}x{h} (alignment {aw}x{ah}): {} packets from {} frames (first after \
|
||||
{delay:?}), keyframes at {keyframes:?}, decoded {decoded}, lowest PSNR {worst:.1} dB",
|
||||
sent.len(),
|
||||
sources.len()
|
||||
);
|
||||
@@ -139,7 +151,7 @@ fn software_encoders_roundtrip() {
|
||||
let mut tested = Vec::new();
|
||||
for name in ["libx264", "libopenh264", "libsvtav1", "librav1e", "libaom-av1"] {
|
||||
if available(name) {
|
||||
roundtrip(name);
|
||||
roundtrip(name, W, H);
|
||||
tested.push(name);
|
||||
} else {
|
||||
eprintln!("{name} skipped: not available");
|
||||
@@ -148,6 +160,40 @@ fn software_encoders_roundtrip() {
|
||||
eprintln!("tested: {tested:?}");
|
||||
}
|
||||
|
||||
/// What the GPU encoders produce, through the same round-trip as the
|
||||
/// software ones: our own decoders have to decode it (OpenH264 for H.264 with
|
||||
/// `VOELIN_OPENH264_LIB`, dav1d for AV1 with `--features av1`), keyframes
|
||||
/// where asked, timestamps kept, PSNR above 28 dB.
|
||||
///
|
||||
/// Also at 1920x1080, which is not a whole number of 16-pixel macroblocks:
|
||||
/// the H.264 SPS has to crop the 1088 coded rows, and AV1 has no cropping at
|
||||
/// all, so a GPU that only encodes aligned sizes shows as a wrong decoded
|
||||
/// size.
|
||||
///
|
||||
/// Whatever hardware the machine has; skipped where none of it works. HEVC is
|
||||
/// left out, having no decoder here.
|
||||
#[test]
|
||||
fn hardware_encoders_roundtrip() {
|
||||
if ffmpeg().is_none() {
|
||||
return;
|
||||
}
|
||||
let names: Vec<&'static str> = BACKENDS
|
||||
.iter()
|
||||
.filter(|b| b.is_hardware() && matches!(b.codec, Codec::H264 | Codec::Av1))
|
||||
.map(|b| b.name)
|
||||
.filter(|name| available(name))
|
||||
.collect();
|
||||
if names.is_empty() {
|
||||
eprintln!("no usable hardware encoder, skipped");
|
||||
return;
|
||||
}
|
||||
for name in &names {
|
||||
roundtrip(name, W, H);
|
||||
roundtrip(name, 1920, 1080);
|
||||
}
|
||||
eprintln!("tested: {names:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn x264_is_constrained_high_and_changes_size() {
|
||||
if ffmpeg().is_none() || !available("libx264") {
|
||||
@@ -183,11 +229,24 @@ fn x264_is_constrained_high_and_changes_size() {
|
||||
|
||||
/// `profile_idc` of the first SPS in an Annex B stream.
|
||||
fn h264_profile(data: &[u8]) -> Option<u8> {
|
||||
sps(data).map(|(profile, _, _)| profile)
|
||||
}
|
||||
|
||||
/// `profile_idc`, the constraint-flag byte (`constraint_set0..5` in the top
|
||||
/// six bits) and `level_idc` of the first SPS in an Annex B stream: the very
|
||||
/// three bytes of `profile-level-id` in the SDP `a=fmtp` line.
|
||||
///
|
||||
/// They are the first three bytes of the SPS payload, so no bit reading is
|
||||
/// needed. Emulation prevention cannot touch them either: it only ever
|
||||
/// inserts a byte after two zeros, and no valid SPS starts
|
||||
/// `profile_idc == 0`.
|
||||
fn sps(data: &[u8]) -> Option<(u8, u8, u8)> {
|
||||
let mut i = 0;
|
||||
while i + 4 < data.len() {
|
||||
while i + 3 < data.len() {
|
||||
if data[i..i + 3] == [0, 0, 1] {
|
||||
if data[i + 3] & 0x1f == 7 {
|
||||
return data.get(i + 4).copied();
|
||||
let p = data.get(i + 4..i + 7)?;
|
||||
return Some((p[0], p[1], p[2]));
|
||||
}
|
||||
i += 3;
|
||||
} else {
|
||||
@@ -197,6 +256,92 @@ fn h264_profile(data: &[u8]) -> Option<u8> {
|
||||
None
|
||||
}
|
||||
|
||||
/// What every usable H.264 backend puts in the SPS against the
|
||||
/// `profile-level-id` the signalling offers for the same stream. A decoder
|
||||
/// set up from our offer must be able to decode what we send, so the
|
||||
/// emitted `level_idc` may never exceed the offered one, and `profile_idc`
|
||||
/// has to be the profile we claim.
|
||||
///
|
||||
/// The constraint-flag byte is only reported, not asserted: VA-API has no
|
||||
/// Constrained High profile at all (`h264_vaapi` offers `main`, `high`,
|
||||
/// `high10`, `constrained_baseline`), so it emits plain High with the flags
|
||||
/// clear, while AMF's `constrained_high` sets `constraint_set4` and
|
||||
/// `constraint_set5` as the offer says. See `docs/media.md`.
|
||||
#[test]
|
||||
fn sps_carries_the_offered_profile_and_level() {
|
||||
use voelin_media::H264Profile;
|
||||
if ffmpeg().is_none() {
|
||||
return;
|
||||
}
|
||||
// 720p30 (offered level 3.1) and 1080p60 (4.2).
|
||||
const CASES: [(u32, u32, u32, u32); 2] =
|
||||
[(1280, 720, 30, 4_000_000), (1920, 1080, 60, 6_000_000)];
|
||||
let mut tested = 0;
|
||||
for status in probe().iter().filter(|s| s.available.is_ok()) {
|
||||
if status.spec.codec != Codec::H264 {
|
||||
continue;
|
||||
}
|
||||
for profile in [H264Profile::ConstrainedHigh, H264Profile::ConstrainedBaseline] {
|
||||
let (offered_profile, want_idc) = match profile {
|
||||
H264Profile::ConstrainedHigh => (voelin_stream::H264Profile::ConstrainedHigh, 100),
|
||||
H264Profile::ConstrainedBaseline => {
|
||||
(voelin_stream::H264Profile::ConstrainedBaseline, 66)
|
||||
}
|
||||
};
|
||||
for (w, h, fps, bitrate) in CASES {
|
||||
let config = EncoderConfig {
|
||||
fps,
|
||||
bitrate_bps: bitrate,
|
||||
h264_profile: profile,
|
||||
..EncoderConfig::default()
|
||||
};
|
||||
let mut encoder = FfmpegEncoder::new(status.spec.name, config).unwrap();
|
||||
let screen = SyntheticScreen::new(w, h);
|
||||
// Hardware encoders hold a frame or two before the first packet.
|
||||
let mut packets = Vec::new();
|
||||
for n in 0..8 {
|
||||
packets.extend(encoder.encode(&screen.frame(n, fps), n == 0).unwrap());
|
||||
if !packets.is_empty() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let Some(first) = packets.first() else {
|
||||
panic!("{} produced no packet at {w}x{h}", status.spec.name)
|
||||
};
|
||||
let Some((idc, flags, level)) = sps(&first.data) else {
|
||||
panic!("{} sent no SPS at {w}x{h}", status.spec.name)
|
||||
};
|
||||
let offered = voelin_stream::h264::offer_profile_level_id(
|
||||
offered_profile,
|
||||
w,
|
||||
h,
|
||||
fps,
|
||||
u64::from(bitrate),
|
||||
);
|
||||
let offered_level = (offered & 0xff) as u8;
|
||||
eprintln!(
|
||||
"{:<12} {profile:?} {w}x{h}@{fps}: SPS {idc:02x} {flags:02x} {level:02x}, \
|
||||
offer {:06x}",
|
||||
status.spec.name, offered
|
||||
);
|
||||
assert_eq!(
|
||||
idc, want_idc,
|
||||
"{} emits profile_idc {idc}, the offer claims {want_idc}",
|
||||
status.spec.name
|
||||
);
|
||||
assert!(
|
||||
level <= offered_level,
|
||||
"{} emits level_idc {level} at {w}x{h}@{fps}, above the offered {offered_level}: \
|
||||
a decoder set up from our SDP could refuse it",
|
||||
status.spec.name
|
||||
);
|
||||
tested += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(tested > 0, "no usable H.264 backend to check");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codecs_prefer_ffmpeg_h264_over_nothing() {
|
||||
if ffmpeg().is_none() || !available("libx264") {
|
||||
@@ -255,29 +400,46 @@ fn bitrate_changes_without_live_reconfiguration() {
|
||||
assert!(!key(&mut encoder, 6, false));
|
||||
}
|
||||
|
||||
/// DMA-BUF import is for VA-API encoders and NV12 buffers; anything else is
|
||||
/// refused as unavailable, so the caller maps the buffer instead.
|
||||
/// DMA-BUF import is for VA-API encoders and NV12 or RGB buffers; anything
|
||||
/// else is refused as unavailable, so the caller maps the buffer instead. A
|
||||
/// buffer the driver cannot import is an error, not a crash: the encoder
|
||||
/// takes the next frame, and drops cleanly although nothing went in (FFmpeg
|
||||
/// 9's VA-API encoders crash when drained before their first frame).
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn dmabuf_import_is_refused_cleanly() {
|
||||
use std::os::fd::AsRawFd;
|
||||
use voelin_media::capture::{DRM_MOD_LINEAR, DmaBufRef, drm_fourcc};
|
||||
if ffmpeg().is_none() {
|
||||
return;
|
||||
}
|
||||
let not_a_dmabuf = std::fs::File::open("/dev/null").unwrap();
|
||||
let frame = DmaBufRef {
|
||||
width: W,
|
||||
height: H,
|
||||
timestamp: Duration::ZERO,
|
||||
fourcc: drm_fourcc(b"XR24"),
|
||||
modifier: DRM_MOD_LINEAR,
|
||||
fd: -1,
|
||||
fd: not_a_dmabuf.as_raw_fd(),
|
||||
size: (W * H * 4) as usize,
|
||||
planes: [(0, (W * 4) as usize), (0, 0), (0, 0), (0, 0)],
|
||||
plane_count: 1,
|
||||
};
|
||||
for name in ["libx264", "h264_vaapi"] {
|
||||
let unavailable = |name: &str, frame: &DmaBufRef| {
|
||||
let mut encoder = FfmpegEncoder::new(name, EncoderConfig::default()).unwrap();
|
||||
let err = encoder.encode_dmabuf(&frame, true, &mut |_| {}).unwrap_err();
|
||||
let err = encoder.encode_dmabuf(frame, true, &mut |_| {}).unwrap_err();
|
||||
assert!(matches!(err, voelin_media::Error::CodecUnavailable { .. }), "{name}: {err}");
|
||||
};
|
||||
unavailable("libx264", &frame);
|
||||
unavailable("h264_vaapi", &DmaBufRef { fourcc: drm_fourcc(b"YUYV"), ..frame });
|
||||
if !available("h264_vaapi") {
|
||||
return;
|
||||
}
|
||||
let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
|
||||
assert!(encoder.encode_dmabuf(&frame, true, &mut |_| {}).is_err(), "/dev/null imported");
|
||||
drop(encoder);
|
||||
let mut encoder = FfmpegEncoder::new("h264_vaapi", EncoderConfig::default()).unwrap();
|
||||
assert!(encoder.encode_dmabuf(&frame, true, &mut |_| {}).is_err());
|
||||
let black = voelin_media::VideoFrame::black_i420(W, H);
|
||||
assert!(!encoder.encode(&black, true).unwrap().is_empty(), "no packet after a failed import");
|
||||
}
|
||||
@@ -200,7 +200,34 @@ impl Daemons {
|
||||
std::fs::write(
|
||||
conf.join("voelin-test-sink.conf"),
|
||||
"context.objects = [ { factory = adapter args = { factory.name = support.null-audio-sink \
|
||||
node.name = voelin-test-sink media.class = Audio/Sink audio.position = [ FL FR ] } } ]\n",
|
||||
node.name = voelin-test-sink media.class = Audio/Sink audio.position = [ FL FR ] \
|
||||
priority.session = 3000 priority.driver = 3000 } } ]\n",
|
||||
)
|
||||
.unwrap();
|
||||
// No hardware: WirePlumber's default profile monitors the sound
|
||||
// cards, Bluetooth and cameras, and the tones would play on the
|
||||
// machine's real speakers. 0.5 reads the profile, 0.4 the Lua
|
||||
// fragments; each ignores the other's files.
|
||||
let wireplumber_conf = dir.join("config/wireplumber");
|
||||
for sub in ["wireplumber.conf.d", "main.lua.d", "bluetooth.lua.d"] {
|
||||
std::fs::create_dir_all(wireplumber_conf.join(sub)).unwrap();
|
||||
}
|
||||
std::fs::write(
|
||||
wireplumber_conf.join("wireplumber.conf.d/voelin-test.conf"),
|
||||
"wireplumber.profiles = { main = { hardware.audio = disabled \
|
||||
hardware.bluetooth = disabled hardware.video-capture = disabled } }\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
wireplumber_conf.join("main.lua.d/51-voelin-test.lua"),
|
||||
"if alsa_monitor then alsa_monitor.enabled = false end\n\
|
||||
if v4l2_monitor then v4l2_monitor.enabled = false end\n\
|
||||
if libcamera_monitor then libcamera_monitor.enabled = false end\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(
|
||||
wireplumber_conf.join("bluetooth.lua.d/51-voelin-test.lua"),
|
||||
"if bluez_monitor then bluez_monitor.enabled = false end\n",
|
||||
)
|
||||
.unwrap();
|
||||
let mut command = Command::new(pipewire);
|
||||
|
||||
@@ -10,7 +10,8 @@ publish.workspace = true
|
||||
|
||||
[features]
|
||||
default = ["portal", "x11"]
|
||||
# Wayland global shortcuts through xdg-desktop-portal (Linux).
|
||||
# Wayland global shortcuts and the file chooser through xdg-desktop-portal
|
||||
# (Linux).
|
||||
portal = ["dep:ashpd", "dep:futures-util"]
|
||||
# X11 global hotkeys through XInput2 raw events (Linux).
|
||||
x11 = ["dep:x11rb"]
|
||||
@@ -23,7 +24,7 @@ tokio = { version = "1", features = ["rt", "sync"] }
|
||||
tracing = "0.1"
|
||||
|
||||
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
|
||||
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts"], optional = true }
|
||||
ashpd = { version = "0.13", default-features = false, features = ["tokio", "global_shortcuts", "file_chooser"], optional = true }
|
||||
futures-util = { version = "0.3", optional = true }
|
||||
notify-rust = { version = "4.18", default-features = false, features = ["z-with-tokio"] }
|
||||
x11rb = { version = "0.13", features = ["xinput"], optional = true }
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
//! Asking the user for a file.
|
||||
//!
|
||||
//! Linux uses xdg-desktop-portal's file chooser (feature `portal`), which
|
||||
//! works on Wayland and X11 and inside a Flatpak. Other platforms have no
|
||||
//! backend yet; [`available`] says so, so a window can hide what it cannot
|
||||
//! offer.
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::{Error, Result};
|
||||
|
||||
/// Whether [`pick_file`] can ask the user.
|
||||
pub const fn available() -> bool {
|
||||
cfg!(all(unix, not(target_os = "macos"), feature = "portal"))
|
||||
}
|
||||
|
||||
/// Ask the user for one existing file; `None` when they cancelled.
|
||||
pub async fn pick_file(title: &str) -> Result<Option<PathBuf>> {
|
||||
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
|
||||
return portal_pick(title).await;
|
||||
#[cfg(not(all(unix, not(target_os = "macos"), feature = "portal")))]
|
||||
{
|
||||
let _ = title;
|
||||
Err(Error::Unsupported("no file chooser on this platform".into()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
|
||||
async fn portal_pick(title: &str) -> Result<Option<PathBuf>> {
|
||||
use ashpd::desktop::file_chooser::SelectedFiles;
|
||||
|
||||
let request = SelectedFiles::open_file()
|
||||
.title(title)
|
||||
.multiple(false)
|
||||
.modal(true)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| Error::Backend(e.to_string()))?;
|
||||
let files = match request.response() {
|
||||
Ok(files) => files,
|
||||
// Cancelling is not a failure.
|
||||
Err(ashpd::Error::Response(_)) => return Ok(None),
|
||||
Err(e) => return Err(Error::Backend(e.to_string())),
|
||||
};
|
||||
Ok(files.uris().first().and_then(|uri| file_uri_path(uri.as_str())))
|
||||
}
|
||||
|
||||
/// The path of a `file://` URI, with percent escapes resolved.
|
||||
#[cfg(all(unix, not(target_os = "macos"), feature = "portal"))]
|
||||
fn file_uri_path(uri: &str) -> Option<PathBuf> {
|
||||
let rest = uri.strip_prefix("file://")?;
|
||||
// file:///path and file://localhost/path both mean a local file.
|
||||
let path = rest.strip_prefix("localhost").unwrap_or(rest);
|
||||
let bytes = path.as_bytes();
|
||||
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
if bytes[i] == b'%' && i + 2 < bytes.len() {
|
||||
let hex = std::str::from_utf8(&bytes[i + 1..i + 3]).ok()?;
|
||||
if let Ok(byte) = u8::from_str_radix(hex, 16) {
|
||||
out.push(byte);
|
||||
i += 3;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
out.push(bytes[i]);
|
||||
i += 1;
|
||||
}
|
||||
let path = PathBuf::from(String::from_utf8(out).ok()?);
|
||||
path.is_absolute().then_some(path)
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix, not(target_os = "macos"), feature = "portal"))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn paths_of_file_uris() {
|
||||
assert_eq!(file_uri_path("file:///tmp/a%20b.png"), Some("/tmp/a b.png".into()));
|
||||
assert_eq!(file_uri_path("file://localhost/tmp/x"), Some("/tmp/x".into()));
|
||||
assert_eq!(file_uri_path("https://example.com/x"), None);
|
||||
assert_eq!(file_uri_path("file://relative"), None);
|
||||
}
|
||||
}
|
||||
@@ -3,12 +3,14 @@
|
||||
//! - [`hotkey`]: global push-to-talk hotkeys with press and release events
|
||||
//! (xdg-desktop-portal on Wayland, XInput2 on X11, a keyboard hook on
|
||||
//! Windows)
|
||||
//! - [`files`]: asking the user for a file (xdg-desktop-portal)
|
||||
//! - [`notify`]: desktop notifications
|
||||
//! - [`paths`]: data, config, cache and state directories
|
||||
//! - [`crash`]: opt-in local crash reports (panic hook)
|
||||
//! - [`notices`]: third-party notices for the About page
|
||||
|
||||
pub mod crash;
|
||||
pub mod files;
|
||||
pub mod hotkey;
|
||||
pub mod notices;
|
||||
pub mod notify;
|
||||
|
||||
@@ -178,6 +178,11 @@ pub enum PeerError {
|
||||
Io(#[from] std::io::Error),
|
||||
#[error("invalid SDP: {0}")]
|
||||
Sdp(String),
|
||||
/// The offer's video uses none of the codecs we decode.
|
||||
#[error(
|
||||
"no video codec in common: the stream offers {offered}, this client decodes {accepted}"
|
||||
)]
|
||||
NoCommonCodec { offered: String, accepted: String },
|
||||
#[error("WebRTC: {0}")]
|
||||
Rtc(#[from] RtcError),
|
||||
#[error("no usable local address")]
|
||||
@@ -304,10 +309,24 @@ impl Peer {
|
||||
/// Viewer side: accept the streamer's offer; returns our SDP answer.
|
||||
pub async fn answer(config: &PeerConfig, offer: &str) -> Result<(Self, String), PeerError> {
|
||||
// Our codecs in the order of the offer, then the rest.
|
||||
let mut codecs: Vec<_> = offered_video_codecs(offer)
|
||||
.into_iter()
|
||||
.filter(|c| config.accept_video_codecs.contains(c))
|
||||
.collect();
|
||||
let offered = offered_video_codecs(offer);
|
||||
let mut codecs: Vec<_> =
|
||||
offered.iter().copied().filter(|c| config.accept_video_codecs.contains(c)).collect();
|
||||
// Without one, the answer's video section would list no payload type,
|
||||
// which no peer (str0m included) can parse.
|
||||
if config.video
|
||||
&& codecs.is_empty()
|
||||
&& offer.lines().any(|l| l.trim_start().starts_with("m=video "))
|
||||
{
|
||||
let names = |codecs: &[VideoCodec]| match codecs {
|
||||
[] => "none we know".to_owned(),
|
||||
_ => codecs.iter().map(|c| c.sdp_name()).collect::<Vec<_>>().join(", "),
|
||||
};
|
||||
return Err(PeerError::NoCommonCodec {
|
||||
offered: names(&offered),
|
||||
accepted: names(&config.accept_video_codecs),
|
||||
});
|
||||
}
|
||||
for c in &config.accept_video_codecs {
|
||||
if !codecs.contains(c) {
|
||||
codecs.push(*c);
|
||||
@@ -924,6 +943,23 @@ mod tests {
|
||||
assert_eq!(offered_video_codecs(&answer), [VideoCodec::Vp8], "{answer}");
|
||||
}
|
||||
|
||||
/// An offer of codecs we cannot decode is refused with the reason, not
|
||||
/// answered with a video section the streamer cannot parse.
|
||||
#[tokio::test]
|
||||
async fn no_common_codec_is_refused() {
|
||||
let streamer =
|
||||
PeerConfig { video_codecs: vec![VideoCodec::H264], ..PeerConfig::loopback() };
|
||||
let (_peer, offer) = Peer::offer(&streamer, "s").await.unwrap();
|
||||
let vp8_only =
|
||||
PeerConfig { accept_video_codecs: vec![VideoCodec::Vp8], ..PeerConfig::loopback() };
|
||||
let error = Peer::answer(&vp8_only, &offer).await.err().expect("refused");
|
||||
assert!(matches!(error, PeerError::NoCommonCodec { .. }), "{error}");
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"no video codec in common: the stream offers H264, this client decodes VP8"
|
||||
);
|
||||
}
|
||||
|
||||
/// Several codecs offered: the streamer learns which one each viewer's
|
||||
/// answer chose; H.264 carries the level the stream needs.
|
||||
#[tokio::test]
|
||||
|
||||
@@ -31,6 +31,8 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
|
||||
unicode-segmentation = "1.13"
|
||||
voelin-audio = { path = "../voelin-audio" }
|
||||
voelin-core = { path = "../voelin-core", default-features = false, features = ["audio-device"] }
|
||||
# Gateway data types (topics, pins, reactions, capability names).
|
||||
voelin-gateway-proto = { path = "../voelin-gateway-proto" }
|
||||
voelin-model = { path = "../voelin-model" }
|
||||
# Crash reports and notices everywhere; hotkey backends on desktop (below).
|
||||
voelin-platform = { path = "../voelin-platform", default-features = false }
|
||||
|
||||
@@ -19,8 +19,10 @@ use tokio::runtime::Runtime;
|
||||
use tracing::warn;
|
||||
use voelin_core::settings::{AUDIO, CRASH_REPORTS, Settings};
|
||||
use voelin_core::stream::StreamInfo;
|
||||
use voelin_core::{AudioSettings, Command, Engine, Event, SessionState, VoiceState};
|
||||
use voelin_model::{Capabilities, ChannelId, ChatTarget, Presence};
|
||||
use voelin_core::{
|
||||
AudioSettings, Command, Engine, Event, History, HistoryMessage, SessionState, VoiceState,
|
||||
};
|
||||
use voelin_model::{Capabilities, ChannelId, ChatTarget, GroupInfo, Presence};
|
||||
use voelin_platform::crash;
|
||||
use voelin_store::{Bookmark, MemorySecrets, Secrets, Store};
|
||||
|
||||
@@ -108,20 +110,76 @@ impl Secrets for FallbackSecrets {
|
||||
}
|
||||
}
|
||||
|
||||
/// A message of a chat with the handle the UI knows it by: the engine's
|
||||
/// local ids are 64 bit, a Slint `int` is not.
|
||||
pub(crate) struct Msg {
|
||||
pub key: i32,
|
||||
pub message: HistoryMessage,
|
||||
}
|
||||
|
||||
/// A chat of a session: its lines are the model the chat view shows while
|
||||
/// the tab is selected, so a new message is one row appended.
|
||||
pub(crate) struct Tab {
|
||||
pub target: ChatTarget,
|
||||
pub title: String,
|
||||
pub lines: Rc<VecModel<ChatLine>>,
|
||||
/// The last message, for grouping the next one.
|
||||
/// The messages, oldest first, by `(ts_ms, id)`.
|
||||
pub messages: Vec<Msg>,
|
||||
/// Live messages of a session that keeps no history (no server unique
|
||||
/// id yet): grouped from the message before, without ids.
|
||||
pub last: Option<Previous>,
|
||||
pub unread: i32,
|
||||
/// Nothing older exists as far as the engine can tell.
|
||||
pub complete: bool,
|
||||
/// A gateway page arrived: the chat is not only what we saw.
|
||||
pub synced: bool,
|
||||
/// An older page was asked for.
|
||||
pub loading: bool,
|
||||
/// The next message handle.
|
||||
next_key: i32,
|
||||
/// The pins of this chat, once asked for.
|
||||
pub pins: Vec<crate::chat::PinRow>,
|
||||
pub pins_loaded: bool,
|
||||
/// The gateway topics of this chat, and the open one with its messages.
|
||||
pub topics: Vec<voelin_gateway_proto::TopicInfo>,
|
||||
pub topics_loaded: bool,
|
||||
pub topic: Option<i64>,
|
||||
pub topic_messages: Vec<Msg>,
|
||||
/// The message jumped to from the pins.
|
||||
pub marked: Option<i64>,
|
||||
}
|
||||
|
||||
impl Tab {
|
||||
pub fn new(target: ChatTarget, title: String) -> Self {
|
||||
Self { target, title, lines: Rc::new(VecModel::default()), last: None, unread: 0 }
|
||||
Self {
|
||||
target,
|
||||
title,
|
||||
lines: Rc::new(VecModel::default()),
|
||||
messages: Vec::new(),
|
||||
last: None,
|
||||
unread: 0,
|
||||
complete: false,
|
||||
synced: false,
|
||||
loading: false,
|
||||
next_key: 1,
|
||||
pins: Vec::new(),
|
||||
pins_loaded: false,
|
||||
topics: Vec::new(),
|
||||
topics_loaded: false,
|
||||
topic: None,
|
||||
topic_messages: Vec::new(),
|
||||
marked: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A handle for a message that has none yet.
|
||||
pub fn take_key(&mut self) -> i32 {
|
||||
self.next_key += 1;
|
||||
self.next_key
|
||||
}
|
||||
|
||||
pub fn message(&self, key: i32) -> Option<&HistoryMessage> {
|
||||
self.messages.iter().chain(&self.topic_messages).find(|m| m.key == key).map(|m| &m.message)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -140,6 +198,23 @@ pub(crate) struct SessionView {
|
||||
pub streams: Vec<StreamInfo>,
|
||||
/// Clients whose stored volume was sent for this voice connection.
|
||||
pub applied_playback: HashSet<u16>,
|
||||
/// Avatar pictures in the engine's cache, by unique id
|
||||
/// ([`Event::AvatarReady`]).
|
||||
pub avatars: HashMap<String, PathBuf>,
|
||||
/// Icons in the engine's cache, by icon id ([`Event::IconReady`]).
|
||||
pub icons: HashMap<u32, PathBuf>,
|
||||
/// The server groups in display order ([`Event::Groups`]).
|
||||
pub server_groups: Vec<GroupInfo>,
|
||||
/// What the session's gateway offers (`voelin_gateway_proto::feature`).
|
||||
pub gateway_caps: Vec<String>,
|
||||
/// The client whose member card is open.
|
||||
pub member_card: Option<u16>,
|
||||
/// Viewers of the streams in the gateway's directory, by stream id.
|
||||
pub stream_viewers: HashMap<String, u32>,
|
||||
/// Downloads started from chat, by transfer id.
|
||||
pub downloads: HashMap<u64, crate::chat::Download>,
|
||||
/// The next transfer id.
|
||||
pub next_transfer: u64,
|
||||
}
|
||||
|
||||
impl Default for SessionView {
|
||||
@@ -155,6 +230,14 @@ impl Default for SessionView {
|
||||
focused_own_channel: false,
|
||||
streams: Vec::new(),
|
||||
applied_playback: HashSet::new(),
|
||||
avatars: HashMap::new(),
|
||||
icons: HashMap::new(),
|
||||
server_groups: Vec::new(),
|
||||
gateway_caps: Vec::new(),
|
||||
member_card: None,
|
||||
stream_viewers: HashMap::new(),
|
||||
downloads: HashMap::new(),
|
||||
next_transfer: 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,6 +260,24 @@ impl SessionView {
|
||||
pub fn unread(&self) -> i32 {
|
||||
self.tabs.iter().map(|t| t.unread).sum()
|
||||
}
|
||||
|
||||
/// The session's gateway offers this feature
|
||||
/// (`voelin_gateway_proto::feature`).
|
||||
pub fn gateway_has(&self, feature: &str) -> bool {
|
||||
self.gateway_caps.iter().any(|c| c == feature)
|
||||
}
|
||||
|
||||
/// The chat history is kept by the engine (it knows the server): its
|
||||
/// messages come with ids, reactions and pins.
|
||||
pub fn has_history(&self) -> bool {
|
||||
self.state.server_uid.is_some()
|
||||
}
|
||||
|
||||
/// The avatar picture of a client, if the engine fetched one.
|
||||
pub fn avatar(&self, client: u16) -> Option<&PathBuf> {
|
||||
let uid = self.presence.clients.get(&client)?.uid.as_deref()?;
|
||||
self.avatars.get(uid)
|
||||
}
|
||||
}
|
||||
|
||||
/// The models the Bridge shows, created once and updated row by row
|
||||
@@ -185,9 +286,15 @@ pub(crate) struct Models {
|
||||
pub servers: Rc<VecModel<ServerItem>>,
|
||||
pub tree: Rc<VecModel<TreeItem>>,
|
||||
pub members: Rc<VecModel<MemberItem>>,
|
||||
pub server_members: Rc<VecModel<MemberItem>>,
|
||||
pub tabs: Rc<VecModel<ChatTab>>,
|
||||
pub streams: Rc<VecModel<StreamItem>>,
|
||||
pub viewers: Rc<VecModel<ViewerItem>>,
|
||||
pub pins: Rc<VecModel<PinItem>>,
|
||||
pub topics: Rc<VecModel<TopicItem>>,
|
||||
pub topic_messages: Rc<VecModel<ChatLine>>,
|
||||
/// The quality choices of the watched stream.
|
||||
pub qualities: Rc<VecModel<slint::SharedString>>,
|
||||
/// Shown when there is no chat.
|
||||
pub no_chat: Rc<VecModel<ChatLine>>,
|
||||
}
|
||||
@@ -198,17 +305,27 @@ impl Models {
|
||||
servers: Rc::default(),
|
||||
tree: Rc::default(),
|
||||
members: Rc::default(),
|
||||
server_members: Rc::default(),
|
||||
tabs: Rc::default(),
|
||||
streams: Rc::default(),
|
||||
viewers: Rc::default(),
|
||||
pins: Rc::default(),
|
||||
topics: Rc::default(),
|
||||
topic_messages: Rc::default(),
|
||||
qualities: Rc::default(),
|
||||
no_chat: Rc::default(),
|
||||
};
|
||||
bridge.set_servers(ModelRc::from(models.servers.clone()));
|
||||
bridge.set_tree(ModelRc::from(models.tree.clone()));
|
||||
bridge.set_members(ModelRc::from(models.members.clone()));
|
||||
bridge.set_server_members(ModelRc::from(models.server_members.clone()));
|
||||
bridge.set_tabs(ModelRc::from(models.tabs.clone()));
|
||||
bridge.set_streams(ModelRc::from(models.streams.clone()));
|
||||
bridge.set_share_viewers(ModelRc::from(models.viewers.clone()));
|
||||
bridge.set_pins(ModelRc::from(models.pins.clone()));
|
||||
bridge.set_topics(ModelRc::from(models.topics.clone()));
|
||||
bridge.set_topic_messages(ModelRc::from(models.topic_messages.clone()));
|
||||
bridge.set_viewer_qualities(ModelRc::from(models.qualities.clone()));
|
||||
bridge.set_messages(ModelRc::from(models.no_chat.clone()));
|
||||
models
|
||||
}
|
||||
@@ -227,6 +344,13 @@ pub(crate) struct App {
|
||||
pub status: String,
|
||||
/// The top bar's search: filters the channel tree.
|
||||
pub tree_filter: String,
|
||||
/// The members panel's search.
|
||||
pub member_filter: String,
|
||||
/// The topics drawer's search.
|
||||
pub topic_filter: String,
|
||||
/// The voice channel view is shown (its people come first in the
|
||||
/// members panel).
|
||||
pub voice_view: bool,
|
||||
/// The settings service (shared with the engine); `settings`, `audio`
|
||||
/// and `playback` are working copies of its keys.
|
||||
pub prefs: Settings,
|
||||
@@ -237,6 +361,8 @@ pub(crate) struct App {
|
||||
pub inputs: DeviceChoices,
|
||||
pub outputs: DeviceChoices,
|
||||
pub playback: ClientPlaybackMap,
|
||||
/// The engine's contacts, by unique id ([`Event::ContactsChanged`]).
|
||||
pub contacts: HashMap<String, voelin_core::Contact>,
|
||||
/// The client in the volume dialog: session, client id, unique id.
|
||||
pub playback_dialog: Option<(i64, u16, Option<String>)>,
|
||||
pub mic_test: bool,
|
||||
@@ -261,6 +387,9 @@ pub(crate) struct App {
|
||||
pub open_client_pending: bool,
|
||||
/// The notices are in the About page's model.
|
||||
pub notices_loaded: bool,
|
||||
/// Files being uploaded to a channel from the composer: session,
|
||||
/// channel and name, so the link can be posted when they are up.
|
||||
pub uploads: HashMap<u64, (i64, u64, String)>,
|
||||
/// The Stream Studio (studio.rs).
|
||||
pub studio: crate::studio::StudioState,
|
||||
}
|
||||
@@ -373,6 +502,12 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
};
|
||||
let store =
|
||||
Store::open(&dir.join("client.db")).context("failed to open the client database")?;
|
||||
// Chat history and contacts live in the client database; without this
|
||||
// the engine would keep them for this run only.
|
||||
match History::open(&dir.join("client.db")) {
|
||||
Ok(history) => engine.send(Command::AttachHistory(history)),
|
||||
Err(e) => warn!(%e, "chat history is not stored this time"),
|
||||
}
|
||||
let identity = match store.identities()?.first() {
|
||||
Some(entry) => store.identity(entry.id)?,
|
||||
None => {
|
||||
@@ -425,6 +560,9 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
models,
|
||||
status: String::new(),
|
||||
tree_filter: String::new(),
|
||||
member_filter: String::new(),
|
||||
topic_filter: String::new(),
|
||||
voice_view: false,
|
||||
prefs,
|
||||
settings,
|
||||
audio,
|
||||
@@ -432,6 +570,7 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
inputs: DeviceChoices::default(),
|
||||
outputs: DeviceChoices::default(),
|
||||
playback,
|
||||
contacts: HashMap::new(),
|
||||
playback_dialog: None,
|
||||
mic_test: false,
|
||||
ptt,
|
||||
@@ -446,6 +585,7 @@ pub fn run(options: RunOptions) -> Result<()> {
|
||||
autoshare: switches.autoshare,
|
||||
open_client_pending: switches.open_client,
|
||||
notices_loaded: false,
|
||||
uploads: HashMap::new(),
|
||||
studio: Default::default(),
|
||||
};
|
||||
APP.with(|a| *a.borrow_mut() = Some(app));
|
||||
@@ -666,7 +806,49 @@ impl App {
|
||||
Event::MicrophoneTestError { message } => {
|
||||
self.set_status(format!("Microphone test: {message}"))
|
||||
}
|
||||
Event::Chat { session, message } => self.add_message(session as i64, message),
|
||||
// Only for sessions the engine keeps no history for (it does not
|
||||
// know the server yet): those get ids and reactions instead.
|
||||
Event::Chat { session, message } => {
|
||||
let id = session as i64;
|
||||
if !self.sessions.entry(id).or_default().has_history() {
|
||||
self.add_message(id, message);
|
||||
}
|
||||
}
|
||||
Event::ChatHistory { session, target, messages, source, complete } => {
|
||||
self.history_batch(session as i64, &target, messages, source, complete);
|
||||
}
|
||||
Event::Gateway { session, update } => self.gateway_update(session as i64, update),
|
||||
Event::Groups { session, server_groups, .. } => {
|
||||
let view = self.sessions.entry(session as i64).or_default();
|
||||
view.server_groups = (*server_groups).clone();
|
||||
// Display order, as TeamSpeak sorts them.
|
||||
view.server_groups.sort_by_key(|g| (g.sort_id, g.id));
|
||||
if self.current == Some(session as i64) {
|
||||
self.refresh_tree();
|
||||
}
|
||||
}
|
||||
Event::AvatarReady { session, client_uid, path, .. } => {
|
||||
let view = self.sessions.entry(session as i64).or_default();
|
||||
view.avatars.insert(client_uid, path);
|
||||
if self.current == Some(session as i64) {
|
||||
self.refresh_tree();
|
||||
self.refresh_chat();
|
||||
}
|
||||
}
|
||||
Event::IconReady { session, icon, path } => {
|
||||
let view = self.sessions.entry(session as i64).or_default();
|
||||
view.icons.insert(icon, path);
|
||||
if self.current == Some(session as i64) {
|
||||
self.refresh_tree();
|
||||
}
|
||||
}
|
||||
Event::Transfer { session, transfer, state } => {
|
||||
self.transfer_progress(session as i64, transfer, state);
|
||||
}
|
||||
Event::ContactsChanged { contacts } => {
|
||||
self.contacts = contacts.iter().map(|c| (c.uid.clone(), c.clone())).collect();
|
||||
self.refresh_member_card();
|
||||
}
|
||||
// The sample sessions of VOELIN_DEMO_UI are unknown to the engine.
|
||||
Event::Error { .. } if self.demo_ui => {}
|
||||
Event::Error { message, .. } => self.set_status(message),
|
||||
|
||||
@@ -8,7 +8,7 @@ use tracing::warn;
|
||||
use crate::app::{App, AppearanceForm, Bridge, Nav, Theme};
|
||||
use crate::images;
|
||||
use crate::settings::{
|
||||
ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_NARROW_BREAKPOINT, UI_THEME,
|
||||
ThemeChoice, UI_FONT_SCALE, UI_IMAGE_CACHE_MB, UI_MEMBERS_WIDTH, UI_NARROW_BREAKPOINT, UI_THEME,
|
||||
};
|
||||
|
||||
impl App {
|
||||
@@ -23,7 +23,12 @@ impl App {
|
||||
let t = ui.global::<Theme>();
|
||||
t.set_mode(theme.as_str().into());
|
||||
t.set_font_scale(scale);
|
||||
ui.global::<Nav>().set_narrow_breakpoint(breakpoint as f32);
|
||||
let nav = ui.global::<Nav>();
|
||||
nav.set_narrow_breakpoint(breakpoint as f32);
|
||||
let width = self.prefs.get(&UI_MEMBERS_WIDTH) as f32;
|
||||
if nav.get_right_panel_width() != width {
|
||||
nav.set_right_panel_width(width);
|
||||
}
|
||||
let bridge = ui.global::<Bridge>();
|
||||
bridge.set_appearance(AppearanceForm {
|
||||
theme: theme.as_str().into(),
|
||||
@@ -54,4 +59,16 @@ impl App {
|
||||
// may not run the settings service (tests, a hosted engine).
|
||||
self.apply_appearance();
|
||||
}
|
||||
|
||||
/// The members panel was dragged to another width: store it, so it
|
||||
/// comes back the same and `--set ui.members_width` can change it.
|
||||
pub(crate) fn panel_resized(&mut self, width: f32) {
|
||||
let width = width.max(0.0).round() as u32;
|
||||
if self.prefs.get(&UI_MEMBERS_WIDTH) == width {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = self.prefs.set(&UI_MEMBERS_WIDTH, width) {
|
||||
warn!(%e, "could not store the panel width");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
//! The chat view.
|
||||
//! The chat view: tabs, messages, reactions, pins, topics and files.
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use voelin_model::{ChannelId, ChatTarget};
|
||||
|
||||
use crate::app::{Bridge, MainWindow, with_app};
|
||||
use crate::app::{App, Bridge, MainWindow, with_app};
|
||||
|
||||
pub(super) fn wire(ui: &MainWindow) {
|
||||
let bridge = ui.global::<Bridge>();
|
||||
bridge.on_search_topics(|text| {
|
||||
with_app(|app| app.search_topics(text.to_string()));
|
||||
});
|
||||
bridge.on_open_channel_chat(|cid| {
|
||||
with_app(|app| app.open_chat(ChatTarget::Channel(cid as ChannelId), true));
|
||||
});
|
||||
@@ -19,4 +22,46 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
bridge.on_send_message(|text| {
|
||||
with_app(|app| app.send_message(text.to_string()));
|
||||
});
|
||||
bridge.on_load_older(|| {
|
||||
with_app(App::load_older);
|
||||
});
|
||||
bridge.on_react(|key, emoji| {
|
||||
with_app(|app| app.react(key, emoji.to_string()));
|
||||
});
|
||||
bridge.on_pin(|key, on| {
|
||||
with_app(|app| app.pin(key, on));
|
||||
});
|
||||
bridge.on_download_file(|key, index| {
|
||||
with_app(|app| app.download_file(key, index));
|
||||
});
|
||||
bridge.on_attach_file(|| {
|
||||
with_app(App::attach_file);
|
||||
});
|
||||
bridge.on_open_pins(|| {
|
||||
with_app(App::open_pins);
|
||||
});
|
||||
bridge.on_jump_to_pin(|key| {
|
||||
with_app(|app| app.jump_to_pin(key));
|
||||
});
|
||||
bridge.on_open_topics(|| {
|
||||
with_app(App::open_topics);
|
||||
});
|
||||
bridge.on_open_topic(|id| {
|
||||
with_app(|app| app.open_topic(id));
|
||||
});
|
||||
bridge.on_send_topic_message(|text| {
|
||||
with_app(|app| app.send_topic_message(text.to_string()));
|
||||
});
|
||||
bridge.on_create_topic(|key, title| {
|
||||
with_app(|app| app.create_topic(key, title.to_string()));
|
||||
});
|
||||
bridge.on_open_member(|id| {
|
||||
with_app(|app| app.open_member(id));
|
||||
});
|
||||
bridge.on_member_action(|action| {
|
||||
with_app(|app| app.member_action(&action));
|
||||
});
|
||||
bridge.on_member_volume(|percent| {
|
||||
with_app(|app| app.member_volume(percent));
|
||||
});
|
||||
}
|
||||
@@ -35,7 +35,9 @@ fn show(ui: &MainWindow, category: i32, list: Vec<PickerEmoji>) {
|
||||
}
|
||||
|
||||
pub(super) fn wire(ui: &MainWindow) {
|
||||
ui.global::<Images>().on_emoji(|key| images::emoji(&key));
|
||||
let images_global = ui.global::<Images>();
|
||||
images_global.on_emoji(|key| images::emoji(&key));
|
||||
images_global.on_emoji_text(|key| emoji::text_of(&key).into());
|
||||
let global = ui.global::<Emoji>();
|
||||
let weak = ui.as_weak();
|
||||
global.on_load(move || {
|
||||
|
||||
@@ -14,6 +14,12 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
bridge.on_search(|text| {
|
||||
with_app(|app| app.search(text.to_string()));
|
||||
});
|
||||
bridge.on_search_members(|text| {
|
||||
with_app(|app| app.search_members(text.to_string()));
|
||||
});
|
||||
bridge.on_show_voice_view(|on| {
|
||||
with_app(|app| app.show_voice_view(on));
|
||||
});
|
||||
bridge.on_connect_voice(|| {
|
||||
with_app(|app| app.connect_voice());
|
||||
});
|
||||
|
||||
@@ -27,6 +27,9 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
bridge.on_download_h264(|| {
|
||||
with_app(|app| app.download_h264());
|
||||
});
|
||||
bridge.on_panel_resized(|width| {
|
||||
with_app(|app| app.panel_resized(width));
|
||||
});
|
||||
bridge.on_appearance_changed(|form| {
|
||||
with_app(|app| app.appearance_changed(&form));
|
||||
});
|
||||
|
||||
@@ -37,4 +37,7 @@ pub(super) fn wire(ui: &MainWindow) {
|
||||
bridge.on_toggle_fullscreen(|| {
|
||||
with_app(|app| app.toggle_fullscreen());
|
||||
});
|
||||
bridge.on_set_stream_quality(|index| {
|
||||
with_app(|app| app.set_stream_quality(index));
|
||||
});
|
||||
}
|
||||
@@ -1,13 +1,59 @@
|
||||
//! Chat: tabs per session (server, channels, private chats) and their
|
||||
//! messages. Each tab keeps its lines as a model; the chat view shows the
|
||||
//! selected tab's model, so a new message appends one row.
|
||||
//! Chat: tabs per session (server, channels, private chats), their
|
||||
//! messages, and what a gateway adds to them (pins, reactions, topics).
|
||||
//!
|
||||
//! The engine keeps the history: [`Event::ChatHistory`] is an upsert of
|
||||
//! messages by their local id (see `voelin_core::history`), so a tab holds
|
||||
//! the messages it was given, ordered by `(ts_ms, id)`, and the lines of
|
||||
//! the selected tab are rebuilt from them with [`vm::list::sync`], which
|
||||
//! touches only the rows that changed. Sessions the engine keeps no history
|
||||
//! for (it does not know the server yet) fall back to [`Event::Chat`].
|
||||
|
||||
use std::path::PathBuf;
|
||||
|
||||
use slint::{ComponentHandle, ModelRc};
|
||||
use voelin_core::Command;
|
||||
use voelin_core::gateway::Pin;
|
||||
use voelin_core::{
|
||||
Command, DownloadTo, GatewayRequest, GatewayUpdate, HistoryMessage, HistorySource,
|
||||
TransferState,
|
||||
};
|
||||
use voelin_gateway_proto::{TopicInfo, feature};
|
||||
use voelin_model::{ChatMessage, ChatTarget};
|
||||
|
||||
use crate::app::{App, Bridge, ChatTab, Tab};
|
||||
use crate::app::{App, Bridge, ChatLine, ChatTab, FileItem, Msg, PinItem, SessionView, Tab};
|
||||
use crate::vm;
|
||||
use crate::vm::chat::{LineCtx, Previous};
|
||||
|
||||
/// A file being downloaded from a chat message.
|
||||
pub(crate) struct Download {
|
||||
/// The message's handle and which of its links this is.
|
||||
pub key: i32,
|
||||
pub index: usize,
|
||||
pub name: String,
|
||||
pub state: TransferState,
|
||||
}
|
||||
|
||||
/// A pinned message of a chat, with who pinned it.
|
||||
pub(crate) struct PinRow {
|
||||
pub key: i32,
|
||||
pub message: HistoryMessage,
|
||||
pub by: String,
|
||||
pub ts_ms: i64,
|
||||
}
|
||||
|
||||
/// "3 min ago", "yesterday", "12 Mar".
|
||||
fn ago(ts_ms: i64) -> String {
|
||||
let Some(then) = chrono::DateTime::from_timestamp_millis(ts_ms) else { return String::new() };
|
||||
let minutes = (chrono::Utc::now() - then).num_minutes();
|
||||
match minutes {
|
||||
i64::MIN..=0 => "just now".into(),
|
||||
1 => "1 min ago".into(),
|
||||
2..=59 => format!("{minutes} min ago"),
|
||||
60..=119 => "1 hour ago".into(),
|
||||
120..=1439 => format!("{} hours ago", minutes / 60),
|
||||
1440..=2879 => "yesterday".into(),
|
||||
_ => then.with_timezone(&chrono::Local).format("%e %b").to_string().trim().into(),
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(crate) fn open_chat(&mut self, target: ChatTarget, focus: bool) {
|
||||
@@ -48,6 +94,7 @@ impl App {
|
||||
{
|
||||
view.current_tab = index;
|
||||
view.tabs[index].unread = 0;
|
||||
view.tabs[index].topic = None;
|
||||
}
|
||||
self.refresh_chat();
|
||||
self.refresh_servers();
|
||||
@@ -72,32 +119,47 @@ impl App {
|
||||
self.engine.send(Command::SendChat { session: id as u64, target, text });
|
||||
}
|
||||
|
||||
/// The index of `target`'s tab, opening one if it is new.
|
||||
fn tab_for(
|
||||
view: &mut SessionView,
|
||||
target: &ChatTarget,
|
||||
title: impl FnOnce() -> String,
|
||||
) -> usize {
|
||||
match view.tabs.iter().position(|t| t.target == *target) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
view.tabs.push(Tab::new(target.clone(), title()));
|
||||
view.tabs.len() - 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn tab_title(view: &SessionView, target: &ChatTarget, author: &str) -> String {
|
||||
match target {
|
||||
ChatTarget::Channel(cid) => format!(
|
||||
"#{}",
|
||||
view.presence
|
||||
.channels
|
||||
.get(cid)
|
||||
.map(|c| c.name.clone())
|
||||
.unwrap_or_else(|| cid.to_string())
|
||||
),
|
||||
ChatTarget::Private(_) => format!("@{author}"),
|
||||
ChatTarget::Server => "Server".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A live message of a session without stored history: appended as it
|
||||
/// comes, without an id.
|
||||
pub(crate) fn add_message(&mut self, id: i64, message: ChatMessage) {
|
||||
let current = self.current == Some(id);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let index = match view.tabs.iter().position(|t| t.target == message.target) {
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let title = match &message.target {
|
||||
ChatTarget::Channel(cid) => format!(
|
||||
"#{}",
|
||||
view.presence
|
||||
.channels
|
||||
.get(cid)
|
||||
.map(|c| c.name.clone())
|
||||
.unwrap_or_else(|| cid.to_string())
|
||||
),
|
||||
ChatTarget::Private(_) => format!("@{}", message.author_name),
|
||||
ChatTarget::Server => "Server".into(),
|
||||
};
|
||||
view.tabs.push(Tab::new(message.target.clone(), title));
|
||||
view.tabs.len() - 1
|
||||
}
|
||||
};
|
||||
let title = Self::tab_title(view, &message.target, &message.author_name);
|
||||
let index = Self::tab_for(view, &message.target, || title);
|
||||
let shown = current && view.current_tab == index;
|
||||
let tab = &mut view.tabs[index];
|
||||
let line = vm::chat::line(&message, tab.last.as_ref());
|
||||
tab.last = Some(vm::chat::Previous::of(&message));
|
||||
tab.last = Some(Previous::of(&message));
|
||||
tab.lines.push(line);
|
||||
if !shown {
|
||||
tab.unread += 1;
|
||||
@@ -110,55 +172,612 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// Messages the engine stored: added or updated by their local id.
|
||||
pub(crate) fn history_batch(
|
||||
&mut self,
|
||||
id: i64,
|
||||
target: &ChatTarget,
|
||||
messages: Vec<HistoryMessage>,
|
||||
source: HistorySource,
|
||||
complete: bool,
|
||||
) {
|
||||
let current = self.current == Some(id);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let author = messages.first().map_or("", |m| m.message.author_name.as_str());
|
||||
let title = Self::tab_title(view, target, author);
|
||||
let index = Self::tab_for(view, target, || title);
|
||||
let shown = current && view.current_tab == index;
|
||||
let tab = &mut view.tabs[index];
|
||||
if source == HistorySource::Gateway {
|
||||
tab.synced = true;
|
||||
}
|
||||
if source != HistorySource::Live {
|
||||
tab.loading = false;
|
||||
tab.complete = tab.complete || complete;
|
||||
}
|
||||
let mut fresh = 0;
|
||||
for message in messages {
|
||||
match tab.messages.iter().position(|m| m.message.id == message.id) {
|
||||
Some(i) => tab.messages[i].message = message,
|
||||
None => {
|
||||
let key = tab.take_key();
|
||||
if source == HistorySource::Live {
|
||||
fresh += 1;
|
||||
}
|
||||
tab.messages.push(Msg { key, message });
|
||||
}
|
||||
}
|
||||
}
|
||||
tab.messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id));
|
||||
if !shown {
|
||||
tab.unread += fresh;
|
||||
}
|
||||
if current {
|
||||
self.refresh_chat();
|
||||
}
|
||||
if fresh > 0 && !shown {
|
||||
self.refresh_servers();
|
||||
}
|
||||
}
|
||||
|
||||
/// The page of messages before the oldest one shown.
|
||||
pub(crate) fn load_older(&mut self) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(view) = self.sessions.get_mut(&id) else { return };
|
||||
let tab = &mut view.tabs[view.current_tab];
|
||||
if tab.loading || tab.complete {
|
||||
return;
|
||||
}
|
||||
tab.loading = true;
|
||||
let target = tab.target.clone();
|
||||
let before = tab.messages.first().map(|m| m.message.id);
|
||||
self.engine.send(Command::LoadOlderHistory { session: id as u64, target, before });
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
/// The lines of a tab, grouped and with everything the row shows.
|
||||
fn lines_of(&self, view: &SessionView, tab: &Tab, messages: &[Msg]) -> Vec<ChatLine> {
|
||||
let gateway = view.gateway_has(feature::PINS)
|
||||
|| view.gateway_has(feature::REACTIONS)
|
||||
|| view.gateway_has(feature::TOPICS);
|
||||
let mut previous: Option<Previous> = None;
|
||||
let mut lines = Vec::with_capacity(messages.len());
|
||||
for m in messages {
|
||||
let avatar =
|
||||
m.message.message.author_uid.as_ref().and_then(|uid| view.avatars.get(uid));
|
||||
let topic = m
|
||||
.message
|
||||
.topic_id
|
||||
.filter(|_| tab.topic.is_none())
|
||||
.and_then(|t| tab.topics.iter().find(|i| i.id == t))
|
||||
.map(|t| t.title.clone())
|
||||
.unwrap_or_default();
|
||||
let ctx = LineCtx {
|
||||
key: m.key,
|
||||
avatar: vm::avatar::image(avatar),
|
||||
gateway,
|
||||
marked: tab.marked == Some(m.message.id),
|
||||
topic,
|
||||
downloads: self.downloads_of(view, m.key),
|
||||
};
|
||||
lines.push(vm::chat::history_line(&m.message, previous.as_ref(), &ctx));
|
||||
previous = Some(Previous::of(&m.message.message));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// The file cards of a message that has downloads running.
|
||||
fn downloads_of(&self, view: &SessionView, key: i32) -> Vec<(usize, FileItem)> {
|
||||
view.downloads
|
||||
.values()
|
||||
.filter(|d| d.key == key)
|
||||
.map(|d| {
|
||||
let (detail, status, progress) = match &d.state {
|
||||
TransferState::Requested => ("Starting…".to_owned(), "running", 0.0),
|
||||
TransferState::Started { size, offset } => (
|
||||
format!(
|
||||
"{} of {}",
|
||||
vm::chat::size_text(*offset),
|
||||
vm::chat::size_text(*size)
|
||||
),
|
||||
"running",
|
||||
if *size > 0 { *offset as f32 / *size as f32 } else { 0.0 },
|
||||
),
|
||||
TransferState::Progress { done, size } => (
|
||||
format!("{} of {}", vm::chat::size_text(*done), vm::chat::size_text(*size)),
|
||||
"running",
|
||||
if *size > 0 { *done as f32 / *size as f32 } else { 0.0 },
|
||||
),
|
||||
TransferState::Done { size, .. } => {
|
||||
(format!("Downloaded · {}", vm::chat::size_text(*size)), "done", 1.0)
|
||||
}
|
||||
TransferState::Failed(e) => (e.clone(), "failed", 0.0),
|
||||
TransferState::Cancelled => ("Cancelled".to_owned(), "failed", 0.0),
|
||||
};
|
||||
(
|
||||
d.index,
|
||||
FileItem {
|
||||
name: d.name.clone().into(),
|
||||
detail: detail.into(),
|
||||
index: d.index as i32,
|
||||
state: status.into(),
|
||||
progress,
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Tabs and the shown tab's messages.
|
||||
pub(crate) fn refresh_chat(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let (tabs, lines) = match self.view() {
|
||||
None => (
|
||||
vec![ChatTab { title: "Server".into(), ..Default::default() }],
|
||||
ModelRc::from(self.models.no_chat.clone()),
|
||||
),
|
||||
Some(view) => {
|
||||
let tabs: Vec<ChatTab> = view
|
||||
.tabs
|
||||
.iter()
|
||||
.map(|t| ChatTab {
|
||||
title: t.title.clone().into(),
|
||||
name: t.title.trim_start_matches(['#', '@']).into(),
|
||||
kind: match t.target {
|
||||
ChatTarget::Server => 0,
|
||||
ChatTarget::Channel(_) => 1,
|
||||
ChatTarget::Private(_) => 2,
|
||||
},
|
||||
id: match t.target {
|
||||
ChatTarget::Channel(cid) => cid as i32,
|
||||
_ => 0,
|
||||
},
|
||||
unread: t.unread,
|
||||
topic: match t.target {
|
||||
ChatTarget::Channel(cid) => view
|
||||
.presence
|
||||
.channels
|
||||
.get(&cid)
|
||||
.and_then(|c| c.topic.clone())
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
_ => Default::default(),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
(tabs, ModelRc::from(view.tabs[view.current_tab].lines.clone()))
|
||||
let Some(view) = self.view() else {
|
||||
vm::list::sync(
|
||||
&self.models.tabs,
|
||||
&[ChatTab { title: "Server".into(), ..Default::default() }],
|
||||
);
|
||||
let empty = ModelRc::from(self.models.no_chat.clone());
|
||||
if bridge.get_messages() != empty {
|
||||
bridge.set_messages(empty);
|
||||
}
|
||||
return;
|
||||
};
|
||||
let tabs: Vec<ChatTab> = view
|
||||
.tabs
|
||||
.iter()
|
||||
.map(|t| ChatTab {
|
||||
title: t.title.clone().into(),
|
||||
name: t.title.trim_start_matches(['#', '@']).into(),
|
||||
kind: match t.target {
|
||||
ChatTarget::Server => 0,
|
||||
ChatTarget::Channel(_) => 1,
|
||||
ChatTarget::Private(_) => 2,
|
||||
},
|
||||
id: match t.target {
|
||||
ChatTarget::Channel(cid) => cid as i32,
|
||||
_ => 0,
|
||||
},
|
||||
unread: t.unread,
|
||||
topic: match t.target {
|
||||
ChatTarget::Channel(cid) => view
|
||||
.presence
|
||||
.channels
|
||||
.get(&cid)
|
||||
.and_then(|c| c.topic.clone())
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
_ => Default::default(),
|
||||
},
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.models.tabs, &tabs);
|
||||
let current = self.view().map_or(0, |v| v.current_tab as i32);
|
||||
let current = view.current_tab as i32;
|
||||
if bridge.get_current_tab() != current {
|
||||
bridge.set_current_tab(current);
|
||||
}
|
||||
// Swap the model only when another tab is shown.
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
// Sessions without stored history push their lines themselves.
|
||||
if view.has_history() {
|
||||
vm::list::sync(&tab.lines, &self.lines_of(view, tab, &tab.messages));
|
||||
}
|
||||
let lines = ModelRc::from(tab.lines.clone());
|
||||
if bridge.get_messages() != lines {
|
||||
bridge.set_messages(lines);
|
||||
}
|
||||
bridge.set_more_history(view.has_history() && !tab.complete);
|
||||
bridge.set_loading_history(tab.loading);
|
||||
bridge.set_local_history(
|
||||
view.has_history() && !tab.synced && view.gateway_has(feature::HISTORY),
|
||||
);
|
||||
bridge.set_has_pins(view.gateway_has(feature::PINS));
|
||||
bridge.set_has_reactions(view.gateway_has(feature::REACTIONS));
|
||||
bridge.set_has_topics(view.gateway_has(feature::TOPICS));
|
||||
bridge.set_pins_loading(!tab.pins_loaded && view.gateway_has(feature::PINS));
|
||||
bridge.set_topics_loading(!tab.topics_loaded && view.gateway_has(feature::TOPICS));
|
||||
let pins: Vec<PinItem> = tab
|
||||
.pins
|
||||
.iter()
|
||||
.map(|p| {
|
||||
let avatar =
|
||||
p.message.message.author_uid.as_ref().and_then(|u| view.avatars.get(u));
|
||||
let ctx = LineCtx {
|
||||
key: p.key,
|
||||
avatar: vm::avatar::image(avatar),
|
||||
gateway: true,
|
||||
..Default::default()
|
||||
};
|
||||
PinItem {
|
||||
line: vm::chat::history_line(&p.message, None, &ctx),
|
||||
by: format!("Pinned by {} · {}", p.by, vm::chat::time_of(p.ts_ms)).into(),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.models.pins, &pins);
|
||||
let filter = self.topic_filter.trim().to_lowercase();
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
let topics: Vec<crate::app::TopicItem> = tab
|
||||
.topics
|
||||
.iter()
|
||||
.filter(|t| filter.is_empty() || t.title.to_lowercase().contains(&filter))
|
||||
.map(|t| crate::app::TopicItem {
|
||||
id: t.id as i32,
|
||||
title: t.title.clone().into(),
|
||||
creator: t.creator.name.clone().into(),
|
||||
detail: format!(
|
||||
"{} {} · by {}",
|
||||
t.message_count,
|
||||
if t.message_count == 1 { "message" } else { "messages" },
|
||||
t.creator.name
|
||||
)
|
||||
.into(),
|
||||
activity: format!("Last active {}", ago(t.last_activity_ms)).into(),
|
||||
recent: now - t.last_activity_ms < 3_600_000,
|
||||
archived: t.archived,
|
||||
})
|
||||
.collect();
|
||||
vm::list::sync(&self.models.topics, &topics);
|
||||
bridge.set_current_topic(tab.topic.map_or(-1, |t| t as i32));
|
||||
bridge.set_topic_title(
|
||||
tab.topic
|
||||
.and_then(|t| tab.topics.iter().find(|i| i.id == t))
|
||||
.map(|t| t.title.clone())
|
||||
.unwrap_or_default()
|
||||
.into(),
|
||||
);
|
||||
vm::list::sync(&self.models.topic_messages, &self.lines_of(view, tab, &tab.topic_messages));
|
||||
}
|
||||
|
||||
// Gateway features of a chat.
|
||||
|
||||
/// A request to the current session's gateway.
|
||||
fn gateway(&self, request: GatewayRequest) {
|
||||
self.command(|session| Command::Gateway { session, request });
|
||||
}
|
||||
|
||||
pub(crate) fn gateway_update(&mut self, id: i64, update: GatewayUpdate) {
|
||||
let current = self.current == Some(id);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
match update {
|
||||
GatewayUpdate::Connected { capabilities, .. }
|
||||
| GatewayUpdate::Capabilities { capabilities } => view.gateway_caps = capabilities,
|
||||
GatewayUpdate::Disconnected { .. } => {
|
||||
view.gateway_caps.clear();
|
||||
for tab in &mut view.tabs {
|
||||
tab.pins_loaded = false;
|
||||
tab.topics_loaded = false;
|
||||
}
|
||||
}
|
||||
GatewayUpdate::Pins { target, pins } => {
|
||||
let index = Self::tab_for(view, &target, || "Server".into());
|
||||
let tab = &mut view.tabs[index];
|
||||
tab.pins_loaded = true;
|
||||
tab.pins = pins.into_iter().map(|p| pin_row(tab.take_key(), p)).collect();
|
||||
tab.pins.sort_by_key(|p| -p.ts_ms);
|
||||
}
|
||||
GatewayUpdate::Pinned { target, pin } => {
|
||||
let index = Self::tab_for(view, &target, || "Server".into());
|
||||
let tab = &mut view.tabs[index];
|
||||
let row = pin_row(tab.take_key(), pin);
|
||||
tab.pins.retain(|p| p.message.id != row.message.id);
|
||||
tab.pins.insert(0, row);
|
||||
}
|
||||
GatewayUpdate::Unpinned { target, message_id, .. } => {
|
||||
let index = Self::tab_for(view, &target, || "Server".into());
|
||||
view.tabs[index].pins.retain(|p| p.message.remote_id != Some(message_id));
|
||||
}
|
||||
GatewayUpdate::Topics { target, topics } => {
|
||||
let index = Self::tab_for(view, &target, || "Server".into());
|
||||
view.tabs[index].topics = topics;
|
||||
view.tabs[index].topics_loaded = true;
|
||||
}
|
||||
GatewayUpdate::Topic { topic } => {
|
||||
let index = Self::tab_for(view, &topic.target.clone(), || "Server".into());
|
||||
upsert_topic(&mut view.tabs[index].topics, topic);
|
||||
}
|
||||
GatewayUpdate::TopicHistory { target, topic, messages, .. } => {
|
||||
let index = Self::tab_for(view, &target, || "Server".into());
|
||||
let tab = &mut view.tabs[index];
|
||||
if tab.topic != Some(topic) {
|
||||
return;
|
||||
}
|
||||
for message in messages {
|
||||
match tab.topic_messages.iter().position(|m| m.message.id == message.id) {
|
||||
Some(i) => tab.topic_messages[i].message = message,
|
||||
None => {
|
||||
let key = tab.take_key();
|
||||
tab.topic_messages.push(Msg { key, message });
|
||||
}
|
||||
}
|
||||
}
|
||||
tab.topic_messages.sort_by_key(|m| (m.message.message.ts_ms, m.message.id));
|
||||
}
|
||||
GatewayUpdate::Failed { request, message, .. } => {
|
||||
self.set_status(format!("{request}: {message}"));
|
||||
return;
|
||||
}
|
||||
// The stream directory: how many watch each stream.
|
||||
GatewayUpdate::Streams { streams } => {
|
||||
view.stream_viewers = streams.iter().filter_map(viewers_of).collect();
|
||||
return self.stream_viewers_changed(current);
|
||||
}
|
||||
GatewayUpdate::StreamStarted { stream }
|
||||
| GatewayUpdate::StreamUpdated { stream }
|
||||
| GatewayUpdate::StreamRegistered { stream } => {
|
||||
if let Some((id, viewers)) = viewers_of(&stream) {
|
||||
view.stream_viewers.insert(id, viewers);
|
||||
}
|
||||
return self.stream_viewers_changed(current);
|
||||
}
|
||||
GatewayUpdate::StreamEnded { id, .. } => {
|
||||
view.stream_viewers.remove(&id);
|
||||
return self.stream_viewers_changed(current);
|
||||
}
|
||||
// Posts, pins and reactions also arrive as stored messages.
|
||||
_ => return,
|
||||
}
|
||||
if current {
|
||||
self.refresh_chat();
|
||||
}
|
||||
}
|
||||
|
||||
fn stream_viewers_changed(&self, current: bool) {
|
||||
if current {
|
||||
self.refresh_streams();
|
||||
self.refresh_viewer();
|
||||
}
|
||||
}
|
||||
|
||||
/// The message a Slint row stands for, in the current chat.
|
||||
fn message_of(&self, key: i32) -> Option<&HistoryMessage> {
|
||||
let view = self.view()?;
|
||||
view.tabs.get(view.current_tab)?.message(key)
|
||||
}
|
||||
|
||||
/// Add or remove our reaction to a message.
|
||||
pub(crate) fn react(&mut self, key: i32, emoji: String) {
|
||||
let Some(message) = self.message_of(key) else { return };
|
||||
let Some(message_id) = message.remote_id else { return };
|
||||
let had = message.reactions.iter().any(|r| r.emoji == emoji && r.me);
|
||||
self.gateway(if had {
|
||||
GatewayRequest::Unreact { message_id, emoji }
|
||||
} else {
|
||||
GatewayRequest::React { message_id, emoji }
|
||||
});
|
||||
}
|
||||
|
||||
pub(crate) fn pin(&mut self, key: i32, on: bool) {
|
||||
let Some(message) = self.message_of(key) else { return };
|
||||
let Some(message_id) = message.remote_id else { return };
|
||||
self.gateway(if on {
|
||||
GatewayRequest::Pin { message_id }
|
||||
} else {
|
||||
GatewayRequest::Unpin { message_id }
|
||||
});
|
||||
}
|
||||
|
||||
/// Open the pins of the current chat (loading them once).
|
||||
pub(crate) fn open_pins(&mut self) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
if !tab.pins_loaded {
|
||||
let target = tab.target.clone();
|
||||
self.gateway(GatewayRequest::Pins { target });
|
||||
}
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
/// Highlight a pinned message in the chat.
|
||||
pub(crate) fn jump_to_pin(&mut self, key: i32) {
|
||||
let Some(view) = self.view_mut() else { return };
|
||||
let tab = &mut view.tabs[view.current_tab];
|
||||
tab.marked = tab.pins.iter().find(|p| p.key == key).map(|p| p.message.id);
|
||||
// The message is in the chat, not in an open topic.
|
||||
if tab.topic.take().is_some() {
|
||||
tab.topic_messages.clear();
|
||||
}
|
||||
// Older than what is loaded: only highlighted once it is.
|
||||
let row = tab.marked.and_then(|id| tab.messages.iter().position(|m| m.message.id == id));
|
||||
self.refresh_chat();
|
||||
if let (Some(row), Some(ui)) = (row, self.ui.upgrade()) {
|
||||
let bridge = ui.global::<Bridge>();
|
||||
bridge.set_jump_index(row as i32);
|
||||
bridge.set_jump_requests(bridge.get_jump_requests().wrapping_add(1));
|
||||
}
|
||||
}
|
||||
|
||||
/// The topics drawer's search.
|
||||
pub(crate) fn search_topics(&mut self, text: String) {
|
||||
if self.topic_filter != text {
|
||||
self.topic_filter = text;
|
||||
self.refresh_chat();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn open_topics(&mut self) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
if !tab.topics_loaded {
|
||||
let target = tab.target.clone();
|
||||
self.gateway(GatewayRequest::Topics { target, include_archived: false });
|
||||
}
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
/// Show a topic's messages (`-1` goes back to the chat).
|
||||
pub(crate) fn open_topic(&mut self, id: i32) {
|
||||
let Some(view) = self.view_mut() else { return };
|
||||
let tab = &mut view.tabs[view.current_tab];
|
||||
tab.topic_messages.clear();
|
||||
tab.topic = (id >= 0).then_some(id as i64);
|
||||
let target = tab.target.clone();
|
||||
if let Some(topic) = tab.topic {
|
||||
self.gateway(GatewayRequest::TopicHistory { target, topic, before: None, limit: None });
|
||||
}
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
pub(crate) fn send_topic_message(&mut self, text: String) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let tab = &view.tabs[view.current_tab];
|
||||
let (Some(topic), target) = (tab.topic, tab.target.clone()) else { return };
|
||||
self.gateway(GatewayRequest::Post { target, text, topic: Some(topic) });
|
||||
}
|
||||
|
||||
/// Start a topic from a message (`key` < 0: a standalone topic).
|
||||
pub(crate) fn create_topic(&mut self, key: i32, title: String) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let target = view.tabs[view.current_tab].target.clone();
|
||||
let message_id = self.message_of(key).and_then(|m| m.remote_id);
|
||||
self.gateway(GatewayRequest::CreateTopic { target, title, message_id });
|
||||
}
|
||||
|
||||
// Files in chat.
|
||||
|
||||
/// Download a file a message links, into the download folder.
|
||||
pub(crate) fn download_file(&mut self, key: i32, index: i32) {
|
||||
let Some(id) = self.current else { return };
|
||||
let index = index.max(0) as usize;
|
||||
let Some(file) =
|
||||
self.message_of(key).and_then(|m| m.message.file_refs().into_iter().nth(index))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let dir = dirs::download_dir().unwrap_or_else(|| PathBuf::from("."));
|
||||
let path = dir.join(&file.name);
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let transfer = view.next_transfer;
|
||||
view.next_transfer += 1;
|
||||
view.downloads.insert(
|
||||
transfer,
|
||||
Download { key, index, name: file.name.clone(), state: TransferState::Requested },
|
||||
);
|
||||
self.engine.send(Command::DownloadChatFile {
|
||||
session: id as u64,
|
||||
transfer,
|
||||
file,
|
||||
password: None,
|
||||
to: DownloadTo::Path { path, resume: false },
|
||||
});
|
||||
self.refresh_chat();
|
||||
}
|
||||
|
||||
pub(crate) fn transfer_progress(&mut self, id: i64, transfer: u64, state: TransferState) {
|
||||
// An upload from the composer: post the file's link once it is up.
|
||||
if let Some((_, channel, name)) = self.uploads.get(&transfer).cloned() {
|
||||
match &state {
|
||||
TransferState::Done { size, .. } => {
|
||||
self.uploads.remove(&transfer);
|
||||
let file = voelin_model::FileRef {
|
||||
channel,
|
||||
path: "/".into(),
|
||||
name: name.clone(),
|
||||
size: Some(*size),
|
||||
..Default::default()
|
||||
};
|
||||
self.engine.send(Command::SendChat {
|
||||
session: id as u64,
|
||||
target: ChatTarget::Channel(channel),
|
||||
text: file.to_bbcode(),
|
||||
});
|
||||
self.set_status(format!("{name} shared"));
|
||||
}
|
||||
TransferState::Failed(e) => {
|
||||
self.uploads.remove(&transfer);
|
||||
self.set_status(format!("Could not upload {name}: {e}"));
|
||||
}
|
||||
TransferState::Cancelled => {
|
||||
self.uploads.remove(&transfer);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let done = matches!(state, TransferState::Done { .. });
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let Some(entry) = view.downloads.get_mut(&transfer) else { return };
|
||||
entry.state = state;
|
||||
let name = entry.name.clone();
|
||||
if done {
|
||||
self.set_status(format!("{name} downloaded"));
|
||||
}
|
||||
if self.current == Some(id) {
|
||||
self.refresh_chat();
|
||||
}
|
||||
}
|
||||
|
||||
/// Attach a file to the current channel chat: ask for one, upload it
|
||||
/// into the channel and post its link.
|
||||
pub(crate) fn attach_file(&mut self) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(view) = self.sessions.get(&id) else { return };
|
||||
let ChatTarget::Channel(channel) = view.tabs[view.current_tab].target else {
|
||||
self.set_status("Files can be attached to a channel's chat.");
|
||||
return;
|
||||
};
|
||||
if !voelin_platform::files::available() {
|
||||
self.set_status("No file chooser on this platform.");
|
||||
return;
|
||||
}
|
||||
let runtime = self.engine.runtime().clone();
|
||||
runtime.spawn(async move {
|
||||
let picked = voelin_platform::files::pick_file("Attach a file").await;
|
||||
crate::app::later(move |app| match picked {
|
||||
Ok(Some(path)) => app.upload(id, channel, path),
|
||||
Ok(None) => {}
|
||||
Err(e) => app.set_status(format!("Could not open the file chooser: {e}")),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Upload a file into a channel and link it in the chat once it is up.
|
||||
fn upload(&mut self, id: i64, channel: u64, from: PathBuf) {
|
||||
let Some(name) = from.file_name().map(|n| n.to_string_lossy().to_string()) else { return };
|
||||
let view = self.sessions.entry(id).or_default();
|
||||
let transfer = view.next_transfer;
|
||||
view.next_transfer += 1;
|
||||
self.uploads.insert(transfer, (id, channel, name.clone()));
|
||||
self.engine.send(Command::UploadFile {
|
||||
session: id as u64,
|
||||
transfer,
|
||||
channel,
|
||||
password: None,
|
||||
path: format!("/{name}"),
|
||||
from,
|
||||
overwrite: true,
|
||||
resume: false,
|
||||
});
|
||||
self.set_status(format!("Uploading {name}…"));
|
||||
}
|
||||
}
|
||||
|
||||
/// A directory entry's stream id and viewer count, when it has both.
|
||||
fn viewers_of(entry: &voelin_gateway_proto::StreamEntry) -> Option<(String, u32)> {
|
||||
Some((entry.stream_id.clone()?, entry.viewers?))
|
||||
}
|
||||
|
||||
fn pin_row(key: i32, pin: Pin) -> PinRow {
|
||||
PinRow { key, message: pin.message, by: pin.by.name, ts_ms: pin.ts_ms }
|
||||
}
|
||||
|
||||
fn upsert_topic(topics: &mut Vec<TopicInfo>, topic: TopicInfo) {
|
||||
match topics.iter().position(|t| t.id == topic.id) {
|
||||
Some(i) => topics[i] = topic,
|
||||
None => topics.insert(0, topic),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn relative_times() {
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
assert_eq!(ago(now), "just now");
|
||||
assert_eq!(ago(now - 3 * 60_000), "3 min ago");
|
||||
assert_eq!(ago(now - 3 * 3_600_000), "3 hours ago");
|
||||
assert_eq!(ago(now - 36 * 3_600_000), "yesterday");
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,11 @@
|
||||
//! `server`, `settings[:<section>]` (voice, keybinds, streaming, privacy,
|
||||
//! appearance, or 0-4), `about`, `share`, `bookmark` (add a server),
|
||||
//! `emoji` (the picker), `client` (the volume dialog of the first other
|
||||
//! client once connected), `panel` / `no-panel` (the right panel),
|
||||
//! client once connected), `panel` / `no-panel` (the members panel),
|
||||
//! `voice` (the voice channel view), `pins`, `topics` (the drawers),
|
||||
//! `topic:<id>` (a topic's messages), `member` (the member card of the
|
||||
//! first other client), `watch` (the first stream; with sample data the
|
||||
//! local test pattern in its place), `popout` (the same, popped out),
|
||||
//! `tab:<home|servers|chat|activity|you>` (phone layout),
|
||||
//! `studio[:<what>]`: the Stream Studio (with `VOELIN_DEMO_UI` a demo
|
||||
//! studio from synthetic sources), `studio:window` in a window of its own,
|
||||
@@ -31,12 +35,19 @@ use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
|
||||
use voelin_core::gateway::Pin;
|
||||
use voelin_core::stream::{StreamInfo, StreamKind};
|
||||
use voelin_core::{Event, ObserveState, SessionState, Source, VoiceState};
|
||||
use voelin_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, Presence, ServerFlavor};
|
||||
use voelin_store::Bookmark;
|
||||
use voelin_core::{
|
||||
Event, GatewayUpdate, HistoryMessage, HistorySource, ObserveState, SessionState, Source,
|
||||
VoiceState,
|
||||
};
|
||||
use voelin_gateway_proto::{ReactionCount, StreamEntry, StreamSource, TopicInfo, UserRef, feature};
|
||||
use voelin_model::{
|
||||
ChannelInfo, ChatMessage, ChatTarget, ClientInfo, GroupInfo, Presence, ServerFlavor,
|
||||
};
|
||||
use voelin_store::{Bookmark, MessageSource};
|
||||
|
||||
use crate::app::{App, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
|
||||
use crate::app::{App, Bridge, MainWindow, MobileTab, Nav, Page, SettingsSection, with_app};
|
||||
|
||||
/// The switches read at start.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
@@ -110,6 +121,7 @@ fn mobile_tab(name: &str) -> MobileTab {
|
||||
/// Timers that must live while the window runs.
|
||||
pub(crate) struct Running {
|
||||
_screenshot: Option<slint::Timer>,
|
||||
_resize: Option<slint::Timer>,
|
||||
}
|
||||
|
||||
/// Apply the switches once the app is set up.
|
||||
@@ -143,6 +155,27 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
|
||||
"panel" => nav.set_right_panel_open(true),
|
||||
"no-panel" => nav.set_right_panel_open(false),
|
||||
"tab" => nav.set_mobile_tab(mobile_tab(arg)),
|
||||
"voice" => nav.invoke_show_voice(true),
|
||||
"pins" => nav.invoke_show_pins(true),
|
||||
"topics" => nav.invoke_show_topics(true),
|
||||
"topic" => {
|
||||
with_app(|app| {
|
||||
app.open_topic(arg.parse().unwrap_or(1));
|
||||
// No gateway answers in demo mode.
|
||||
if switches.demo_ui {
|
||||
demo_topic(app);
|
||||
}
|
||||
});
|
||||
}
|
||||
"member" => {
|
||||
with_app(|app| app.open_first_member());
|
||||
}
|
||||
"watch" | "popout" => {
|
||||
with_app(|app| {
|
||||
if switches.demo_ui { app.demo_watch() } else { app.watch_first_stream() }
|
||||
});
|
||||
ui.global::<Bridge>().set_viewer_popped(what == "popout");
|
||||
}
|
||||
"studio" => {
|
||||
if arg != "window" {
|
||||
nav.invoke_open_studio();
|
||||
@@ -154,6 +187,23 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
|
||||
other => eprintln!("VOELIN_OPEN: unknown screen {other:?}"),
|
||||
}
|
||||
}
|
||||
// A window manager can refuse the size set before the window opened,
|
||||
// so ask again once it is up. (Under `xvfb-run` in a Wayland session,
|
||||
// remove WAYLAND_DISPLAY, or winit opens the window on the desktop.)
|
||||
let resize = switches.window_size.map(|(w, h)| {
|
||||
let weak = ui.as_weak();
|
||||
let timer = slint::Timer::default();
|
||||
timer.start(
|
||||
slint::TimerMode::SingleShot,
|
||||
Duration::from_millis(switches.screenshot_delay * 1000 / 2),
|
||||
move || {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.window().set_size(slint::LogicalSize::new(w, h));
|
||||
}
|
||||
},
|
||||
);
|
||||
timer
|
||||
});
|
||||
let screenshot = switches.screenshot.clone().map(|path| {
|
||||
let weak = ui.as_weak();
|
||||
let timer = slint::Timer::default();
|
||||
@@ -171,7 +221,7 @@ pub(crate) fn start(ui: &MainWindow, switches: &Switches) -> Running {
|
||||
);
|
||||
timer
|
||||
});
|
||||
Running { _screenshot: screenshot }
|
||||
Running { _screenshot: screenshot, _resize: resize }
|
||||
}
|
||||
|
||||
fn save_screenshot(ui: &MainWindow, path: &std::path::Path) -> Result<()> {
|
||||
@@ -279,14 +329,48 @@ fn demo_ui(app: &mut App) {
|
||||
clients[4].input_muted = true;
|
||||
clients[7].away = Some("brb".into());
|
||||
clients[8].output_muted = true;
|
||||
// Groups, badges and descriptions, as the members panel shows them.
|
||||
clients[0].server_groups = vec![GROUP_MOD];
|
||||
clients[0].talk_power = 75;
|
||||
clients[0].description = Some("Raid lead. Ask me about the Tuesday runs.".into());
|
||||
clients[1].server_groups = vec![GROUP_ADMIN];
|
||||
clients[1].talk_power = 100;
|
||||
clients[1].priority_speaker = true;
|
||||
clients[1].description = Some("Streaming most evenings.".into());
|
||||
clients[2].server_groups = vec![GROUP_MOD];
|
||||
clients[2].channel_commander = true;
|
||||
clients[2].talk_power = 75;
|
||||
clients[3].server_groups = vec![GROUP_MEMBER];
|
||||
clients[3].recording = true;
|
||||
clients[4].server_groups = vec![GROUP_MEMBER];
|
||||
clients[5].server_groups = vec![GROUP_MEMBER];
|
||||
clients[6].server_groups = vec![GROUP_GUEST];
|
||||
clients[7].server_groups = vec![GROUP_GUEST];
|
||||
for c in clients {
|
||||
p.clients.insert(c.id, c);
|
||||
}
|
||||
|
||||
let group = |id: u64, sort_id: i32, name: &str| GroupInfo {
|
||||
id,
|
||||
name: name.into(),
|
||||
icon: 0,
|
||||
sort_id,
|
||||
..Default::default()
|
||||
};
|
||||
let flavor = ServerFlavor::from_version_string("6.0.0-beta13.1 [Build: 1]");
|
||||
let capabilities = flavor.capabilities();
|
||||
let events = [
|
||||
Event::ServerInfo { session, name: "Nightfall Guild".into(), flavor, capabilities },
|
||||
Event::Groups {
|
||||
session,
|
||||
server_groups: Arc::new(vec![
|
||||
group(GROUP_ADMIN, 10, "Server Admin"),
|
||||
group(GROUP_MOD, 20, "Moderator"),
|
||||
group(GROUP_MEMBER, 30, "Member"),
|
||||
group(GROUP_GUEST, 40, "Guest"),
|
||||
]),
|
||||
channel_groups: Arc::new(Vec::new()),
|
||||
},
|
||||
Event::Presence { session, presence: Arc::new(p) },
|
||||
Event::State {
|
||||
session,
|
||||
@@ -295,9 +379,28 @@ fn demo_ui(app: &mut App) {
|
||||
presence_source: Some(Source::Voice),
|
||||
own_channel: Some(2),
|
||||
own_client: Some(1),
|
||||
// The engine keeps history for a server it knows, so the
|
||||
// chat is driven by `Event::ChatHistory` like a real one.
|
||||
server_uid: Some("demo-server".into()),
|
||||
..Default::default()
|
||||
},
|
||||
},
|
||||
// A gateway with everything the chat screens need.
|
||||
Event::Gateway {
|
||||
session,
|
||||
update: GatewayUpdate::Connected {
|
||||
gateway_id: "demo".into(),
|
||||
server_uid: "demo-server".into(),
|
||||
server_name: "Nightfall Guild".into(),
|
||||
uid: "demo-1".into(),
|
||||
capabilities: vec![
|
||||
feature::HISTORY.into(),
|
||||
feature::PINS.into(),
|
||||
feature::REACTIONS.into(),
|
||||
feature::TOPICS.into(),
|
||||
],
|
||||
},
|
||||
},
|
||||
Event::Talking { session, client: 3, talking: true },
|
||||
Event::StreamsChanged {
|
||||
session,
|
||||
@@ -319,61 +422,326 @@ fn demo_ui(app: &mut App) {
|
||||
for event in events {
|
||||
app.handle_event(event);
|
||||
}
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
let lines = [
|
||||
(
|
||||
DEMO,
|
||||
ChatTarget::Channel(2),
|
||||
"Nova",
|
||||
"Beautiful morning for a game. Who's up for a session later? ☀️",
|
||||
0,
|
||||
false,
|
||||
),
|
||||
(DEMO, ChatTarget::Channel(2), "Kairo", "Definitely! I'll be on after lunch.", 4, false),
|
||||
(DEMO, ChatTarget::Channel(2), "Kairo", "Bringing snacks 🍕🍩", 4, false),
|
||||
(
|
||||
DEMO,
|
||||
ChatTarget::Channel(2),
|
||||
"Mira",
|
||||
"Working on a new video today — here's a sneak peek soon! 🎬",
|
||||
7,
|
||||
false,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
ChatTarget::Channel(2),
|
||||
"Lumen",
|
||||
"Going live in Chill Zone — exploring the Lands Between. Come hang! 🔥🗡️",
|
||||
48,
|
||||
false,
|
||||
),
|
||||
(DEMO, ChatTarget::Channel(2), "dex", "🎉🎉", 50, false),
|
||||
(
|
||||
DEMO,
|
||||
ChatTarget::Channel(2),
|
||||
"Ari",
|
||||
"Anyone want to run some co-op later? 👀 Posting from the web.",
|
||||
55,
|
||||
true,
|
||||
),
|
||||
(DEMO, ChatTarget::Server, "Talon", "Server restart tonight at 23:00.", 20, false),
|
||||
(DEMO + 1, ChatTarget::Server, "Ivy", "Welcome to the lounge!", 30, false),
|
||||
(DEMO + 1, ChatTarget::Server, "Ivy", "New channel for artists 🎨", 31, false),
|
||||
];
|
||||
for (id, target, author, text, minute, relay) in lines {
|
||||
let message = ChatMessage {
|
||||
target,
|
||||
author_name: author.into(),
|
||||
author_uid: None,
|
||||
author_id: None,
|
||||
text: text.into(),
|
||||
ts_ms: now - (60 - minute) * 60_000,
|
||||
via_relay: relay,
|
||||
blocked: false,
|
||||
};
|
||||
app.add_message(id, message);
|
||||
}
|
||||
demo_chat(app, session);
|
||||
// No toast over the screenshots.
|
||||
app.set_status("");
|
||||
app.refresh_all();
|
||||
}
|
||||
|
||||
/// Server group ids of the sample server.
|
||||
const GROUP_ADMIN: u64 = 6;
|
||||
const GROUP_MOD: u64 = 7;
|
||||
const GROUP_MEMBER: u64 = 8;
|
||||
const GROUP_GUEST: u64 = 9;
|
||||
|
||||
/// A file link as TeamSpeak clients post it.
|
||||
fn file_link(channel: u64, name: &str, size: u64) -> String {
|
||||
voelin_model::FileRef {
|
||||
channel,
|
||||
path: "/".into(),
|
||||
name: name.into(),
|
||||
size: Some(size),
|
||||
..Default::default()
|
||||
}
|
||||
.to_bbcode()
|
||||
}
|
||||
|
||||
/// One sample message: chat, author, its client, text, how many minutes
|
||||
/// ago, relayed, reactions, pinned, and the topic it belongs to.
|
||||
type SampleLine =
|
||||
(i64, &'static str, u16, String, i64, bool, Vec<ReactionCount>, bool, Option<i64>);
|
||||
|
||||
/// The sample chats, as stored messages with reactions, pins and topics.
|
||||
fn demo_chat(app: &mut App, session: u64) {
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
let react =
|
||||
|emoji: &str, count: u32, me: bool| ReactionCount { emoji: emoji.into(), count, me };
|
||||
let lines: Vec<SampleLine> = vec![
|
||||
(
|
||||
DEMO,
|
||||
"Nova",
|
||||
1,
|
||||
"Beautiful morning for a game. Who's up for a session later? ☀️".into(),
|
||||
60,
|
||||
false,
|
||||
vec![react("👍", 3, false), react("☀️", 1, true)],
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Kairo",
|
||||
3,
|
||||
"Definitely! I'll be on after lunch.".into(),
|
||||
56,
|
||||
false,
|
||||
Vec::new(),
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(DEMO, "Kairo", 3, "Bringing snacks 🍕🍩".into(), 56, false, Vec::new(), false, None),
|
||||
(
|
||||
DEMO,
|
||||
"Mira",
|
||||
4,
|
||||
format!(
|
||||
"Route for tonight, print it out: {}",
|
||||
file_link(2, "raid-route.pdf", 2_411_724)
|
||||
),
|
||||
40,
|
||||
false,
|
||||
vec![react("🎉", 5, true)],
|
||||
true,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Nova",
|
||||
1,
|
||||
"Reminder: raid starts 20:00 sharp, bring elixirs.".into(),
|
||||
30,
|
||||
false,
|
||||
Vec::new(),
|
||||
true,
|
||||
Some(1),
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"dex",
|
||||
5,
|
||||
"Can somebody look at the wiki page? The old link is dead.".into(),
|
||||
26,
|
||||
false,
|
||||
Vec::new(),
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Kairo",
|
||||
3,
|
||||
"Fixed, it points at the new host now.".into(),
|
||||
24,
|
||||
false,
|
||||
vec![react("👍", 2, false)],
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Mira",
|
||||
4,
|
||||
format!("And the banner I promised: {}", file_link(2, "guild-banner.png", 486_912)),
|
||||
20,
|
||||
false,
|
||||
Vec::new(),
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Talon",
|
||||
6,
|
||||
"That looks great. Putting it on the site tonight.".into(),
|
||||
17,
|
||||
false,
|
||||
vec![react("❤️", 4, true)],
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(
|
||||
DEMO,
|
||||
"Lumen",
|
||||
2,
|
||||
"Going live in Chill Zone — exploring the Lands Between. Come hang! 🔥🗡️".into(),
|
||||
12,
|
||||
false,
|
||||
vec![react("🔥", 8, false)],
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(DEMO, "dex", 5, "🎉🎉".into(), 10, false, Vec::new(), false, None),
|
||||
(
|
||||
DEMO,
|
||||
"Ari",
|
||||
0,
|
||||
"Anyone want to run some co-op later? 👀 Posting from the web.".into(),
|
||||
5,
|
||||
true,
|
||||
Vec::new(),
|
||||
false,
|
||||
None,
|
||||
),
|
||||
(DEMO + 1, "Ivy", 0, "Welcome to the lounge!".into(), 30, false, Vec::new(), false, None),
|
||||
(
|
||||
DEMO + 1,
|
||||
"Ivy",
|
||||
0,
|
||||
"New channel for artists 🎨".into(),
|
||||
29,
|
||||
false,
|
||||
Vec::new(),
|
||||
false,
|
||||
None,
|
||||
),
|
||||
];
|
||||
let mut id = 1;
|
||||
let mut pinned: Vec<HistoryMessage> = Vec::new();
|
||||
for (chat, author, client, text, ago, relay, reactions, pin, topic) in lines {
|
||||
let target = if chat == DEMO { ChatTarget::Channel(2) } else { ChatTarget::Server };
|
||||
let message = HistoryMessage {
|
||||
id,
|
||||
message: ChatMessage {
|
||||
target: target.clone(),
|
||||
author_name: author.into(),
|
||||
author_uid: Some(format!("demo-{client}")),
|
||||
author_id: (client > 0).then_some(client),
|
||||
text,
|
||||
ts_ms: now - ago * 60_000,
|
||||
via_relay: relay,
|
||||
blocked: false,
|
||||
},
|
||||
source: MessageSource::Voice,
|
||||
remote_id: Some(id),
|
||||
topic_id: topic,
|
||||
reactions,
|
||||
pinned: pin,
|
||||
rev: 1,
|
||||
};
|
||||
if pin {
|
||||
pinned.push(message.clone());
|
||||
}
|
||||
app.handle_event(Event::ChatHistory {
|
||||
session: if chat == DEMO { session } else { session + 1 },
|
||||
target,
|
||||
messages: vec![message],
|
||||
source: HistorySource::Gateway,
|
||||
complete: false,
|
||||
});
|
||||
id += 1;
|
||||
}
|
||||
// A server chat besides the channel chat.
|
||||
app.handle_event(Event::ChatHistory {
|
||||
session,
|
||||
target: ChatTarget::Server,
|
||||
messages: vec![HistoryMessage {
|
||||
id: 100,
|
||||
message: ChatMessage {
|
||||
target: ChatTarget::Server,
|
||||
author_name: "Talon".into(),
|
||||
author_uid: Some("demo-6".into()),
|
||||
author_id: Some(6),
|
||||
text: "Server restart tonight at 23:00.".into(),
|
||||
ts_ms: now - 40 * 60_000,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
},
|
||||
source: MessageSource::Voice,
|
||||
remote_id: Some(100),
|
||||
topic_id: None,
|
||||
reactions: Vec::new(),
|
||||
pinned: false,
|
||||
rev: 1,
|
||||
}],
|
||||
source: HistorySource::Gateway,
|
||||
complete: true,
|
||||
});
|
||||
// The gateway's answers (no gateway runs in demo mode): the stream
|
||||
// directory, and the pins and topics for the drawers.
|
||||
app.handle_event(Event::Gateway {
|
||||
session,
|
||||
update: GatewayUpdate::Streams {
|
||||
streams: vec![StreamEntry {
|
||||
id: "demo-stream".into(),
|
||||
stream_id: Some("demo-stream".into()),
|
||||
streamer: UserRef { uid: "demo-2".into(), name: "Lumen".into() },
|
||||
client_id: Some(2),
|
||||
channel: Some(2),
|
||||
title: "Exploring the Lands Between".into(),
|
||||
kind: "screen".into(),
|
||||
started_ms: now - 12 * 60_000,
|
||||
viewers: Some(12),
|
||||
source: StreamSource::Registered,
|
||||
event_id: None,
|
||||
}],
|
||||
},
|
||||
});
|
||||
let by = |name: &str| UserRef { uid: format!("demo-{name}"), name: name.into() };
|
||||
app.handle_event(Event::Gateway {
|
||||
session,
|
||||
update: GatewayUpdate::Pins {
|
||||
target: ChatTarget::Channel(2),
|
||||
pins: pinned
|
||||
.into_iter()
|
||||
.map(|message| Pin {
|
||||
ts_ms: message.message.ts_ms + 60_000,
|
||||
by: by("Nova"),
|
||||
message,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
});
|
||||
let topic = |id: i64, title: &str, count: u64, ago: i64| TopicInfo {
|
||||
id,
|
||||
target: ChatTarget::Channel(2),
|
||||
title: title.into(),
|
||||
creator: by("Nova"),
|
||||
created_ms: now - 5 * 86_400_000,
|
||||
root_message_id: Some(5),
|
||||
last_activity_ms: now - ago * 60_000,
|
||||
message_count: count,
|
||||
archived: false,
|
||||
};
|
||||
app.handle_event(Event::Gateway {
|
||||
session,
|
||||
update: GatewayUpdate::Topics {
|
||||
target: ChatTarget::Channel(2),
|
||||
topics: vec![
|
||||
topic(1, "Tonight's raid", 14, 3),
|
||||
topic(2, "Build ideas for the new patch", 42, 95),
|
||||
topic(3, "Server rules", 6, 2880),
|
||||
],
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/// The messages of the sample topic, as the gateway answers when it is
|
||||
/// opened.
|
||||
fn demo_topic(app: &mut App) {
|
||||
let now = chrono::Utc::now().timestamp_millis();
|
||||
app.handle_event(Event::Gateway {
|
||||
session: DEMO as u64,
|
||||
update: GatewayUpdate::TopicHistory {
|
||||
target: ChatTarget::Channel(2),
|
||||
topic: 1,
|
||||
messages: (0..4)
|
||||
.map(|i| HistoryMessage {
|
||||
id: 200 + i,
|
||||
message: ChatMessage {
|
||||
target: ChatTarget::Channel(2),
|
||||
author_name: ["Nova", "Kairo", "Mira", "dex"][i as usize].into(),
|
||||
author_uid: Some(format!("demo-{}", [1, 3, 4, 5][i as usize])),
|
||||
author_id: Some([1, 3, 4, 5][i as usize]),
|
||||
text: [
|
||||
"Reminder: raid starts 20:00 sharp, bring elixirs.",
|
||||
"I can tank if nobody else wants to.",
|
||||
"Recording it again, say if you would rather not be in it.",
|
||||
"Bringing the good soup 🍲",
|
||||
][i as usize]
|
||||
.into(),
|
||||
ts_ms: now - (20 - i * 4) * 60_000,
|
||||
via_relay: false,
|
||||
blocked: false,
|
||||
},
|
||||
source: MessageSource::Gateway,
|
||||
remote_id: Some(200 + i),
|
||||
topic_id: Some(1),
|
||||
reactions: Vec::new(),
|
||||
pinned: false,
|
||||
rev: 1,
|
||||
})
|
||||
.collect(),
|
||||
has_more: false,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -253,7 +253,7 @@ fn key_of(cps: &[u32]) -> String {
|
||||
|
||||
/// The characters of an archive key, with U+FE0F after a lone character
|
||||
/// that is text by default, so other clients show an emoji too.
|
||||
fn text_of(key: &str) -> String {
|
||||
pub fn text_of(key: &str) -> String {
|
||||
let cps: Vec<u32> = key.split('-').filter_map(|p| u32::from_str_radix(p, 16).ok()).collect();
|
||||
let mut text: String = cps.iter().filter_map(|&cp| char::from_u32(cp)).collect();
|
||||
if cps.len() == 1 && !emoji_presentation(cps[0]) {
|
||||
@@ -294,6 +294,12 @@ pub fn key_for(grapheme: &str) -> Option<String> {
|
||||
archive.contains(&bare).then_some(bare)
|
||||
}
|
||||
|
||||
/// The archive key of the first emoji in `text` (a reaction's emoji, which
|
||||
/// may be any string).
|
||||
pub fn first_key(text: &str) -> Option<String> {
|
||||
text.graphemes(true).find_map(key_for)
|
||||
}
|
||||
|
||||
/// A piece of text: plain, or one emoji (`emoji` is its key).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Run {
|
||||
|
||||
@@ -101,6 +101,21 @@ pub fn usage_text() -> String {
|
||||
})
|
||||
}
|
||||
|
||||
/// A picture the engine put in its cache (avatars, group and client icons),
|
||||
/// decoded once and kept by its path.
|
||||
pub fn file(path: &std::path::Path) -> Image {
|
||||
let key = path.to_string_lossy();
|
||||
CACHE
|
||||
.with(|c| {
|
||||
c.borrow_mut().get_or_load(&key, || {
|
||||
let image = Image::load_from_path(path).ok()?;
|
||||
let size = image.size();
|
||||
Some((image, size.width as usize * size.height as usize * 4))
|
||||
})
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A Twemoji by key; an empty image if there is none.
|
||||
pub fn emoji(key: &str) -> Image {
|
||||
if key.is_empty() {
|
||||
|
||||
@@ -8,6 +8,7 @@ mod dev;
|
||||
mod emoji;
|
||||
mod hotkey;
|
||||
mod images;
|
||||
mod members;
|
||||
mod servers;
|
||||
mod settings;
|
||||
mod settings_page;
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
//! The members panel: the card over a member row and what it can do
|
||||
//! (private chat, poke, contacts, per-client volume). The rows themselves
|
||||
//! are built in `vm::tree::members`.
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use voelin_core::{Command, Contact, Relation};
|
||||
use voelin_model::ChatTarget;
|
||||
|
||||
use crate::app::{App, Bridge, MemberCard};
|
||||
use crate::settings::ClientPlayback;
|
||||
use crate::vm;
|
||||
|
||||
impl App {
|
||||
/// `VOELIN_OPEN=member`: the card of the first person that is not us.
|
||||
pub(crate) fn open_first_member(&mut self) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let own = view.state.own_client;
|
||||
let mut others: Vec<u16> = view
|
||||
.presence
|
||||
.members(view.state.own_channel.unwrap_or_default())
|
||||
.filter(|c| Some(c.id) != own)
|
||||
.map(|c| c.id)
|
||||
.collect();
|
||||
others.sort_unstable();
|
||||
if let Some(id) = others.first().copied() {
|
||||
self.open_member(i32::from(id));
|
||||
}
|
||||
}
|
||||
|
||||
/// Open the card of a client (`-1` closes it).
|
||||
pub(crate) fn open_member(&mut self, client: i32) {
|
||||
if let Some(view) = self.view_mut() {
|
||||
view.member_card = u16::try_from(client).ok();
|
||||
}
|
||||
self.refresh_member_card();
|
||||
}
|
||||
|
||||
pub(crate) fn refresh_member_card(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let card = self
|
||||
.view()
|
||||
.and_then(|view| {
|
||||
let id = view.member_card?;
|
||||
let client = view.presence.clients.get(&id)?;
|
||||
let uid = client.uid.clone();
|
||||
let contact = uid.as_ref().and_then(|u| self.contacts.get(u));
|
||||
let playback =
|
||||
uid.as_ref().and_then(|u| self.playback.get(u)).copied().unwrap_or_default();
|
||||
let groups: Vec<slint::SharedString> = client
|
||||
.server_groups
|
||||
.iter()
|
||||
.filter_map(|g| view.server_groups.iter().find(|i| i.id == *g))
|
||||
.map(|g| g.name.clone().into())
|
||||
.collect();
|
||||
Some(MemberCard {
|
||||
open: true,
|
||||
id: i32::from(id),
|
||||
name: client.nickname.clone().into(),
|
||||
initials: vm::avatar::initials(&client.nickname).into(),
|
||||
tint: vm::avatar::tint(&client.nickname),
|
||||
avatar: vm::avatar::image(view.avatar(id)),
|
||||
status: vm::tree::status_of(client, view.talking.contains(&id)).into(),
|
||||
description: client.description.clone().unwrap_or_default().into(),
|
||||
groups: crate::app::model(groups),
|
||||
country: client.country.clone().unwrap_or_default().into(),
|
||||
talk_power: client.talk_power,
|
||||
friend: contact.is_some_and(|c| c.relation == Relation::Friend),
|
||||
blocked: contact.is_some_and(|c| c.relation == Relation::Blocked),
|
||||
volume: playback.volume * 100.0,
|
||||
muted: playback.muted,
|
||||
known: uid.is_some(),
|
||||
})
|
||||
})
|
||||
.unwrap_or_default();
|
||||
bridge.set_member_card(card);
|
||||
}
|
||||
|
||||
/// The card's buttons: "message", "poke", "friend", "blocked", "mute".
|
||||
pub(crate) fn member_action(&mut self, action: &str) {
|
||||
let Some(id) = self.current else { return };
|
||||
let Some(view) = self.sessions.get(&id) else { return };
|
||||
let Some(client) = view.member_card.and_then(|c| view.presence.clients.get(&c)) else {
|
||||
return;
|
||||
};
|
||||
let (client_id, nickname, uid) = (client.id, client.nickname.clone(), client.uid.clone());
|
||||
match action {
|
||||
"message" => {
|
||||
if let Some(uid) = uid {
|
||||
self.open_chat(ChatTarget::Private(uid), true);
|
||||
self.open_member(-1);
|
||||
}
|
||||
}
|
||||
"poke" => {
|
||||
self.command(|session| Command::Poke {
|
||||
session,
|
||||
client: client_id,
|
||||
message: String::new(),
|
||||
});
|
||||
self.set_status(format!("Poked {nickname}"));
|
||||
}
|
||||
"friend" | "blocked" => {
|
||||
let Some(uid) = uid else { return };
|
||||
let wanted = if action == "friend" { Relation::Friend } else { Relation::Blocked };
|
||||
let current = self.contacts.get(&uid).map(|c| c.relation);
|
||||
let mut contact =
|
||||
self.contacts.get(&uid).cloned().unwrap_or_else(|| Contact::new(uid.clone()));
|
||||
contact.nickname = nickname;
|
||||
contact.relation = if current == Some(wanted) { Relation::Neutral } else { wanted };
|
||||
self.contacts.insert(uid, contact.clone());
|
||||
self.engine.send(Command::SetContact { contact: Box::new(contact) });
|
||||
self.refresh_member_card();
|
||||
}
|
||||
"mute" => {
|
||||
let Some(uid) = uid else { return };
|
||||
let mut playback = self.playback.get(&uid).copied().unwrap_or_default();
|
||||
playback.muted = !playback.muted;
|
||||
self.set_playback(&uid, client_id, playback);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The card's volume slider, in percent.
|
||||
pub(crate) fn member_volume(&mut self, percent: f32) {
|
||||
let Some(view) = self.view() else { return };
|
||||
let Some(client) = view.member_card.and_then(|c| view.presence.clients.get(&c)) else {
|
||||
return;
|
||||
};
|
||||
let (client_id, Some(uid)) = (client.id, client.uid.clone()) else { return };
|
||||
let mut playback = self.playback.get(&uid).copied().unwrap_or_default();
|
||||
playback.volume = (percent / 100.0).clamp(0.0, 4.0);
|
||||
self.set_playback(&uid, client_id, playback);
|
||||
}
|
||||
|
||||
/// Store one client's playback and apply it to the session.
|
||||
fn set_playback(&mut self, uid: &str, client: u16, playback: ClientPlayback) {
|
||||
if playback.is_default() {
|
||||
self.playback.remove(uid);
|
||||
} else {
|
||||
self.playback.insert(uid.to_owned(), playback);
|
||||
}
|
||||
if let Err(e) = self.prefs.set(&crate::settings::CLIENT_PLAYBACK, self.playback.clone()) {
|
||||
tracing::warn!(%e, "could not store client volumes");
|
||||
}
|
||||
self.command(|session| Command::SetClientMuted { session, client, muted: playback.muted });
|
||||
self.command(|session| Command::SetClientVolume {
|
||||
session,
|
||||
client,
|
||||
volume: playback.volume,
|
||||
});
|
||||
self.refresh_tree();
|
||||
self.refresh_member_card();
|
||||
}
|
||||
}
|
||||
@@ -226,11 +226,15 @@ impl App {
|
||||
.into(),
|
||||
);
|
||||
bridge.set_nickname(bookmark.map(|b| b.nickname.clone()).unwrap_or_default().into());
|
||||
let own_channel = view
|
||||
.and_then(|v| state.own_channel.and_then(|c| v.presence.channels.get(&c)))
|
||||
.map(|c| c.name.clone())
|
||||
.unwrap_or_default();
|
||||
bridge.set_own_channel(own_channel.into());
|
||||
let own_channel =
|
||||
view.and_then(|v| state.own_channel.and_then(|c| v.presence.channels.get(&c)));
|
||||
bridge.set_own_channel(own_channel.map(|c| c.name.clone()).unwrap_or_default().into());
|
||||
bridge.set_own_channel_topic(
|
||||
own_channel.and_then(|c| c.topic.clone()).unwrap_or_default().into(),
|
||||
);
|
||||
bridge.set_own_channel_limit(
|
||||
own_channel.and_then(|c| c.max_clients).filter(|m| *m >= 0).unwrap_or(-1),
|
||||
);
|
||||
bridge.set_voice_connected(state.voice == VoiceState::Connected);
|
||||
bridge.set_voice_connecting(state.voice == VoiceState::Connecting);
|
||||
bridge.set_observing(state.observe != ObserveState::Off);
|
||||
@@ -255,11 +259,13 @@ impl App {
|
||||
}
|
||||
}
|
||||
|
||||
/// The channel tree and the members of our channel.
|
||||
/// The channel tree, the members of our channel and everyone on the
|
||||
/// server.
|
||||
pub(crate) fn refresh_tree(&self) {
|
||||
let Some(view) = self.view() else {
|
||||
vm::list::sync(&self.models.tree, &[]);
|
||||
vm::list::sync(&self.models.members, &[]);
|
||||
vm::list::sync(&self.models.server_members, &[]);
|
||||
return;
|
||||
};
|
||||
let input = vm::tree::TreeInput {
|
||||
@@ -270,14 +276,44 @@ impl App {
|
||||
own_channel: view.state.own_channel,
|
||||
own_client: view.state.own_client,
|
||||
filter: &self.tree_filter,
|
||||
avatars: &view.avatars,
|
||||
icons: &view.icons,
|
||||
groups: &view.server_groups,
|
||||
};
|
||||
vm::list::sync(&self.models.tree, &vm::tree::rows(&input));
|
||||
let members = if view.state.voice == VoiceState::Connected {
|
||||
vm::tree::members(&input)
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let connected = view.state.voice == VoiceState::Connected;
|
||||
let members = if connected { vm::tree::members(&input) } else { Vec::new() };
|
||||
vm::list::sync(&self.models.members, &members);
|
||||
// The people in our channel first while their view is shown.
|
||||
let watching = self.watch.as_ref().is_some_and(|w| w.shown);
|
||||
let voice_first = connected && (self.voice_view || watching);
|
||||
let everyone = vm::tree::server_members(&input, voice_first);
|
||||
let filter = self.member_filter.trim().to_lowercase();
|
||||
let shown =
|
||||
if filter.is_empty() { everyone } else { vm::tree::matching(everyone, &filter) };
|
||||
vm::list::sync(&self.models.server_members, &shown);
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
let total = view.presence.clients.values().filter(|c| !c.is_query).count();
|
||||
ui.global::<crate::app::Bridge>().set_member_total(total as i32);
|
||||
}
|
||||
}
|
||||
|
||||
/// The members panel's search.
|
||||
pub(crate) fn search_members(&mut self, text: String) {
|
||||
if self.member_filter != text {
|
||||
self.member_filter = text;
|
||||
self.refresh_tree();
|
||||
}
|
||||
}
|
||||
|
||||
/// The voice channel view was opened or closed: its chat is our
|
||||
/// channel's, and its people lead the members panel.
|
||||
pub(crate) fn show_voice_view(&mut self, on: bool) {
|
||||
self.voice_view = on;
|
||||
if on && let Some(channel) = self.view().and_then(|v| v.state.own_channel) {
|
||||
self.open_chat(voelin_model::ChatTarget::Channel(channel), true);
|
||||
}
|
||||
self.refresh_tree();
|
||||
}
|
||||
|
||||
pub(crate) fn toggle_collapse(&mut self, channel: u64) {
|
||||
|
||||
@@ -91,9 +91,18 @@ pub static UI_IMAGE_CACHE_MB: Key<u32> = Key::new(
|
||||
|| 64,
|
||||
);
|
||||
|
||||
/// `ui.members_width`: how wide the members and streams panel is, in
|
||||
/// pixels. Dragging its handle stores it; there is no built-in maximum.
|
||||
pub static UI_MEMBERS_WIDTH: Key<u32> = Key::new(
|
||||
"ui.members_width",
|
||||
Kind::UInt { min: 0 },
|
||||
"Width of the members and streams panel in pixels.",
|
||||
|| 280,
|
||||
);
|
||||
|
||||
/// The UI's keys besides [`UI`] and [`CLIENT_PLAYBACK`], for registering.
|
||||
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 4] {
|
||||
[&UI_THEME, &UI_FONT_SCALE, &UI_NARROW_BREAKPOINT, &UI_IMAGE_CACHE_MB]
|
||||
pub fn appearance_keys() -> [&'static dyn voelin_core::settings::Setting; 5] {
|
||||
[&UI_THEME, &UI_FONT_SCALE, &UI_NARROW_BREAKPOINT, &UI_IMAGE_CACHE_MB, &UI_MEMBERS_WIDTH]
|
||||
}
|
||||
|
||||
/// Frame rates and bitrates (kbit/s) the share dialog offers; any other
|
||||
|
||||
@@ -6,7 +6,9 @@ use slint::{ComponentHandle, Model};
|
||||
use tracing::warn;
|
||||
use voelin_core::media::audio_source_specs;
|
||||
use voelin_core::settings::{STREAM_AUDIO_SOURCES, STREAM_BITRATE_KBPS, STREAM_FPS};
|
||||
use voelin_core::stream::{EndReason, LeaveReason, StreamSetup, ViewerInfo, ViewerState};
|
||||
use voelin_core::stream::{
|
||||
EndReason, LayerId, LayerSpec, LeaveReason, StreamKind, StreamSetup, ViewerInfo, ViewerState,
|
||||
};
|
||||
use voelin_core::{Command, Event, StreamState, WatchState};
|
||||
|
||||
use crate::app::{App, Bridge, ShareForm, SourceItem, StreamItem, ViewerItem, later, model};
|
||||
@@ -40,8 +42,45 @@ pub(crate) struct Watch {
|
||||
ended: bool,
|
||||
has_frame: bool,
|
||||
/// Shown instead of the chat.
|
||||
shown: bool,
|
||||
pub(crate) shown: bool,
|
||||
decoder: Option<Decoder>,
|
||||
/// When the picture started, for the elapsed time.
|
||||
since: Option<std::time::Instant>,
|
||||
/// The simulcast layers the streamer offers, largest first.
|
||||
layers: Vec<LayerSpec>,
|
||||
/// The layer chosen by hand; `None` follows the bandwidth estimate.
|
||||
layer: Option<LayerId>,
|
||||
}
|
||||
|
||||
impl Watch {
|
||||
/// "12:34" since the picture started.
|
||||
fn elapsed(&self) -> String {
|
||||
let Some(since) = self.since else { return String::new() };
|
||||
let seconds = since.elapsed().as_secs();
|
||||
match seconds / 3600 {
|
||||
0 => format!("{:02}:{:02}", seconds / 60, seconds % 60),
|
||||
hours => format!("{hours}:{:02}:{:02}", (seconds / 60) % 60, seconds % 60),
|
||||
}
|
||||
}
|
||||
|
||||
/// "Auto" and one entry per layer the streamer offers.
|
||||
fn qualities(&self) -> Vec<slint::SharedString> {
|
||||
if self.layers.len() < 2 {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut names = vec![slint::SharedString::from("Auto")];
|
||||
names.extend(self.layers.iter().map(|l| layer_name(l).into()));
|
||||
names
|
||||
}
|
||||
}
|
||||
|
||||
/// "720p · 2.4 Mbit/s", or the scale when the size is not fixed.
|
||||
fn layer_name(layer: &LayerSpec) -> String {
|
||||
let size = match layer.size {
|
||||
Some((_, h)) => format!("{h}p"),
|
||||
None => format!("{:.0}%", layer.scale * 100.0),
|
||||
};
|
||||
format!("{size} · {:.1} Mbit/s", layer.bitrate as f64 / 1_000_000.0)
|
||||
}
|
||||
|
||||
fn end_text(reason: &EndReason, streamer: &str) -> String {
|
||||
@@ -64,6 +103,16 @@ fn share_end_text(reason: &EndReason) -> String {
|
||||
}
|
||||
}
|
||||
|
||||
/// "8 Mbit/s", "640 kbit/s" (the stream's announced bitrate, kbit/s); "" for 0.
|
||||
fn bitrate_text(kbps: u32) -> String {
|
||||
match kbps {
|
||||
0 => String::new(),
|
||||
1..=999 => format!("{kbps} kbit/s"),
|
||||
_ if kbps.is_multiple_of(1000) => format!("{} Mbit/s", kbps / 1000),
|
||||
_ => format!("{:.1} Mbit/s", f64::from(kbps) / 1000.0),
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(crate) fn stream_event(&mut self, event: Event) {
|
||||
match event {
|
||||
@@ -175,9 +224,19 @@ impl App {
|
||||
id: s.id.clone().into(),
|
||||
name: s.name.clone().into(),
|
||||
streamer: view.nickname(s.streamer.0).into(),
|
||||
streamer_id: i32::from(s.streamer.0),
|
||||
viewers: view.stream_viewers.get(&s.id).map_or(0, |v| *v as i32),
|
||||
audio: s.audio,
|
||||
watching,
|
||||
own: view.state.own_client == Some(s.streamer.0),
|
||||
kind: match s.kind {
|
||||
StreamKind::Screen => "Screen",
|
||||
StreamKind::Window => "Window",
|
||||
StreamKind::Camera => "Camera",
|
||||
StreamKind::Other(_) => "",
|
||||
}
|
||||
.into(),
|
||||
bitrate: bitrate_text(s.bitrate).into(),
|
||||
});
|
||||
}
|
||||
// Streams that started before we joined: the server did not
|
||||
@@ -194,6 +253,7 @@ impl App {
|
||||
items.push(StreamItem {
|
||||
name: c.nickname.clone().into(),
|
||||
streamer: c.nickname.clone().into(),
|
||||
streamer_id: i32::from(c.id),
|
||||
..StreamItem::default()
|
||||
});
|
||||
}
|
||||
@@ -207,6 +267,7 @@ impl App {
|
||||
audio: false,
|
||||
watching: self.watch.as_ref().is_some_and(|w| w.session.is_none() && !w.ended),
|
||||
own: false,
|
||||
..StreamItem::default()
|
||||
});
|
||||
}
|
||||
bridge.set_streams_available(self.demo || view.is_some_and(|v| v.streams_available()));
|
||||
@@ -255,7 +316,7 @@ impl App {
|
||||
bridge.set_share_status(status.into());
|
||||
}
|
||||
|
||||
fn refresh_viewer(&self) {
|
||||
pub(crate) fn refresh_viewer(&self) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let bridge = ui.global::<Bridge>();
|
||||
let Some(watch) = &self.watch else {
|
||||
@@ -272,13 +333,49 @@ impl App {
|
||||
bridge.set_viewer_ended(watch.ended);
|
||||
bridge.set_viewer_has_frame(watch.has_frame);
|
||||
bridge.set_viewer_volume(self.stream_volume);
|
||||
let info = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default();
|
||||
let info = [format!("by {}", watch.streamer), info]
|
||||
let decoded = watch.decoder.as_ref().map(Decoder::info).unwrap_or_default();
|
||||
let info = [format!("by {}", watch.streamer), decoded.clone()]
|
||||
.into_iter()
|
||||
.filter(|s| !s.is_empty())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" · ");
|
||||
bridge.set_viewer_info(info.into());
|
||||
bridge.set_viewer_streamer(watch.streamer.clone().into());
|
||||
let streamer = self
|
||||
.view()
|
||||
.and_then(|v| v.streams.iter().find(|s| s.id == watch.stream_id))
|
||||
.map_or(-1, |s| i32::from(s.streamer.0));
|
||||
bridge.set_viewer_streamer_id(streamer);
|
||||
bridge.set_viewer_elapsed(watch.elapsed().into());
|
||||
let viewers = self.view().and_then(|v| v.stream_viewers.get(&watch.stream_id)).copied();
|
||||
bridge.set_viewer_count(viewers.unwrap_or(0) as i32);
|
||||
let qualities = watch.qualities();
|
||||
let chosen = watch
|
||||
.layer
|
||||
.and_then(|id| watch.layers.iter().position(|l| l.id == id))
|
||||
.map_or(0, |i| i as i32 + 1);
|
||||
crate::vm::list::sync(&self.models.qualities, &qualities);
|
||||
if bridge.get_viewer_quality() != chosen {
|
||||
bridge.set_viewer_quality(chosen);
|
||||
}
|
||||
bridge.set_viewer_quality_detail(decoded.into());
|
||||
}
|
||||
|
||||
/// A simulcast layer of the watched stream (0: follow the bandwidth
|
||||
/// estimate). The streamer picks the layer from each viewer's estimate,
|
||||
/// so this asks for the picture again; a viewer-side choice needs an
|
||||
/// engine API that does not exist yet.
|
||||
pub(crate) fn set_stream_quality(&mut self, index: i32) {
|
||||
let Some(watch) = &mut self.watch else { return };
|
||||
watch.layer =
|
||||
usize::try_from(index - 1).ok().and_then(|i| watch.layers.get(i)).map(|l| l.id);
|
||||
if let Some(session) = watch.session {
|
||||
self.engine.send(Command::RequestStreamKeyframe {
|
||||
session: session as u64,
|
||||
stream_id: watch.stream_id.clone(),
|
||||
});
|
||||
}
|
||||
self.refresh_viewer();
|
||||
}
|
||||
|
||||
/// Once a second: statistics, a capture that ended, decoder problems.
|
||||
@@ -524,9 +621,27 @@ impl App {
|
||||
has_frame: false,
|
||||
shown: true,
|
||||
decoder: Some(decoder),
|
||||
since: None,
|
||||
layers: Vec::new(),
|
||||
layer: None,
|
||||
});
|
||||
self.refresh_viewer();
|
||||
self.refresh_streams();
|
||||
// The people in our channel lead the members panel beside the viewer.
|
||||
self.refresh_tree();
|
||||
}
|
||||
|
||||
/// `VOELIN_OPEN=watch`: watch the first stream of our channel.
|
||||
pub(crate) fn watch_first_stream(&mut self) {
|
||||
let Some(id) = self.view().and_then(|v| {
|
||||
v.streams
|
||||
.iter()
|
||||
.find(|s| v.state.own_client != Some(s.streamer.0))
|
||||
.map(|s| s.id.clone())
|
||||
}) else {
|
||||
return;
|
||||
};
|
||||
self.watch_stream(id);
|
||||
}
|
||||
|
||||
/// The local test stream in the viewer (`VOELIN_DEMO_STREAM`).
|
||||
@@ -543,6 +658,9 @@ impl App {
|
||||
has_frame: false,
|
||||
shown: true,
|
||||
decoder: None,
|
||||
since: None,
|
||||
layers: Vec::new(),
|
||||
layer: None,
|
||||
});
|
||||
let runtime = self.engine.runtime().clone();
|
||||
let wake = || later(|app| app.show_picture());
|
||||
@@ -560,6 +678,21 @@ impl App {
|
||||
});
|
||||
self.refresh_viewer();
|
||||
self.refresh_streams();
|
||||
// The people in our channel lead the members panel beside the viewer.
|
||||
self.refresh_tree();
|
||||
}
|
||||
|
||||
/// `VOELIN_OPEN=watch` with sample data: the local test pattern in the
|
||||
/// viewer, dressed as the first stream of our channel.
|
||||
pub(crate) fn demo_watch(&mut self) {
|
||||
let sample = self.view().and_then(|v| {
|
||||
v.streams.first().map(|s| (s.id.clone(), s.name.clone(), v.nickname(s.streamer.0)))
|
||||
});
|
||||
self.start_demo();
|
||||
if let (Some(watch), Some((id, title, streamer))) = (&mut self.watch, sample) {
|
||||
(watch.stream_id, watch.title, watch.streamer) = (id, title, streamer);
|
||||
}
|
||||
self.refresh_viewer();
|
||||
}
|
||||
|
||||
/// A decoded picture is waiting.
|
||||
@@ -570,6 +703,7 @@ impl App {
|
||||
watch.has_frame = true;
|
||||
if first {
|
||||
watch.status.clear();
|
||||
watch.since = Some(std::time::Instant::now());
|
||||
}
|
||||
if let Some(ui) = self.ui.upgrade() {
|
||||
let bridge = ui.global::<Bridge>();
|
||||
@@ -589,6 +723,8 @@ impl App {
|
||||
}
|
||||
self.refresh_viewer();
|
||||
self.refresh_streams();
|
||||
// The people in our channel lead the members panel beside the viewer.
|
||||
self.refresh_tree();
|
||||
}
|
||||
|
||||
/// Stop watching and close the viewer.
|
||||
@@ -603,6 +739,8 @@ impl App {
|
||||
self.set_fullscreen(false);
|
||||
self.refresh_viewer();
|
||||
self.refresh_streams();
|
||||
// The people in our channel lead the members panel beside the viewer.
|
||||
self.refresh_tree();
|
||||
}
|
||||
|
||||
pub(crate) fn set_stream_volume(&mut self, percent: f32) {
|
||||
@@ -634,3 +772,14 @@ impl App {
|
||||
ui.window().set_fullscreen(full);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn bitrates() {
|
||||
assert_eq!(super::bitrate_text(0), "");
|
||||
assert_eq!(super::bitrate_text(640), "640 kbit/s");
|
||||
assert_eq!(super::bitrate_text(8000), "8 Mbit/s");
|
||||
assert_eq!(super::bitrate_text(4608), "4.6 Mbit/s");
|
||||
}
|
||||
}
|
||||
@@ -24,6 +24,12 @@ pub fn initials(name: &str) -> String {
|
||||
letters.to_uppercase()
|
||||
}
|
||||
|
||||
/// A picture from the engine's cache (an avatar, a group icon), decoded
|
||||
/// once; an empty image when there is none.
|
||||
pub fn image(path: Option<&std::path::PathBuf>) -> slint::Image {
|
||||
path.map(|p| crate::images::file(p)).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// A stable colour for a name (FNV-1a).
|
||||
pub fn tint(name: &str) -> Color {
|
||||
let mut hash: u32 = 0x811c_9dc5;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
//! Chat lines.
|
||||
//! Chat lines: one [`ChatLine`] per message, with its reactions and the
|
||||
//! files it links.
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use slint::{ModelRc, VecModel};
|
||||
use voelin_model::ChatMessage;
|
||||
use slint::{Image, ModelRc, VecModel};
|
||||
use voelin_core::HistoryMessage;
|
||||
use voelin_model::{ChatMessage, FileRef};
|
||||
|
||||
use crate::app::{ChatLine, TextRun};
|
||||
use crate::app::{ChatLine, FileItem, ReactionItem, TextRun};
|
||||
use crate::emoji;
|
||||
use crate::vm::avatar;
|
||||
|
||||
@@ -30,50 +32,186 @@ impl Previous {
|
||||
}
|
||||
}
|
||||
|
||||
fn time_of(ts_ms: i64) -> String {
|
||||
/// What a line needs besides the message itself.
|
||||
#[derive(Default)]
|
||||
pub struct LineCtx {
|
||||
/// The message's handle in its chat.
|
||||
pub key: i32,
|
||||
/// The author's avatar picture.
|
||||
pub avatar: Image,
|
||||
/// The gateway takes reactions and pins for this chat.
|
||||
pub gateway: bool,
|
||||
/// Highlighted (jumped to from the pins).
|
||||
pub marked: bool,
|
||||
/// The topic the message belongs to, when it should be shown.
|
||||
pub topic: String,
|
||||
/// The state of the downloads started from this message, by link index.
|
||||
pub downloads: Vec<(usize, FileItem)>,
|
||||
}
|
||||
|
||||
/// When a message was sent, for its header (see [`stamp`]).
|
||||
pub fn time_of(ts_ms: i64) -> String {
|
||||
chrono::DateTime::from_timestamp_millis(ts_ms)
|
||||
.map(|t| t.with_timezone(&chrono::Local).format("%H:%M").to_string())
|
||||
.map(|t| {
|
||||
stamp(t.with_timezone(&chrono::Local).naive_local(), chrono::Local::now().naive_local())
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The line of a message; `previous` is the line before it in the chat.
|
||||
/// "Today at 10:14", "Yesterday at 10:14", "12 Mar at 10:14", and the year
|
||||
/// when it is not this one.
|
||||
pub fn stamp(then: chrono::NaiveDateTime, now: chrono::NaiveDateTime) -> String {
|
||||
use chrono::Datelike;
|
||||
let time = then.format("%H:%M");
|
||||
let days = (now.date() - then.date()).num_days();
|
||||
match days {
|
||||
0 => format!("Today at {time}"),
|
||||
1 => format!("Yesterday at {time}"),
|
||||
_ if then.year() == now.year() => format!("{} at {time}", then.format("%-d %b")),
|
||||
_ => format!("{} at {time}", then.format("%-d %b %Y")),
|
||||
}
|
||||
}
|
||||
|
||||
/// "2.4 MB", "912 kB", "48 B".
|
||||
pub fn size_text(bytes: u64) -> String {
|
||||
const UNITS: [(u64, &str); 3] = [(1 << 30, "GB"), (1 << 20, "MB"), (1 << 10, "kB")];
|
||||
for (unit, name) in UNITS {
|
||||
if bytes >= unit {
|
||||
return format!("{:.1} {name}", bytes as f64 / unit as f64);
|
||||
}
|
||||
}
|
||||
format!("{bytes} B")
|
||||
}
|
||||
|
||||
/// The text without the file links that became cards.
|
||||
fn without_links(text: &str, files: &[FileRef]) -> String {
|
||||
let mut out = text.to_owned();
|
||||
for file in files {
|
||||
for pattern in [
|
||||
format!("[URL={}]{}[/URL]", file.url, file.name),
|
||||
format!("[URL={}]", file.url),
|
||||
format!("[url={}]", file.url),
|
||||
file.url.clone(),
|
||||
] {
|
||||
out = out.replace(&pattern, "");
|
||||
}
|
||||
}
|
||||
out.replace("[/URL]", "").replace("[/url]", "").trim().to_owned()
|
||||
}
|
||||
|
||||
fn runs_model(runs: &[emoji::Run]) -> ModelRc<TextRun> {
|
||||
ModelRc::from(Rc::new(VecModel::from(
|
||||
runs.iter()
|
||||
.map(|r| TextRun {
|
||||
text: r.text.clone().into(),
|
||||
emoji: r.emoji.clone().unwrap_or_default().into(),
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)))
|
||||
}
|
||||
|
||||
/// The line of a stored message; `previous` is the line before it.
|
||||
pub fn history_line(
|
||||
message: &HistoryMessage,
|
||||
previous: Option<&Previous>,
|
||||
ctx: &LineCtx,
|
||||
) -> ChatLine {
|
||||
let files = message.message.file_refs();
|
||||
let mut line = line_of(&message.message, previous, ctx, &files);
|
||||
line.pinned = message.pinned;
|
||||
line.remote = ctx.gateway && message.remote_id.is_some();
|
||||
line.reactions = ModelRc::from(Rc::new(VecModel::from(
|
||||
message
|
||||
.reactions
|
||||
.iter()
|
||||
.map(|r| ReactionItem {
|
||||
key: emoji::first_key(&r.emoji).unwrap_or_default().into(),
|
||||
text: r.emoji.clone().into(),
|
||||
count: r.count as i32,
|
||||
me: r.me,
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
)));
|
||||
line
|
||||
}
|
||||
|
||||
/// The line of a message the engine keeps no history for (no ids, no
|
||||
/// reactions).
|
||||
pub fn line(message: &ChatMessage, previous: Option<&Previous>) -> ChatLine {
|
||||
let files = message.file_refs();
|
||||
line_of(message, previous, &LineCtx::default(), &files)
|
||||
}
|
||||
|
||||
fn line_of(
|
||||
message: &ChatMessage,
|
||||
previous: Option<&Previous>,
|
||||
ctx: &LineCtx,
|
||||
files: &[FileRef],
|
||||
) -> ChatLine {
|
||||
let continued = previous.is_some_and(|p| {
|
||||
p.author == message.author_name
|
||||
&& p.relayed == message.via_relay
|
||||
&& (0..GROUP_MS).contains(&(message.ts_ms - p.ts_ms))
|
||||
});
|
||||
let runs = emoji::runs(&message.text);
|
||||
let text =
|
||||
if files.is_empty() { message.text.clone() } else { without_links(&message.text, files) };
|
||||
let runs = emoji::runs(&text);
|
||||
let jumbo = runs.as_deref().is_some_and(emoji::is_jumbo);
|
||||
let runs_model = match &runs {
|
||||
Some(runs) => ModelRc::from(Rc::new(VecModel::from(
|
||||
runs.iter()
|
||||
.map(|r| TextRun {
|
||||
text: r.text.clone().into(),
|
||||
emoji: r.emoji.clone().unwrap_or_default().into(),
|
||||
})
|
||||
.collect::<Vec<_>>(),
|
||||
))),
|
||||
None => ModelRc::default(),
|
||||
};
|
||||
let cards: Vec<FileItem> = files
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, f)| {
|
||||
let mut item = FileItem {
|
||||
name: f.name.clone().into(),
|
||||
detail: f.size.map(size_text).unwrap_or_default().into(),
|
||||
index: i as i32,
|
||||
picture: is_picture(&f.name),
|
||||
..Default::default()
|
||||
};
|
||||
// A download of this link shows its progress instead of the size.
|
||||
if let Some((_, running)) = ctx.downloads.iter().find(|(index, _)| *index == i) {
|
||||
item.detail = running.detail.clone();
|
||||
item.state = running.state.clone();
|
||||
item.progress = running.progress;
|
||||
}
|
||||
item
|
||||
})
|
||||
.collect();
|
||||
ChatLine {
|
||||
key: ctx.key,
|
||||
author: message.author_name.clone().into(),
|
||||
text: message.text.clone().into(),
|
||||
text: text.clone().into(),
|
||||
time: time_of(message.ts_ms).into(),
|
||||
relayed: message.via_relay,
|
||||
runs: runs_model,
|
||||
runs: runs.as_deref().map(runs_model).unwrap_or_default(),
|
||||
rich: runs.is_some(),
|
||||
jumbo,
|
||||
continued,
|
||||
initials: avatar::initials(&message.author_name).into(),
|
||||
tint: avatar::tint(&message.author_name),
|
||||
avatar: ctx.avatar.clone(),
|
||||
blocked: message.blocked,
|
||||
pinned: false,
|
||||
reactions: ModelRc::default(),
|
||||
files: ModelRc::from(Rc::new(VecModel::from(cards))),
|
||||
remote: false,
|
||||
topic: ctx.topic.clone().into(),
|
||||
marked: ctx.marked,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_picture(name: &str) -> bool {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
[".png", ".jpg", ".jpeg", ".gif", ".webp", ".bmp", ".svg"].iter().any(|e| lower.ends_with(e))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use slint::Model;
|
||||
use voelin_core::HistoryMessage;
|
||||
use voelin_gateway_proto::ReactionCount;
|
||||
use voelin_model::ChatTarget;
|
||||
use voelin_store::MessageSource;
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -90,6 +228,19 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
fn stored(message: ChatMessage) -> HistoryMessage {
|
||||
HistoryMessage {
|
||||
id: 1,
|
||||
message,
|
||||
source: MessageSource::Voice,
|
||||
remote_id: Some(7),
|
||||
topic_id: None,
|
||||
reactions: vec![ReactionCount { emoji: "🎉".into(), count: 2, me: true }],
|
||||
pinned: true,
|
||||
rev: 1,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grouping() {
|
||||
let first = message("Alice", "hi", 1_000_000);
|
||||
@@ -112,4 +263,45 @@ mod tests {
|
||||
assert_eq!(rich.runs.row_data(1).unwrap().emoji, "1f389");
|
||||
assert!(line(&message("A", "🎉", 0), None).jumbo);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reactions_and_pins() {
|
||||
let ctx = LineCtx { key: 4, gateway: true, ..Default::default() };
|
||||
let line = history_line(&stored(message("A", "hi", 0)), None, &ctx);
|
||||
assert!(line.pinned && line.remote && line.key == 4);
|
||||
assert_eq!(line.reactions.row_count(), 1);
|
||||
let r = line.reactions.row_data(0).unwrap();
|
||||
assert_eq!((r.key.as_str(), r.count, r.me), ("1f389", 2, true));
|
||||
// Without a gateway nothing can be pinned or reacted to.
|
||||
let plain = history_line(&stored(message("A", "hi", 0)), None, &LineCtx::default());
|
||||
assert!(!plain.remote);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_cards_leave_the_text() {
|
||||
let url = "ts3file://plan.pdf?channel=2&path=/&filename=plan.pdf&isDir=0&size=2048";
|
||||
let text = format!("here you go [URL={url}]plan.pdf[/URL] 🎉");
|
||||
let line = line(&message("A", &text, 0), None);
|
||||
assert_eq!(line.files.row_count(), 1);
|
||||
let file = line.files.row_data(0).unwrap();
|
||||
assert_eq!((file.name.as_str(), file.detail.as_str()), ("plan.pdf", "2.0 kB"));
|
||||
assert!(!line.text.contains("ts3file"), "{}", line.text);
|
||||
assert!(line.text.starts_with("here you go"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stamps() {
|
||||
let at = |d: &str| chrono::NaiveDateTime::parse_from_str(d, "%Y-%m-%d %H:%M").unwrap();
|
||||
let now = at("2026-10-03 09:00");
|
||||
assert_eq!(stamp(at("2026-10-03 08:05"), now), "Today at 08:05");
|
||||
assert_eq!(stamp(at("2026-10-02 23:59"), now), "Yesterday at 23:59");
|
||||
assert_eq!(stamp(at("2026-03-12 10:14"), now), "12 Mar at 10:14");
|
||||
assert_eq!(stamp(at("2025-12-31 10:14"), now), "31 Dec 2025 at 10:14");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes() {
|
||||
assert_eq!(size_text(48), "48 B");
|
||||
assert_eq!(size_text(2 << 20), "2.0 MB");
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
//! The channel tree and the members of our channel.
|
||||
//! The channel tree, the members of our channel and everyone on the
|
||||
//! server for the members panel.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use voelin_model::{ChannelId, ClientInfo, Presence, TreeRow, tree_rows};
|
||||
use voelin_model::{ChannelId, ClientInfo, GroupInfo, Presence, TreeRow, tree_rows};
|
||||
|
||||
use crate::app::{MemberItem, TreeItem};
|
||||
use crate::settings::ClientPlaybackMap;
|
||||
@@ -19,6 +21,42 @@ pub struct TreeInput<'a> {
|
||||
/// Search text: only matching channels and clients (and the channels
|
||||
/// above them) are shown. Empty: everything.
|
||||
pub filter: &'a str,
|
||||
/// Avatar pictures in the engine's cache, by unique id.
|
||||
pub avatars: &'a HashMap<String, PathBuf>,
|
||||
/// Icons in the engine's cache, by icon id (group icons).
|
||||
pub icons: &'a HashMap<u32, PathBuf>,
|
||||
/// The server groups in display order; members are grouped by the
|
||||
/// first one each client is in.
|
||||
pub groups: &'a [GroupInfo],
|
||||
}
|
||||
|
||||
impl TreeInput<'_> {
|
||||
fn avatar(&self, client: &ClientInfo) -> slint::Image {
|
||||
avatar::image(client.uid.as_ref().and_then(|uid| self.avatars.get(uid)))
|
||||
}
|
||||
|
||||
/// The group a client is sorted under: the first of its server groups
|
||||
/// in display order.
|
||||
fn group_of(&self, client: &ClientInfo) -> Option<&GroupInfo> {
|
||||
self.groups.iter().find(|g| client.server_groups.contains(&g.id))
|
||||
}
|
||||
}
|
||||
|
||||
/// "Speaking", "Away: brb", "Muted", …
|
||||
pub fn status_of(client: &ClientInfo, talking: bool) -> String {
|
||||
if talking {
|
||||
"Speaking".to_owned()
|
||||
} else if client.streaming == Some(true) {
|
||||
"Streaming".to_owned()
|
||||
} else if let Some(message) = &client.away {
|
||||
if message.is_empty() { "Away".to_owned() } else { format!("Away: {message}") }
|
||||
} else if client.output_muted {
|
||||
"Sound off".to_owned()
|
||||
} else if client.input_muted {
|
||||
"Muted".to_owned()
|
||||
} else {
|
||||
"Listening".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn talking(input: &TreeInput, client: &ClientInfo) -> bool {
|
||||
@@ -66,6 +104,7 @@ pub fn rows(input: &TreeInput) -> Vec<TreeItem> {
|
||||
myself: input.own_client == Some(client.id),
|
||||
initials: avatar::initials(&client.nickname).into(),
|
||||
tint: avatar::tint(&client.nickname),
|
||||
avatar: input.avatar(client),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
@@ -105,43 +144,170 @@ pub fn stats(p: &Presence) -> String {
|
||||
format!("{online} online · {channels} {}", if channels == 1 { "channel" } else { "channels" })
|
||||
}
|
||||
|
||||
/// The clients in our channel, for the members panel, by name.
|
||||
/// Names of server groups whose members wear the crown (the server's
|
||||
/// admins). TeamSpeak has no flag for it, so the usual names are matched.
|
||||
fn is_admin_group(name: &str) -> bool {
|
||||
let lower = name.to_lowercase();
|
||||
["admin", "owner", "operator", "leiter"].iter().any(|w| lower.contains(w))
|
||||
}
|
||||
|
||||
/// Moderator groups, shown as a role next to the name.
|
||||
fn is_moderator_group(name: &str) -> bool {
|
||||
name.to_lowercase().contains("mod")
|
||||
}
|
||||
|
||||
impl TreeInput<'_> {
|
||||
/// The position of a client's group in display order (no group last).
|
||||
fn group_rank(&self, client: &ClientInfo) -> usize {
|
||||
self.groups.iter().position(|g| client.server_groups.contains(&g.id)).unwrap_or(usize::MAX)
|
||||
}
|
||||
|
||||
/// One row of the members panel or the voice channel, under `section`.
|
||||
fn member(&self, c: &ClientInfo, section: &Section) -> MemberItem {
|
||||
let talking = talking(self, c);
|
||||
let group = self.group_of(c).map_or("", |g| g.name.as_str());
|
||||
let admin = is_admin_group(group);
|
||||
// Someone elsewhere on the server: where they are says more than
|
||||
// "Listening".
|
||||
let elsewhere = self.own_channel != Some(c.channel)
|
||||
&& !talking
|
||||
&& c.streaming != Some(true)
|
||||
&& c.away.is_none();
|
||||
let status = match self.presence.channels.get(&c.channel) {
|
||||
Some(channel) if elsewhere => format!("In {}", channel.name),
|
||||
_ => status_of(c, talking),
|
||||
};
|
||||
MemberItem {
|
||||
id: c.id as i32,
|
||||
name: c.nickname.clone().into(),
|
||||
initials: avatar::initials(&c.nickname).into(),
|
||||
tint: avatar::tint(&c.nickname),
|
||||
avatar: self.avatar(c),
|
||||
talking,
|
||||
muted: c.input_muted,
|
||||
sound_off: c.output_muted,
|
||||
away: c.away.is_some(),
|
||||
streaming: c.streaming == Some(true),
|
||||
myself: self.own_client == Some(c.id),
|
||||
status: status.into(),
|
||||
away_message: c.away.clone().unwrap_or_default().into(),
|
||||
group: section.title.clone().into(),
|
||||
group_icon: section.icon.clone(),
|
||||
first_in_group: false,
|
||||
group_count: 0,
|
||||
admin,
|
||||
role: if !admin && is_moderator_group(group) { group.into() } else { "".into() },
|
||||
priority: c.priority_speaker,
|
||||
commander: c.channel_commander,
|
||||
recording: c.recording,
|
||||
talk_power: c.talk_power,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A heading of the members panel.
|
||||
#[derive(Clone, Default)]
|
||||
struct Section {
|
||||
title: String,
|
||||
icon: slint::Image,
|
||||
}
|
||||
|
||||
/// Rows in sections: each section's first row carries the heading and how
|
||||
/// many rows follow.
|
||||
fn sectioned(
|
||||
input: &TreeInput,
|
||||
mut clients: Vec<(Section, usize, &ClientInfo)>,
|
||||
) -> Vec<MemberItem> {
|
||||
clients.sort_by_key(|(_, rank, c)| (*rank, c.nickname.to_lowercase(), c.id));
|
||||
let mut rows: Vec<MemberItem> = clients.iter().map(|(s, _, c)| input.member(c, s)).collect();
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let rank = clients[start].1;
|
||||
let count = clients[start..].iter().take_while(|(_, r, _)| *r == rank).count();
|
||||
rows[start].first_in_group = true;
|
||||
rows[start].group_count = count as i32;
|
||||
start += count;
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// The section of a client's server group.
|
||||
fn group_section(input: &TreeInput, client: &ClientInfo) -> (Section, usize) {
|
||||
match input.group_of(client) {
|
||||
Some(g) => (
|
||||
Section {
|
||||
title: g.name.clone(),
|
||||
icon: avatar::image(
|
||||
Some(g.icon).filter(|i| *i != 0).and_then(|i| input.icons.get(&i)),
|
||||
),
|
||||
},
|
||||
1 + input.group_rank(client),
|
||||
),
|
||||
None => (Section { title: "Online".into(), ..Default::default() }, usize::MAX),
|
||||
}
|
||||
}
|
||||
|
||||
/// The clients in our channel, grouped by server group (in the server's
|
||||
/// display order) and by name inside a group.
|
||||
pub fn members(input: &TreeInput) -> Vec<MemberItem> {
|
||||
let Some(channel) = input.own_channel else { return Vec::new() };
|
||||
let mut clients: Vec<&ClientInfo> = input.presence.members(channel).collect();
|
||||
clients.sort_by_key(|c| c.nickname.to_lowercase());
|
||||
clients
|
||||
.into_iter()
|
||||
let clients = input
|
||||
.presence
|
||||
.members(channel)
|
||||
.map(|c| {
|
||||
let talking = talking(input, c);
|
||||
let status = if talking {
|
||||
"Speaking".to_owned()
|
||||
} else if c.streaming == Some(true) {
|
||||
"Streaming".to_owned()
|
||||
} else if let Some(message) = &c.away {
|
||||
if message.is_empty() { "Away".to_owned() } else { format!("Away: {message}") }
|
||||
} else if c.output_muted {
|
||||
"Sound off".to_owned()
|
||||
} else if c.input_muted {
|
||||
"Muted".to_owned()
|
||||
let (section, rank) = group_section(input, c);
|
||||
(section, rank, c)
|
||||
})
|
||||
.collect();
|
||||
sectioned(input, clients)
|
||||
}
|
||||
|
||||
/// The rows whose name contains `filter` (lower case), in sections
|
||||
/// counted again.
|
||||
pub fn matching(rows: Vec<MemberItem>, filter: &str) -> Vec<MemberItem> {
|
||||
let mut rows: Vec<MemberItem> =
|
||||
rows.into_iter().filter(|m| m.name.to_lowercase().contains(filter)).collect();
|
||||
let mut start = 0;
|
||||
while start < rows.len() {
|
||||
let group = rows[start].group.clone();
|
||||
let count = rows[start..].iter().take_while(|m| m.group == group).count();
|
||||
for (i, row) in rows[start..start + count].iter_mut().enumerate() {
|
||||
row.first_in_group = i == 0;
|
||||
row.group_count = if i == 0 { count as i32 } else { 0 };
|
||||
}
|
||||
start += count;
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// Everyone on the server for the members panel: first the people in our
|
||||
/// voice channel (`voice_first`, in the voice channel and stream views) or
|
||||
/// those streaming, then each server group in the server's order.
|
||||
pub fn server_members(input: &TreeInput, voice_first: bool) -> Vec<MemberItem> {
|
||||
let first = Section {
|
||||
title: if voice_first { "In Voice" } else { "Streaming" }.into(),
|
||||
icon: slint::Image::default(),
|
||||
};
|
||||
let clients = input
|
||||
.presence
|
||||
.clients
|
||||
.values()
|
||||
.filter(|c| !c.is_query)
|
||||
.map(|c| {
|
||||
let lead = if voice_first {
|
||||
input.own_channel == Some(c.channel)
|
||||
} else {
|
||||
"Listening".to_owned()
|
||||
c.streaming == Some(true)
|
||||
};
|
||||
MemberItem {
|
||||
id: c.id as i32,
|
||||
name: c.nickname.clone().into(),
|
||||
initials: avatar::initials(&c.nickname).into(),
|
||||
tint: avatar::tint(&c.nickname),
|
||||
talking,
|
||||
muted: c.input_muted,
|
||||
sound_off: c.output_muted,
|
||||
away: c.away.is_some(),
|
||||
streaming: c.streaming == Some(true),
|
||||
myself: input.own_client == Some(c.id),
|
||||
status: status.into(),
|
||||
if lead {
|
||||
(first.clone(), 0, c)
|
||||
} else {
|
||||
let (section, rank) = group_section(input, c);
|
||||
(section, rank, c)
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
.collect();
|
||||
sectioned(input, clients)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -178,12 +344,21 @@ mod tests {
|
||||
p
|
||||
}
|
||||
|
||||
/// Empty caches and no groups, for the tests below.
|
||||
#[derive(Default)]
|
||||
struct Extras {
|
||||
avatars: HashMap<String, PathBuf>,
|
||||
icons: HashMap<u32, PathBuf>,
|
||||
groups: Vec<GroupInfo>,
|
||||
}
|
||||
|
||||
fn input<'a>(
|
||||
p: &'a Presence,
|
||||
talking: &'a HashSet<u16>,
|
||||
collapsed: &'a HashSet<ChannelId>,
|
||||
playback: &'a ClientPlaybackMap,
|
||||
filter: &'a str,
|
||||
extras: &'a Extras,
|
||||
) -> TreeInput<'a> {
|
||||
TreeInput {
|
||||
presence: p,
|
||||
@@ -193,6 +368,9 @@ mod tests {
|
||||
own_channel: Some(2),
|
||||
own_client: Some(11),
|
||||
filter,
|
||||
avatars: &extras.avatars,
|
||||
icons: &extras.icons,
|
||||
groups: &extras.groups,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +378,8 @@ mod tests {
|
||||
fn tree_rows_and_counts() {
|
||||
let p = presence();
|
||||
let (t, c, pb) = (HashSet::from([11]), HashSet::new(), ClientPlaybackMap::new());
|
||||
let rows = rows(&input(&p, &t, &c, &pb, ""));
|
||||
let e = Extras::default();
|
||||
let rows = rows(&input(&p, &t, &c, &pb, "", &e));
|
||||
let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
|
||||
assert_eq!(names, ["Lobby", "Alice", "Games", "bob", "Chess", "Carol"]);
|
||||
assert_eq!((rows[0].members, rows[0].max_members), (1, -1));
|
||||
@@ -214,10 +393,11 @@ mod tests {
|
||||
fn search_keeps_parents() {
|
||||
let p = presence();
|
||||
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
|
||||
let rows = rows(&input(&p, &t, &c, &pb, "car"));
|
||||
let e = Extras::default();
|
||||
let rows = rows(&input(&p, &t, &c, &pb, "car", &e));
|
||||
let names: Vec<_> = rows.iter().map(|r| r.name.as_str()).collect();
|
||||
assert_eq!(names, ["Games", "Chess", "Carol"]);
|
||||
let rows = super::rows(&input(&p, &t, &c, &pb, "LOBBY"));
|
||||
let rows = super::rows(&input(&p, &t, &c, &pb, "LOBBY", &e));
|
||||
assert_eq!(rows.len(), 1);
|
||||
}
|
||||
|
||||
@@ -227,8 +407,94 @@ mod tests {
|
||||
p.clients.get_mut(&12).unwrap().channel = 2;
|
||||
p.clients.get_mut(&12).unwrap().away = Some(String::new());
|
||||
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
|
||||
let members = members(&input(&p, &t, &c, &pb, ""));
|
||||
let e = Extras::default();
|
||||
let members = members(&input(&p, &t, &c, &pb, "", &e));
|
||||
let names: Vec<_> = members.iter().map(|m| (m.name.as_str(), m.status.as_str())).collect();
|
||||
assert_eq!(names, [("bob", "Listening"), ("Carol", "Away")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn members_are_grouped_by_server_group() {
|
||||
let mut p = presence();
|
||||
p.clients.get_mut(&12).unwrap().channel = 2;
|
||||
p.clients.get_mut(&12).unwrap().server_groups = vec![6];
|
||||
p.clients.get_mut(&11).unwrap().server_groups = vec![7];
|
||||
let group = |id, sort_id, name: &str| GroupInfo {
|
||||
id,
|
||||
name: name.into(),
|
||||
icon: 0,
|
||||
sort_id,
|
||||
..Default::default()
|
||||
};
|
||||
let e = Extras {
|
||||
groups: vec![group(6, 10, "Server Admin"), group(7, 20, "Guest")],
|
||||
..Default::default()
|
||||
};
|
||||
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
|
||||
let members = members(&input(&p, &t, &c, &pb, "", &e));
|
||||
let rows: Vec<_> =
|
||||
members.iter().map(|m| (m.name.as_str(), m.group.as_str(), m.first_in_group)).collect();
|
||||
assert_eq!(rows, [("Carol", "Server Admin", true), ("bob", "Guest", true)]);
|
||||
assert!(members[0].admin && !members[1].admin);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn everyone_in_sections() {
|
||||
let mut p = presence();
|
||||
p.clients.get_mut(&10).unwrap().server_groups = vec![7];
|
||||
p.clients.get_mut(&12).unwrap().server_groups = vec![7];
|
||||
p.clients.get_mut(&12).unwrap().streaming = Some(true);
|
||||
p.clients.get_mut(&11).unwrap().server_groups = vec![6];
|
||||
let group = |id, sort_id, name: &str| GroupInfo {
|
||||
id,
|
||||
name: name.into(),
|
||||
icon: 0,
|
||||
sort_id,
|
||||
..Default::default()
|
||||
};
|
||||
let e = Extras {
|
||||
groups: vec![group(6, 10, "Moderator"), group(7, 20, "Guest")],
|
||||
..Default::default()
|
||||
};
|
||||
let (t, c, pb) = (HashSet::new(), HashSet::new(), ClientPlaybackMap::new());
|
||||
let rows = |voice_first| {
|
||||
server_members(&input(&p, &t, &c, &pb, "", &e), voice_first)
|
||||
.iter()
|
||||
.map(|m| {
|
||||
(
|
||||
m.name.to_string(),
|
||||
m.first_in_group.then(|| format!("{} — {}", m.group, m.group_count)),
|
||||
m.status.to_string(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let row = |name: &str, head: Option<&str>, status: &str| {
|
||||
(name.to_owned(), head.map(str::to_owned), status.to_owned())
|
||||
};
|
||||
// The query client is left out; people elsewhere show their channel.
|
||||
assert_eq!(
|
||||
rows(false),
|
||||
[
|
||||
row("Carol", Some("Streaming — 1"), "Streaming"),
|
||||
row("bob", Some("Moderator — 1"), "Listening"),
|
||||
row("Alice", Some("Guest — 1"), "In Lobby"),
|
||||
]
|
||||
);
|
||||
assert_eq!(
|
||||
rows(true),
|
||||
[
|
||||
row("bob", Some("In Voice — 1"), "Listening"),
|
||||
row("Alice", Some("Guest — 2"), "In Lobby"),
|
||||
row("Carol", None, "Streaming"),
|
||||
]
|
||||
);
|
||||
let all = server_members(&input(&p, &t, &c, &pb, "", &e), false);
|
||||
assert_eq!(all[1].role, "Moderator");
|
||||
assert!(!all[1].admin);
|
||||
// The search keeps the sections of what it finds.
|
||||
let found = matching(all, "al");
|
||||
assert_eq!(found.len(), 1);
|
||||
assert!(found[0].first_in_group && found[0].group == "Guest" && found[0].group_count == 1);
|
||||
}
|
||||
}
|
||||
@@ -19,7 +19,10 @@ import { MobileShell } from "shells/mobile.slint";
|
||||
import { Panel } from "shells/common.slint";
|
||||
import { ServerHeader, ConnectActions, ChannelTree } from "screens/channels.slint";
|
||||
import { ChatView } from "screens/chat.slint";
|
||||
import { StreamsPanel, StreamViewer } from "screens/streams.slint";
|
||||
import { PinsDrawer, TopicsDrawer, TopicDialog } from "screens/drawers.slint";
|
||||
import { MemberCardPopup, MembersPanel } from "screens/members.slint";
|
||||
import { VoiceView } from "screens/voice.slint";
|
||||
import { StreamViewer } from "screens/streams.slint";
|
||||
import { SettingsNav, SettingsPage } from "screens/settings.slint";
|
||||
import { HomeNav, HomePage } from "screens/home.slint";
|
||||
import { MobileServers, ActivityPage, YouPage } from "screens/mobile.slint";
|
||||
@@ -61,8 +64,8 @@ export component MainWindow inherits Window {
|
||||
keyboard-inset = self.virtual-keyboard-size.height > 0 ? self.height - self.virtual-keyboard-position.y : 0;
|
||||
}
|
||||
|
||||
// The viewer takes the whole window in full screen.
|
||||
property <bool> chrome: !(Bridge.viewer-open && Bridge.viewer-fullscreen);
|
||||
// The viewer takes the whole window in full screen and when popped out.
|
||||
property <bool> chrome: !(Bridge.viewer-open && (Bridge.viewer-fullscreen || Bridge.viewer-popped));
|
||||
|
||||
// The standard widgets follow the theme. In "system" mode the palette
|
||||
// is left alone (it tracks the system) unless an explicit mode was
|
||||
@@ -85,6 +88,13 @@ export component MainWindow inherits Window {
|
||||
property <string> status: Bridge.status-text;
|
||||
changed status => { toast.shown = status != ""; }
|
||||
|
||||
// The right column: members, pins or topics.
|
||||
property <bool> side-panel: Nav.right-panel-open || Nav.pins-open || Nav.topics-open;
|
||||
|
||||
// Dragging the members panel stores its width (`ui.members_width`).
|
||||
property <length> panel-width: Nav.right-panel-width;
|
||||
changed panel-width => { Bridge.panel-resized(panel-width / 1px); }
|
||||
|
||||
// Compatibility with callers from before the navigation global.
|
||||
public function open-share-dialog() {
|
||||
Nav.open-share();
|
||||
@@ -128,18 +138,23 @@ export component MainWindow inherits Window {
|
||||
if Nav.page == Page.server: Panel {
|
||||
horizontal-stretch: 1;
|
||||
if Bridge.viewer-open: StreamViewer { }
|
||||
if !Bridge.viewer-open: ChatView { }
|
||||
if !Bridge.viewer-open && Nav.voice-view && Bridge.voice-connected: VoiceView { }
|
||||
if !Bridge.viewer-open && !(Nav.voice-view && Bridge.voice-connected): ChatView { }
|
||||
}
|
||||
if Nav.page == Page.server && Nav.right-panel-open: ResizeHandle {
|
||||
// The members panel, or the pins or the topics in its place.
|
||||
if Nav.page == Page.server && root.side-panel: ResizeHandle {
|
||||
size <=> Nav.right-panel-width;
|
||||
minimum: Theme.right-panel-min;
|
||||
maximum: Theme.right-panel-max;
|
||||
// As wide as the window allows, leaving the chat 400 px.
|
||||
maximum: max(Theme.right-panel-min, root.width - Theme.rail-width - Theme.sidebar-width - 400px);
|
||||
left: false;
|
||||
}
|
||||
if Nav.page == Page.server && Nav.right-panel-open: Panel {
|
||||
if Nav.page == Page.server && root.side-panel: Panel {
|
||||
width: Nav.right-panel-width;
|
||||
horizontal-stretch: 0;
|
||||
StreamsPanel { }
|
||||
if Nav.pins-open: PinsDrawer { }
|
||||
if Nav.topics-open && !Nav.pins-open: TopicsDrawer { }
|
||||
if !Nav.pins-open && !Nav.topics-open: MembersPanel { }
|
||||
}
|
||||
if Nav.page == Page.settings: Sidebar {
|
||||
SettingsNav { }
|
||||
@@ -186,19 +201,46 @@ export component MainWindow inherits Window {
|
||||
text: Bridge.status-text;
|
||||
}
|
||||
|
||||
// The member card of the members panel, over everything.
|
||||
if Bridge.member-card.open: Rectangle {
|
||||
TouchArea {
|
||||
clicked => { Bridge.open-member(-1); }
|
||||
}
|
||||
MemberCardPopup {
|
||||
x: max(8px, parent.width - self.width - (Nav.narrow ? 8px : root.side-panel && Nav.page == Page.server ? Nav.right-panel-width + 24px : 32px));
|
||||
y: max(8px, min(parent.height - self.height - 8px, 120px));
|
||||
}
|
||||
}
|
||||
|
||||
if Nav.emoji-open: Rectangle {
|
||||
// Clicks outside the picker close it.
|
||||
TouchArea {
|
||||
clicked => { Nav.emoji-open = false; }
|
||||
}
|
||||
EmojiPicker {
|
||||
x: max(8px, parent.width - self.width - (Nav.narrow ? 8px : Nav.right-panel-open && Nav.page == Page.server ? Nav.right-panel-width + 40px : 32px));
|
||||
x: max(8px, parent.width - self.width - (Nav.narrow ? 8px : root.side-panel && Nav.page == Page.server ? Nav.right-panel-width + 40px : 32px));
|
||||
y: max(8px, parent.height - self.height - (Nav.narrow ? 150px : 90px));
|
||||
picked(cell) => { Nav.draft = Nav.draft + cell.text; }
|
||||
close => { Nav.emoji-open = false; }
|
||||
// Picked for a message: a reaction; otherwise the composer.
|
||||
picked(cell) => {
|
||||
if Nav.react-key != 0 {
|
||||
Bridge.react(Nav.react-key, cell.text);
|
||||
Nav.react-key = 0;
|
||||
Nav.emoji-open = false;
|
||||
} else {
|
||||
Nav.draft = Nav.draft + cell.text;
|
||||
}
|
||||
}
|
||||
close => {
|
||||
Nav.react-key = 0;
|
||||
Nav.emoji-open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if Nav.topic-form-open: TopicDialog {
|
||||
done => { Nav.topic-form-open = false; }
|
||||
}
|
||||
|
||||
if Nav.bookmark-open: BookmarkDialog {
|
||||
form <=> Nav.bookmark-form;
|
||||
done => { Nav.bookmark-open = false; }
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
<!-- @license lucide-static v1.48.0 - ISC -->
|
||||
<svg
|
||||
class="lucide lucide-book-open"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="24"
|
||||
height="24"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
>
|
||||
<path d="M12 7v14" />
|
||||
<path d="M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z" />
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 458 B |
@@ -39,17 +39,21 @@ export struct TreeItem {
|
||||
// Avatar of a client.
|
||||
initials: string,
|
||||
tint: color,
|
||||
// The client's avatar picture, empty without one.
|
||||
avatar: image,
|
||||
// Channels: clients inside, and the limit (-1: none).
|
||||
members: int,
|
||||
max-members: int,
|
||||
}
|
||||
|
||||
// A client in our channel, for the members panel.
|
||||
// A client for the members panel (everyone on the server) and the voice
|
||||
// channel view (our channel).
|
||||
export struct MemberItem {
|
||||
id: int,
|
||||
name: string,
|
||||
initials: string,
|
||||
tint: color,
|
||||
avatar: image,
|
||||
talking: bool,
|
||||
muted: bool,
|
||||
sound-off: bool,
|
||||
@@ -58,6 +62,49 @@ export struct MemberItem {
|
||||
myself: bool,
|
||||
// "Speaking", "Streaming", "Away", ...
|
||||
status: string,
|
||||
// The away message, empty without one.
|
||||
away-message: string,
|
||||
// The section the row is in (a server group, "In Voice",
|
||||
// "Streaming"), and the group's icon.
|
||||
group: string,
|
||||
group-icon: image,
|
||||
// The first row of its section draws the heading, with the number of
|
||||
// rows in the section.
|
||||
first-in-group: bool,
|
||||
group-count: int,
|
||||
// Badges: a crown for the server's admin groups.
|
||||
admin: bool,
|
||||
// A moderator group's name, shown as a role next to the name.
|
||||
role: string,
|
||||
priority: bool,
|
||||
commander: bool,
|
||||
recording: bool,
|
||||
// `client_talk_power`; shown when the channel needs it.
|
||||
talk-power: int,
|
||||
}
|
||||
|
||||
// The member card over a member row: everything about one client and what
|
||||
// can be done with them.
|
||||
export struct MemberCard {
|
||||
open: bool,
|
||||
id: int,
|
||||
name: string,
|
||||
initials: string,
|
||||
tint: color,
|
||||
avatar: image,
|
||||
status: string,
|
||||
description: string,
|
||||
// Server groups, one per line.
|
||||
groups: [string],
|
||||
country: string,
|
||||
talk-power: int,
|
||||
friend: bool,
|
||||
blocked: bool,
|
||||
// Local playback, in percent.
|
||||
volume: float,
|
||||
muted: bool,
|
||||
// The client has a unique id, so contacts and private chats work.
|
||||
known: bool,
|
||||
}
|
||||
|
||||
export struct ChatTab {
|
||||
@@ -80,7 +127,35 @@ export struct TextRun {
|
||||
emoji: string,
|
||||
}
|
||||
|
||||
// One emoji under a message, with how many put it there.
|
||||
export struct ReactionItem {
|
||||
// The Twemoji key of the first emoji in `text` ("1f389"), for the image.
|
||||
key: string,
|
||||
text: string,
|
||||
count: int,
|
||||
// We reacted with it.
|
||||
me: bool,
|
||||
}
|
||||
|
||||
// A file linked in a message (`ChatMessage::file_refs`).
|
||||
export struct FileItem {
|
||||
name: string,
|
||||
// "2.4 MB", or what the transfer is doing.
|
||||
detail: string,
|
||||
// Index of the link in the message (what `download-file` takes).
|
||||
index: int,
|
||||
// "", "running", "done", "failed"
|
||||
state: string,
|
||||
// 0 … 1 while it downloads.
|
||||
progress: float,
|
||||
// A picture, so the icon differs.
|
||||
picture: bool,
|
||||
}
|
||||
|
||||
export struct ChatLine {
|
||||
// A handle for this message in its chat, stable while the chat is open
|
||||
// (the engine's ids do not fit a Slint int).
|
||||
key: int,
|
||||
author: string,
|
||||
text: string,
|
||||
time: string,
|
||||
@@ -94,6 +169,39 @@ export struct ChatLine {
|
||||
continued: bool,
|
||||
initials: string,
|
||||
tint: color,
|
||||
avatar: image,
|
||||
// From a blocked contact.
|
||||
blocked: bool,
|
||||
pinned: bool,
|
||||
reactions: [ReactionItem],
|
||||
files: [FileItem],
|
||||
// The gateway knows this message: it can be pinned, reacted to and
|
||||
// made into a topic.
|
||||
remote: bool,
|
||||
// The topic it belongs to, "" outside a topic.
|
||||
topic: string,
|
||||
// Highlighted after jumping to it from the pins.
|
||||
marked: bool,
|
||||
}
|
||||
|
||||
// A pinned message in the pins drawer.
|
||||
export struct PinItem {
|
||||
line: ChatLine,
|
||||
// "pinned by Nova · 12:04"
|
||||
by: string,
|
||||
}
|
||||
|
||||
// A gateway topic (thread).
|
||||
export struct TopicItem {
|
||||
id: int,
|
||||
title: string,
|
||||
creator: string,
|
||||
// "12 messages · by Nova"
|
||||
detail: string,
|
||||
// "Last active 3 min ago", and whether that was within the hour.
|
||||
activity: string,
|
||||
recent: bool,
|
||||
archived: bool,
|
||||
}
|
||||
|
||||
export struct BookmarkForm {
|
||||
@@ -115,7 +223,14 @@ export struct StreamItem {
|
||||
id: string,
|
||||
name: string,
|
||||
streamer: string,
|
||||
// The streamer's client id (their avatar in the members).
|
||||
streamer-id: int,
|
||||
// How many watch it (the gateway's directory; 0 unknown).
|
||||
viewers: int,
|
||||
audio: bool,
|
||||
// "Screen", "Window", "Camera"; and the announced bitrate ("8 Mbit/s").
|
||||
kind: string,
|
||||
bitrate: string,
|
||||
// Shown in the viewer.
|
||||
watching: bool,
|
||||
// Our own stream.
|
||||
@@ -196,9 +311,37 @@ export global Bridge {
|
||||
in property <[TreeItem]> tree;
|
||||
// Clients in our channel.
|
||||
in property <[MemberItem]> members;
|
||||
// Everyone on the server, in sections, for the members panel.
|
||||
in property <[MemberItem]> server-members;
|
||||
// How many people are on the server (not counting query clients).
|
||||
in property <int> member-total;
|
||||
in property <[ChatTab]> tabs;
|
||||
in-out property <int> current-tab: 0;
|
||||
in property <[ChatLine]> messages;
|
||||
// Older messages can still be loaded in the current chat.
|
||||
in property <bool> more-history;
|
||||
in property <bool> loading-history;
|
||||
// The current chat holds only what this device saw (no gateway sync).
|
||||
in property <bool> local-history;
|
||||
// Features of the session's gateway: hide what is missing.
|
||||
in property <bool> has-pins;
|
||||
in property <bool> has-reactions;
|
||||
in property <bool> has-topics;
|
||||
// The pins drawer.
|
||||
in property <[PinItem]> pins;
|
||||
in property <bool> pins-loading;
|
||||
// The topics drawer, and the open topic.
|
||||
in property <[TopicItem]> topics;
|
||||
in property <bool> topics-loading;
|
||||
in-out property <int> current-topic: -1;
|
||||
in property <string> topic-title;
|
||||
in property <[ChatLine]> topic-messages;
|
||||
// The member card over the members panel.
|
||||
in-out property <MemberCard> member-card;
|
||||
// Jumping to a pinned message: its row in `messages`, and a counter
|
||||
// that changes with every jump.
|
||||
in property <int> jump-index: -1;
|
||||
in property <int> jump-requests;
|
||||
in property <string> status-text;
|
||||
// Unread messages in all chats of the current server.
|
||||
in property <int> unread-total;
|
||||
@@ -208,6 +351,9 @@ export global Bridge {
|
||||
// Our nickname on the current server, and the channel we are in.
|
||||
in property <string> nickname;
|
||||
in property <string> own-channel;
|
||||
// Its topic, and how many people it takes (-1: no limit).
|
||||
in property <string> own-channel-topic;
|
||||
in property <int> own-channel-limit: -1;
|
||||
in property <bool> voice-connected;
|
||||
in property <bool> voice-connecting;
|
||||
in property <bool> observing;
|
||||
@@ -236,12 +382,25 @@ export global Bridge {
|
||||
in property <image> viewer-frame;
|
||||
in property <bool> viewer-has-frame;
|
||||
in property <string> viewer-title;
|
||||
// Who streams it (their client id: -1 unknown).
|
||||
in property <string> viewer-streamer;
|
||||
in property <int> viewer-streamer-id: -1;
|
||||
// Shown instead of (or over) the picture: waiting, ended, errors.
|
||||
in property <string> viewer-status;
|
||||
in property <string> viewer-info;
|
||||
in property <bool> viewer-ended;
|
||||
in-out property <float> viewer-volume: 100;
|
||||
in property <bool> viewer-fullscreen;
|
||||
// The viewer fills the window without the shell ("pop out").
|
||||
in-out property <bool> viewer-popped;
|
||||
// "12:34" since the stream was joined.
|
||||
in property <string> viewer-elapsed;
|
||||
in property <int> viewer-count;
|
||||
// Simulcast layers the streamer offers, "Auto" first.
|
||||
in property <[string]> viewer-qualities;
|
||||
in-out property <int> viewer-quality: 0;
|
||||
// What "Auto" picked ("720p · 2.4 Mbit/s").
|
||||
in property <string> viewer-quality-detail;
|
||||
|
||||
// Settings.
|
||||
in property <[string]> input-devices;
|
||||
@@ -284,6 +443,27 @@ export global Bridge {
|
||||
callback select-tab(int);
|
||||
callback close-tab(int);
|
||||
callback send-message(string);
|
||||
// The page before the oldest shown message.
|
||||
callback load-older();
|
||||
// A message of the current chat, by its `key`.
|
||||
callback react(int, string);
|
||||
callback pin(int, bool);
|
||||
callback download-file(int, int);
|
||||
// Attach a file to the current channel chat (opens a file chooser).
|
||||
callback attach-file();
|
||||
// Pins drawer.
|
||||
callback open-pins();
|
||||
callback jump-to-pin(int);
|
||||
// Topics drawer: load them, open one (-1 closes), post into the open
|
||||
// one, start one from a message (by its `key`).
|
||||
callback open-topics();
|
||||
callback open-topic(int);
|
||||
callback send-topic-message(string);
|
||||
callback create-topic(int, string);
|
||||
// The member card: open it for a client (-1 closes it).
|
||||
callback open-member(int);
|
||||
callback member-action(string);
|
||||
callback member-volume(float);
|
||||
callback set-input-muted(bool);
|
||||
callback set-output-muted(bool);
|
||||
callback push-to-talk(bool);
|
||||
@@ -302,6 +482,8 @@ export global Bridge {
|
||||
callback leave-stream();
|
||||
callback set-stream-volume(float);
|
||||
callback toggle-fullscreen();
|
||||
// A simulcast layer of the watched stream (0: Auto).
|
||||
callback set-stream-quality(int);
|
||||
|
||||
callback open-settings();
|
||||
callback close-settings();
|
||||
@@ -311,6 +493,14 @@ export global Bridge {
|
||||
callback set-h264(bool);
|
||||
callback download-h264();
|
||||
callback appearance-changed(AppearanceForm);
|
||||
// The members panel was dragged to another width (pixels).
|
||||
callback panel-resized(float);
|
||||
// The voice channel view was opened or closed.
|
||||
callback show-voice-view(bool);
|
||||
// The members panel's search field.
|
||||
callback search-members(string);
|
||||
// The topics drawer's search field.
|
||||
callback search-topics(string);
|
||||
callback open-client(int) -> bool;
|
||||
callback client-audio-changed(ClientAudio);
|
||||
callback set-crash-reports(bool);
|
||||
@@ -326,6 +516,8 @@ export global Bridge {
|
||||
export global Images {
|
||||
// A Twemoji by key ("1f600", "1f468-200d-1f4bb"); empty if unknown.
|
||||
pure callback emoji(string) -> image;
|
||||
// The characters of a Twemoji key, to react with or to insert.
|
||||
pure callback emoji-text(string) -> string;
|
||||
}
|
||||
|
||||
// One emoji of the picker. `text` is what picking it inserts.
|
||||
|
||||
@@ -46,11 +46,12 @@ export component Button inherits Rectangle {
|
||||
property <color> fill: kind == ButtonKind.primary ? (active ? Theme.accent-pressed : touch.has-hover ? Theme.accent-hover : Theme.accent)
|
||||
: kind == ButtonKind.danger ? (active ? Theme.danger : touch.has-hover ? Theme.danger-soft.brighter(0.3) : Theme.danger-soft)
|
||||
: kind == ButtonKind.ghost ? (active ? Theme.surface-4 : touch.has-hover ? Theme.surface-3 : transparent)
|
||||
: checked ? (touch.has-hover ? Theme.accent-soft-hover : Theme.accent-soft)
|
||||
: (active ? Theme.surface-4 : touch.has-hover ? Theme.surface-3 : Theme.surface-2);
|
||||
property <color> ink: kind == ButtonKind.primary ? Theme.on-accent
|
||||
: !enabled ? Theme.text-disabled
|
||||
: kind == ButtonKind.danger ? (active ? Theme.on-accent : Theme.danger)
|
||||
: checked ? Theme.accent-text : Theme.text;
|
||||
: Theme.text;
|
||||
|
||||
min-width: self.min-height;
|
||||
min-height: small ? Theme.control-height-sm : Theme.control-height;
|
||||
|
||||
@@ -286,11 +286,13 @@ export component ResizeHandle inherits Rectangle {
|
||||
accessible-value: round(size / 1px);
|
||||
accessible-action-increment => { size = min(maximum, size + 16px); }
|
||||
accessible-action-decrement => { size = max(minimum, size - 16px); }
|
||||
Rectangle {
|
||||
width: 2px;
|
||||
height: 36px;
|
||||
border-radius: 1px;
|
||||
background: touch.has-hover || touch.pressed ? Theme.accent : Theme.border-strong;
|
||||
// Three dots, as a grip.
|
||||
for i in 3: Rectangle {
|
||||
y: (parent.height - 22px) / 2 + i * 9px;
|
||||
width: 4px;
|
||||
height: 4px;
|
||||
border-radius: 2px;
|
||||
background: touch.has-hover || touch.pressed ? Theme.accent : Theme.text-muted;
|
||||
}
|
||||
// The handle moves with the edge, so each move adds the distance from
|
||||
// where it was pressed.
|
||||
|
||||
@@ -11,6 +11,7 @@ export global Icons {
|
||||
out property <image> at-sign: @image-url("assets/icons/at-sign.svg");
|
||||
out property <image> audio-lines: @image-url("assets/icons/audio-lines.svg");
|
||||
out property <image> bell: @image-url("assets/icons/bell.svg");
|
||||
out property <image> book-open: @image-url("assets/icons/book-open.svg");
|
||||
out property <image> bookmark: @image-url("assets/icons/bookmark.svg");
|
||||
out property <image> calendar: @image-url("assets/icons/calendar.svg");
|
||||
out property <image> camera: @image-url("assets/icons/camera.svg");
|
||||
|
||||
@@ -45,6 +45,18 @@ export global Nav {
|
||||
in-out property <length> right-panel-width: 280px;
|
||||
// Incremented to focus the search field (Ctrl+K).
|
||||
in-out property <int> search-requests;
|
||||
// The voice channel we are in (people, streams, its chat) instead of
|
||||
// the plain chat.
|
||||
in-out property <bool> voice-view: false;
|
||||
// Drawers in place of the members panel (gateway features).
|
||||
in-out property <bool> pins-open;
|
||||
in-out property <bool> topics-open;
|
||||
// The message the emoji picker reacts to; 0: it fills the composer.
|
||||
in-out property <int> react-key;
|
||||
// "Start a topic" asks for a title first.
|
||||
in-out property <bool> topic-form-open;
|
||||
in-out property <int> topic-form-key;
|
||||
in-out property <string> topic-form-title;
|
||||
|
||||
// Dialogs.
|
||||
in-out property <bool> about-open;
|
||||
@@ -116,6 +128,48 @@ export global Nav {
|
||||
}
|
||||
}
|
||||
|
||||
// The pins and the topics share the drawer, so opening one closes the
|
||||
// other.
|
||||
public function show-pins(on: bool) {
|
||||
pins-open = on;
|
||||
if on {
|
||||
topics-open = false;
|
||||
Bridge.open-pins();
|
||||
}
|
||||
}
|
||||
|
||||
public function show-topics(on: bool) {
|
||||
topics-open = on;
|
||||
if on {
|
||||
pins-open = false;
|
||||
Bridge.open-topics();
|
||||
}
|
||||
}
|
||||
|
||||
// The members button: back from a drawer, or the panel on and off.
|
||||
public function toggle-members() {
|
||||
if pins-open || topics-open {
|
||||
pins-open = false;
|
||||
topics-open = false;
|
||||
right-panel-open = true;
|
||||
} else {
|
||||
right-panel-open = !right-panel-open;
|
||||
}
|
||||
}
|
||||
|
||||
// The voice channel view, or back to the chat (Rust opens the
|
||||
// channel's chat and puts the people in it first in the panel).
|
||||
public function show-voice(on: bool) {
|
||||
voice-view = on;
|
||||
Bridge.show-voice-view(on);
|
||||
}
|
||||
|
||||
public function start-topic(key: int) {
|
||||
topic-form-key = key;
|
||||
topic-form-title = "";
|
||||
topic-form-open = true;
|
||||
}
|
||||
|
||||
public function select-server(id: int) {
|
||||
show(Page.server);
|
||||
Bridge.select-server(id);
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// The chat: header, chat tabs, messages (virtualised), the composer with
|
||||
// the emoji picker.
|
||||
// The chat: header, chat tabs, the compact voice bar, messages
|
||||
// (virtualised) with reactions, pins and file cards, and the composer with
|
||||
// the emoji picker and the file attachment.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, ChatLine } from "../bridge.slint";
|
||||
import { Bridge, ChatLine, ReactionItem, FileItem, Images } from "../bridge.slint";
|
||||
import { Nav } from "../nav.slint";
|
||||
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, ListView } from "../components/index.slint";
|
||||
import { Icon, IconButton, Avatar, Chip, TabItem, TextField, RichText, Banner, Button, ButtonKind, Spinner, Tooltip, ListView } from "../components/index.slint";
|
||||
|
||||
// The header of the main area: an icon, a title and a description, and
|
||||
// actions (@children) at the right.
|
||||
@@ -57,19 +58,230 @@ export component PageHeader inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
// The emoji under a message; clicking one adds or removes ours, the last
|
||||
// pill picks another.
|
||||
export component Reactions inherits HorizontalLayout {
|
||||
in property <int> key;
|
||||
in property <[ReactionItem]> model;
|
||||
spacing: Theme.space-3;
|
||||
alignment: start;
|
||||
for reaction in root.model: Rectangle {
|
||||
width: pill.preferred-width + 22px;
|
||||
height: 30px;
|
||||
border-radius: Theme.radius-pill;
|
||||
background: reaction.me ? Theme.accent-soft : area.has-hover ? Theme.surface-3 : Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: reaction.me ? Theme.accent : Theme.border-strong;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: @tr("{} reacted {} times", reaction.text, reaction.count);
|
||||
accessible-checkable: true;
|
||||
accessible-checked: reaction.me;
|
||||
accessible-action-default => { Bridge.react(root.key, reaction.text); }
|
||||
area := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => { Bridge.react(root.key, reaction.text); }
|
||||
}
|
||||
pill := HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
alignment: center;
|
||||
if reaction.key != "": Image {
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
source: Images.emoji(reaction.key);
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if reaction.key == "": Text {
|
||||
text: reaction.text;
|
||||
font-size: Theme.font-body;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
text: reaction.count;
|
||||
color: reaction.me ? Theme.accent-text : Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
font-weight: Theme.weight-semibold;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
if Bridge.has-reactions: Rectangle {
|
||||
width: 40px;
|
||||
height: 30px;
|
||||
border-radius: Theme.radius-pill;
|
||||
background: add.has-hover ? Theme.surface-3 : Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border-strong;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: @tr("Add a reaction");
|
||||
accessible-action-default => {
|
||||
Nav.react-key = root.key;
|
||||
Nav.emoji-open = true;
|
||||
}
|
||||
Icon {
|
||||
source: Icons.smile-plus;
|
||||
size: 18px;
|
||||
tint: Theme.text-secondary;
|
||||
}
|
||||
add := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => {
|
||||
Nav.react-key = root.key;
|
||||
Nav.emoji-open = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A file a message links: name, size or progress, and a download button.
|
||||
component FileCard inherits Rectangle {
|
||||
in property <int> key;
|
||||
in property <FileItem> file;
|
||||
height: 64px;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: file.state == "failed" ? Theme.danger : Theme.border-strong;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: file.name;
|
||||
HorizontalLayout {
|
||||
padding: Theme.space-3;
|
||||
padding-left: Theme.space-4;
|
||||
spacing: Theme.space-4;
|
||||
Rectangle {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
border-radius: 20px;
|
||||
background: Theme.surface-4;
|
||||
Icon {
|
||||
source: file.picture ? Icons.image : Icons.file-text;
|
||||
size: Theme.icon-md;
|
||||
tint: Theme.accent-text;
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
spacing: 2px;
|
||||
Text {
|
||||
text: file.name;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-medium;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: file.detail;
|
||||
color: file.state == "failed" ? Theme.danger : Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
if file.state == "running": Rectangle {
|
||||
height: 3px;
|
||||
border-radius: 1.5px;
|
||||
background: Theme.surface-4;
|
||||
Rectangle {
|
||||
x: 0;
|
||||
width: parent.width * file.progress;
|
||||
height: parent.height;
|
||||
border-radius: parent.border-radius;
|
||||
background: Theme.accent;
|
||||
}
|
||||
}
|
||||
}
|
||||
if file.state != "running": IconButton {
|
||||
icon: file.state == "done" ? Icons.folder-open : Icons.download;
|
||||
label: file.state == "done" ? @tr("Downloaded") : @tr("Download {}", file.name);
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.download-file(root.key, file.index); }
|
||||
}
|
||||
if file.state == "running": Spinner {
|
||||
size: 18px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Quick reactions, pin and "start a topic" on a hovered message.
|
||||
component MessageActions inherits Rectangle {
|
||||
in property <int> key;
|
||||
in property <bool> pinned;
|
||||
width: row.preferred-width;
|
||||
height: 30px;
|
||||
border-radius: Theme.radius-md;
|
||||
background: Theme.surface-3;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border-strong;
|
||||
row := HorizontalLayout {
|
||||
padding-left: 2px;
|
||||
padding-right: 2px;
|
||||
spacing: 0px;
|
||||
if Bridge.has-reactions: HorizontalLayout {
|
||||
spacing: 0px;
|
||||
for quick in ["1f44d", "2764", "1f389", "1f602", "1f440"]: Rectangle {
|
||||
width: 26px;
|
||||
accessible-role: AccessibleRole.button;
|
||||
accessible-label: @tr("React");
|
||||
accessible-action-default => { Bridge.react(root.key, Images.emoji-text(quick)); }
|
||||
Image {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
source: Images.emoji(quick);
|
||||
}
|
||||
TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => { Bridge.react(root.key, Images.emoji-text(quick)); }
|
||||
}
|
||||
}
|
||||
}
|
||||
if Bridge.has-reactions: IconButton {
|
||||
icon: Icons.smile-plus;
|
||||
label: @tr("More emoji");
|
||||
size: 26px;
|
||||
icon-size: Theme.icon-sm;
|
||||
clicked => {
|
||||
Nav.react-key = root.key;
|
||||
Nav.emoji-open = true;
|
||||
}
|
||||
}
|
||||
if Bridge.has-pins: IconButton {
|
||||
icon: Icons.pin;
|
||||
label: root.pinned ? @tr("Unpin") : @tr("Pin");
|
||||
checked: root.pinned;
|
||||
size: 26px;
|
||||
icon-size: Theme.icon-sm;
|
||||
clicked => { Bridge.pin(root.key, !root.pinned); }
|
||||
}
|
||||
if Bridge.has-topics: IconButton {
|
||||
icon: Icons.messages-square;
|
||||
label: @tr("Start a topic");
|
||||
size: 26px;
|
||||
icon-size: Theme.icon-sm;
|
||||
clicked => { Nav.start-topic(root.key); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One message; `continued` lines (same author just before) omit the header.
|
||||
component MessageRow inherits Rectangle {
|
||||
export component MessageRow inherits Rectangle {
|
||||
in property <ChatLine> line;
|
||||
property <length> avatar: 40px;
|
||||
// The pins and topic lists show messages without their actions.
|
||||
in property <bool> actions: true;
|
||||
property <length> avatar: 44px;
|
||||
min-height: body.preferred-height;
|
||||
background: line.marked ? Theme.accent-soft : hover.has-hover ? Theme.surface-2.transparentize(0.6) : transparent;
|
||||
accessible-role: AccessibleRole.list-item;
|
||||
accessible-label: line.author + ": " + line.text;
|
||||
accessible-description: line.time;
|
||||
hover := TouchArea {
|
||||
// Let clicks through to the buttons inside.
|
||||
mouse-cursor: MouseCursor.default;
|
||||
}
|
||||
body := HorizontalLayout {
|
||||
padding-left: Theme.space-6;
|
||||
padding-right: Theme.space-6;
|
||||
padding-top: line.continued ? 1px : Theme.space-4;
|
||||
padding-bottom: 1px;
|
||||
padding-top: line.continued ? 2px : Theme.space-5;
|
||||
padding-bottom: 2px;
|
||||
spacing: Theme.space-4;
|
||||
VerticalLayout {
|
||||
width: root.avatar;
|
||||
@@ -78,6 +290,7 @@ component MessageRow inherits Rectangle {
|
||||
size: root.avatar;
|
||||
initials: line.initials;
|
||||
tint: line.tint;
|
||||
image: line.avatar;
|
||||
label: line.author;
|
||||
}
|
||||
}
|
||||
@@ -90,14 +303,14 @@ component MessageRow inherits Rectangle {
|
||||
Text {
|
||||
text: line.author;
|
||||
color: line.relayed ? Theme.accent-text : Theme.name-text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-semibold;
|
||||
font-size: Theme.font-lg;
|
||||
font-weight: Theme.weight-medium;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
text: line.time;
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-xs;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
if line.relayed: Chip {
|
||||
@@ -106,15 +319,213 @@ component MessageRow inherits Rectangle {
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if line.pinned: Chip {
|
||||
text: @tr("pinned");
|
||||
icon: Icons.pin;
|
||||
tint: Theme.warning;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if line.topic != "": Chip {
|
||||
text: line.topic;
|
||||
icon: Icons.messages-square;
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
if !line.rich: Text {
|
||||
if line.blocked: Text {
|
||||
text: @tr("Message from a blocked contact.");
|
||||
color: Theme.text-disabled;
|
||||
font-size: Theme.font-sm;
|
||||
font-italic: true;
|
||||
}
|
||||
if !line.blocked && !line.rich && line.text != "": Text {
|
||||
text: line.text;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-md;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
if line.rich: RichText {
|
||||
if !line.blocked && line.rich: RichText {
|
||||
runs: line.runs;
|
||||
emoji-size: line.jumbo ? 44px : Theme.font-body * 1.4;
|
||||
font-size: Theme.font-md;
|
||||
emoji-size: line.jumbo ? 44px : Theme.font-md * 1.4;
|
||||
}
|
||||
if line.files.length > 0 && !line.blocked: VerticalLayout {
|
||||
padding-top: Theme.space-2;
|
||||
padding-bottom: Theme.space-1;
|
||||
spacing: Theme.space-2;
|
||||
for file in line.files: FileCard {
|
||||
key: line.key;
|
||||
file: file;
|
||||
max-width: 440px;
|
||||
}
|
||||
}
|
||||
if line.reactions.length > 0: VerticalLayout {
|
||||
padding-top: Theme.space-2;
|
||||
padding-bottom: Theme.space-1;
|
||||
Reactions {
|
||||
key: line.key;
|
||||
model: line.reactions;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if root.actions && line.remote && hover.has-hover: MessageActions {
|
||||
x: parent.width - self.width - Theme.space-6;
|
||||
y: -12px;
|
||||
key: line.key;
|
||||
pinned: line.pinned;
|
||||
}
|
||||
}
|
||||
|
||||
// The messages of the current chat (or of an open topic). The list starts
|
||||
// at the newest message and follows new ones while it is at the end;
|
||||
// scrolling up stops that until the end is reached again.
|
||||
export component MessageList inherits VerticalLayout {
|
||||
in property <[ChatLine]> model;
|
||||
in property <bool> older;
|
||||
property <bool> follow: true;
|
||||
property <length> end: min(0px, list.visible-height - list.content-height);
|
||||
property <length> scrolled: list.content-y;
|
||||
changed end => {
|
||||
if root.follow {
|
||||
list.content-y = root.end;
|
||||
}
|
||||
}
|
||||
changed scrolled => { root.follow = root.scrolled <= root.end + 2px; }
|
||||
// Another chat: start at its end.
|
||||
property <int> tab: Bridge.current-tab;
|
||||
changed tab => {
|
||||
root.follow = true;
|
||||
list.content-y = root.end;
|
||||
}
|
||||
// A pinned message was jumped to: scroll to where its row is. Rows
|
||||
// differ in height, so this is the place of an average row (as the
|
||||
// standard list estimates it); the row itself is highlighted.
|
||||
property <int> jumps: Bridge.jump-requests;
|
||||
changed jumps => {
|
||||
if root.older && root.model.length > 0 {
|
||||
list.content-y = max(root.end, min(0px, list.visible-height / 3 - Bridge.jump-index * list.content-height / root.model.length));
|
||||
}
|
||||
}
|
||||
if Bridge.local-history: Rectangle {
|
||||
height: 30px;
|
||||
background: Theme.warning-soft;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-6;
|
||||
spacing: Theme.space-2;
|
||||
Icon {
|
||||
source: Icons.hard-drive;
|
||||
size: 14px;
|
||||
tint: Theme.warning;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: @tr("Only messages seen by this device.");
|
||||
color: Theme.warning;
|
||||
font-size: Theme.font-xs;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
}
|
||||
if root.older && Bridge.more-history: Rectangle {
|
||||
height: 40px;
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
Button {
|
||||
small: true;
|
||||
icon: Icons.chevron-up;
|
||||
text: Bridge.loading-history ? @tr("Loading…") : @tr("Older messages");
|
||||
enabled: !Bridge.loading-history;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.load-older(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
list := ListView {
|
||||
vertical-stretch: 1;
|
||||
// A long chat must not make the window taller: the list scrolls.
|
||||
preferred-height: 0px;
|
||||
accessible-label: @tr("Messages");
|
||||
for line in root.model: MessageRow {
|
||||
line: line;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The composer: a round attach button, the text field with the emoji
|
||||
// picker and send.
|
||||
export component Composer inherits HorizontalLayout {
|
||||
in property <string> placeholder;
|
||||
in property <bool> topic;
|
||||
padding: Theme.space-4;
|
||||
padding-left: Theme.space-5;
|
||||
padding-right: Theme.space-5;
|
||||
spacing: Theme.space-3;
|
||||
// Files go to the channel's file browser and a link into the chat.
|
||||
if !root.topic: IconButton {
|
||||
icon: Icons.plus;
|
||||
label: @tr("Attach a file");
|
||||
round: true;
|
||||
filled: true;
|
||||
size: 44px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.attach-file(); }
|
||||
}
|
||||
Rectangle {
|
||||
horizontal-stretch: 1;
|
||||
min-height: 48px;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: input.has-focus ? Theme.accent : Theme.border-strong;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-5;
|
||||
padding-right: Theme.space-2;
|
||||
spacing: Theme.space-2;
|
||||
input := TextField {
|
||||
text <=> Nav.draft;
|
||||
bare: true;
|
||||
placeholder: root.placeholder;
|
||||
label: @tr("Message");
|
||||
accepted(text) => {
|
||||
if text != "" {
|
||||
if root.topic {
|
||||
Bridge.send-topic-message(text);
|
||||
} else {
|
||||
Bridge.send-message(text);
|
||||
}
|
||||
self.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.smile;
|
||||
label: @tr("Emoji");
|
||||
checked: Nav.emoji-open;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => {
|
||||
Nav.react-key = 0;
|
||||
Nav.emoji-open = !Nav.emoji-open;
|
||||
}
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.send;
|
||||
label: @tr("Send");
|
||||
round: true;
|
||||
enabled: input.text != "";
|
||||
tint: input.text != "" ? Theme.on-accent : Theme.accent-text;
|
||||
filled: input.text != "";
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => {
|
||||
if input.text != "" {
|
||||
if root.topic {
|
||||
Bridge.send-topic-message(input.text);
|
||||
} else {
|
||||
Bridge.send-message(input.text);
|
||||
}
|
||||
input.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -133,25 +544,41 @@ export component ChatView inherits VerticalLayout {
|
||||
icon: root.tab-kind == 1 ? Icons.hash : root.tab-kind == 2 ? Icons.at-sign : Icons.message-square;
|
||||
title: root.tab-name;
|
||||
description: root.tab-topic != "" ? root.tab-topic : Bridge.server-title;
|
||||
if Bridge.presence-source != "": Chip {
|
||||
// Only when the chat does not come through our voice connection
|
||||
// (an invisible observer or a relay).
|
||||
if Bridge.presence-source != "" && !Bridge.voice-connected: Chip {
|
||||
text: Bridge.presence-source;
|
||||
icon: Icons.radio;
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if Bridge.viewer-open == false && Bridge.streams.length > 0: Button {
|
||||
small: true;
|
||||
icon: Icons.monitor-up;
|
||||
text: @tr("Streams ({})", Bridge.streams.length);
|
||||
if Bridge.has-pins: Button {
|
||||
icon: Icons.pin;
|
||||
text: @tr("Pinned Messages");
|
||||
checked: Nav.pins-open;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.right-panel-open = true; }
|
||||
clicked => { Nav.show-pins(!Nav.pins-open); }
|
||||
}
|
||||
if Bridge.has-topics: Button {
|
||||
icon: Icons.book-open;
|
||||
text: @tr("Topics");
|
||||
checked: Nav.topics-open;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.show-topics(!Nav.topics-open); }
|
||||
}
|
||||
// The voice channel we are in, with the people and the streams.
|
||||
if Bridge.voice-connected: IconButton {
|
||||
icon: Icons.volume-2;
|
||||
label: @tr("Voice channel");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.show-voice(true); }
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.users;
|
||||
label: @tr("Members and streams");
|
||||
checked: Nav.right-panel-open;
|
||||
label: @tr("Members");
|
||||
checked: Nav.right-panel-open && !Nav.pins-open && !Nav.topics-open;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.right-panel-open = !Nav.right-panel-open; }
|
||||
clicked => { Nav.toggle-members(); }
|
||||
}
|
||||
}
|
||||
if Bridge.crash-notice != "": Rectangle {
|
||||
@@ -207,65 +634,50 @@ export component ChatView inherits VerticalLayout {
|
||||
}
|
||||
}
|
||||
}
|
||||
messages := ListView {
|
||||
vertical-stretch: 1;
|
||||
accessible-label: @tr("Messages");
|
||||
for line in Bridge.messages: MessageRow {
|
||||
line: line;
|
||||
}
|
||||
}
|
||||
// Composer.
|
||||
HorizontalLayout {
|
||||
padding: Theme.space-4;
|
||||
padding-left: Theme.space-5;
|
||||
padding-right: Theme.space-5;
|
||||
spacing: Theme.space-3;
|
||||
composer := Rectangle {
|
||||
horizontal-stretch: 1;
|
||||
min-height: 48px;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: input.has-focus ? Theme.accent : Theme.border;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-5;
|
||||
padding-right: Theme.space-2;
|
||||
spacing: Theme.space-2;
|
||||
input := TextField {
|
||||
text <=> Nav.draft;
|
||||
bare: true;
|
||||
placeholder: root.tab-title != "" ? @tr("Message {}", root.tab-title) : @tr("Message");
|
||||
label: @tr("Message");
|
||||
accepted(text) => {
|
||||
if text != "" {
|
||||
Bridge.send-message(text);
|
||||
self.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.smile;
|
||||
label: @tr("Emoji");
|
||||
checked: Nav.emoji-open;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.emoji-open = !Nav.emoji-open; }
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.send;
|
||||
label: @tr("Send");
|
||||
round: true;
|
||||
enabled: input.text != "";
|
||||
tint: input.text != "" ? Theme.on-accent : Theme.text-muted;
|
||||
filled: input.text != "";
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => {
|
||||
if input.text != "" {
|
||||
Bridge.send-message(input.text);
|
||||
input.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
// The open topic replaces the chat.
|
||||
if Bridge.current-topic >= 0: Rectangle {
|
||||
height: 44px;
|
||||
background: Theme.surface-2.transparentize(0.4);
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-4;
|
||||
spacing: Theme.space-3;
|
||||
IconButton {
|
||||
icon: Icons.arrow-left;
|
||||
label: @tr("Back to the chat");
|
||||
size: 28px;
|
||||
icon-size: Theme.icon-sm;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.open-topic(-1); }
|
||||
}
|
||||
Icon {
|
||||
source: Icons.messages-square;
|
||||
size: Theme.icon-sm;
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.topic-title;
|
||||
color: Theme.text;
|
||||
font-weight: Theme.weight-semibold;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
}
|
||||
if Bridge.current-topic >= 0: MessageList {
|
||||
vertical-stretch: 1;
|
||||
model: Bridge.topic-messages;
|
||||
}
|
||||
if Bridge.current-topic < 0: MessageList {
|
||||
vertical-stretch: 1;
|
||||
model: Bridge.messages;
|
||||
older: true;
|
||||
}
|
||||
Composer {
|
||||
topic: Bridge.current-topic >= 0;
|
||||
placeholder: Bridge.current-topic >= 0 ? @tr("Reply in {}", Bridge.topic-title)
|
||||
: root.tab-title != "" ? @tr("Message {}", root.tab-title) : @tr("Message");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,376 @@
|
||||
// The pinned messages and the topics (threads) of the current chat. They
|
||||
// take the place of the members panel; both need a gateway, and the chat
|
||||
// header hides their buttons when the gateway does not offer them.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, PinItem, TopicItem, Images } from "../bridge.slint";
|
||||
import { Nav } from "../nav.slint";
|
||||
import { Icon, IconButton, Button, ButtonKind, TextField, SearchBox, Avatar, RichText, Spinner, Modal, ListView } from "../components/index.slint";
|
||||
import { Reactions } from "chat.slint";
|
||||
|
||||
// The title row both drawers share, above their content (@children).
|
||||
component Drawer inherits VerticalLayout {
|
||||
in property <string> title;
|
||||
in property <image> icon;
|
||||
callback closed();
|
||||
padding-top: Theme.space-4;
|
||||
spacing: Theme.space-3;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: title;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-5;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-3;
|
||||
if root.icon.width > 0: Icon {
|
||||
source: root.icon;
|
||||
size: Theme.icon-md;
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: root.title;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-lg;
|
||||
font-weight: Theme.weight-semibold;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.x;
|
||||
label: @tr("Close");
|
||||
size: 32px;
|
||||
icon-size: Theme.icon-md;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { root.closed(); }
|
||||
}
|
||||
}
|
||||
@children
|
||||
}
|
||||
|
||||
// A pinned message as a card: who and when, the pin (unpin), the text and
|
||||
// its reactions. Clicking the card jumps to the message in the chat.
|
||||
component PinCard inherits Rectangle {
|
||||
in property <PinItem> pin;
|
||||
min-height: body.preferred-height;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: area.has-hover ? Theme.surface-3 : Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border-strong;
|
||||
accessible-role: AccessibleRole.list-item;
|
||||
accessible-label: pin.line.author + ": " + pin.line.text;
|
||||
accessible-description: pin.by;
|
||||
accessible-action-default => {
|
||||
Bridge.jump-to-pin(pin.line.key);
|
||||
Nav.pins-open = false;
|
||||
}
|
||||
area := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => {
|
||||
Bridge.jump-to-pin(pin.line.key);
|
||||
Nav.pins-open = false;
|
||||
}
|
||||
}
|
||||
body := VerticalLayout {
|
||||
padding: Theme.space-4;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-2;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
Avatar {
|
||||
size: 28px;
|
||||
initials: pin.line.initials;
|
||||
tint: pin.line.tint;
|
||||
image: pin.line.avatar;
|
||||
label: pin.line.author;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: pin.line.author;
|
||||
color: Theme.name-text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-medium;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: pin.line.time;
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.pin;
|
||||
label: @tr("Unpin");
|
||||
tint: Theme.accent-text;
|
||||
size: 28px;
|
||||
icon-size: Theme.icon-sm;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.pin(pin.line.key, false); }
|
||||
}
|
||||
}
|
||||
if !pin.line.rich && pin.line.text != "": Text {
|
||||
text: pin.line.text;
|
||||
color: Theme.text;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
if pin.line.rich: RichText {
|
||||
runs: pin.line.runs;
|
||||
}
|
||||
for file in pin.line.files: HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Icon {
|
||||
source: file.picture ? Icons.image : Icons.file-text;
|
||||
size: Theme.icon-sm;
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: file.name;
|
||||
color: Theme.accent-text;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
if pin.line.reactions.length > 0: VerticalLayout {
|
||||
padding-top: Theme.space-2;
|
||||
Reactions {
|
||||
key: pin.line.key;
|
||||
model: pin.line.reactions;
|
||||
}
|
||||
}
|
||||
Text {
|
||||
text: pin.by;
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-xs;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The pinned messages of the current chat.
|
||||
export component PinsDrawer inherits Drawer {
|
||||
title: @tr("Pinned Messages");
|
||||
icon: Icons.pin;
|
||||
closed => { Nav.pins-open = false; }
|
||||
if Bridge.pins-loading: HorizontalLayout {
|
||||
padding: Theme.space-6;
|
||||
alignment: center;
|
||||
Spinner { size: 20px; }
|
||||
}
|
||||
if !Bridge.pins-loading && Bridge.pins.length == 0: VerticalLayout {
|
||||
padding: Theme.space-6;
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: @tr("Nothing pinned yet.");
|
||||
color: Theme.text-secondary;
|
||||
font-weight: Theme.weight-medium;
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
Text {
|
||||
text: @tr("Hover a message and press the pin.");
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
horizontal-alignment: center;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
ListView {
|
||||
vertical-stretch: 1;
|
||||
accessible-label: @tr("Pinned messages");
|
||||
for pin in Bridge.pins: VerticalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
padding-bottom: Theme.space-3;
|
||||
PinCard {
|
||||
pin: pin;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A topic: its icon, title, what is in it and when it was last active.
|
||||
component TopicCard inherits Rectangle {
|
||||
in property <TopicItem> topic;
|
||||
min-height: body.preferred-height;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: Bridge.current-topic == topic.id ? Theme.accent-soft : area.has-hover ? Theme.surface-3 : Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: Bridge.current-topic == topic.id ? Theme.accent : Theme.border-strong;
|
||||
accessible-role: AccessibleRole.list-item;
|
||||
accessible-label: topic.title;
|
||||
accessible-description: topic.detail;
|
||||
accessible-action-default => {
|
||||
Bridge.open-topic(topic.id);
|
||||
Nav.topics-open = false;
|
||||
}
|
||||
area := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => {
|
||||
Bridge.open-topic(topic.id);
|
||||
Nav.topics-open = false;
|
||||
}
|
||||
}
|
||||
body := HorizontalLayout {
|
||||
padding: Theme.space-4;
|
||||
spacing: Theme.space-4;
|
||||
VerticalLayout {
|
||||
alignment: start;
|
||||
Rectangle {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: Theme.radius-md;
|
||||
background: Theme.surface-4;
|
||||
Icon {
|
||||
source: topic.archived ? Icons.bookmark : Icons.messages-square;
|
||||
size: 22px;
|
||||
tint: topic.archived ? Theme.text-muted : Theme.text-secondary;
|
||||
}
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
horizontal-stretch: 1;
|
||||
spacing: Theme.space-1;
|
||||
Text {
|
||||
text: topic.title;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-medium;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: topic.detail;
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
padding-top: Theme.space-1;
|
||||
Rectangle {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
border-radius: 3.5px;
|
||||
background: topic.recent ? Theme.success : Theme.offline;
|
||||
}
|
||||
Text {
|
||||
text: topic.activity;
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The topics (threads) of the current chat: search, open, create.
|
||||
export component TopicsDrawer inherits Drawer {
|
||||
title: @tr("Topics");
|
||||
closed => { Nav.topics-open = false; }
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
SearchBox {
|
||||
height: 40px;
|
||||
show-shortcut: false;
|
||||
placeholder: @tr("Search topics…");
|
||||
label: @tr("Search topics");
|
||||
edited(text) => { Bridge.search-topics(text); }
|
||||
}
|
||||
}
|
||||
if Bridge.topics-loading: HorizontalLayout {
|
||||
padding: Theme.space-6;
|
||||
alignment: center;
|
||||
Spinner { size: 20px; }
|
||||
}
|
||||
if !Bridge.topics-loading && Bridge.topics.length == 0: VerticalLayout {
|
||||
padding: Theme.space-6;
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: @tr("No topics yet.");
|
||||
color: Theme.text-secondary;
|
||||
font-weight: Theme.weight-medium;
|
||||
horizontal-alignment: center;
|
||||
}
|
||||
Text {
|
||||
text: @tr("Start one from a message, or below.");
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
horizontal-alignment: center;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
ListView {
|
||||
vertical-stretch: 1;
|
||||
accessible-label: @tr("Topics");
|
||||
for topic in Bridge.topics: VerticalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
padding-bottom: Theme.space-3;
|
||||
TopicCard {
|
||||
topic: topic;
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding: Theme.space-3;
|
||||
padding-bottom: Theme.space-4;
|
||||
Button {
|
||||
horizontal-stretch: 1;
|
||||
kind: ButtonKind.primary;
|
||||
icon: Icons.plus;
|
||||
text: @tr("Create Topic");
|
||||
clicked => { Nav.start-topic(-1); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Asking for a topic's title (from a message, or standalone).
|
||||
export component TopicDialog inherits Modal {
|
||||
title: @tr("Start a topic");
|
||||
subtitle: Nav.topic-form-key > 0 ? @tr("From the chosen message.") : @tr("A new thread in this chat.");
|
||||
icon: Icons.messages-square;
|
||||
card-width: 460px;
|
||||
card-height: 260px;
|
||||
callback done();
|
||||
dismissed => { root.done(); }
|
||||
VerticalLayout {
|
||||
spacing: Theme.space-4;
|
||||
field := TextField {
|
||||
text <=> Nav.topic-form-title;
|
||||
placeholder: @tr("What is it about?");
|
||||
label: @tr("Title");
|
||||
accepted(text) => {
|
||||
if text != "" {
|
||||
Bridge.create-topic(Nav.topic-form-key, text);
|
||||
root.done();
|
||||
}
|
||||
}
|
||||
}
|
||||
Rectangle { vertical-stretch: 1; }
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
alignment: end;
|
||||
Button {
|
||||
text: @tr("Cancel");
|
||||
clicked => { root.done(); }
|
||||
}
|
||||
Button {
|
||||
kind: ButtonKind.primary;
|
||||
icon: Icons.check;
|
||||
text: @tr("Create");
|
||||
enabled: field.text != "";
|
||||
clicked => {
|
||||
Bridge.create-topic(Nav.topic-form-key, field.text);
|
||||
root.done();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,424 @@
|
||||
// The members panel: everyone on the server in sections (the people in our
|
||||
// voice channel or those streaming first, then each server group), a
|
||||
// search, and a card for one person.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, MemberItem } from "../bridge.slint";
|
||||
import { Nav } from "../nav.slint";
|
||||
import { Icon, IconButton, Button, ButtonKind, Avatar, Status, LiveBadge, Chip, Divider, Slider, SpeakingBars, Tooltip, SearchBox, ListView } from "../components/index.slint";
|
||||
|
||||
// Crown, priority speaker, channel commander, recording.
|
||||
component MemberBadges inherits HorizontalLayout {
|
||||
in property <MemberItem> member;
|
||||
in property <length> size: 14px;
|
||||
spacing: 3px;
|
||||
if member.admin: Icon {
|
||||
source: Icons.crown;
|
||||
size: root.size;
|
||||
tint: Theme.gold;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: @tr("server admin");
|
||||
}
|
||||
if member.priority: Icon {
|
||||
source: Icons.star;
|
||||
size: root.size;
|
||||
tint: Theme.accent-text;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: @tr("priority speaker");
|
||||
}
|
||||
if member.commander: Icon {
|
||||
source: Icons.flag;
|
||||
size: root.size;
|
||||
tint: Theme.info;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: @tr("channel commander");
|
||||
}
|
||||
if member.recording: Icon {
|
||||
source: Icons.record;
|
||||
size: root.size;
|
||||
tint: Theme.danger;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: @tr("recording");
|
||||
}
|
||||
}
|
||||
|
||||
// The heading above the first member of a section: "Moderator — 3".
|
||||
export component GroupHeader inherits HorizontalLayout {
|
||||
in property <MemberItem> member;
|
||||
padding-top: Theme.space-5;
|
||||
padding-bottom: Theme.space-2;
|
||||
padding-left: Theme.space-2;
|
||||
spacing: Theme.space-2;
|
||||
if member.group-icon.width > 0: Image {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
source: member.group-icon;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: member.group-count > 0 ? @tr("{} — {}", member.group, member.group-count) : member.group;
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-medium;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
|
||||
// One person in the panel: avatar, name with badges and role, what they
|
||||
// are doing.
|
||||
export component MemberRow inherits Rectangle {
|
||||
in property <MemberItem> member;
|
||||
height: 52px * Theme.font-scale;
|
||||
border-radius: Theme.radius-md;
|
||||
background: Bridge.member-card.open && Bridge.member-card.id == member.id ? Theme.accent-soft
|
||||
: area.has-hover ? Theme.surface-3 : transparent;
|
||||
accessible-role: AccessibleRole.list-item;
|
||||
accessible-label: member.name;
|
||||
accessible-description: member.status;
|
||||
accessible-action-default => { Bridge.open-member(member.id); }
|
||||
area := TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => { Bridge.open-member(member.id); }
|
||||
}
|
||||
opacity: member.away ? 0.6 : 1.0;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-2;
|
||||
padding-right: Theme.space-2;
|
||||
spacing: Theme.space-3;
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
Avatar {
|
||||
size: 40px;
|
||||
initials: member.initials;
|
||||
tint: member.tint;
|
||||
image: member.avatar;
|
||||
speaking: member.talking;
|
||||
status: member.away ? Status.idle : member.sound-off ? Status.dnd : Status.online;
|
||||
label: member.name;
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
spacing: 1px;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
Text {
|
||||
text: member.name;
|
||||
color: member.myself ? Theme.accent-text : member.role != "" ? Theme.name-text : Theme.text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-medium;
|
||||
overflow: elide;
|
||||
}
|
||||
MemberBadges {
|
||||
member: member;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
Text {
|
||||
text: member.status;
|
||||
color: member.talking ? Theme.success : Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
if member.talking: SpeakingBars {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if member.streaming: Icon {
|
||||
source: Icons.monitor;
|
||||
size: 14px;
|
||||
tint: Theme.text-secondary;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
if member.role != "": Icon {
|
||||
source: Icons.shield-check;
|
||||
size: 18px;
|
||||
tint: #c06cff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if member.role != "": Chip {
|
||||
text: member.role;
|
||||
fill: Theme.surface-3;
|
||||
outlined: true;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if member.streaming: VerticalLayout {
|
||||
alignment: center;
|
||||
LiveBadge { }
|
||||
}
|
||||
if member.muted: Icon {
|
||||
source: Icons.mic-off;
|
||||
size: 16px;
|
||||
tint: Theme.danger;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if member.sound-off: Icon {
|
||||
source: Icons.headphone-off;
|
||||
size: 16px;
|
||||
tint: Theme.danger;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if member.talk-power > 0: Text {
|
||||
text: member.talk-power;
|
||||
color: Theme.text-disabled;
|
||||
font-size: Theme.font-xs;
|
||||
vertical-alignment: center;
|
||||
accessible-label: @tr("talk power {}", member.talk-power);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Everything about one person, over the panel.
|
||||
export component MemberCardPopup inherits Rectangle {
|
||||
property <length> card-width: 300px;
|
||||
width: root.card-width;
|
||||
height: card.preferred-height;
|
||||
background: Theme.surface-3;
|
||||
border-radius: Theme.radius-lg;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border-strong;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: Bridge.member-card.name;
|
||||
// Clicks inside stay inside.
|
||||
TouchArea { }
|
||||
card := VerticalLayout {
|
||||
padding: Theme.space-4;
|
||||
spacing: Theme.space-3;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
Avatar {
|
||||
size: 52px;
|
||||
initials: Bridge.member-card.initials;
|
||||
tint: Bridge.member-card.tint;
|
||||
image: Bridge.member-card.avatar;
|
||||
label: Bridge.member-card.name;
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
spacing: 2px;
|
||||
Text {
|
||||
text: Bridge.member-card.name;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-lg;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.member-card.status;
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.x;
|
||||
label: @tr("Close");
|
||||
size: 26px;
|
||||
icon-size: Theme.icon-sm;
|
||||
clicked => { Bridge.open-member(-1); }
|
||||
}
|
||||
}
|
||||
if Bridge.member-card.description != "": Text {
|
||||
text: Bridge.member-card.description;
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
if Bridge.member-card.groups.length > 0: VerticalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: @tr("Groups");
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-xs;
|
||||
font-weight: Theme.weight-semibold;
|
||||
}
|
||||
for group in Bridge.member-card.groups: Text {
|
||||
text: group;
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
if Bridge.member-card.talk-power > 0: Chip {
|
||||
text: @tr("talk power {}", Bridge.member-card.talk-power);
|
||||
icon: Icons.mic;
|
||||
}
|
||||
if Bridge.member-card.country != "": Chip {
|
||||
text: Bridge.member-card.country;
|
||||
icon: Icons.globe;
|
||||
}
|
||||
}
|
||||
Divider { }
|
||||
// Local playback of this person.
|
||||
VerticalLayout {
|
||||
spacing: Theme.space-2;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: @tr("Volume");
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
}
|
||||
Text {
|
||||
text: @tr("{}%", round(Bridge.member-card.volume));
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-xs;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
IconButton {
|
||||
icon: Bridge.member-card.muted ? Icons.volume-x : Icons.volume-2;
|
||||
label: Bridge.member-card.muted ? @tr("Unmute for me") : @tr("Mute for me");
|
||||
checked: Bridge.member-card.muted;
|
||||
danger: true;
|
||||
size: 30px;
|
||||
icon-size: Theme.icon-sm;
|
||||
enabled: Bridge.member-card.known;
|
||||
clicked => { Bridge.member-action("mute"); }
|
||||
}
|
||||
Slider {
|
||||
horizontal-stretch: 1;
|
||||
minimum: 0;
|
||||
maximum: 200;
|
||||
step: 5;
|
||||
value: Bridge.member-card.volume;
|
||||
enabled: Bridge.member-card.known && !Bridge.member-card.muted;
|
||||
label: @tr("Volume of {}", Bridge.member-card.name);
|
||||
changed(v) => { Bridge.member-volume(v); }
|
||||
}
|
||||
}
|
||||
}
|
||||
Divider { }
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Button {
|
||||
horizontal-stretch: 1;
|
||||
small: true;
|
||||
icon: Icons.message-square;
|
||||
text: @tr("Message");
|
||||
enabled: Bridge.member-card.known;
|
||||
clicked => { Bridge.member-action("message"); }
|
||||
}
|
||||
Button {
|
||||
horizontal-stretch: 1;
|
||||
small: true;
|
||||
icon: Icons.hand;
|
||||
text: @tr("Poke");
|
||||
clicked => { Bridge.member-action("poke"); }
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Button {
|
||||
horizontal-stretch: 1;
|
||||
small: true;
|
||||
icon: Icons.user-plus;
|
||||
text: Bridge.member-card.friend ? @tr("Friend") : @tr("Add friend");
|
||||
checked: Bridge.member-card.friend;
|
||||
enabled: Bridge.member-card.known;
|
||||
clicked => { Bridge.member-action("friend"); }
|
||||
}
|
||||
Button {
|
||||
horizontal-stretch: 1;
|
||||
small: true;
|
||||
kind: Bridge.member-card.blocked ? ButtonKind.danger : ButtonKind.secondary;
|
||||
icon: Icons.shield;
|
||||
text: Bridge.member-card.blocked ? @tr("Blocked") : @tr("Block");
|
||||
enabled: Bridge.member-card.known;
|
||||
clicked => { Bridge.member-action("blocked"); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The right panel of a server: "Members — 412", a search, everyone in
|
||||
// sections. Its width is the setting `ui.members_width`.
|
||||
export component MembersPanel inherits VerticalLayout {
|
||||
property <bool> searching;
|
||||
padding-top: Theme.space-4;
|
||||
padding-bottom: Theme.space-2;
|
||||
spacing: Theme.space-2;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-5;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: @tr("Members — {}", Bridge.member-total);
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-lg;
|
||||
font-weight: Theme.weight-medium;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.search;
|
||||
label: @tr("Search members");
|
||||
checked: root.searching;
|
||||
size: 32px;
|
||||
icon-size: Theme.icon-sm;
|
||||
clicked => {
|
||||
root.searching = !root.searching;
|
||||
if !root.searching {
|
||||
Bridge.search-members("");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if root.searching: HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-4;
|
||||
SearchBox {
|
||||
height: 36px;
|
||||
show-shortcut: false;
|
||||
placeholder: @tr("Search members…");
|
||||
label: @tr("Search members");
|
||||
init => { self.focus(); }
|
||||
edited(text) => { Bridge.search-members(text); }
|
||||
}
|
||||
}
|
||||
if Bridge.server-members.length == 0: HorizontalLayout {
|
||||
padding-left: Theme.space-5;
|
||||
padding-right: Theme.space-5;
|
||||
Text {
|
||||
text: @tr("Connect or observe to see who is here.");
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
}
|
||||
ListView {
|
||||
vertical-stretch: 1;
|
||||
accessible-role: AccessibleRole.list;
|
||||
accessible-label: @tr("Members");
|
||||
for member in Bridge.server-members: VerticalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
if member.first-in-group: GroupHeader {
|
||||
member: member;
|
||||
}
|
||||
MemberRow {
|
||||
member: member;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,13 @@
|
||||
// Streams: the right panel (people in our channel, streams, requests to
|
||||
// Streams: the phone's panel (people in our channel, streams, requests to
|
||||
// watch ours) and the viewer.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, StreamItem, MemberItem } from "../bridge.slint";
|
||||
import { Nav } from "../nav.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, Avatar, Status, LiveBadge, Chip, SectionHeader, SpeakingBars, Slider, Spinner, ListView, ScrollView } from "../components/index.slint";
|
||||
import { Icon, Button, ButtonKind, IconButton, Avatar, Status, LiveBadge, Chip, Select, SectionHeader, SpeakingBars, Slider, Spinner, TextField, TabItem, ListView, ScrollView } from "../components/index.slint";
|
||||
import { MemberRow, GroupHeader } from "members.slint";
|
||||
import { PageHeader, MessageList, Composer } from "chat.slint";
|
||||
|
||||
// A stream card: the streamer, the title, watch / show / leave.
|
||||
component StreamCard inherits Rectangle {
|
||||
@@ -88,82 +90,6 @@ component StreamCard inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
// A person in our channel.
|
||||
component MemberRow inherits Rectangle {
|
||||
in property <MemberItem> member;
|
||||
height: 48px * Theme.font-scale;
|
||||
border-radius: Theme.radius-md;
|
||||
background: area.has-hover ? Theme.surface-3 : transparent;
|
||||
accessible-role: AccessibleRole.list-item;
|
||||
accessible-label: member.name;
|
||||
accessible-description: member.status;
|
||||
accessible-action-default => { Nav.open-client(member.id); }
|
||||
area := TouchArea {
|
||||
enabled: !member.myself;
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => { Nav.open-client(member.id); }
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-2;
|
||||
padding-right: Theme.space-2;
|
||||
spacing: Theme.space-3;
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
Avatar {
|
||||
size: 34px;
|
||||
initials: member.initials;
|
||||
tint: member.tint;
|
||||
speaking: member.talking;
|
||||
status: member.away ? Status.idle : member.sound-off ? Status.dnd : Status.online;
|
||||
label: member.name;
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: member.name;
|
||||
color: member.myself ? Theme.accent-text : Theme.name-text;
|
||||
font-weight: Theme.weight-medium;
|
||||
overflow: elide;
|
||||
}
|
||||
if member.streaming: VerticalLayout {
|
||||
alignment: center;
|
||||
LiveBadge { }
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: member.status;
|
||||
color: member.talking ? Theme.success : Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
if member.talking: SpeakingBars {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
if member.muted: Icon {
|
||||
source: Icons.mic-off;
|
||||
size: 16px;
|
||||
tint: Theme.danger;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if member.sound-off: Icon {
|
||||
source: Icons.headphone-off;
|
||||
size: 16px;
|
||||
tint: Theme.danger;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The right panel of a server: who is in our channel, the streams there,
|
||||
// and requests to watch ours.
|
||||
export component StreamsPanel inherits VerticalLayout {
|
||||
@@ -199,8 +125,13 @@ export component StreamsPanel inherits VerticalLayout {
|
||||
width: sv.visible-width;
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
for member in Bridge.members: MemberRow {
|
||||
member: member;
|
||||
for member in Bridge.members: VerticalLayout {
|
||||
if member.first-in-group: GroupHeader {
|
||||
member: member;
|
||||
}
|
||||
MemberRow {
|
||||
member: member;
|
||||
}
|
||||
}
|
||||
if Bridge.streams-available: VerticalLayout {
|
||||
padding-top: Theme.space-4;
|
||||
@@ -258,158 +189,342 @@ export component StreamsPanel inherits VerticalLayout {
|
||||
}
|
||||
}
|
||||
|
||||
// The stream we watch: title bar, picture, player controls.
|
||||
export component StreamViewer inherits Rectangle {
|
||||
background: Theme.dark ? #03060f : #0b1330;
|
||||
// The player: the picture with the streamer, the title and LIVE over its
|
||||
// top, and the controls over its bottom. `compact` (full screen, the
|
||||
// phone) adds Leave, which the header has otherwise.
|
||||
component StreamPlayer inherits Rectangle {
|
||||
in property <bool> compact;
|
||||
border-radius: compact ? 0px : Theme.radius-lg;
|
||||
clip: true;
|
||||
background: #000000;
|
||||
border-width: compact ? 0px : 1px;
|
||||
border-color: Theme.border-strong;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: @tr("Stream viewer");
|
||||
VerticalLayout {
|
||||
// Title bar.
|
||||
Rectangle {
|
||||
height: 64px;
|
||||
background: Theme.surface;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-5;
|
||||
padding-right: Theme.space-4;
|
||||
spacing: Theme.space-4;
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
Avatar {
|
||||
size: 40px;
|
||||
initials: "";
|
||||
tint: Theme.accent-soft;
|
||||
label: Bridge.viewer-title;
|
||||
Icon {
|
||||
source: Icons.monitor-up;
|
||||
tint: #ffffff;
|
||||
}
|
||||
}
|
||||
}
|
||||
VerticalLayout {
|
||||
alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
Text {
|
||||
text: Bridge.viewer-title;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.viewer-info;
|
||||
color: Theme.text-muted;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
if !Bridge.viewer-ended: VerticalLayout {
|
||||
alignment: center;
|
||||
LiveBadge { large: true; }
|
||||
accessible-label: Bridge.viewer-title;
|
||||
Image {
|
||||
width: parent.width;
|
||||
height: parent.height;
|
||||
source: Bridge.viewer-frame;
|
||||
image-fit: contain;
|
||||
visible: Bridge.viewer-has-frame;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: @tr("Stream picture");
|
||||
}
|
||||
if Bridge.viewer-status != "": Rectangle {
|
||||
width: min(parent.width - 32px, status-text.preferred-width + 40px);
|
||||
height: status-text.preferred-height + 24px;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: Theme.overlay;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border-strong;
|
||||
status-text := Text {
|
||||
width: min(root.width - 72px, self.preferred-width);
|
||||
text: Bridge.viewer-status;
|
||||
color: #ffffff;
|
||||
horizontal-alignment: center;
|
||||
wrap: word-wrap;
|
||||
accessible-live-region: polite;
|
||||
}
|
||||
}
|
||||
// Shades for the text over the picture.
|
||||
Rectangle {
|
||||
y: 0;
|
||||
height: 110px;
|
||||
background: @linear-gradient(180deg, #000000c0 0%, #00000000 100%);
|
||||
}
|
||||
Rectangle {
|
||||
y: parent.height - self.height;
|
||||
height: 90px;
|
||||
background: @linear-gradient(180deg, #00000000 0%, #000000c8 100%);
|
||||
}
|
||||
// Who streams what, LIVE and the quality.
|
||||
HorizontalLayout {
|
||||
y: 0;
|
||||
height: 84px;
|
||||
padding: Theme.space-4;
|
||||
spacing: Theme.space-3;
|
||||
if Bridge.viewer-streamer-id >= 0: VerticalLayout {
|
||||
alignment: start;
|
||||
Rectangle {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
for member in Bridge.members: Avatar {
|
||||
visible: member.id == Bridge.viewer-streamer-id;
|
||||
size: 44px;
|
||||
initials: member.initials;
|
||||
tint: member.tint;
|
||||
image: member.avatar;
|
||||
label: member.name;
|
||||
}
|
||||
}
|
||||
}
|
||||
// Picture.
|
||||
Rectangle {
|
||||
vertical-stretch: 1;
|
||||
Image {
|
||||
width: parent.width;
|
||||
height: parent.height;
|
||||
source: Bridge.viewer-frame;
|
||||
image-fit: contain;
|
||||
visible: Bridge.viewer-has-frame;
|
||||
accessible-role: AccessibleRole.image;
|
||||
accessible-label: @tr("Stream picture");
|
||||
VerticalLayout {
|
||||
alignment: start;
|
||||
horizontal-stretch: 1;
|
||||
spacing: 1px;
|
||||
Text {
|
||||
text: Bridge.viewer-streamer;
|
||||
color: Theme.name-text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
}
|
||||
if Bridge.viewer-status != "": Rectangle {
|
||||
width: min(parent.width - 32px, status-text.preferred-width + 40px);
|
||||
height: status-text.preferred-height + 24px;
|
||||
border-radius: Theme.radius-lg;
|
||||
background: Theme.overlay;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border-strong;
|
||||
status-text := Text {
|
||||
width: min(root.width - 72px, self.preferred-width);
|
||||
text: Bridge.viewer-status;
|
||||
color: #ffffff;
|
||||
horizontal-alignment: center;
|
||||
wrap: word-wrap;
|
||||
accessible-live-region: polite;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.viewer-title;
|
||||
color: #ffffff;
|
||||
font-size: Theme.font-md;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.viewer-count > 0 ? @tr("{} watching", Bridge.viewer-count) : "";
|
||||
color: #ffffffb8;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
// Controls.
|
||||
Rectangle {
|
||||
height: 52px;
|
||||
background: Theme.surface;
|
||||
if !Bridge.viewer-ended: VerticalLayout {
|
||||
alignment: start;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-4;
|
||||
spacing: Theme.space-3;
|
||||
Icon {
|
||||
source: Bridge.viewer-volume > 0 ? Icons.volume-2 : Icons.volume-x;
|
||||
tint: Theme.text-secondary;
|
||||
spacing: Theme.space-2;
|
||||
LiveBadge {
|
||||
large: true;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Slider {
|
||||
width: 140px;
|
||||
// Simulcast layers the streamer offers; "Auto" follows the
|
||||
// bandwidth estimate.
|
||||
if Bridge.viewer-qualities.length > 1: Select {
|
||||
width: 150px;
|
||||
horizontal-stretch: 0;
|
||||
icon: Icons.sliders-horizontal;
|
||||
label: @tr("Quality");
|
||||
model: Bridge.viewer-qualities;
|
||||
current-index <=> Bridge.viewer-quality;
|
||||
selected(_) => { Bridge.set-stream-quality(Bridge.viewer-quality); }
|
||||
}
|
||||
// What arrives: the decoded picture's height.
|
||||
if Bridge.viewer-qualities.length <= 1 && Bridge.viewer-has-frame: Chip {
|
||||
text: @tr("{}p", Bridge.viewer-frame.height);
|
||||
tint: #ffffff;
|
||||
fill: #060a18b0;
|
||||
outlined: true;
|
||||
height: 26px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
minimum: 0;
|
||||
maximum: 200;
|
||||
step: 5;
|
||||
value <=> Bridge.viewer-volume;
|
||||
enabled: !Bridge.viewer-ended;
|
||||
label: @tr("Stream volume");
|
||||
changed(v) => { Bridge.set-stream-volume(v); }
|
||||
}
|
||||
Text {
|
||||
text: @tr("{}%", round(Bridge.viewer-volume));
|
||||
width: 44px;
|
||||
vertical-alignment: center;
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
}
|
||||
if !Bridge.viewer-ended: HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
Rectangle {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
border-radius: 4px;
|
||||
background: Theme.live;
|
||||
}
|
||||
Text {
|
||||
text: @tr("LIVE");
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-sm;
|
||||
font-weight: Theme.weight-semibold;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
Rectangle { horizontal-stretch: 1; }
|
||||
IconButton {
|
||||
icon: Bridge.viewer-fullscreen ? Icons.minimize-2 : Icons.maximize;
|
||||
label: Bridge.viewer-fullscreen ? @tr("Exit full screen") : @tr("Full screen");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.toggle-fullscreen(); }
|
||||
}
|
||||
if !Bridge.viewer-fullscreen: Button {
|
||||
small: true;
|
||||
icon: Icons.message-square;
|
||||
text: @tr("Chat");
|
||||
accessible-label: @tr("Back to the chat");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.hide-viewer(); }
|
||||
}
|
||||
Button {
|
||||
small: true;
|
||||
kind: ButtonKind.danger;
|
||||
icon: Icons.log-out;
|
||||
text: Bridge.viewer-ended ? @tr("Close") : @tr("Leave");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.leave-stream(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Controls.
|
||||
HorizontalLayout {
|
||||
y: parent.height - self.height;
|
||||
height: 56px;
|
||||
padding-left: Theme.space-3;
|
||||
padding-right: Theme.space-3;
|
||||
spacing: Theme.space-2;
|
||||
IconButton {
|
||||
icon: Bridge.viewer-volume > 0 ? Icons.volume-2 : Icons.volume-x;
|
||||
label: Bridge.viewer-volume > 0 ? @tr("Mute") : @tr("Unmute");
|
||||
tint: #ffffff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.set-stream-volume(Bridge.viewer-volume > 0 ? 0 : 100); }
|
||||
}
|
||||
Slider {
|
||||
width: 110px;
|
||||
horizontal-stretch: 0;
|
||||
y: (parent.height - self.height) / 2;
|
||||
minimum: 0;
|
||||
maximum: 200;
|
||||
step: 5;
|
||||
value <=> Bridge.viewer-volume;
|
||||
enabled: !Bridge.viewer-ended;
|
||||
label: @tr("Stream volume");
|
||||
changed(v) => { Bridge.set-stream-volume(v); }
|
||||
}
|
||||
if !Bridge.viewer-ended: HorizontalLayout {
|
||||
padding-left: Theme.space-3;
|
||||
spacing: Theme.space-2;
|
||||
horizontal-stretch: 0;
|
||||
Rectangle {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
border-radius: 4px;
|
||||
background: Theme.live;
|
||||
}
|
||||
Text {
|
||||
text: @tr("LIVE");
|
||||
color: #ffffff;
|
||||
font-size: Theme.font-sm;
|
||||
font-weight: Theme.weight-semibold;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.viewer-elapsed;
|
||||
color: #ffffffa0;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
}
|
||||
Rectangle { horizontal-stretch: 1; }
|
||||
if !Bridge.viewer-fullscreen && !Nav.narrow: IconButton {
|
||||
icon: Icons.minimize-2;
|
||||
label: @tr("Back to the chat (keeps watching)");
|
||||
tint: #ffffff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.hide-viewer(); }
|
||||
}
|
||||
if !Nav.narrow: IconButton {
|
||||
icon: Icons.external-link;
|
||||
label: Bridge.viewer-popped ? @tr("Back to the window") : @tr("Pop out");
|
||||
checked: Bridge.viewer-popped;
|
||||
tint: #ffffff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.viewer-popped = !Bridge.viewer-popped; }
|
||||
}
|
||||
IconButton {
|
||||
icon: Bridge.viewer-fullscreen ? Icons.minimize-2 : Icons.maximize;
|
||||
label: Bridge.viewer-fullscreen ? @tr("Exit full screen") : @tr("Full screen");
|
||||
tint: #ffffff;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.toggle-fullscreen(); }
|
||||
}
|
||||
if root.compact: IconButton {
|
||||
icon: Icons.log-out;
|
||||
label: Bridge.viewer-ended ? @tr("Close") : @tr("Leave");
|
||||
tint: Theme.danger;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.leave-stream(); }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// What is known about the watched stream.
|
||||
component StreamInfo inherits VerticalLayout {
|
||||
padding: Theme.space-6;
|
||||
spacing: Theme.space-3;
|
||||
alignment: start;
|
||||
for row in [
|
||||
{ label: @tr("Title"), value: Bridge.viewer-title },
|
||||
{ label: @tr("Streamer"), value: Bridge.viewer-streamer },
|
||||
{ label: @tr("Picture"), value: Bridge.viewer-quality-detail },
|
||||
{ label: @tr("Watching for"), value: Bridge.viewer-elapsed },
|
||||
{ label: @tr("Viewers"), value: Bridge.viewer-count > 0 ? @tr("{}", Bridge.viewer-count) : "" },
|
||||
]: HorizontalLayout {
|
||||
spacing: Theme.space-4;
|
||||
Text {
|
||||
width: 120px;
|
||||
text: row.label;
|
||||
color: Theme.text-muted;
|
||||
}
|
||||
Text {
|
||||
text: row.value != "" ? row.value : "—";
|
||||
color: Theme.text;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The stream we watch. With the shell: the channel's header, the player,
|
||||
// a note that the stream belongs to the channel, and its chat below. In
|
||||
// full screen and on a phone: the player alone.
|
||||
export component StreamViewer inherits Rectangle {
|
||||
// Reading our own width here would loop through the layout, so the
|
||||
// phone breakpoint (a setting) decides.
|
||||
property <bool> alone: Bridge.viewer-fullscreen || Nav.narrow;
|
||||
property <bool> info-tab;
|
||||
property <string> tab-name: Bridge.current-tab >= 0 && Bridge.current-tab < Bridge.tabs.length ? Bridge.tabs[Bridge.current-tab].name : "";
|
||||
background: root.alone ? #000000 : transparent;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: @tr("Stream viewer");
|
||||
if root.alone: StreamPlayer {
|
||||
compact: true;
|
||||
}
|
||||
if !root.alone: VerticalLayout {
|
||||
PageHeader {
|
||||
icon: Icons.volume-2;
|
||||
title: Bridge.own-channel != "" ? Bridge.own-channel : Bridge.viewer-title;
|
||||
description: Bridge.own-channel-topic;
|
||||
if Bridge.members.length > 0: Button {
|
||||
icon: Icons.users;
|
||||
text: @tr("{} in voice", Bridge.members.length);
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.toggle-members(); }
|
||||
}
|
||||
Button {
|
||||
kind: ButtonKind.danger;
|
||||
icon: Icons.log-out;
|
||||
text: Bridge.viewer-ended ? @tr("Close") : @tr("Leave");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Bridge.leave-stream(); }
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
vertical-stretch: 3;
|
||||
min-height: 200px;
|
||||
padding: Theme.space-4;
|
||||
padding-bottom: Theme.space-3;
|
||||
StreamPlayer { }
|
||||
}
|
||||
// Streams on TeamSpeak belong to the channel.
|
||||
if Bridge.own-channel != "": HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-4;
|
||||
Rectangle {
|
||||
height: 40px;
|
||||
border-radius: Theme.radius-md;
|
||||
background: Theme.surface-2;
|
||||
border-width: 1px;
|
||||
border-color: Theme.border;
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-right: Theme.space-4;
|
||||
spacing: Theme.space-3;
|
||||
Icon {
|
||||
source: Icons.lock;
|
||||
size: Theme.icon-sm;
|
||||
tint: Theme.accent-text;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: @tr("This stream is only available while you're in the {} voice channel.", Bridge.own-channel);
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-4;
|
||||
padding-top: Theme.space-2;
|
||||
alignment: start;
|
||||
TabItem {
|
||||
text: root.tab-name != "" ? @tr("{} Chat", root.tab-name) : @tr("Chat");
|
||||
selected: !root.info-tab;
|
||||
clicked => { root.info-tab = false; }
|
||||
}
|
||||
TabItem {
|
||||
text: @tr("Stream Info");
|
||||
selected: root.info-tab;
|
||||
clicked => { root.info-tab = true; }
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
height: 1px;
|
||||
background: Theme.border;
|
||||
}
|
||||
if !root.info-tab: MessageList {
|
||||
vertical-stretch: 2;
|
||||
min-height: 120px;
|
||||
model: Bridge.messages;
|
||||
}
|
||||
if !root.info-tab: Composer {
|
||||
placeholder: root.tab-name != "" ? @tr("Message {}", root.tab-name) : @tr("Message");
|
||||
}
|
||||
if root.info-tab: StreamInfo {
|
||||
vertical-stretch: 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
// The voice channel we are in: who is there (and who talks), the streams
|
||||
// in it, and the channel's chat below.
|
||||
|
||||
import { Theme } from "../theme.slint";
|
||||
import { Icons } from "../icons.slint";
|
||||
import { Bridge, MemberItem, StreamItem } from "../bridge.slint";
|
||||
import { Nav, SettingsSection } from "../nav.slint";
|
||||
import { Icon, IconButton, Button, ButtonKind, Avatar, LiveBadge, Chip, SpeakingBars } from "../components/index.slint";
|
||||
import { MessageList, Composer } from "chat.slint";
|
||||
|
||||
// One person: a large avatar with a ring (green while talking, blue while
|
||||
// streaming), the muted mark, the name and what they do.
|
||||
component Participant inherits VerticalLayout {
|
||||
in property <MemberItem> member;
|
||||
property <length> size: 80px;
|
||||
width: 120px;
|
||||
spacing: Theme.space-2;
|
||||
accessible-role: AccessibleRole.list-item;
|
||||
accessible-label: member.name;
|
||||
accessible-description: member.status;
|
||||
accessible-action-default => { Bridge.open-member(member.id); }
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
Rectangle {
|
||||
width: root.size + 8px;
|
||||
height: root.size + 8px;
|
||||
border-radius: self.width / 2;
|
||||
border-width: member.talking || member.streaming ? 3px : 2px;
|
||||
border-color: member.talking ? Theme.success : member.streaming ? Theme.accent : Theme.border-strong;
|
||||
Avatar {
|
||||
size: root.size;
|
||||
initials: member.initials;
|
||||
tint: member.tint;
|
||||
image: member.avatar;
|
||||
label: member.name;
|
||||
}
|
||||
// Talking, or the microphone off, at the bottom right.
|
||||
if member.talking || member.muted || member.sound-off: Rectangle {
|
||||
x: parent.width - self.width - 2px;
|
||||
y: parent.height - self.height - 2px;
|
||||
width: 26px;
|
||||
height: 26px;
|
||||
border-radius: 13px;
|
||||
background: Theme.surface;
|
||||
border-width: 2px;
|
||||
border-color: Theme.surface;
|
||||
if member.talking: SpeakingBars {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
}
|
||||
if !member.talking: Icon {
|
||||
source: member.sound-off ? Icons.headphone-off : Icons.mic-off;
|
||||
size: 15px;
|
||||
tint: Theme.danger;
|
||||
}
|
||||
}
|
||||
TouchArea {
|
||||
mouse-cursor: MouseCursor.pointer;
|
||||
clicked => { Bridge.open-member(member.id); }
|
||||
}
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
spacing: Theme.space-2;
|
||||
Text {
|
||||
text: member.name;
|
||||
color: member.myself ? Theme.accent-text : Theme.text;
|
||||
font-size: Theme.font-md;
|
||||
font-weight: Theme.weight-medium;
|
||||
overflow: elide;
|
||||
}
|
||||
if member.admin: Icon {
|
||||
source: Icons.crown;
|
||||
size: 15px;
|
||||
tint: Theme.gold;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
alignment: center;
|
||||
spacing: Theme.space-2;
|
||||
if member.talking: SpeakingBars {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: member.talking ? @tr("Speaking") : member.streaming ? @tr("Streaming") : member.away ? @tr("Away") : "";
|
||||
color: member.talking ? Theme.success : Theme.text-secondary;
|
||||
font-size: Theme.font-sm;
|
||||
overflow: elide;
|
||||
}
|
||||
if member.streaming && !member.talking: Icon {
|
||||
source: Icons.monitor;
|
||||
size: 14px;
|
||||
tint: Theme.text-secondary;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A stream in the channel as a large card: LIVE, the title, who streams
|
||||
// what, and Watch.
|
||||
component StreamCard inherits Rectangle {
|
||||
in property <StreamItem> stream;
|
||||
height: 236px;
|
||||
border-radius: Theme.radius-lg;
|
||||
clip: true;
|
||||
// Two stops: the software renderer draws a seam at a middle stop.
|
||||
background: @linear-gradient(160deg, #26237a 0%, #0c1430 100%);
|
||||
border-width: 1px;
|
||||
border-color: stream.watching ? Theme.accent : Theme.border-strong;
|
||||
accessible-role: AccessibleRole.groupbox;
|
||||
accessible-label: stream.name;
|
||||
// The picture while we watch it (the viewer hidden behind the chat).
|
||||
if stream.watching && Bridge.viewer-has-frame: Image {
|
||||
width: parent.width;
|
||||
height: parent.height;
|
||||
source: Bridge.viewer-frame;
|
||||
image-fit: cover;
|
||||
}
|
||||
if !(stream.watching && Bridge.viewer-has-frame): Icon {
|
||||
source: stream.kind == "Camera" ? Icons.video : Icons.monitor-up;
|
||||
size: 72px;
|
||||
tint: #ffffff22;
|
||||
}
|
||||
// Darker at the bottom, for the text.
|
||||
Rectangle {
|
||||
y: parent.height * 0.4;
|
||||
height: parent.height * 0.6;
|
||||
background: @linear-gradient(180deg, #00000000 0%, #060a18e0 100%);
|
||||
}
|
||||
HorizontalLayout {
|
||||
x: Theme.space-4;
|
||||
y: Theme.space-4;
|
||||
height: 28px;
|
||||
spacing: Theme.space-3;
|
||||
LiveBadge {
|
||||
large: true;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
if stream.viewers > 0: Chip {
|
||||
text: @tr("{} watching", stream.viewers);
|
||||
icon: Icons.eye;
|
||||
tint: #ffffff;
|
||||
fill: #060a18a0;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding: Theme.space-4;
|
||||
padding-top: 0px;
|
||||
spacing: Theme.space-3;
|
||||
alignment: stretch;
|
||||
VerticalLayout {
|
||||
alignment: end;
|
||||
horizontal-stretch: 1;
|
||||
spacing: Theme.space-1;
|
||||
Text {
|
||||
text: stream.id == "" ? @tr("{} is streaming", stream.streamer) : stream.name != "" ? stream.name : @tr("Untitled stream");
|
||||
color: #ffffff;
|
||||
font-size: Theme.font-lg;
|
||||
font-weight: Theme.weight-semibold;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
text: stream.kind != "" ? stream.streamer + " • " + stream.kind : stream.streamer;
|
||||
color: #ffffffc0;
|
||||
font-size: Theme.font-body;
|
||||
overflow: elide;
|
||||
}
|
||||
HorizontalLayout {
|
||||
padding-top: Theme.space-2;
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
if stream.bitrate != "": Chip {
|
||||
text: stream.bitrate;
|
||||
tint: #ffffffe0;
|
||||
fill: #ffffff1a;
|
||||
}
|
||||
if stream.audio: Chip {
|
||||
text: @tr("Sound");
|
||||
icon: Icons.volume-2;
|
||||
tint: #ffffffe0;
|
||||
fill: #ffffff1a;
|
||||
}
|
||||
if stream.own: Chip {
|
||||
text: @tr("Your stream");
|
||||
tint: #ffffffe0;
|
||||
fill: #ffffff1a;
|
||||
}
|
||||
}
|
||||
}
|
||||
if stream.id != "" && !stream.own: VerticalLayout {
|
||||
alignment: end;
|
||||
Button {
|
||||
icon: stream.watching ? Icons.monitor : Icons.external-link;
|
||||
text: stream.watching ? @tr("Show Stream") : @tr("Watch Stream");
|
||||
checked: true;
|
||||
clicked => {
|
||||
if stream.watching {
|
||||
Bridge.show-viewer();
|
||||
} else {
|
||||
Bridge.watch-stream(stream.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The voice channel view (desktop): header, people, streams, chat.
|
||||
export component VoiceView inherits VerticalLayout {
|
||||
// The title with the buttons beside it; the topic and the count below
|
||||
// take the whole width.
|
||||
HorizontalLayout {
|
||||
padding-left: Theme.space-7;
|
||||
padding-right: Theme.space-5;
|
||||
padding-top: Theme.space-5;
|
||||
padding-bottom: Theme.space-3;
|
||||
spacing: Theme.space-5;
|
||||
Icon {
|
||||
source: Icons.volume-2;
|
||||
size: 40px;
|
||||
tint: Theme.text-secondary;
|
||||
y: Theme.space-1;
|
||||
}
|
||||
VerticalLayout {
|
||||
horizontal-stretch: 1;
|
||||
spacing: Theme.space-1;
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-3;
|
||||
Text {
|
||||
text: Bridge.own-channel;
|
||||
color: Theme.text;
|
||||
font-size: Theme.font-3xl;
|
||||
font-weight: Theme.weight-semibold;
|
||||
vertical-alignment: center;
|
||||
horizontal-stretch: 1;
|
||||
overflow: elide;
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.message-square;
|
||||
label: @tr("Chat only");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.show-voice(false); }
|
||||
}
|
||||
Button {
|
||||
icon: Icons.settings;
|
||||
text: @tr("Voice Settings");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => { Nav.open-settings(SettingsSection.voice); }
|
||||
}
|
||||
Button {
|
||||
kind: ButtonKind.danger;
|
||||
icon: Icons.phone-off;
|
||||
text: @tr("Leave");
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => {
|
||||
Nav.show-voice(false);
|
||||
Bridge.disconnect-voice();
|
||||
}
|
||||
}
|
||||
}
|
||||
if Bridge.own-channel-topic != "": Text {
|
||||
text: Bridge.own-channel-topic;
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-md;
|
||||
overflow: elide;
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: Theme.space-2;
|
||||
alignment: start;
|
||||
Icon {
|
||||
source: Icons.users;
|
||||
size: 16px;
|
||||
tint: Theme.text-secondary;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: Bridge.own-channel-limit >= 0
|
||||
? @tr("{} in voice / {} total", Bridge.members.length, Bridge.own-channel-limit)
|
||||
: @tr("{} in voice", Bridge.members.length);
|
||||
color: Theme.text-secondary;
|
||||
font-size: Theme.font-body;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The people, centred, wrapping into more rows when there are many.
|
||||
FlexboxLayout {
|
||||
padding-left: Theme.space-6;
|
||||
padding-right: Theme.space-6;
|
||||
padding-top: Theme.space-3;
|
||||
padding-bottom: Theme.space-4;
|
||||
alignment: center;
|
||||
spacing-horizontal: Theme.space-6;
|
||||
spacing-vertical: Theme.space-4;
|
||||
accessible-role: AccessibleRole.list;
|
||||
accessible-label: @tr("In voice");
|
||||
for member in Bridge.members: Participant {
|
||||
member: member;
|
||||
}
|
||||
}
|
||||
if Bridge.streams.length > 0: HorizontalLayout {
|
||||
padding-left: Theme.space-6;
|
||||
padding-right: Theme.space-6;
|
||||
padding-bottom: Theme.space-3;
|
||||
spacing: Theme.space-4;
|
||||
for stream in Bridge.streams: StreamCard {
|
||||
horizontal-stretch: 1;
|
||||
stream: stream;
|
||||
}
|
||||
}
|
||||
MessageList {
|
||||
vertical-stretch: 1;
|
||||
model: Bridge.messages;
|
||||
older: true;
|
||||
}
|
||||
Composer {
|
||||
placeholder: @tr("Message {}", Bridge.own-channel);
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,8 @@ export component HoldToTalk inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
// "Voice Connected — channel / server", disconnect, and hold-to-talk.
|
||||
// "Voice Connected — channel / server", disconnect, and hold-to-talk
|
||||
// with push-to-talk.
|
||||
export component VoiceCard inherits Rectangle {
|
||||
border-radius: Theme.radius-lg;
|
||||
background: Theme.surface-2;
|
||||
@@ -104,7 +105,7 @@ export component VoiceCard inherits Rectangle {
|
||||
clicked => { Bridge.disconnect-voice(); }
|
||||
}
|
||||
}
|
||||
if Bridge.voice-connected: HoldToTalk { }
|
||||
if Bridge.voice-connected && Bridge.audio.transmit == 0: HoldToTalk { }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -163,6 +164,8 @@ export component UserCard inherits Rectangle {
|
||||
initials: Bridge.nickname != "" ? "" : "?";
|
||||
tint: Theme.accent;
|
||||
label: Bridge.nickname;
|
||||
// Green ring while our voice goes out.
|
||||
speaking: Bridge.transmitting;
|
||||
status: Bridge.voice-connected ? Status.online : Bridge.observing ? Status.info : Status.offline;
|
||||
Icon {
|
||||
source: Icons.user;
|
||||
|
||||
@@ -227,12 +227,12 @@ export component TopBar inherits Rectangle {
|
||||
}
|
||||
IconButton {
|
||||
icon: Icons.users;
|
||||
label: @tr("Members and streams");
|
||||
checked: Nav.right-panel-open && Nav.page == Page.server;
|
||||
label: @tr("Members");
|
||||
checked: Nav.right-panel-open && !Nav.pins-open && !Nav.topics-open && Nav.page == Page.server;
|
||||
y: (parent.height - self.height) / 2;
|
||||
clicked => {
|
||||
Nav.show(Page.server);
|
||||
Nav.right-panel-open = !Nav.right-panel-open;
|
||||
Nav.toggle-members();
|
||||
}
|
||||
}
|
||||
Rectangle {
|
||||
|
||||
@@ -136,7 +136,6 @@ export global Theme {
|
||||
out property <length> sidebar-width: 264px * max(1.0, font-scale);
|
||||
out property <length> topbar-height: 56px;
|
||||
out property <length> right-panel-min: 220px;
|
||||
out property <length> right-panel-max: 420px;
|
||||
|
||||
// Motion.
|
||||
out property <duration> fast: 120ms;
|
||||
|
||||
@@ -290,12 +290,15 @@ the software encoders above are used as before.
|
||||
`initial_pool_size` (with or without `internal`, which libavutil 59
|
||||
removed; `device_ctx` and both formats checked in a new context), and for
|
||||
the DMA-BUF import `AVFrame.buf[0]` and `hw_frames_ctx` (a table per
|
||||
libavutil major 56-60 on 64-bit, newer majors tried with the newest entry;
|
||||
`buf[0]` checked on a real frame at load, `hw_frames_ctx` on the first
|
||||
surface). The layouts were compiled from the headers of FFmpeg 4.4, 5.1,
|
||||
6.1, 7.1 and 8.0. A failed check disables only what needs the field
|
||||
(VA-API, or the import) and says why (`LibraryInfo::hw_frames`,
|
||||
`dmabuf_import`, the report).
|
||||
libavutil major, 56-61 on 64-bit; `buf[0]` checked on a real frame at
|
||||
load, `hw_frames_ctx` on the first surface). The layouts were compiled
|
||||
from the headers of FFmpeg 4.4, 5.1, 6.1, 7.1, 8.0 and 9.0. A major that
|
||||
is not in the table turns the import off instead of reusing the newest
|
||||
entry: `AVFrame` has shrunk as well as grown between majors (424 bytes in
|
||||
libavutil 61 against 536 in 56), so an offset guessed for an unknown
|
||||
layout could point past the end of the struct. A failed check disables
|
||||
only what needs the field (VA-API, or the import) and says why
|
||||
(`LibraryInfo::hw_frames`, `dmabuf_import`, the report).
|
||||
- Backends (`ffmpeg::BACKENDS`, FFmpeg's encoder names, also the names in
|
||||
`stream.encoder_backend`): H.264 `h264_nvenc`, `h264_amf`, `h264_vaapi`,
|
||||
`h264_qsv`, `h264_videotoolbox`, `h264_mf`, software `libx264`,
|
||||
@@ -309,11 +312,31 @@ the software encoders above are used as before.
|
||||
node", "not in this FFmpeg build", ...). rav1e holds about 20 frames
|
||||
before its first packet even in low-latency mode (measured, rav1e 0.7), so
|
||||
it is used only when named.
|
||||
- Probe cost: a family whose vendor is not in the machine is not opened at
|
||||
all. Its driver would still run its initialisation before failing, which
|
||||
was the bulk of the startup cost (measured here: `av1_nvenc` 1.7 s,
|
||||
`vp9_qsv` 1.2 s), and the probe takes as long as its slowest test because
|
||||
they run in parallel. The PCI vendors of the DRM render nodes
|
||||
(`/sys/class/drm/*/device/vendor`) are read once; NVENC needs NVIDIA (or
|
||||
`/dev/nvidiactl`, for a driver without a DRM node), Quick Sync Intel, AMF
|
||||
AMD. When the vendors cannot be read nothing is skipped. On the AMD
|
||||
machine below this took `voelinctl stream encoders` from 1.77 s to
|
||||
0.93-1.12 s, testing 12 backends instead of 20, and the report says "no
|
||||
NVIDIA GPU in this machine" instead of a CUDA error code.
|
||||
- Third-party output: FFmpeg's own log goes to `tracing`, but the libraries
|
||||
behind the encoders write to standard error themselves — SVT-AV1 prints a
|
||||
build banner and its allocation totals, AMD's AMF runtime prints
|
||||
`GetProperty(...) not found` warnings, and Mesa prints a `RADV_PERFTEST`
|
||||
deprecation notice when AMF brings up Vulkan. That was about thirty lines
|
||||
on every start. While the self-tests run, standard error is pointed at a
|
||||
temporary file and what landed there comes back as one `debug` record;
|
||||
`VOELIN_FFMPEG_PROBE_STDERR=1` leaves it alone.
|
||||
- Realtime settings: no B-frames, no lookahead, keyframes only at the start
|
||||
and on request (a GOP of 2^30 frames, or what each wrapper takes as
|
||||
unlimited: 65535 for Quick Sync, 0 for AMF and VideoToolbox, 2^29 for
|
||||
rav1e; `keyframe_interval` if set) with forced IDR (`pict_type` I,
|
||||
`forced-idr`), CBR (`maxrate` = `b`, a one-second buffer; SVT-AV1 `rc=2`),
|
||||
`forced-idr`), CBR (`maxrate` = `b`, a one-second buffer, two seconds for
|
||||
`av1_vaapi`, whose rate control overshoots with one; SVT-AV1 `rc=2`),
|
||||
time base 1/fps (hardware rate control budgets per frame from it; pts are
|
||||
frame numbers from the capture timestamps), BT.601 limited range. Per
|
||||
family: x264 `veryfast` (`EncoderConfig::speed` picks another preset),
|
||||
@@ -329,6 +352,24 @@ the software encoders above are used as before.
|
||||
without B-frames (Constrained High, what TeamSpeak decodes) or Constrained
|
||||
Baseline (`EncoderConfig::h264_profile`). Options a release does not know
|
||||
are skipped; alternatives are tried in order.
|
||||
- H.264 level: the level the signalling offers
|
||||
(`voelin_stream::h264::level_idc`, ITU-T Table A-1) is computed again from
|
||||
the session's own size, rate and bitrate and set on both the codec context
|
||||
and the wrapper's private option. Without it every wrapper picked its own,
|
||||
and a generous one: measured on the GPU below, `h264_amf` wrote level 4.2
|
||||
into the SPS of a 720p30 stream whose offer said 3.1, and 5.0 for a
|
||||
1440p60 stream offered as 5.1. A viewer that sizes its decoder from our
|
||||
SDP may refuse a stream that declares more than the offer did, which is
|
||||
how a stream fails against an official client. With the level set,
|
||||
`h264_vaapi`, `h264_amf` and `libx264` all emit exactly the offered level
|
||||
(`tests/ffmpeg.rs`, `sps_carries_the_offered_profile_and_level`, parses
|
||||
the SPS). The level table is a second copy of voelin-stream's, because
|
||||
neither crate can depend on the other; a unit test pins the two together.
|
||||
The constraint-flag byte still differs and is left alone: the offer claims
|
||||
Constrained High (`0c`) and Constrained Baseline (`e0`) as WebRTC
|
||||
implementations conventionally do, `h264_vaapi` and `h264_amf` emit `0c`
|
||||
for the former and `libx264` emits `00`, and all three emit `40` or `c0`
|
||||
for the latter. Those bits do not change what a decoder can decode.
|
||||
- Runtime changes: x264, NVENC and Quick Sync take bitrate changes on the
|
||||
running encoder (FFmpeg's wrappers compare `b` / `maxrate` / `bufsize`
|
||||
before each frame); the others reopen at the next keyframe, at once
|
||||
@@ -343,19 +384,45 @@ the software encoders above are used as before.
|
||||
(`encode_with`). VA-API frames come from a surface pool
|
||||
(`av_hwframe_ctx_init`, surfaces allocated on demand and recycled) filled
|
||||
with `av_hwframe_transfer_data`; the device is `VOELIN_VAAPI_DEVICE` or the
|
||||
first `/dev/dri/renderD*`, shared by all encoders. Odd sizes are cropped to
|
||||
even ones. The streamer's steady state is 1.1 heap allocations per encoded
|
||||
frame with x264 or SVT-AV1, as with libvpx (`voelinctl stream bench`).
|
||||
first `/dev/dri/renderD*`, shared by all encoders. Frames are cropped to
|
||||
the sizes a backend encodes exactly: even ones for most, and for AV1 the
|
||||
alignment its self-test measured (`BackendStatus::alignment`). The AV1
|
||||
self-test encodes 258x258 (2 more than a power of two) and reads the
|
||||
frame size the sequence header declares: an encoder that pads to 64
|
||||
declares 320. AV1 has no cropping like H.264's SPS, so padding would
|
||||
reach the viewer as picture. The streamer's steady state is 1.1 heap
|
||||
allocations per encoded frame with x264 or SVT-AV1, as with libvpx
|
||||
(`voelinctl stream bench`). A session is flushed only if a frame went
|
||||
in: FFmpeg 9's `h264_vaapi` crashes (SIGSEGV in `avcodec_send_frame`)
|
||||
when drained before its first frame, which is what dropping an encoder
|
||||
whose first frame failed used to do.
|
||||
- Zero-copy (Linux): `FfmpegEncoder::encode_dmabuf(&DmaBufRef, ...)` maps a
|
||||
DRM PRIME frame onto a VA-API surface (`av_hwframe_map`) that the encoder
|
||||
reads without a copy, for NV12 buffers. Screen capture delivers RGB
|
||||
(BGRx), which needs a colour conversion on the GPU first (VA-API video
|
||||
processing); that step is not implemented, so RGB buffers are refused and
|
||||
mapped for the CPU path as before. The capture side has the hook
|
||||
(`FrameSink::accepts_dmabuf` / `dmabuf`: the portal offers a buffer before
|
||||
mapping it and would pass tiled ones through), but no sink accepts yet
|
||||
and the portal still negotiates LINEAR buffers only; offering tiled
|
||||
modifiers needs the encoder's import modifiers. Untested on a GPU.
|
||||
DRM PRIME frame onto a VA-API surface (`av_hwframe_map`), so the CPU never
|
||||
reads the buffer. NV12 buffers (one layer of two planes, which is how a
|
||||
compositor hands one over) go to the encoder as they are. RGB buffers
|
||||
(`XR24`, `AR24`, `XB24`, `AB24`: what screen capture delivers) are
|
||||
mapped onto a surface of their own size and converted into the session's
|
||||
NV12 surface by VA-API video processing (`ffmpeg/vpp.rs`: libva's
|
||||
`VAEntrypointVideoProc` on FFmpeg's own `VADisplay`, found through
|
||||
`AVHWDeviceContext.hwctx`), cropped to the coded size on the way; the
|
||||
call returns once the GPU has read the buffer, so it can go back to the
|
||||
compositor. libva is the library FFmpeg's VA-API support already loaded
|
||||
(`libva.so.2`, ABI unchanged since libva 2); FFmpeg itself has this
|
||||
conversion only in libavfilter (`scale_vaapi`), which would be another
|
||||
library and a filter graph for one call. The input is described with
|
||||
BT.601 primaries and transfer, like the output, so the driver applies
|
||||
the matrix only, as the CPU path does: left to itself Mesa also converts
|
||||
the transfer function and every dark pixel came out about 5 levels too
|
||||
bright. Anything else (another format, an encoder that is not VA-API)
|
||||
fails with `Error::CodecUnavailable` and the caller maps the buffer for
|
||||
the CPU path. The capture side has the hook (`FrameSink::accepts_dmabuf`
|
||||
/ `dmabuf`: the portal offers a buffer before mapping it), but the
|
||||
streamer's sink (`Ingest` in voelin-core) does not accept DMA-BUFs yet,
|
||||
so no captured frame takes this path in the app. The portal negotiates
|
||||
LINEAR DMA-BUFs, which the import takes (tested); tiled ones would save
|
||||
the compositor a copy but need the modifiers the encoder's driver
|
||||
imports, which are not known on the capture side. See [the
|
||||
measurements](#zero-copy-measured).
|
||||
|
||||
Installing FFmpeg (runtime libraries only, no `-dev` packages):
|
||||
|
||||
@@ -469,10 +536,13 @@ Notes:
|
||||
the portal supports it. Buffers: LINEAR DMA-BUFs are offered first (a
|
||||
mandatory modifier property we fixate; mapped once per buffer, read
|
||||
between `DMA_BUF_IOCTL_SYNC` start and end), shared memory
|
||||
(BGRx/BGRA/RGBx/RGBA) second. If reading DMA-BUFs is slower than 6 ns per
|
||||
(BGRx/BGRA/RGBx/RGBA) second. If reading DMA-BUFs is slower than 1 ns per
|
||||
pixel over the first 30 frames (uncached VRAM), the stream renegotiates to
|
||||
shared memory; `VOELIN_PORTAL_DMABUF=0` or `with_dmabuf(false)` skips them.
|
||||
Tiled modifiers would need a GPU import (a later step). The frame rate
|
||||
A sink that accepts DMA-BUFs gets them before anything is mapped (with
|
||||
the buffer object's size, which compositors leave out of `maxsize`), and
|
||||
then the CPU never reads them. Tiled modifiers are not offered (see
|
||||
zero-copy above). The frame rate
|
||||
asked of the compositor is the sink's cap, renegotiated when it changes;
|
||||
compositors send frames only when the screen changes. Without a session
|
||||
bus or portal, `start` returns `Error::CaptureUnavailable`; a cancelled
|
||||
@@ -513,6 +583,10 @@ voelinctl stream bench --res 1280x720 --encoder h264_vaapi
|
||||
voelinctl stream bench --res 2560x1440 --fps 30 \
|
||||
--layer scale=1,bitrate=6M --layer scale=0.5,bitrate=1500k,fps=30 \
|
||||
--layer size=640x360,bitrate=400k,fps=15
|
||||
# A real screen capture instead of the pattern (the portal asks the user;
|
||||
# --start-timeout bounds the wait so it cannot hang):
|
||||
voelinctl stream bench --source portal --fps 60 --encoder h264_vaapi
|
||||
voelinctl stream bench --source monitor:0 --fps 60 # X11
|
||||
# Conversion and scaling alone:
|
||||
cargo bench -p voelin-media --bench convert
|
||||
```
|
||||
@@ -547,6 +621,154 @@ Conversion and scaling take 0.3 ms (720p) to 3-5 ms (1440p, busy) per frame
|
||||
on 4 threads. With three layers (1440p30 at 6 Mbit/s, 720p30, 360p15) the
|
||||
quiet machine kept every layer at its rate with 1.6-1.7 cores.
|
||||
|
||||
### Hardware encoders, measured
|
||||
|
||||
Release build, AMD Radeon RX 7900 GRE (radeonsi / RADV, `renderD128`), 32
|
||||
cores, FFmpeg 9.0.1, desktop pattern, one layer, 10 s after a 2 s warm-up,
|
||||
`voelinctl stream bench`. "cpu" is cores of the whole process (capture,
|
||||
conversion and encode together), "encode" the wall time of one
|
||||
`encode_with`.
|
||||
|
||||
1080p60, 6000 kbit/s asked for:
|
||||
|
||||
| encoder | fps | kbit/s | encode ms | cpu cores | allocations per frame |
|
||||
|---|---|---|---|---|---|
|
||||
| `h264_vaapi` | 60.0 | 5951 | 2.52 | 0.25 | 1.02 |
|
||||
| `h264_amf` | 60.0 | 5910 | 2.17 | 0.31 | 1.02 |
|
||||
| `av1_vaapi`, as first measured | 60.0 | 6211 | 2.23 | 0.20 | 1.02 |
|
||||
| `av1_vaapi`, two-second buffer * | 60.0 | 5982 | 2.24-2.33 | 0.28-0.29 | 1.02 |
|
||||
| `av1_amf` | 60.0 | 5962 | 2.75 | 0.29 | 1.02 |
|
||||
| `libx264` | 60.0 | 5674 | 2.33 | 1.16 | 1.02 |
|
||||
| libvpx VP8 | 60.0 | 6031 | 4.93 | 1.69 | 1.02 |
|
||||
|
||||
1440p60, 10000 kbit/s asked for:
|
||||
|
||||
| encoder | fps | kbit/s | encode ms | cpu cores | allocations per frame |
|
||||
|---|---|---|---|---|---|
|
||||
| `h264_vaapi` | 60.0 | 10112 | 3.96 | 0.33 | 1.02 |
|
||||
| `h264_amf` | 60.0 | 10188 | 2.80 | 0.41 | 1.02 |
|
||||
| `av1_vaapi`, as first measured | 60.0 | 10794 | 3.56 | 0.34 | 1.02 |
|
||||
| `av1_vaapi`, two-second buffer * | 60.0 | 9920 | 3.49-3.50 | 0.38-0.52 | 1.02 |
|
||||
| `av1_amf` | 60.0 | 10079 | 2.91 | 0.42 | 1.02 |
|
||||
| `libx264` | 59.9 | 9406 | 11.88 | 2.17 | 1.03 |
|
||||
| libvpx VP8 | 60.0 | 10038 | 4.32 | 2.55 | 1.02 |
|
||||
|
||||
Simulcast, 1440p30 source, three layers (1440p30 at 8 Mbit/s, 720p30 at
|
||||
2 Mbit/s, 360p15 at 600 kbit/s), same run:
|
||||
|
||||
| encoder | layer 0 | layer 1 | layer 2 | cpu cores |
|
||||
|---|---|---|---|---|
|
||||
| `h264_vaapi` | 30.0 fps, 7666 kbit/s, 4.37 ms | 30.0, 2121, 1.71 ms | 15.0, 596, 1.22 ms | 0.25 |
|
||||
| `h264_amf` | 30.0 fps, 7499 kbit/s, 3.56 ms | 30.0, 2015, 2.02 ms | 15.0, 598, 1.94 ms | 0.32 |
|
||||
| `libx264` | 30.0 fps, 7428 kbit/s, 4.40 ms | 30.0, 1993, 2.19 ms | 15.0, 593, 2.51 ms | 1.33 |
|
||||
|
||||
What the numbers say: every encoder, hardware and software, holds the full
|
||||
frame rate at both sizes on this machine, so the difference is CPU, not
|
||||
throughput. Hardware costs 0.20-0.52 cores against 1.16-2.55 for software,
|
||||
a factor of four to eight, and the gap widens with size — at 1440p60 x264
|
||||
needs 2.17 cores and is the only encoder that dropped a frame. Every backend
|
||||
honoured the target bitrate within 2 % except `av1_vaapi`, which overshot by
|
||||
3.5-8 % with the one-second rate-control buffer every backend gets.
|
||||
|
||||
\* Two runs each, later, while the machine was in use (a control run of
|
||||
`h264_vaapi` at 1080p60 gave 0.27 cores against the 0.25 above, the same
|
||||
5951 kbit/s); the bitrates repeat exactly between runs, the CPU figures do
|
||||
not. Measured on the encoder alone, only the buffer moved Mesa's AV1 rate
|
||||
control (`maxrate`, `rc_mode`, `blbrc`, the QP bounds did nothing): with
|
||||
two seconds it lands within 1.2 % at 1440p60, 1080p60 and 720p30, and is
|
||||
no burstier than the other hardware encoders — at 1440p60 its peak over
|
||||
100 ms is 13.6 Mbit/s against 14.0-14.4 for `h264_vaapi`, `h264_amf` and
|
||||
`av1_amf`, and over 250 ms to 1 s it is lower than with one second. So
|
||||
`av1_vaapi` alone gets two. The steady state is 1.02 allocations per encoded frame (the
|
||||
`Arc<[u8]>` of `EncodedFrame`) with hardware as with software: no reopen
|
||||
storm, no per-frame allocation in the import or upload path. Conversion and
|
||||
scaling cost 0.16-0.30 ms per frame at these sizes and are not the
|
||||
bottleneck. The per-layer "threads" the bench prints is the CPU budget the
|
||||
layer was given, not what a hardware encoder uses — it encodes on the GPU.
|
||||
|
||||
What the GPU encoders produce, decoded by our own decoders (OpenH264 2.6.0,
|
||||
dav1d 1.5.4): `tests/ffmpeg.rs` `hardware_encoders_roundtrip`, twelve
|
||||
frames of the test pattern with a keyframe forced at frame 8 and a bitrate
|
||||
change at frame 5.
|
||||
|
||||
| encoder | 320x240 | 1920x1080 |
|
||||
|---|---|---|
|
||||
| `h264_vaapi` | 12 of 12 decoded, lowest PSNR 38.1 dB | 1920x1080, 37.8 dB |
|
||||
| `h264_amf` | 12 of 12, 38.1 dB (first packet after one frame) | 1920x1080, 37.8 dB |
|
||||
| `av1_vaapi` | 12 of 12, 37.8 dB | 1920x1082 before, 1920x1072 now (cropped), 43.7 dB |
|
||||
| `av1_amf` | 12 of 12, 37.8 dB (first packet after one frame) | 1920x1082 before, 1920x1072 now (cropped), 43.6 dB |
|
||||
|
||||
Keyframes came out at frames 0 and 8 and timestamps in order everywhere.
|
||||
The AV1 encoder of this GPU (both through VA-API and AMF) does not encode
|
||||
every size: it pads the width to a multiple of 64 and the height to 16,
|
||||
except that a height 8 more than a multiple of 16 gets 2 rows (1366x768 is
|
||||
sent as 1408x768, 3440x1440 as 3456x1440, 1600x900 as 1600x912, 1920x1080
|
||||
as 1920x1082, 642x482 as 704x496; sizes that are multiples of 64x16 come out
|
||||
exact). The padding is picture as far as AV1 is concerned, so every viewer
|
||||
showed it. The encoders now crop to 64x16 instead, measured by the
|
||||
self-test: 1920x1080 is sent as 1920x1072, 1366x768 as 1344x768. H.264 has
|
||||
no such problem; its SPS crops whatever the hardware pads (exact at all 12
|
||||
sizes tried, 320x240 to 3440x1440).
|
||||
|
||||
### Wayland screen capture, measured
|
||||
|
||||
Same machine, a 2560x1440 Wayland desktop through the ScreenCast portal,
|
||||
`h264_vaapi` at 60 fps and 12 Mbit/s, `voelinctl stream bench --source
|
||||
portal`. This path had never been run against a real compositor.
|
||||
|
||||
| buffers | capture fps | convert + scale | cpu cores | dropped |
|
||||
|---|---|---|---|---|
|
||||
| DMA-BUF (LINEAR), as first written | – | – | – | every frame |
|
||||
| DMA-BUF (LINEAR), mapping fixed | 60.0 | 11.95 ms | 19.54 | 0 |
|
||||
| shared memory | 59.9 | 0.27 ms | 0.41 | 0 |
|
||||
| what it does now (switches by itself) | 60.1 | 0.30 ms | 0.55 | 0 |
|
||||
|
||||
The first row is the bug behind the low frame rates on Wayland: the mapping
|
||||
length was taken from `mapoffset + maxsize`, which describe a mapping that
|
||||
only shared memory has, while a DMA-BUF's size lives in its buffer object and
|
||||
this compositor leaves both fields 0. Every map was refused and nothing was
|
||||
ever delivered.
|
||||
|
||||
The second row is why shared memory is the right choice on a discrete GPU:
|
||||
the CPU reads its memory uncached, so the same conversion costs 44 times the
|
||||
time and 48 times the CPU. `SLOW_DMABUF_NS_PER_PIXEL` exists for exactly
|
||||
this, but at 6.0 ns per pixel it never fired against the DMA-BUF path's
|
||||
3.24; it now sits between the two measurements. Zero-copy is the real answer
|
||||
for this hardware — the buffer would never be read by the CPU at all; the
|
||||
next section measures the encoder's half of it.
|
||||
|
||||
### Zero-copy, measured
|
||||
|
||||
Same machine, `h264_vaapi`, release build: what the CPU spends per
|
||||
2560x1440 frame on its way into the encoder, 600 frames after 30 of
|
||||
warm-up, CPU time of every thread of the process
|
||||
(`ffmpeg::encoder::tests::zero_copy_cpu_cost`, run with `--ignored`).
|
||||
"Shared memory" is the path a captured frame takes today: the picture
|
||||
converted to I420 on every core (`convert::Converter`), interleaved to NV12
|
||||
and uploaded into a VA-API surface by `encode_with`. "DMA-BUF" is an RGB
|
||||
(`XR24`) DMA-BUF of the same picture through `encode_dmabuf`: imported,
|
||||
converted to NV12 by the GPU, encoded. Three runs each:
|
||||
|
||||
| path | CPU per frame | wall per frame | cores at 60 fps |
|
||||
|---|---|---|---|
|
||||
| shared memory (CPU converts and uploads) | 4.28-5.15 ms | 4.09-4.28 ms | 0.26-0.31 |
|
||||
| DMA-BUF (GPU converts) | 0.08-0.09 ms | 2.77-2.78 ms | 0.005 |
|
||||
|
||||
The DMA-BUF path's wall time is the call waiting for the GPU (the
|
||||
conversion has to finish before the buffer goes back to the compositor,
|
||||
and the encoder keeps one frame in flight); the thread is free for other
|
||||
work then. Its output matches the CPU's conversion: Y identical, U and V
|
||||
within 0.7 on average (another chroma filter at edges), and through
|
||||
`h264_vaapi` and `av1_vaapi` to our decoders within 0.3 dB of the CPU path
|
||||
(`an_rgb_dmabuf_is_converted_on_the_gpu`), from the driver's own tiled
|
||||
buffer and from a LINEAR one with a padded pitch (`/dev/udmabuf`), which is
|
||||
what the portal negotiates.
|
||||
|
||||
What this does not show yet is a real capture through it: the streamer's
|
||||
sink does not take DMA-BUFs yet (see the zero-copy bullet above), so the
|
||||
Wayland numbers above are all shared memory. A capture through the GPU
|
||||
path needs that sink and another portal run.
|
||||
|
||||
Build profiles: the dev profile builds the media hot path (yuv,
|
||||
voelin-media, str0m, x11rb-protocol, pipewire, wayland-client, ...) with
|
||||
`opt-level = 3`; release builds use fat LTO with one codegen unit.
|
||||
@@ -587,6 +809,7 @@ has not run on Windows yet.
|
||||
| `ashpd`, `pipewire`, `libspa` / libpipewire | MIT | libpipewire is dynamic |
|
||||
| `windows-capture`, `wasapi`, `windows` | MIT (`windows`: MIT OR Apache-2.0) | Windows only |
|
||||
| FFmpeg (libavcodec, libavutil, libavformat) | LGPL-2.1+ (GPL-2+ in builds with x264 and other GPL parts) | the user's installed libraries, loaded at runtime; never linked or shipped |
|
||||
| libva | MIT | the user's `libva.so.2` (the one FFmpeg's VA-API support uses), loaded at runtime for the GPU colour conversion; never linked or shipped |
|
||||
| `libloading` | ISC | opens FFmpeg (and OpenH264, through the `openh264` crate) |
|
||||
| `bzip2` / `libbz2-rs-sys` | MIT OR Apache-2.0 / bzip2-1.0.6 | unpacks the OpenH264 download; `bzip2-1.0.6` is allowed in `deny.toml` |
|
||||
|
||||
@@ -599,23 +822,33 @@ has not run on Windows yet.
|
||||
| H.264 with Cisco's 2.6.0 library (PSNR, Constrained High `profile_idc` 100, Baseline 66) | `tests/openh264.rs` with `VOELIN_OPENH264_LIB` | tested locally, skipped without the library |
|
||||
| OpenH264 download, SHA-256 check, reuse | `tests/openh264.rs -- --ignored` | tested locally (network) |
|
||||
| H.264 library missing / unknown file | unit + integration tests | tested |
|
||||
| AV1 decoder construction, garbage input | unit test (`--features av1`) | tested; no AV1 stream decoded (no encoder available) |
|
||||
| AV1 decoder construction, garbage input | unit test (`--features av1`) | tested; streams of SVT-AV1, rav1e, libaom, `av1_vaapi` and `av1_amf` decoded (rows below) |
|
||||
| X11 capture (MIT-SHM and GetImage), sources, window capture → VP8 → decode, cursor | `tests/x11_capture.rs` under Xvfb | tested |
|
||||
| wlroots capture (wlr-screencopy v3): outputs, pixels, a change arriving as a new frame, queue API | `tests/wlroots_capture.rs` against headless sway 1.9 (`VOELIN_WLROOTS_TEST_DISPLAY`) | tested; the ext-image-copy-capture path is untested (sway 1.9 predates it) |
|
||||
| Converter (strides, unpadded last row, odd sizes, RGBA/I420/NV12), scaler (flat, area average, half), pyramid (sharing, recycling, steady-state pools) | unit tests | tested |
|
||||
| Simulcast layers (sizes, fps caps, per-layer keyframes), reconfigure (codec, layers, fps) | `voelin-core` `media::tests::simulcast_layers_and_reconfigure` | tested |
|
||||
| Portal DMA-BUF negotiation | unit test of the offered formats | compiles and formats parse; no compositor with the portal here |
|
||||
| Portal DMA-BUF negotiation | unit test of the offered formats; a real capture (row below) | formats parse; LINEAR DMA-BUFs negotiated with the compositor of the 2560x1440 desktop below |
|
||||
| Portal / PipeWire error paths (no bus, bus without portal, no daemon) | unit tests, manual probe | tested |
|
||||
| Portal capture (shared memory and DMA-BUF), PipeWire video and audio streams | – | compiles only (no portal or PipeWire daemon here) |
|
||||
| Portal capture (shared memory and DMA-BUF), PipeWire video and audio streams | `voelinctl stream bench --source portal` on a 2560x1440 Wayland desktop | tested: it delivered no frames at all (the DMA-BUF mapping length), and the DMA-BUF path cost 19.5 cores where shared memory costs 0.41. Both fixed; 1440p60 now runs on 0.55 cores (see the table above). Portal audio is still untested |
|
||||
| Windows Graphics Capture, WASAPI | – | type-checked for `x86_64-pc-windows-gnu` only |
|
||||
| FFmpeg loader: sonames, missing FFmpeg, layout checks on a real release | `ffmpeg::sys` / `ffmpeg` unit tests; mirrors compared with offsets compiled from the 4.4-8.0 headers | tested (FFmpeg 6.1.1 on Ubuntu 24.04) |
|
||||
| FFmpeg loader: sonames, missing FFmpeg, layout checks on a real release | `ffmpeg::sys` / `ffmpeg` unit tests; mirrors compared with offsets compiled from the 4.4-9.0 headers | tested (FFmpeg 6.1.1 on Ubuntu 24.04; FFmpeg 9.0.1 / libavutil 61 / libavcodec 63 on Arch, every offset compared with that release's own headers) |
|
||||
| FFmpeg software encoders → our decoders: x264 → OpenH264, SVT-AV1 / rav1e / libaom → dav1d (PSNR > 28 dB, keyframes at start and on request, timestamps, bitrate change, size change, odd sizes, Constrained High / Baseline) | `tests/ffmpeg.rs` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested |
|
||||
| Self-test failures (NVENC without CUDA, Quick Sync without a session, VA-API without a render node, encoders not in the build) | `tests/ffmpeg.rs`, `voelinctl stream encoders` | tested: each fails alone with FFmpeg's reason |
|
||||
| Encoder preference (auto, software, named, hardware off), report ranks | `codec::tests::encoder_preference` | tested |
|
||||
| An encoder per codec viewers chose (made, dropped, stream codec skipped, preference change) | `voelin-core` `media::tests::an_encoder_per_codec_viewers_chose` | tested |
|
||||
| Answer's codec reported to the streamer, H.264 level in the offer, HEVC offered | `voelin-stream` `peer::tests::streamer_learns_the_answered_codec`, `h264::tests` | tested (str0m on loopback) |
|
||||
| x264 / SVT-AV1 / libaom in the streamer pipeline | `voelinctl stream bench --encoder ...` | 720p30: x264 8.7 ms per frame, SVT-AV1 1.3 ms, libaom 37 ms; 1.1 allocations per encoded frame |
|
||||
| Hardware encoders (VA-API, NVENC, Quick Sync, AMF, Media Foundation, VideoToolbox), DMA-BUF import | – | compile only (no GPU here); the Windows code type-checks for `x86_64-pc-windows-gnu` |
|
||||
| Hardware encoders VA-API and AMF (H.264, HEVC, AV1) in the streamer pipeline | `voelinctl stream bench` on a Radeon RX 7900 GRE, 1080p60 / 1440p60 / simulcast | tested: full frame rate, 0.20-0.52 cores against 1.16-2.55 for software, 1.02 allocations per encoded frame, every backend within 2 % of the target bitrate once `av1_vaapi` got a two-second buffer (it overshot by 3.5-8 %; see the tables above) |
|
||||
| Hardware encoders → our decoders: `h264_vaapi` / `h264_amf` → OpenH264, `av1_vaapi` / `av1_amf` → dav1d (PSNR > 28 dB, decoded size, keyframes at start and on request, timestamps, bitrate change) at 320x240 and 1920x1080 | `tests/ffmpeg.rs` `hardware_encoders_roundtrip` (`VOELIN_OPENH264_LIB`, `--features av1`) | tested on the Radeon RX 7900 GRE: it found the AV1 encoder padding 1080 rows to 1082 (and other sizes to 64x16), now cropped (see above). HEVC is not decoded (no decoder here) |
|
||||
| The alignment an AV1 encoder pads to, from the sequence header it writes | `ffmpeg::encoder::tests::av1_declared_size_and_alignment` (every optional header field), the self-test on the GPU | tested: (64, 16) for `av1_vaapi` and `av1_amf`, (2, 2) for SVT-AV1, rav1e and libaom |
|
||||
| Hardware encoders NVENC, Quick Sync, Media Foundation, VideoToolbox | – | not tested (no such hardware here); NVENC and Quick Sync are skipped by the vendor check and the Windows code type-checks for `x86_64-pc-windows-gnu` |
|
||||
| H.264 SPS against the offered `profile-level-id` (`profile_idc`, `level_idc`) for every usable backend, two sizes, both profiles | `tests/ffmpeg.rs` `sps_carries_the_offered_profile_and_level` | tested: it found `h264_amf` emitting level 4.2 where the offer said 3.1; with the level now set, all backends emit the offered level |
|
||||
| The encoder's H.264 level table against the signalling's | `ffmpeg::encoder::tests::levels_agree_with_the_signalling` | tested (8 sizes x 5 rates x 4 bitrates x 2 profiles) |
|
||||
| Zero-copy DMA-BUF import into a VA-API encoder | `ffmpeg::encoder::tests::a_dmabuf_really_reaches_a_vaapi_encoder` (a VA-API surface exported as DRM PRIME and fed back in) | tested: imports and encodes, with an AMD **tiling** modifier (`0x200000028a01f04`), not only LINEAR |
|
||||
| RGB DMA-BUFs converted to NV12 on the GPU (VA-API video processing): against the CPU conversion, then through `h264_vaapi` and `av1_vaapi` (cropping 642x362 to 640x352) to our decoders, from a tiled buffer and from a LINEAR one with a padded pitch | `ffmpeg::encoder::tests::an_rgb_dmabuf_is_converted_on_the_gpu`, `vpp::tests` (the parameter struct against libva 2.24's header) | tested on the Radeon RX 7900 GRE: Y identical to the CPU's, U/V within 0.7 on average, within 0.3 dB of the CPU path after encoding. It found Mesa converting the transfer function by default (dark pixels 5 levels too bright), now described away |
|
||||
| CPU cost of the GPU path | `zero_copy_cpu_cost` (`--ignored`) | measured: 0.08-0.09 ms per 2560x1440 frame against 4.3-5.2 ms through shared memory (see above) |
|
||||
| A failed DMA-BUF import: an error, the encoder goes on, and drops cleanly | `tests/ffmpeg.rs` `dmabuf_import_is_refused_cleanly` (`/dev/null` as the buffer) | tested: it found FFmpeg 9's `h264_vaapi` crashing when a session that never got a frame is flushed; such sessions are no longer flushed |
|
||||
| Zero-copy from screen capture | – | not reached: the encoder side works (rows above) and the portal hands a DMA-BUF to a sink that accepts one, but the streamer's sink (`Ingest` in voelin-core) does not, so no captured frame has gone through it |
|
||||
| Offer [VP9, VP8], a viewer that decodes only VP8 → its own VP8 encoder, VP9 idle, pictures decoded | `voelin-core/tests/media_live.rs` `ts6_viewer_gets_the_codec_it_chose` (`VOELIN_LIVE=1`) | tested against the TeamSpeak 6 dev server (our client on both ends) |
|
||||
| Several codecs against official TeamSpeak viewers | – | not tested (no official client here) |
|
||||
| Test pattern → VP8 → decoder, rectangle position and colour | `voelin-core` `media::tests::local_preview_decodes_the_pattern` | tested |
|
||||
|
||||
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 95 KiB After Width: | Height: | Size: 105 KiB |
|
Before Width: | Height: | Size: 79 KiB After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 128 KiB After Width: | Height: | Size: 131 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 81 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 143 KiB |
|
After Width: | Height: | Size: 130 KiB |
|
After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 30 KiB |
|
Before Width: | Height: | Size: 105 KiB After Width: | Height: | Size: 112 KiB |
|
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 54 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 99 KiB After Width: | Height: | Size: 108 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 96 KiB |
|
After Width: | Height: | Size: 92 KiB |
|
After Width: | Height: | Size: 105 KiB |
|
After Width: | Height: | Size: 124 KiB |
|
Before Width: | Height: | Size: 39 KiB After Width: | Height: | Size: 44 KiB |
|
Before Width: | Height: | Size: 34 KiB After Width: | Height: | Size: 34 KiB |
|
Before Width: | Height: | Size: 29 KiB After Width: | Height: | Size: 28 KiB |
|
Before Width: | Height: | Size: 41 KiB After Width: | Height: | Size: 42 KiB |
|
Before Width: | Height: | Size: 28 KiB After Width: | Height: | Size: 28 KiB |
@@ -22,13 +22,14 @@ crates/voelin-ui/
|
||||
components/ the design system (catalogue below); index.slint exports all
|
||||
shells/ desktop.slint (rail, top bar, Sidebar), mobile.slint (bottom
|
||||
navigation), common.slint (Panel, VoiceCard, UserCard, ...)
|
||||
screens/ channels, chat, streams (panel and viewer), settings, home,
|
||||
dialogs, mobile (phone-only pages)
|
||||
screens/ channels, chat, members (panel, card), drawers (pins, topics),
|
||||
voice (the voice channel), streams (viewer; the phone's
|
||||
panel), settings, home, dialogs, mobile (phone-only pages)
|
||||
assets/ fonts/ (Inter, OFL), icons/ (Lucide, ISC), logo.svg
|
||||
assets/twemoji.bin the Twemoji SVGs packed by scripts/pack-twemoji.py
|
||||
src/
|
||||
app.rs setup, App state, event dispatch
|
||||
servers.rs chat.rs streams.rs settings_page.rs appearance.rs
|
||||
servers.rs chat.rs members.rs streams.rs settings_page.rs appearance.rs
|
||||
the logic of each area
|
||||
vm/ pure view models (engine state → Slint structs), unit-tested
|
||||
bind/ callbacks of each area, wired once
|
||||
@@ -62,7 +63,7 @@ literal colours.
|
||||
| Radii | `radius-xs` 4, `radius-sm` 6, `radius-md` 8, `radius-lg` 12, `radius-xl` 16, `radius-pill` |
|
||||
| Spacing | `space-1` 2 … `space-8` 32 (2, 4, 8, 12, 16, 20, 24, 32) |
|
||||
| Type (scaled) | `font-xs` 11, `font-sm` 12, `font-body` 14, `font-md` 15, `font-lg` 17, `font-xl` 20, `font-2xl` 24, `font-3xl` 30; `weight-regular` … `weight-bold` |
|
||||
| Sizes | `row-height`, `control-height` 36, `control-height-sm` 28, `icon-sm/md/lg` 16/20/24, `rail-width` 72, `sidebar-width` 264 (grows with the font scale), `topbar-height` 56, `right-panel-min/max` |
|
||||
| Sizes | `row-height`, `control-height` 36, `control-height-sm` 28, `icon-sm/md/lg` 16/20/24, `rail-width` 72, `sidebar-width` 264 (grows with the font scale), `topbar-height` 56, `right-panel-min` |
|
||||
| Motion | `fast` 120 ms, `normal` 200 ms |
|
||||
|
||||
A light palette is filled in for every colour; `mode` switches at runtime.
|
||||
@@ -119,6 +120,26 @@ Shell pieces (ui/shells/): `DesktopShell` (rail + top bar + panels as
|
||||
`Panel`, `ServerRail`, `TopBar`, `MobileShell` (top bar, page, bottom
|
||||
navigation), `VoiceCard`, `VoiceButtons`, `UserCard`, `HoldToTalk`.
|
||||
|
||||
## The server page
|
||||
|
||||
The server page follows the design mockups 03 to 08 (desktop). Each part
|
||||
comes from the engine's events; what a gateway adds is hidden without it.
|
||||
|
||||
| Part | `VOELIN_OPEN` | What it shows | Engine data |
|
||||
|---|---|---|---|
|
||||
| Chat | `server` | Header with Pinned Messages, Topics, the voice channel and the members button; chat tabs; messages grouped by author ("Today at 10:14"), avatars, emoji, reactions with an add button, pin and topic marks, file cards with download; composer with attach, emoji and send. Opens at the newest message and follows new ones while at the end | `ChatHistory` (and `Chat` for servers without history), `AvatarReady`, `Transfer`, `Gateway` (pins; reactions arrive as stored messages); `Command::LoadOlderHistory`, `DownloadChatFile`, `UploadFile`, `GatewayRequest::React`, `Unreact`, `Pin`, `Unpin` |
|
||||
| Members panel | `server` (`panel`, `no-panel`) | "Members — N" and a search; those streaming first (the people in our channel while the voice channel or a stream is shown), then each server group in the server's order with its icon, then those without a group. Rows: avatar with status, name, crown (admin groups), priority speaker, channel commander, recording, moderator role, talk power, what they do or the channel they are in. Resizable: the width is `ui.members_width` | `Presence`, `Groups`, `Talking`, `IconReady` |
|
||||
| Member card | `member` | Description, groups, talk power, country; private message, poke, friend, block; volume and mute for us | `ContactsChanged`; `Command::SetContact`, `SetClientVolume`, `SetClientMuted`, `Poke` |
|
||||
| Pinned messages | `pins` | In the members panel's place: cards with author, time, text, files and reactions; the pin unpins, a click jumps to the message | `Gateway` `Pins`, `Pinned`, `Unpinned`; `GatewayRequest::Pins`, `Unpin` |
|
||||
| Topics | `topics`, `topic:<id>` | In the members panel's place: search, cards with the message count, creator and last activity, Create Topic; an open topic replaces the chat's messages and takes replies | `Gateway` `Topics`, `Topic`, `TopicHistory`; `GatewayRequest::Topics`, `TopicHistory`, `CreateTopic`, `Post` |
|
||||
| Voice channel | `voice` | Title, topic, "5 in voice / 50 total", Voice Settings, Leave; the people as large avatars (talking ring and bars, muted, crown, streaming); the streams as cards (LIVE, viewers, kind, bitrate, sound, Watch Stream); the channel's chat | `Presence`, `Talking`, `StreamsChanged`, `Gateway` stream directory (viewer counts) |
|
||||
| Watching a stream | `watch`, `popout` | The channel's header with "5 in voice" and Leave; the player with the streamer, title, viewers, LIVE, the picture's height (the simulcast picker when the streamer offers layers), volume, elapsed time, back to the chat, pop out, full screen; a note that the stream belongs to the channel; the channel's chat and a Stream Info tab. Popped out (and in full screen) it fills the window | `WatchState`, decoded frames (`src/video.rs`), `Gateway` stream directory |
|
||||
|
||||
The pins and topics share the place of the members panel: opening one
|
||||
closes the other, and the members button brings the panel back. On the
|
||||
phone the chat is the Chat tab and the members of our channel are on the
|
||||
Activity tab.
|
||||
|
||||
## Adding a screen
|
||||
|
||||
1. Write the screen in `ui/screens/<name>.slint` from the components
|
||||
@@ -150,6 +171,7 @@ live when they change (settings page, `--set`, another window):
|
||||
| `ui.font_scale` | number above 0 | 1.0 | every type size |
|
||||
| `ui.narrow_breakpoint` | pixels | 800 | below this width the phone layout |
|
||||
| `ui.image_cache_mb` | megabytes | 64 | decoded images kept in memory (0: none) |
|
||||
| `ui.members_width` | pixels | 280 | width of the members panel (dragging its edge sets it) |
|
||||
|
||||
In a config file write them as dotted keys at the top level
|
||||
(`"ui.theme" = "light"`): a `[ui]` table is read as the `ui` value.
|
||||
@@ -180,29 +202,48 @@ Environment variables (see `src/dev.rs`):
|
||||
a stream, without a server (nothing is stored).
|
||||
- `VOELIN_OPEN=<what>[,<what>...]`: `home`, `server`, `settings[:voice|keybinds|streaming|privacy|appearance]`,
|
||||
`about`, `share`, `bookmark`, `emoji`, `client`, `panel`, `no-panel`,
|
||||
`tab:<home|servers|chat|activity|you>` (phone layout).
|
||||
`voice`, `pins`, `topics`, `topic:<id>`, `member`, `watch`, `popout`
|
||||
(the server page, above), `tab:<home|servers|chat|activity|you>` (phone
|
||||
layout). With sample data, `watch` plays the local test pattern in the
|
||||
sample stream's place.
|
||||
- `VOELIN_WINDOW_SIZE=390x844`: window size (phone layout below the breakpoint).
|
||||
- `VOELIN_SCREENSHOT=<png>`, `VOELIN_SCREENSHOT_DELAY=<s>`: save the window and exit.
|
||||
- `VOELIN_DEMO_STREAM=1`, `VOELIN_AUTOCONNECT`, `VOELIN_AUTOWATCH`,
|
||||
`VOELIN_AUTOSHARE`, `VOELIN_DATA_DIR` as before.
|
||||
|
||||
```sh
|
||||
SLINT_BACKEND=winit-software VOELIN_DATA_DIR=$(mktemp -d) VOELIN_DEMO_UI=1 \
|
||||
VOELIN_OPEN=settings:appearance VOELIN_WINDOW_SIZE=1440x960 \
|
||||
scripts/shots.sh shot.png settings:appearance 1440x960
|
||||
# which runs, headless:
|
||||
env -u WAYLAND_DISPLAY SLINT_BACKEND=winit-software VOELIN_DATA_DIR=$(mktemp -d) \
|
||||
VOELIN_DEMO_UI=1 VOELIN_OPEN=settings:appearance VOELIN_WINDOW_SIZE=1440x960 \
|
||||
VOELIN_SCREENSHOT=shot.png VOELIN_SCREENSHOT_DELAY=4 \
|
||||
xvfb-run -a -s "-screen 0 1600x1100x24" target/debug/voelin
|
||||
xvfb-run -a -s "-screen 0 1440x960x24" target/debug/voelin
|
||||
```
|
||||
|
||||
The pictures in `docs/screenshots/` were made this way (reduced to 256
|
||||
colours with `convert -colors 256 PNG8:`).
|
||||
Remove `WAYLAND_DISPLAY` as above in a Wayland session: winit prefers
|
||||
Wayland, so the window would open on the desktop instead of on the Xvfb
|
||||
server (and take whatever size the compositor gives it). The script also
|
||||
turns FFmpeg off (`VOELIN_FFMPEG=0`: probing hardware encoders is not
|
||||
needed for pictures and has crashed in a driver), makes the screen twice
|
||||
the window's size so the pointer is not over the window, and passes
|
||||
`$ARGS` to the app (`ARGS="--set ui.theme=light"`). The pictures in
|
||||
`docs/screenshots/` were made this way (reduced to 256 colours with
|
||||
`convert -colors 256 PNG8:`).
|
||||
|
||||
| Server page | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
| Desktop | |
|
||||
|---|---|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  |  |
|
||||
|  | |
|
||||
|
||||
| Phone layout | | | | |
|
||||
|---|---|---|---|---|
|
||||
@@ -212,6 +253,16 @@ colours with `convert -colors 256 PNG8:`).
|
||||
|
||||
- No drop shadows or blur (the software renderer draws none): glows are
|
||||
translucent rings, the backdrop is a gradient rectangle.
|
||||
- Avatars are initials on a colour from the name; the image cache is ready
|
||||
for pictures (server icons, avatars) once the engine provides them.
|
||||
- Avatars are the clients' pictures from the engine's cache
|
||||
(`AvatarReady`), or initials on a colour from the name; group icons come
|
||||
from `IconReady`.
|
||||
- The members panel lists the people online: TeamSpeak tells a client
|
||||
nothing about offline members, so the mockup's "Offline" section and a
|
||||
server-wide member count are left out.
|
||||
- The quality picker shows only when the streamer's simulcast layers are
|
||||
known; the engine does not yet tell a viewer which layers a stream has,
|
||||
so in practice the player shows the decoded picture's height.
|
||||
- Popping the stream out fills the main window (no second window yet).
|
||||
- A jump to a pinned message scrolls to where an average row would be
|
||||
(rows differ in height), and only to messages already loaded.
|
||||
- The window keeps its native decorations (no custom title bar).
|
||||
@@ -0,0 +1,31 @@
|
||||
#!/bin/sh
|
||||
# Take a screenshot of the app with sample data, headless.
|
||||
#
|
||||
# scripts/shots.sh <out.png> <VOELIN_OPEN> [<width>x<height>]
|
||||
#
|
||||
# The pictures in docs/screenshots/ are made this way (and reduced to 256
|
||||
# colours with `convert -colors 256 PNG8:`).
|
||||
#
|
||||
# WAYLAND_DISPLAY is removed so the window opens on the Xvfb server and not
|
||||
# on the desktop of a Wayland session (winit prefers Wayland when it can).
|
||||
# The screen is twice the window's size, so the pointer (in its middle) is
|
||||
# not over the window and nothing shows as hovered. FFmpeg stays off: the
|
||||
# pictures need no hardware encoders, and probing them can crash in some
|
||||
# drivers. Extra arguments (`--set ui.theme=light`) come from $ARGS.
|
||||
set -eu
|
||||
out=$1
|
||||
open=$2
|
||||
size=${3:-1440x960}
|
||||
w=${size%x*}
|
||||
h=${size#*x}
|
||||
bin=${VOELIN_BIN:-$CARGO_TARGET_DIR/debug/voelin}
|
||||
env -u WAYLAND_DISPLAY \
|
||||
SLINT_BACKEND=winit-software \
|
||||
VOELIN_FFMPEG=0 \
|
||||
VOELIN_DATA_DIR="$(mktemp -d)" \
|
||||
VOELIN_DEMO_UI=1 \
|
||||
VOELIN_OPEN="$open" \
|
||||
VOELIN_WINDOW_SIZE="$size" \
|
||||
VOELIN_SCREENSHOT="$out" \
|
||||
VOELIN_SCREENSHOT_DELAY="${DELAY:-4}" \
|
||||
xvfb-run -a -s "-screen 0 $((w * 2))x$((h * 2))x24" "$bin" ${ARGS:-} >/dev/null 2>&1
|
||||
@@ -51,6 +51,16 @@ struct EncodersArgs {
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
struct BenchArgs {
|
||||
/// What to capture: `synthetic` (the test pattern), `portal` (the
|
||||
/// desktop's screen-share dialog, Wayland and X11), `monitor:<n>` or
|
||||
/// `window:<id>` (X11). Anything but `synthetic` ignores --res and
|
||||
/// --pattern and measures the real capture → convert → encode pipeline.
|
||||
#[arg(long, default_value = "synthetic")]
|
||||
source: String,
|
||||
/// Give up if the capture has not started after this many seconds (the
|
||||
/// portal opens a dialog the user has to accept).
|
||||
#[arg(long, default_value_t = 60)]
|
||||
start_timeout: u64,
|
||||
/// Size of the test pattern.
|
||||
#[arg(long, default_value = "1920x1080")]
|
||||
res: String,
|
||||
@@ -212,6 +222,19 @@ impl MediaSink for BenchSink {
|
||||
}
|
||||
}
|
||||
|
||||
/// `synthetic`, `portal`, `monitor:<n>` or `window:<id>`.
|
||||
fn parse_source(value: &str) -> Result<SourceId> {
|
||||
Ok(match value.split_once(':') {
|
||||
Some(("monitor", n)) => SourceId::Monitor(n.parse().context("monitor index")?),
|
||||
Some(("window", id)) => SourceId::Window(id.parse().context("window id")?),
|
||||
_ => match value {
|
||||
"synthetic" => SourceId::Synthetic,
|
||||
"portal" => SourceId::Portal,
|
||||
other => bail!("unknown source {other:?}: synthetic, portal, monitor:<n>, window:<id>"),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/// `<width>x<height>`.
|
||||
fn parse_size(size: &str) -> Result<(u32, u32)> {
|
||||
let parsed = size.split_once('x').and_then(|(w, h)| Some((w.parse().ok()?, h.parse().ok()?)));
|
||||
@@ -317,8 +340,9 @@ fn bench(args: BenchArgs) -> Result<()> {
|
||||
.collect::<Result<Vec<_>>>()?;
|
||||
let ids: Vec<LayerId> =
|
||||
if layers.is_empty() { vec![0] } else { layers.iter().map(|l| l.id).collect() };
|
||||
let source = parse_source(&args.source)?;
|
||||
let config = StreamerConfig {
|
||||
source: SourceId::Synthetic,
|
||||
source: source.clone(),
|
||||
synthetic_size: (width, height),
|
||||
synthetic_pattern: pattern,
|
||||
fps: args.fps,
|
||||
@@ -330,23 +354,54 @@ fn bench(args: BenchArgs) -> Result<()> {
|
||||
..StreamerConfig::default()
|
||||
};
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
let streamer = runtime.block_on(Streamer::start(&codecs, config)).context("streamer")?;
|
||||
let timeout = Duration::from_secs(args.start_timeout.max(1));
|
||||
// The portal opens a dialog on the desktop; without an answer the start
|
||||
// never returns, so it is given a deadline instead of hanging.
|
||||
let started = runtime
|
||||
.block_on(async { tokio::time::timeout(timeout, Streamer::start(&codecs, config)).await });
|
||||
let streamer = match started {
|
||||
Ok(result) => result.context("streamer")?,
|
||||
Err(_) => bail!(
|
||||
"the capture did not start within {} s (the {} source was not accepted)",
|
||||
timeout.as_secs(),
|
||||
args.source
|
||||
),
|
||||
};
|
||||
let sink = Arc::new(BenchSink {
|
||||
layers: ids.iter().map(|id| (*id, LayerCount::default())).collect(),
|
||||
keyframe: AtomicBool::new(true),
|
||||
});
|
||||
streamer.attach(sink.clone());
|
||||
let backend = streamer.stats().layers.first().and_then(|l| l.backend);
|
||||
let what = if source == SourceId::Synthetic {
|
||||
format!("{width}x{height} {} test pattern", args.pattern)
|
||||
} else {
|
||||
format!("{} capture", args.source)
|
||||
};
|
||||
println!(
|
||||
"{width}x{height} {} test pattern at {} fps, {codec} ({}), {} layer(s), {} s after {} s \
|
||||
warm-up",
|
||||
args.pattern,
|
||||
"{what} at {} fps, {codec} ({}), {} layer(s), {} s after {} s warm-up",
|
||||
args.fps,
|
||||
backend.map_or("?".to_owned(), |b| b.to_string()),
|
||||
ids.len(),
|
||||
args.seconds,
|
||||
args.warmup
|
||||
);
|
||||
// A real source only delivers once the user has picked something.
|
||||
if source != SourceId::Synthetic {
|
||||
let deadline = Instant::now() + timeout;
|
||||
while streamer.stats().captured_frames == 0 {
|
||||
if Instant::now() >= deadline {
|
||||
bail!(
|
||||
"no frame from the {} source within {} s (nobody accepted the dialog?)",
|
||||
args.source,
|
||||
timeout.as_secs()
|
||||
);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
let stats = streamer.stats();
|
||||
println!("capturing {}x{}", stats.width, stats.height);
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(args.warmup));
|
||||
let start = sample(&sink, &streamer);
|
||||
std::thread::sleep(Duration::from_secs(args.seconds));
|
||||
@@ -368,7 +423,13 @@ fn bench(args: BenchArgs) -> Result<()> {
|
||||
let frames = b.frames - a.frames;
|
||||
output_frames += frames;
|
||||
let spec = layers.iter().find(|l| l.id == *id);
|
||||
let size = spec.map_or((width, height), |l| l.output_size(width, height));
|
||||
let layer_stats = stats.layers.iter().find(|l| l.id == *id);
|
||||
// What was really encoded: with a real source the size comes from the
|
||||
// capture, not from --res.
|
||||
let size = match layer_stats.filter(|l| l.width > 0) {
|
||||
Some(l) => (l.width, l.height),
|
||||
None => spec.map_or((width, height), |l| l.output_size(width, height)),
|
||||
};
|
||||
let dropped = |s: &Sample| s.dropped.iter().find(|d| d.0 == *id).map_or(0, |d| d.1);
|
||||
let layer = stats.layers.iter().find(|l| l.id == *id);
|
||||
println!(
|
||||
|
||||
@@ -14,7 +14,7 @@ use tokio::time::{Instant, Interval, sleep_until};
|
||||
use tsclientlib::prelude::*;
|
||||
use tsclientlib::{ClientId, Connection, MessageHandle, StreamItem};
|
||||
use voelin_core::media::voelin_media::capture::SourceId;
|
||||
use voelin_core::media::voelin_media::{Codecs, VideoFrame, convert};
|
||||
use voelin_core::media::voelin_media::{Codec, Codecs, VideoFrame, convert};
|
||||
use voelin_core::media::{
|
||||
CaptureBackend, EncodedSource, EncoderPreference, Latest, Streamer, StreamerConfig,
|
||||
VideoPipeline, peer_config, preferred_codec, stream_codec, video_codec,
|
||||
@@ -96,8 +96,8 @@ pub enum StreamCommand {
|
||||
/// bitrate, no encoder) instead of capturing.
|
||||
#[arg(long, conflicts_with_all = ["source", "synthetic"])]
|
||||
placeholder: bool,
|
||||
/// Video codec: vp8, vp9, h264, av1 [default: the first the encoder
|
||||
/// choice gives: hardware first, else VP8].
|
||||
/// Video codec: vp8, vp9, h264, av1 [default: VP8, which every client
|
||||
/// decodes; with --encoder, that encoder's codec]. One codec is offered.
|
||||
#[arg(long)]
|
||||
codec: Option<String>,
|
||||
/// Encoder: `auto`, `software` or a backend name from `voelinctl
|
||||
@@ -177,6 +177,9 @@ pub async fn run(con: &mut Connection, args: &StreamArgs) -> Result<()> {
|
||||
} else {
|
||||
let configured = match codec {
|
||||
Some(codec) => Some(codec.parse().map_err(|e| anyhow::anyhow!("{e}"))?),
|
||||
// One codec is offered (below): by default the one every
|
||||
// client decodes. A named encoder brings its own codec.
|
||||
None if encoder == "auto" => Some(Codec::Vp8),
|
||||
None => None,
|
||||
};
|
||||
if let Some(codec) = preferred_codec(&codecs, configured) {
|
||||
|
||||