Skip to content

Your Android phone and your Windows PC, working as one. Local-first, end-to-end encrypted, no account.

Screen mirroring, PC side: decode a phone's screen and show it

Bee37dad51a115e
diff --git a/core/nectarlink-cli/src/main.rs b/core/nectarlink-cli/src/main.rs
index 28cd663..258e85a 100644
--- a/core/nectarlink-cli/src/main.rs
+++ b/core/nectarlink-cli/src/main.rs
@@ -164,6 +164,18 @@ enum Command {
/// Show new photos from paired phones as this PC would, and fetch each
/// one; stays online until Ctrl+C.
Photos,
+ /// Act as a phone sharing its screen (use with --as-phone): when a PC
+ /// asks, streams an H.264 file (Annex B, with access unit delimiters) in
+ /// a loop at `fps`. Stays online.
+ Screen {
+ video: PathBuf,
+ #[arg(long)]
+ width: u32,
+ #[arg(long)]
+ height: u32,
+ #[arg(long, default_value_t = 60)]
+ fps: u32,
+ },
/// Act as a phone with a few sample conversations (use with --as-phone),
/// so a PC can read them and text through this client; stays online.
Texts,
@@ -289,6 +301,10 @@ enum OnOff {
Off,
}
+/// PCs that asked for the screen, for `screen`.
+static SCREEN_ASKS: std::sync::OnceLock<tokio::sync::mpsc::UnboundedSender<DeviceId>> =
+ std::sync::OnceLock::new();
+
/// A sample text for `texts`: (thread, number, name, incoming, body, Unix ms).
type SampleText = (u32, String, String, bool, String, i64);
static TEXTS: std::sync::Mutex<Vec<SampleText>> = std::sync::Mutex::new(Vec::new());
@@ -330,6 +346,21 @@ const PHOTO_ID: &str = "cli-photo";
struct TerminalPlatform;
impl Platform for TerminalPlatform {
+ fn mirror_requested(
+ &self,
+ peer: &DeviceId,
+ options: &nectarlink_core::MirrorStart,
+ ) -> std::result::Result<(), String> {
+ let asks = SCREEN_ASKS.get().ok_or("not sharing a screen (run `screen`)")?;
+ println!("A PC asked for the screen ({}px, {} fps); sharing it.", options.max_size, options.fps);
+ asks.send(*peer).map_err(|e| e.to_string())
+ }
+ fn mirror_stop_requested(&self, _peer: &DeviceId) {
+ println!("The PC stopped watching.");
+ }
+ fn mirror_keyframe_requested(&self, _peer: &DeviceId) {
+ println!("The PC asked for a keyframe.");
+ }
fn sms_threads(&self, limit: u32) -> std::result::Result<Vec<nectarlink_core::SmsThread>, String> {
let texts = TEXTS.lock().unwrap();
let mut threads: Vec<nectarlink_core::SmsThread> = Vec::new();
@@ -650,6 +681,38 @@ async fn run(cli: &Cli, node: &Node) -> Result<()> {
node.update_power(node_power(cli), offers).await;
watch(node, true).await?;
}
+ Command::Screen { video, width, height, fps } => {
+ if !cli.as_phone {
+ bail!("screens are shared by phones: add --as-phone");
+ }
+ let stream = std::fs::read(video).context("can't read the video")?;
+ let units = access_units(&stream);
+ if units.is_empty() {
+ bail!("no access unit delimiters in the video");
+ }
+ let (asks, mut asked) = tokio::sync::mpsc::unbounded_channel();
+ let _ = SCREEN_ASKS.set(asks);
+ let mut offers = cli.offers.clone();
+ offers.push(nectarlink_core::MIRROR_CAPTURE.into());
+ node.update_power(node_power(cli), offers).await;
+ println!("Sharing a {width}x{height} screen ({} frames) with PCs that ask.", units.len());
+ let streamer = node.clone();
+ let (width, height, fps) = (*width, *height, *fps);
+ tokio::spawn(async move {
+ while let Some(pc) = asked.recv().await {
+ let mirror = match streamer.mirror_open(pc).await {
+ Ok(mirror) => std::sync::Arc::new(mirror),
+ Err(e) => {
+ println!("Couldn't open the stream: {e}");
+ continue;
+ }
+ };
+ let units = units.clone();
+ std::thread::spawn(move || stream_screen(&mirror, &units, width, height, fps));
+ }
+ });
+ watch(node, false).await?;
+ }
Command::Texts => {
if !cli.as_phone {
bail!("texts are on phones: add --as-phone");
@@ -1272,3 +1335,52 @@ fn print_qr(data: &str) {
Err(e) => tracing::warn!(error = %e, "could not render QR code"),
}
}
+
+/// Splits an Annex B stream at its access unit delimiters (a 4-byte start
+/// code, then NAL type 9).
+fn access_units(stream: &[u8]) -> Vec<Vec<u8>> {
+ let starts: Vec<usize> =
+ (0..stream.len()).filter(|&i| stream[i..].starts_with(&[0, 0, 0, 1, 9])).collect();
+ starts
+ .iter()
+ .enumerate()
+ .map(|(n, &s)| stream[s..*starts.get(n + 1).unwrap_or(&stream.len())].to_vec())
+ .collect()
+}
+
+/// Whether an access unit holds an IDR picture (NAL type 5).
+fn is_keyframe(unit: &[u8]) -> bool {
+ unit.windows(4).any(|w| w[..3] == [0, 0, 1] && w[3] & 0x1f == 5)
+}
+
+/// Streams `units` in a loop at `fps` until the PC stops watching.
+fn stream_screen(
+ mirror: &nectarlink_core::MirrorStream,
+ units: &[Vec<u8>],
+ width: u32,
+ height: u32,
+ fps: u32,
+) {
+ use nectarlink_core::{MirrorSend, PacketKind};
+ let config = nectarlink_core::MirrorConfig { codec: "h264".into(), width, height }.to_cbor();
+ if mirror.send(PacketKind::Config, 0, config) == MirrorSend::Closed {
+ return;
+ }
+ let frame = std::time::Duration::from_secs_f64(1.0 / f64::from(fps.max(1)));
+ let started = std::time::Instant::now();
+ let mut dropped = 0u32;
+ for (n, unit) in units.iter().cycle().enumerate() {
+ let due = started + frame * n as u32;
+ if let Some(wait) = due.checked_duration_since(std::time::Instant::now()) {
+ std::thread::sleep(wait);
+ }
+ let kind = if is_keyframe(unit) { PacketKind::Keyframe } else { PacketKind::Frame };
+ let time = started.elapsed().as_micros() as u64;
+ match mirror.send(kind, time, unit.clone()) {
+ MirrorSend::Queued => {}
+ MirrorSend::NeedKeyframe => dropped += 1,
+ MirrorSend::Closed => break,
+ }
+ }
+ println!("Stopped sharing the screen ({dropped} frames dropped to keep up).");
+}
diff --git a/core/nectarlink-core/src/config.rs b/core/nectarlink-core/src/config.rs
index 364cb0c..c75641c 100644
--- a/core/nectarlink-core/src/config.rs
+++ b/core/nectarlink-core/src/config.rs
@@ -123,6 +123,33 @@ pub trait Platform: Send + Sync + 'static {
Err("this device doesn't share photos".into())
}
+ /// Where a phone's screen goes on this PC, when it starts streaming
+ /// (after [`Node::mirror_start`](crate::Node::mirror_start)). `None`
+ /// refuses the stream.
+ fn mirror_sink(
+ &self,
+ _peer: &nectarlink_protocol::DeviceId,
+ ) -> Option<std::sync::Arc<dyn crate::MirrorSink>> {
+ None
+ }
+
+ /// A PC asked for this phone's screen: ask the user, then (if they
+ /// agree) stream it with [`Node::mirror_open`](crate::Node::mirror_open).
+ /// `Err` (a reason for logs) when the user can't be asked.
+ fn mirror_requested(
+ &self,
+ _peer: &nectarlink_protocol::DeviceId,
+ _options: &crate::MirrorStart,
+ ) -> Result<(), String> {
+ Err("this device doesn't share its screen".into())
+ }
+
+ /// The PC stopped watching: stop sharing the screen.
+ fn mirror_stop_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}
+
+ /// The PC's decoder needs a fresh start: encode a keyframe next.
+ fn mirror_keyframe_requested(&self, _peer: &nectarlink_protocol::DeviceId) {}
+
/// This phone's latest conversations, newest first (a PC asked).
fn sms_threads(&self, _limit: u32) -> Result<Vec<crate::SmsThread>, String> {
Err("this device has no messages".into())
diff --git a/core/nectarlink-core/src/events.rs b/core/nectarlink-core/src/events.rs
index 15a1c9f..6e45ce7 100644
--- a/core/nectarlink-core/src/events.rs
+++ b/core/nectarlink-core/src/events.rs
@@ -139,6 +139,11 @@ pub enum NodeEvent {
device: DeviceId,
call: crate::CallState,
},
+ /// A phone's screen started or stopped showing here.
+ Mirroring {
+ device: DeviceId,
+ on: bool,
+ },
/// A phone's messages changed: in `thread`, or anywhere when `None`.
SmsChanged {
device: DeviceId,
diff --git a/core/nectarlink-core/src/features.rs b/core/nectarlink-core/src/features.rs
index 8f3964f..358a431 100644
--- a/core/nectarlink-core/src/features.rs
+++ b/core/nectarlink-core/src/features.rs
@@ -333,6 +333,7 @@ pub const DEVICE_TOGGLES: &[(&str, bool)] = &[
("media", true),
("photos", true),
("pc_actions", true),
+ ("mirroring", true),
// Browsing the PC's files from anywhere is opt-in.
("remote_files", false),
];
@@ -647,7 +648,11 @@ pub const FEATURES: &[FeatureDef] = &[
FeatureDef {
id: "mirroring.view",
group: FeatureGroup::Mirroring,
- requires: &[phone("mirror.capture", UPDATE)],
+ requires: &[
+ phone("mirror.capture", UPDATE),
+ desktop("mirror.view", UPDATE),
+ DeviceToggle("mirroring"),
+ ],
partial: None,
},
FeatureDef {
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 12a8a52..d3e2467 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -15,6 +15,7 @@ mod events;
pub mod features;
mod identity;
mod media;
+mod mirror;
mod node;
mod notifications;
mod pairing;
@@ -34,15 +35,17 @@ pub use events::{
pub use features::{CapabilityMatrix, FeatureState};
pub use identity::{KeyProtector, PlainKeyProtector, default_protector};
pub use media::{MediaAction, MediaError};
+pub use mirror::{MirrorSend, MirrorSink, MirrorStream};
pub use nectarlink_protocol::messages::clip::{
IMAGE_TYPES as CLIP_IMAGE_TYPES, MAX_IMAGE_BYTES as CLIP_MAX_IMAGE_BYTES,
};
pub use nectarlink_protocol::{
- DeviceId,
+ DeviceId, PacketKind,
messages::{
- Battery, CLIP_MAX_BYTES, CallState, DeviceInfo, DeviceKind, MediaPlayer, Notification,
- NotificationAction, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart, SmsThread,
+ Battery, CLIP_MAX_BYTES, CallState, DeviceInfo, DeviceKind, MediaPlayer, MirrorConfig, MirrorStart,
+ Notification, NotificationAction, PhotoNew as Photo, PowerLevel, SmsMessage, SmsPart, SmsThread,
calls::{CONTROL as CALLS_CONTROL, SHOW as CALLS_SHOW, STATE as CALLS_STATE},
+ mirror::{CAPTURE as MIRROR_CAPTURE, VIEW as MIRROR_VIEW},
photos::{MAX_THUMB_BYTES as PHOTO_MAX_THUMB_BYTES, READ as PHOTOS_READ, SHOW as PHOTOS_SHOW},
sms::{READ as SMS_READ, SEND as SMS_SEND, SHOW as SMS_SHOW},
},
diff --git a/core/nectarlink-core/src/mirror.rs b/core/nectarlink-core/src/mirror.rs
new file mode 100644
index 0000000..c322ce3
--- /dev/null
+++ b/core/nectarlink-core/src/mirror.rs
@@ -0,0 +1,294 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Screen mirroring (docs/protocol/mirror.md): a PC asks a phone for its
+//! screen; once the phone's user agrees, the phone streams encoded video
+//! on a stream of its own, which the PC decodes and shows.
+//!
+//! The phone side keeps latency low over throughput: when the network
+//! can't keep up, frames are dropped (never queued for long) and the
+//! encoder is asked for a keyframe to start clean from.
+
+use std::sync::{
+ Arc, Mutex,
+ atomic::{AtomicBool, Ordering},
+};
+
+use iroh::endpoint::{RecvStream, SendStream, VarInt};
+use nectarlink_protocol::{
+ DeviceId, Envelope, ErrorCode, PacketKind,
+ messages::{MirrorConfig, MirrorStart, StreamHeader, mirror, types},
+ read_video_packet, video_packet_header, write_frame,
+};
+use tokio::sync::mpsc;
+
+use crate::{Error, Result, events::NodeEvent, node::Shared, session::Session};
+
+/// The device toggle that allows mirroring for a device.
+pub(crate) const TOGGLE: &str = "mirroring";
+/// Packets waiting to go out, at most. Beyond this the network is behind:
+/// sending more would only add delay.
+const QUEUE: usize = 4;
+
+/// What the PC's app gets of a mirroring stream. Called from the core's
+/// threads; must return quickly (hand the work to a thread of its own).
+pub trait MirrorSink: Send + Sync {
+ /// The stream's format: first, and again when it changes.
+ fn config(&self, config: MirrorConfig);
+ /// Encoded video (Annex B), `keyframe` when it starts fresh.
+ fn packet(&self, keyframe: bool, time_us: u64, data: Vec<u8>);
+ /// The stream ended (the phone stopped, or the connection dropped).
+ fn ended(&self);
+}
+
+impl std::fmt::Debug for dyn MirrorSink {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.write_str("MirrorSink")
+ }
+}
+
+// ---- The PC ----
+
+pub(crate) async fn start(shared: &Shared, session: &Session, options: MirrorStart) -> Result<()> {
+ if !shared.toggle_on(&session.peer, TOGGLE) {
+ return Err(Error::Denied);
+ }
+ let env = Envelope::new(types::MIRROR_START, &options)?;
+ session.request(env, crate::session::REQUEST_TIMEOUT).await?.expect(types::OK)?;
+ Ok(())
+}
+
+pub(crate) async fn stop(session: &Session) -> Result<()> {
+ session
+ .request(Envelope::empty(types::MIRROR_STOP), crate::session::REQUEST_TIMEOUT)
+ .await?
+ .expect(types::OK)?;
+ Ok(())
+}
+
+pub(crate) async fn request_keyframe(session: &Session) {
+ let _ = session.send(Envelope::empty(types::MIRROR_KEYFRAME)).await;
+}
+
+/// A phone opened a video stream (its header already read).
+pub(crate) async fn receive(shared: Arc<Shared>, peer: DeviceId, mut send: SendStream, mut recv: RecvStream) {
+ let shows = shared.local_capabilities().iter().any(|c| c == mirror::VIEW);
+ let sink = shows.then(|| shared.platform.mirror_sink(&peer)).flatten();
+ let Some(sink) = sink.filter(|_| shared.toggle_on(&peer, TOGGLE)) else {
+ let _ = send.reset(VarInt::from_u32(mirror::STOPPED));
+ let _ = recv.stop(VarInt::from_u32(mirror::STOPPED));
+ return;
+ };
+ shared.emit(NodeEvent::Mirroring { device: peer, on: true });
+ let stopped = shared.new_mirror_stop(&peer);
+ loop {
+ let packet = tokio::select! {
+ _ = stopped.notified() => break,
+ packet = read_video_packet(&mut recv) => packet,
+ };
+ match packet {
+ Ok(Some(p)) if p.kind == PacketKind::Config => match MirrorConfig::from_cbor(&p.data) {
+ Ok(config) if config.is_valid() => sink.config(config),
+ _ => {
+ tracing::warn!("a phone sent a video format this PC can't show");
+ break;
+ }
+ },
+ Ok(Some(p)) => sink.packet(p.kind == PacketKind::Keyframe, p.time_us, p.data),
+ Ok(None) => break,
+ Err(e) => {
+ tracing::debug!(error = %e, "mirroring stream ended");
+ break;
+ }
+ }
+ }
+ let _ = recv.stop(VarInt::from_u32(mirror::STOPPED));
+ let _ = send.finish();
+ sink.ended();
+ shared.emit(NodeEvent::Mirroring { device: peer, on: false });
+}
+
+// ---- The phone ----
+
+/// Handles `mirror.*` on a session. Returns false for other types.
+pub(crate) async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: &Envelope) -> Result<bool> {
+ let peer = session.peer;
+ let platform = shared.platform.clone();
+ match env.t.as_str() {
+ types::MIRROR_START => {
+ let options: MirrorStart = env.body()?;
+ let reply = if !shared.toggle_on(&peer, TOGGLE) {
+ Envelope::error(ErrorCode::Denied, "mirroring is off for this device")
+ } else if !shared.local_capabilities().iter().any(|c| c == mirror::CAPTURE) {
+ Envelope::error(ErrorCode::Unsupported, "this device doesn't share its screen")
+ } else {
+ match tokio::task::spawn_blocking(move || platform.mirror_requested(&peer, &options))
+ .await
+ .unwrap_or_else(|e| Err(e.to_string()))
+ {
+ Ok(()) => Envelope::empty(types::OK),
+ Err(reason) => {
+ tracing::warn!(reason, "can't ask to share the screen");
+ Envelope::error(ErrorCode::Internal, "the phone couldn't ask")
+ }
+ }
+ };
+ session.send(reply.reply_to(env.id)).await?;
+ }
+ types::MIRROR_STOP => {
+ // The PC's side: stop showing; the phone's: stop sharing.
+ shared.stop_showing(&peer);
+ tokio::task::spawn_blocking(move || platform.mirror_stop_requested(&peer));
+ session.send(Envelope::empty(types::OK).reply_to(env.id)).await?;
+ }
+ types::MIRROR_KEYFRAME => {
+ tokio::task::spawn_blocking(move || platform.mirror_keyframe_requested(&peer));
+ }
+ _ => return Ok(false),
+ }
+ Ok(true)
+}
+
+/// What became of a packet handed to [`MirrorStream::send`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum MirrorSend {
+ Queued,
+ /// Dropped to keep the delay low: send a keyframe next (frames are
+ /// dropped until one comes).
+ NeedKeyframe,
+ /// The PC stopped watching, or the connection is gone: stop sharing.
+ Closed,
+}
+
+/// A phone's video stream to one PC.
+#[derive(Debug)]
+pub struct MirrorStream {
+ queue: mpsc::Sender<(PacketKind, u64, Vec<u8>)>,
+ closed: Arc<AtomicBool>,
+ /// Frames are being dropped until a keyframe.
+ resyncing: Mutex<bool>,
+}
+
+impl MirrorStream {
+ /// Queues a packet without waiting. A config packet waits for room:
+ /// the PC can't decode without it.
+ pub fn send(&self, kind: PacketKind, time_us: u64, data: Vec<u8>) -> MirrorSend {
+ if self.closed.load(Ordering::Acquire) {
+ return MirrorSend::Closed;
+ }
+ let mut resyncing = self.resyncing.lock().unwrap_or_else(|e| e.into_inner());
+ if *resyncing && kind == PacketKind::Frame {
+ return MirrorSend::NeedKeyframe;
+ }
+ let sent = if kind == PacketKind::Config {
+ self.queue.blocking_send((kind, time_us, data)).map_err(|_| ())
+ } else {
+ self.queue.try_send((kind, time_us, data)).map_err(|e| match e {
+ mpsc::error::TrySendError::Full(_) => (),
+ mpsc::error::TrySendError::Closed(_) => self.closed.store(true, Ordering::Release),
+ })
+ };
+ match sent {
+ Ok(()) => {
+ if kind == PacketKind::Keyframe {
+ *resyncing = false;
+ }
+ MirrorSend::Queued
+ }
+ Err(()) if self.closed.load(Ordering::Acquire) => MirrorSend::Closed,
+ Err(()) => {
+ *resyncing = true;
+ MirrorSend::NeedKeyframe
+ }
+ }
+ }
+
+ /// Ends the stream (the phone stopped sharing).
+ pub fn close(&self) {
+ self.closed.store(true, Ordering::Release);
+ }
+
+ pub fn is_closed(&self) -> bool {
+ self.closed.load(Ordering::Acquire) || self.queue.is_closed()
+ }
+}
+
+/// Opens a video stream to a PC that asked for the screen.
+pub(crate) async fn open(shared: &Arc<Shared>, session: &Session) -> Result<MirrorStream> {
+ if !shared.toggle_on(&session.peer, TOGGLE) {
+ return Err(Error::Denied);
+ }
+ let (mut send, mut recv) = session.conn.open_bi().await.map_err(crate::error::net)?;
+ let header =
+ StreamHeader { svc: mirror::SERVICE.into(), op: mirror::OP_VIDEO.into(), v: mirror::VERSION };
+ write_frame(&mut send, &Envelope::new(types::STREAM, &header)?.to_cbor()).await?;
+ // Video goes out as soon as it's written.
+ let _ = send.set_priority(1);
+ let (queue, mut packets) = mpsc::channel::<(PacketKind, u64, Vec<u8>)>(QUEUE);
+ let closed = Arc::new(AtomicBool::new(false));
+ let done = closed.clone();
+ tokio::spawn(async move {
+ let mut ended = Box::pin(async move {
+ // The PC stops reading (STOP_SENDING) when it's done watching.
+ let _ = recv.read_to_end(64).await;
+ });
+ loop {
+ let next = tokio::select! {
+ _ = &mut ended => break,
+ next = packets.recv() => next,
+ };
+ let Some((kind, time, data)) = next else { break };
+ if done.load(Ordering::Acquire) {
+ break;
+ }
+ let Ok(header) = video_packet_header(kind, time, data.len()) else { continue };
+ let written = async {
+ send.write_all(&header).await?;
+ send.write_all(&data).await
+ };
+ if written.await.is_err() {
+ break;
+ }
+ }
+ done.store(true, Ordering::Release);
+ let _ = send.finish();
+ });
+ Ok(MirrorStream { queue, closed, resyncing: Mutex::new(false) })
+}
+
+impl Shared {
+ /// A new stop signal for the PC's reader of `peer`'s stream.
+ fn new_mirror_stop(&self, peer: &DeviceId) -> Arc<tokio::sync::Notify> {
+ let signal = Arc::new(tokio::sync::Notify::new());
+ self.mirror_stops.lock().unwrap_or_else(|e| e.into_inner()).insert(*peer, signal.clone());
+ signal
+ }
+
+ /// Stops showing `peer`'s screen here (kept until the reader sees it).
+ pub(crate) fn stop_showing(&self, peer: &DeviceId) {
+ if let Some(signal) = self.mirror_stops.lock().unwrap_or_else(|e| e.into_inner()).remove(peer) {
+ signal.notify_one();
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test(flavor = "multi_thread")]
+ async fn a_full_queue_drops_frames_until_a_keyframe() {
+ let (queue, mut packets) = mpsc::channel(2);
+ let stream = MirrorStream { queue, closed: Arc::default(), resyncing: Mutex::new(false) };
+ let send = |kind| tokio::task::block_in_place(|| stream.send(kind, 0, vec![1]));
+ assert_eq!(send(PacketKind::Keyframe), MirrorSend::Queued);
+ assert_eq!(send(PacketKind::Frame), MirrorSend::Queued);
+ assert_eq!(send(PacketKind::Frame), MirrorSend::NeedKeyframe, "full");
+ packets.recv().await;
+ // Room again, but the decoder needs a fresh start first.
+ assert_eq!(send(PacketKind::Frame), MirrorSend::NeedKeyframe);
+ assert_eq!(send(PacketKind::Keyframe), MirrorSend::Queued);
+ packets.recv().await;
+ assert_eq!(send(PacketKind::Frame), MirrorSend::Queued);
+ drop(packets);
+ assert_eq!(send(PacketKind::Keyframe), MirrorSend::Closed);
+ }
+}
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 7d11aff..dabfc9d 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -119,6 +119,8 @@ pub(crate) struct Shared {
pub(crate) photos: crate::photos::Recent,
/// This phone's call in progress (docs/protocol/calls.md).
pub(crate) calls: crate::calls::Current,
+ /// Stop signals for phone screens shown here, by phone.
+ pub(crate) mirror_stops: Mutex<HashMap<DeviceId, Arc<tokio::sync::Notify>>>,
pub data_dir: std::path::PathBuf,
/// Where received files go.
pub downloads_dir: std::path::PathBuf,
@@ -610,6 +612,7 @@ impl Node {
players: Default::default(),
photos: Default::default(),
calls: Default::default(),
+ mirror_stops: Mutex::new(HashMap::new()),
data_dir: config.data_dir.clone(),
downloads_dir: config.downloads_dir.clone().unwrap_or_else(|| config.data_dir.join("received")),
transfers: Mutex::new(HashMap::new()),
@@ -921,6 +924,36 @@ impl Node {
crate::actions::open_link(&self.shared, &session, url).await
}
+ // ---- Screen mirroring (docs/protocol/mirror.md) ----
+
+ /// Asks a paired phone for its screen. The phone asks its user; video
+ /// then arrives through [`Platform::mirror_sink`](crate::Platform::mirror_sink).
+ pub async fn mirror_start(&self, peer: DeviceId, options: crate::MirrorStart) -> Result<()> {
+ let session = self.connected(&peer)?;
+ crate::mirror::start(&self.shared, &session, options).await
+ }
+
+ /// Stops showing a phone's screen, and tells the phone.
+ pub async fn mirror_stop(&self, peer: DeviceId) {
+ self.shared.stop_showing(&peer);
+ if let Ok(session) = self.connected(&peer) {
+ let _ = crate::mirror::stop(&session).await;
+ }
+ }
+
+ /// Asks a phone for a keyframe (the decoder lost its place).
+ pub async fn mirror_keyframe(&self, peer: DeviceId) {
+ if let Ok(session) = self.connected(&peer) {
+ crate::mirror::request_keyframe(&session).await;
+ }
+ }
+
+ /// Opens this phone's video stream to a PC that asked for the screen.
+ pub async fn mirror_open(&self, peer: DeviceId) -> Result<crate::MirrorStream> {
+ let session = self.connected(&peer)?;
+ crate::mirror::open(&self.shared, &session).await
+ }
+
// ---- Messages (docs/protocol/sms.md) ----
/// This phone's messages changed (in `thread`, or anywhere): connected
diff --git a/core/nectarlink-core/src/session.rs b/core/nectarlink-core/src/session.rs
index 71eeaf8..2cccf39 100644
--- a/core/nectarlink-core/src/session.rs
+++ b/core/nectarlink-core/src/session.rs
@@ -353,6 +353,7 @@ async fn handle(shared: &Arc<Shared>, session: &Arc<Session>, env: Envelope) ->
t if t.starts_with("photos.") && crate::photos::handle(shared, session, &env).await? => {}
t if t.starts_with("call.") && crate::calls::handle(shared, session, &env).await? => {}
t if t.starts_with("sms.") && crate::sms::handle(shared, session, &env).await? => {}
+ t if t.starts_with("mirror.") && crate::mirror::handle(shared, session, &env).await? => {}
other => {
if env.id.is_some() {
let reply = Envelope::error(ErrorCode::Unsupported, format!("unknown message type {other}"));
diff --git a/core/nectarlink-core/src/transfer.rs b/core/nectarlink-core/src/transfer.rs
index e327b10..718f29b 100644
--- a/core/nectarlink-core/src/transfer.rs
+++ b/core/nectarlink-core/src/transfer.rs
@@ -16,7 +16,7 @@ use nectarlink_protocol::{
DeviceId, Envelope, ErrorCode,
messages::{
ErrorBody, FileEntry, FilesAccept, FilesOffer, StreamHeader, clip, files, is_valid_file_name,
- is_valid_folder, types,
+ is_valid_folder, mirror, types,
},
read_frame, write_frame,
};
@@ -557,6 +557,9 @@ pub(crate) async fn accept_stream(
Some(h) if h.svc == clip::SERVICE && h.op == clip::OP_IMAGE && h.v == clip::VERSION => {
crate::clipboard::receive_image(shared, session.peer, send, recv).await;
}
+ Some(h) if h.svc == mirror::SERVICE && h.op == mirror::OP_VIDEO && h.v == mirror::VERSION => {
+ crate::mirror::receive(shared, session.peer, send, recv).await;
+ }
_ => {
let reply = Envelope::error(ErrorCode::Unsupported, "unknown stream");
let _ = write_frame(&mut send, &reply.to_cbor()).await;
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index 122b97f..6821c06 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -32,6 +32,9 @@ struct RecordingPlatform {
links: Mutex<Vec<String>>,
calls: Mutex<Vec<(String, nectarlink_core::CallCommand)>>,
texts: Mutex<Vec<(Vec<String>, String)>>,
+ mirror_asks: Mutex<Vec<String>>,
+ /// What a PC got of a phone's screen.
+ screen: Arc<ScreenSink>,
/// Photos `open_photo` finds, by ID.
photos: Mutex<std::collections::HashMap<String, std::path::PathBuf>>,
}
@@ -75,6 +78,23 @@ impl Platform for RecordingPlatform {
self.links.lock().unwrap().push(url.to_owned());
Ok(())
}
+ fn mirror_sink(&self, _peer: &nectarlink_core::DeviceId) -> Option<Arc<dyn nectarlink_core::MirrorSink>> {
+ Some(self.screen.clone())
+ }
+ fn mirror_requested(
+ &self,
+ _peer: &nectarlink_core::DeviceId,
+ options: &nectarlink_core::MirrorStart,
+ ) -> Result<(), String> {
+ self.mirror_asks.lock().unwrap().push(format!("start {}", options.max_size));
+ Ok(())
+ }
+ fn mirror_stop_requested(&self, _peer: &nectarlink_core::DeviceId) {
+ self.mirror_asks.lock().unwrap().push("stop".into());
+ }
+ fn mirror_keyframe_requested(&self, _peer: &nectarlink_core::DeviceId) {
+ self.mirror_asks.lock().unwrap().push("keyframe".into());
+ }
fn sms_threads(&self, limit: u32) -> Result<Vec<nectarlink_core::SmsThread>, String> {
let thread = |i: u32| nectarlink_core::SmsThread {
id: i.to_string(),
@@ -136,6 +156,27 @@ impl Platform for RecordingPlatform {
}
}
+#[derive(Debug, Default)]
+struct ScreenSink {
+ got: Mutex<Vec<String>>,
+}
+
+impl nectarlink_core::MirrorSink for ScreenSink {
+ fn config(&self, config: nectarlink_core::MirrorConfig) {
+ self.got.lock().unwrap().push(format!("config {}x{}", config.width, config.height));
+ }
+ fn packet(&self, keyframe: bool, time_us: u64, data: Vec<u8>) {
+ self.got.lock().unwrap().push(format!(
+ "{} {time_us} {}",
+ if keyframe { "key" } else { "frame" },
+ data.len()
+ ));
+ }
+ fn ended(&self) {
+ self.got.lock().unwrap().push("ended".into());
+ }
+}
+
struct TestDevice {
node: Node,
events: Receiver<NodeEvent>,
@@ -987,6 +1028,56 @@ async fn folders_arrive_with_their_layout() {
);
}
+#[tokio::test(flavor = "multi_thread")]
+async fn the_phone_screen_streams_to_the_pc() {
+ use nectarlink_core::{MirrorSend, PacketKind};
+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::MIRROR_VIEW]).await;
+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[nectarlink_core::MIRROR_CAPTURE]).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let (pc_id, phone_id) = (pc.node.device_id(), phone.node.device_id());
+
+ let options = nectarlink_core::MirrorStart { max_size: 1920, fps: 60, bitrate: 8_000_000 };
+ with_timeout("start", pc.node.mirror_start(phone_id, options)).await.unwrap();
+ assert_eq!(*phone.platform.mirror_asks.lock().unwrap(), ["start 1920"]);
+
+ // The user agreed: the phone streams.
+ let stream = Arc::new(with_timeout("open", phone.node.mirror_open(pc_id)).await.unwrap());
+ let config = nectarlink_core::MirrorConfig { codec: "h264".into(), width: 1080, height: 2400 };
+ let sender = stream.clone();
+ let sent = tokio::task::spawn_blocking(move || {
+ [
+ sender.send(PacketKind::Config, 0, config.to_cbor()),
+ sender.send(PacketKind::Keyframe, 1, vec![0; 90_000]),
+ sender.send(PacketKind::Frame, 16_667, vec![0; 4_000]),
+ ]
+ })
+ .await
+ .unwrap();
+ assert!(sent.iter().all(|s| *s == MirrorSend::Queued), "{sent:?}");
+ wait_for(&mut pc, "showing", |e| matches!(e, NodeEvent::Mirroring { on: true, .. }).then_some(())).await;
+ let screen = pc.platform.screen.clone();
+ let deadline = tokio::time::Instant::now() + WAIT;
+ while screen.got.lock().unwrap().len() < 3 && tokio::time::Instant::now() < deadline {
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ assert_eq!(*screen.got.lock().unwrap(), ["config 1080x2400", "key 1 90000", "frame 16667 4000"]);
+
+ pc.node.mirror_keyframe(phone_id).await;
+ // The PC stops watching: the phone hears it, and its stream closes.
+ pc.node.mirror_stop(phone_id).await;
+ wait_for(&mut pc, "stopped", |e| matches!(e, NodeEvent::Mirroring { on: false, .. }).then_some(())).await;
+ assert_eq!(screen.got.lock().unwrap().last().map(String::as_str), Some("ended"));
+ let deadline = tokio::time::Instant::now() + WAIT;
+ while !stream.is_closed() && tokio::time::Instant::now() < deadline {
+ let s = stream.clone();
+ tokio::task::spawn_blocking(move || s.send(PacketKind::Frame, 0, vec![0])).await.unwrap();
+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;
+ }
+ assert!(stream.is_closed(), "the phone's stream closes");
+ let asks = phone.platform.mirror_asks.lock().unwrap().clone();
+ assert!(asks.contains(&"keyframe".to_owned()) && asks.contains(&"stop".to_owned()), "{asks:?}");
+}
+
#[tokio::test(flavor = "multi_thread")]
async fn the_pc_reads_and_sends_texts_through_the_phone() {
let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::SMS_SHOW]).await;
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index 2c9e6c1..41e5a6f 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -434,6 +434,11 @@ pub enum Event {
id: String,
call_id: String,
},
+ /// A paired phone's screen started or stopped showing (PCs only).
+ Mirroring {
+ id: String,
+ on: bool,
+ },
/// A paired phone's messages changed (PCs only).
SmsChanged {
id: String,
@@ -441,6 +446,58 @@ pub enum Event {
},
}
+/// What a mirroring video packet holds (docs/protocol/mirror.md).
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum VideoPacketKind {
+ /// The stream's format, from `mirror_config`.
+ Config,
+ Frame,
+ Keyframe,
+}
+
+/// What became of a video packet.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, uniffi::Enum)]
+pub enum MirrorSendResult {
+ Queued,
+ /// The network is behind: request a keyframe from the encoder (frames
+ /// are dropped until one comes).
+ NeedKeyframe,
+ /// The PC stopped watching: stop sharing the screen.
+ Closed,
+}
+
+/// This phone's screen going to one PC.
+#[derive(Debug, uniffi::Object)]
+pub struct MirrorStream(core::MirrorStream);
+
+#[uniffi::export]
+impl MirrorStream {
+ /// Hands over a packet without waiting (a config packet waits for room).
+ pub fn send(&self, kind: VideoPacketKind, time_us: u64, data: Vec<u8>) -> MirrorSendResult {
+ let kind = match kind {
+ VideoPacketKind::Config => core::PacketKind::Config,
+ VideoPacketKind::Frame => core::PacketKind::Frame,
+ VideoPacketKind::Keyframe => core::PacketKind::Keyframe,
+ };
+ match self.0.send(kind, time_us, data) {
+ core::MirrorSend::Queued => MirrorSendResult::Queued,
+ core::MirrorSend::NeedKeyframe => MirrorSendResult::NeedKeyframe,
+ core::MirrorSend::Closed => MirrorSendResult::Closed,
+ }
+ }
+
+ /// Ends the stream.
+ pub fn close(&self) {
+ self.0.close();
+ }
+}
+
+/// The bytes of a config packet for an H.264 stream of this size.
+#[uniffi::export]
+pub fn mirror_config(width: u32, height: u32) -> Vec<u8> {
+ core::MirrorConfig { codec: "h264".into(), width, height }.to_cbor()
+}
+
/// A conversation (docs/protocol/sms.md).
#[derive(Clone, PartialEq, Eq, uniffi::Record)]
pub struct SmsThread {
@@ -934,6 +991,7 @@ impl From<NodeEvent> for Event {
Event::CallChanged { id: device.to_string(), call_id: call.id }
}
NodeEvent::SmsChanged { device, thread } => Event::SmsChanged { id: device.to_string(), thread },
+ NodeEvent::Mirroring { device, on } => Event::Mirroring { id: device.to_string(), on },
}
}
}
@@ -1043,6 +1101,13 @@ pub trait Platform: Send + Sync {
/// A PC asked to answer, decline or silence call `id` (the call in
/// progress). False if the phone couldn't.
fn call_command(&self, id: String, command: CallCommand) -> bool;
+ /// A PC asked for this phone's screen: ask the user (then call
+ /// `mirror_open`). False if the user couldn't be asked.
+ fn mirror_requested(&self, pc_id: String, max_size: u32, fps: u32, bitrate: u32) -> bool;
+ /// The PC stopped watching: stop sharing.
+ fn mirror_stop_requested(&self, pc_id: String);
+ /// The PC needs a keyframe.
+ fn mirror_keyframe_requested(&self, pc_id: String);
/// A PC asked for the latest conversations, newest first.
fn sms_threads(&self, limit: u32) -> Vec<SmsThread>;
/// A PC asked for a conversation's messages before `before` (Unix ms;
@@ -1115,6 +1180,19 @@ impl core::Platform for PlatformAdapter {
Err("the clipboard rejected it".into())
}
}
+ fn mirror_requested(&self, peer: &DeviceId, options: &core::MirrorStart) -> Result<(), String> {
+ if self.0.mirror_requested(peer.to_string(), options.max_size, options.fps, options.bitrate) {
+ Ok(())
+ } else {
+ Err("the user couldn't be asked".into())
+ }
+ }
+ fn mirror_stop_requested(&self, peer: &DeviceId) {
+ self.0.mirror_stop_requested(peer.to_string());
+ }
+ fn mirror_keyframe_requested(&self, peer: &DeviceId) {
+ self.0.mirror_keyframe_requested(peer.to_string());
+ }
fn sms_threads(&self, limit: u32) -> Result<Vec<core::SmsThread>, String> {
Ok(self
.0
@@ -1471,6 +1549,14 @@ impl NectarlinkNode {
self.run(async move { Ok(node.open_link(id, url).await?) }).await
}
+ /// Opens this phone's screen stream to a PC that asked (after the user
+ /// agreed).
+ pub async fn mirror_open(&self, pc_id: String) -> Result<Arc<MirrorStream>> {
+ let id = parse_id(&pc_id)?;
+ let node = self.node.clone();
+ self.run(async move { Ok(Arc::new(MirrorStream(node.mirror_open(id).await?))) }).await
+ }
+
/// This phone's messages changed (in `thread`, or anywhere when null):
/// PCs that show them catch up.
pub async fn sms_changed(&self, thread: Option<String>) {
diff --git a/core/nectarlink-protocol/src/lib.rs b/core/nectarlink-protocol/src/lib.rs
index f6531df..d0adfe6 100644
--- a/core/nectarlink-protocol/src/lib.rs
+++ b/core/nectarlink-protocol/src/lib.rs
@@ -11,11 +11,13 @@ mod frame;
mod id;
pub mod messages;
pub mod pairing;
+mod video;
pub use envelope::Envelope;
pub use error::{ErrorCode, ProtocolError};
pub use frame::{MAX_FRAME_LEN, decode_frame, encode_frame, read_frame, write_frame};
pub use id::{DeviceId, ParseDeviceIdError};
+pub use video::{MAX_VIDEO_PACKET, PacketKind, VideoPacket, read_video_packet, video_packet_header};
/// ALPN for normal sessions between paired devices.
pub const ALPN_SESSION: &[u8] = b"nectarlink/0";
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index de252e4..37c500e 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -50,6 +50,9 @@ pub mod types {
pub const SMS_SEND: &str = "sms.send";
pub const SMS_PART: &str = "sms.part";
pub const SMS_CHANGED: &str = "sms.changed";
+ pub const MIRROR_START: &str = "mirror.start";
+ pub const MIRROR_STOP: &str = "mirror.stop";
+ pub const MIRROR_KEYFRAME: &str = "mirror.keyframe";
}
/// What kind of device this is.
@@ -463,6 +466,58 @@ pub struct PcPower {
/// The longest link sent, in bytes.
pub const LINK_MAX_BYTES: usize = 4096;
+// ---- Screen mirroring (docs/protocol/mirror.md) ----
+
+pub mod mirror {
+ /// Offered by phones that share their screen (with the user's consent).
+ pub const CAPTURE: &str = "mirror.capture";
+ /// Offered by PCs that show a phone's screen.
+ pub const VIEW: &str = "mirror.view";
+ pub const SERVICE: &str = "mirror";
+ pub const OP_VIDEO: &str = "video";
+ pub const VERSION: u32 = 1;
+ /// Stream reset code: mirroring stopped.
+ pub const STOPPED: u32 = 11;
+ pub const H264: &str = "h264";
+}
+
+/// Body of `mirror.start`: show me your screen.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct MirrorStart {
+ /// The longer side, in pixels, at most (the phone scales down).
+ pub max_size: u32,
+ /// Frames per second, at most.
+ pub fps: u32,
+ /// Bits per second to aim for.
+ pub bitrate: u32,
+}
+
+/// The format of a mirroring stream (a config packet's data, in CBOR).
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+pub struct MirrorConfig {
+ /// `h264`.
+ pub codec: String,
+ pub width: u32,
+ pub height: u32,
+}
+
+impl MirrorConfig {
+ pub fn to_cbor(&self) -> Vec<u8> {
+ let mut out = Vec::new();
+ ciborium::into_writer(self, &mut out).expect("writing to a Vec cannot fail");
+ out
+ }
+
+ pub fn from_cbor(bytes: &[u8]) -> Result<MirrorConfig, crate::ProtocolError> {
+ ciborium::from_reader(bytes).map_err(|e| crate::ProtocolError::BadMessage(e.to_string()))
+ }
+
+ /// A format this version can show: H.264, 1–8192 pixels a side.
+ pub fn is_valid(&self) -> bool {
+ self.codec == mirror::H264 && (1..=8192).contains(&self.width) && (1..=8192).contains(&self.height)
+ }
+}
+
// ---- Messages (docs/protocol/sms.md) ----
pub mod sms {
diff --git a/core/nectarlink-protocol/src/video.rs b/core/nectarlink-protocol/src/video.rs
new file mode 100644
index 0000000..e24fcdf
--- /dev/null
+++ b/core/nectarlink-protocol/src/video.rs
@@ -0,0 +1,133 @@
+// SPDX-License-Identifier: MPL-2.0
+//! Video packets on a mirroring stream (docs/protocol/mirror.md §3):
+//! `u32 length (big-endian) || u8 kind || u64 time (µs, big-endian) || data`,
+//! where `length` counts kind, time and data.
+
+use tokio::io::{AsyncRead, AsyncReadExt};
+
+use crate::ProtocolError;
+
+/// The largest packet accepted (a keyframe at a high bitrate fits easily).
+pub const MAX_VIDEO_PACKET: usize = 8 << 20;
+const HEADER: usize = 1 + 8;
+
+/// What a video packet holds.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+#[repr(u8)]
+pub enum PacketKind {
+ /// The stream's format (a CBOR `MirrorConfig`); comes first, and again
+ /// whenever it changes (the phone turned).
+ Config = 0,
+ /// Encoded video that depends on earlier packets.
+ Frame = 1,
+ /// Encoded video that starts fresh (with its parameter sets).
+ Keyframe = 2,
+}
+
+impl PacketKind {
+ fn from_u8(kind: u8) -> Option<PacketKind> {
+ match kind {
+ 0 => Some(PacketKind::Config),
+ 1 => Some(PacketKind::Frame),
+ 2 => Some(PacketKind::Keyframe),
+ _ => None,
+ }
+ }
+}
+
+/// A packet read from a stream.
+#[derive(Clone, PartialEq, Eq)]
+pub struct VideoPacket {
+ pub kind: PacketKind,
+ /// Capture time on the sender, in microseconds (only differences mean
+ /// anything).
+ pub time_us: u64,
+ pub data: Vec<u8>,
+}
+
+impl std::fmt::Debug for VideoPacket {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("VideoPacket")
+ .field("kind", &self.kind)
+ .field("time_us", &self.time_us)
+ .field("bytes", &self.data.len())
+ .finish()
+ }
+}
+
+/// Encodes a packet's header; the data follows it on the stream.
+pub fn video_packet_header(
+ kind: PacketKind,
+ time_us: u64,
+ data_len: usize,
+) -> Result<[u8; 4 + HEADER], ProtocolError> {
+ let len = HEADER + data_len;
+ if len > MAX_VIDEO_PACKET {
+ return Err(ProtocolError::FrameTooLarge(len));
+ }
+ let mut header = [0u8; 4 + HEADER];
+ header[..4].copy_from_slice(&(len as u32).to_be_bytes());
+ header[4] = kind as u8;
+ header[5..].copy_from_slice(&time_us.to_be_bytes());
+ Ok(header)
+}
+
+/// Reads one packet; `None` at the end of the stream.
+pub async fn read_video_packet<R: AsyncRead + Unpin>(
+ reader: &mut R,
+) -> Result<Option<VideoPacket>, ProtocolError> {
+ let mut len = [0u8; 4];
+ match reader.read_exact(&mut len).await {
+ Ok(_) => {}
+ Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return Ok(None),
+ Err(e) => return Err(e.into()),
+ }
+ let len = u32::from_be_bytes(len) as usize;
+ if !(HEADER..=MAX_VIDEO_PACKET).contains(&len) {
+ return Err(ProtocolError::FrameTooLarge(len));
+ }
+ let mut header = [0u8; HEADER];
+ reader.read_exact(&mut header).await?;
+ let kind = PacketKind::from_u8(header[0]).ok_or(ProtocolError::BadLength)?;
+ let time_us = u64::from_be_bytes(header[1..].try_into().expect("8 bytes"));
+ let mut data = vec![0u8; len - HEADER];
+ reader.read_exact(&mut data).await?;
+ Ok(Some(VideoPacket { kind, time_us, data }))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[tokio::test]
+ async fn packets_round_trip() {
+ let mut stream = Vec::new();
+ for (kind, time, data) in
+ [(PacketKind::Config, 0, b"cfg".to_vec()), (PacketKind::Keyframe, 16_667, vec![7; 70_000])]
+ {
+ stream.extend_from_slice(&video_packet_header(kind, time, data.len()).unwrap());
+ stream.extend_from_slice(&data);
+ }
+ let mut reader = stream.as_slice();
+ let first = read_video_packet(&mut reader).await.unwrap().unwrap();
+ assert_eq!(
+ (first.kind, first.time_us, first.data.as_slice()),
+ (PacketKind::Config, 0, b"cfg".as_slice())
+ );
+ let second = read_video_packet(&mut reader).await.unwrap().unwrap();
+ assert_eq!((second.kind, second.time_us, second.data.len()), (PacketKind::Keyframe, 16_667, 70_000));
+ assert!(read_video_packet(&mut reader).await.unwrap().is_none());
+ }
+
+ #[tokio::test]
+ async fn bad_packets_are_rejected() {
+ assert!(video_packet_header(PacketKind::Frame, 0, MAX_VIDEO_PACKET).is_err());
+ // An unknown kind.
+ let mut bytes = video_packet_header(PacketKind::Frame, 0, 1).unwrap().to_vec();
+ bytes[4] = 9;
+ bytes.push(0);
+ assert!(read_video_packet(&mut bytes.as_slice()).await.is_err());
+ // A length too short for the header.
+ assert!(read_video_packet(&mut [0u8, 0, 0, 3, 1, 2, 3].as_slice()).await.is_err());
+ }
+}
diff --git a/desktop/app/Cargo.toml b/desktop/app/Cargo.toml
index b64d856..b451596 100644
--- a/desktop/app/Cargo.toml
+++ b/desktop/app/Cargo.toml
@@ -66,6 +66,7 @@ windows = { workspace = true, features = [
"Win32_System_Variant",
"Win32_Networking_WinSock",
"Win32_Media_Audio",
+ "Win32_Media_MediaFoundation",
] }
[build-dependencies]
diff --git a/desktop/app/build.rs b/desktop/app/build.rs
index b865b7b..7b0995e 100644
--- a/desktop/app/build.rs
+++ b/desktop/app/build.rs
@@ -18,6 +18,7 @@ mod mark;
const QML: &[&str] = &[
"qml/App.qml",
"qml/MainWindow.qml",
+ "qml/MirrorWindow.qml",
"qml/components/Avatar.qml",
"qml/components/Button.qml",
"qml/components/CaptionButtons.qml",
@@ -185,7 +186,13 @@ fn main() {
CxxQtBuilder::new_qml_module(module)
.qt_module("Quick")
.include_dir("cpp")
- .cpp_files(["cpp/app_helpers.cpp", "cpp/native_window.h", "cpp/native_window.cpp"])
+ .cpp_files([
+ "cpp/app_helpers.cpp",
+ "cpp/native_window.h",
+ "cpp/native_window.cpp",
+ "cpp/video_view.h",
+ "cpp/video_view.cpp",
+ ])
.qrc(fonts_qrc())
.files([
"src/bridge/native.rs",
@@ -194,6 +201,7 @@ fn main() {
"src/bridge/history.rs",
"src/bridge/media.rs",
"src/bridge/messages.rs",
+ "src/bridge/mirror.rs",
"src/bridge/notifications.rs",
"src/bridge/pairing.rs",
"src/bridge/prefs.rs",
diff --git a/desktop/app/cpp/video_view.cpp b/desktop/app/cpp/video_view.cpp
new file mode 100644
index 0000000..b2df454
--- /dev/null
+++ b/desktop/app/cpp/video_view.cpp
@@ -0,0 +1,150 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "video_view.h"
+
+#include <QtCore/QHash>
+#include <QtGui/QImage>
+#include <QtQuick/QQuickWindow>
+#include <QtQuick/QSGSimpleTextureNode>
+#include <QtQuick/QSGTexture>
+
+#include <algorithm>
+#include <mutex>
+#include <vector>
+
+namespace {
+
+struct Latest
+{
+ QImage image;
+ quint64 serial = 0;
+};
+
+// Pictures by stream, and the views to tell. Views register and leave
+// under the lock, so a picture never wakes a view that's being destroyed.
+std::mutex lock;
+QHash<QString, Latest> latest;
+std::vector<VideoView *> views;
+quint64 nextSerial = 1;
+
+void wakeViews(const QString &stream)
+{
+ for (VideoView *view : views) {
+ if (view->stream() == stream)
+ QMetaObject::invokeMethod(view, "frameArrived", Qt::QueuedConnection);
+ }
+}
+
+// Owns its texture (replaced with each picture).
+class VideoNode : public QSGSimpleTextureNode
+{
+public:
+ VideoNode() { setOwnsTexture(false); }
+ ~VideoNode() override { delete texture(); }
+
+ void replaceTexture(QSGTexture *next)
+ {
+ QSGTexture *previous = texture();
+ setTexture(next);
+ delete previous;
+ }
+};
+
+} // namespace
+
+VideoView::VideoView(QQuickItem *parent)
+ : QQuickItem(parent)
+{
+ setFlag(ItemHasContents, true);
+ std::lock_guard guard(lock);
+ views.push_back(this);
+}
+
+VideoView::~VideoView()
+{
+ std::lock_guard guard(lock);
+ views.erase(std::remove(views.begin(), views.end(), this), views.end());
+}
+
+void VideoView::setStream(const QString &stream)
+{
+ if (stream == m_stream)
+ return;
+ {
+ std::lock_guard guard(lock);
+ m_stream = stream;
+ }
+ m_shown = 0;
+ emit streamChanged();
+ frameArrived();
+}
+
+QRectF VideoView::pictureRect() const
+{
+ if (m_frameSize.isEmpty())
+ return {};
+ const QSizeF fitted = QSizeF(m_frameSize).scaled(size(), Qt::KeepAspectRatio);
+ return QRectF((width() - fitted.width()) / 2, (height() - fitted.height()) / 2, fitted.width(), fitted.height());
+}
+
+void VideoView::frameArrived()
+{
+ QSize size;
+ {
+ std::lock_guard guard(lock);
+ size = latest.value(m_stream).image.size();
+ }
+ if (size != m_frameSize) {
+ m_frameSize = size;
+ emit frameSizeChanged();
+ }
+ ++m_frames;
+ emit framesChanged();
+ update();
+}
+
+QSGNode *VideoView::updatePaintNode(QSGNode *old, UpdatePaintNodeData *)
+{
+ Latest picture;
+ {
+ std::lock_guard guard(lock);
+ picture = latest.value(m_stream);
+ }
+ if (picture.image.isNull() || !window()) {
+ delete old;
+ m_shown = 0;
+ return nullptr;
+ }
+ auto *node = static_cast<VideoNode *>(old);
+ if (!node)
+ node = new VideoNode;
+ if (picture.serial != m_shown || !node->texture()) {
+ QSGTexture *texture = window()->createTextureFromImage(picture.image);
+ texture->setFiltering(QSGTexture::Linear);
+ node->replaceTexture(texture);
+ m_shown = picture.serial;
+ }
+ node->setFiltering(QSGTexture::Linear);
+ node->setRect(pictureRect());
+ return node;
+}
+
+void video_frame(rust::Str stream, uint32_t width, uint32_t height, rust::Slice<const uint8_t> bgrx)
+{
+ if (bgrx.size() < size_t(width) * height * 4)
+ return;
+ // One copy, into an image Qt owns.
+ QImage image(reinterpret_cast<const uchar *>(bgrx.data()), int(width), int(height), int(width) * 4,
+ QImage::Format_RGB32);
+ const QString key = QString::fromUtf8(stream.data(), qsizetype(stream.size()));
+ std::lock_guard guard(lock);
+ latest.insert(key, Latest{image.copy(), nextSerial++});
+ wakeViews(key);
+}
+
+void video_clear(rust::Str stream)
+{
+ const QString key = QString::fromUtf8(stream.data(), qsizetype(stream.size()));
+ std::lock_guard guard(lock);
+ latest.remove(key);
+ wakeViews(key);
+}
diff --git a/desktop/app/cpp/video_view.h b/desktop/app/cpp/video_view.h
new file mode 100644
index 0000000..666dbe4
--- /dev/null
+++ b/desktop/app/cpp/video_view.h
@@ -0,0 +1,63 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <QtCore/QSize>
+#include <QtCore/QString>
+#include <QtQml/qqmlregistration.h>
+#include <QtQuick/QQuickItem>
+
+#include <rust/cxx.h>
+
+#include <cstdint>
+
+// Shows the latest picture of a video stream (a phone's screen), scaled to
+// fit with its aspect ratio kept. Pictures come from Rust, on any thread,
+// through `video_frame`; only the newest is drawn.
+class VideoView : public QQuickItem
+{
+ Q_OBJECT
+ QML_ELEMENT
+
+ // Which stream to show (the phone's device ID).
+ Q_PROPERTY(QString stream READ stream WRITE setStream NOTIFY streamChanged)
+ // The pictures' size, in pixels (empty before the first one).
+ Q_PROPERTY(QSize frameSize READ frameSize NOTIFY frameSizeChanged)
+ // Pictures shown so far, for a frame rate readout.
+ Q_PROPERTY(quint64 frames READ frames NOTIFY framesChanged)
+
+public:
+ explicit VideoView(QQuickItem *parent = nullptr);
+ ~VideoView() override;
+
+ QString stream() const { return m_stream; }
+ void setStream(const QString &stream);
+ QSize frameSize() const { return m_frameSize; }
+ quint64 frames() const { return m_frames; }
+
+ // Where the picture is drawn in the item (letterboxed).
+ Q_INVOKABLE QRectF pictureRect() const;
+
+signals:
+ void streamChanged();
+ void frameSizeChanged();
+ void framesChanged();
+
+protected:
+ QSGNode *updatePaintNode(QSGNode *old, UpdatePaintNodeData *) override;
+
+private:
+ Q_INVOKABLE void frameArrived();
+
+ QString m_stream;
+ QSize m_frameSize;
+ quint64 m_frames = 0;
+ // The serial of the picture on screen.
+ quint64 m_shown = 0;
+};
+
+// The latest picture of `stream`: `width` x `height`, 32-bit BGRX rows.
+// Any thread.
+void video_frame(rust::Str stream, uint32_t width, uint32_t height, rust::Slice<const uint8_t> bgrx);
+
+// The stream ended: views of it go blank. Any thread.
+void video_clear(rust::Str stream);
diff --git a/desktop/app/qml/App.qml b/desktop/app/qml/App.qml
index 03475f6..5bad199 100644
--- a/desktop/app/qml/App.qml
+++ b/desktop/app/qml/App.qml
@@ -9,6 +9,8 @@ QtObject {
id: app
property MainWindow mainWindow: null
+ // A phone's screen; shows itself while mirroring.
+ readonly property MirrorWindow mirrorWindow: MirrorWindow {}
readonly property Component mainComponent: Component { MainWindow {} }
readonly property bool startMinimized: Qt.application.arguments.indexOf("--minimized") >= 0
|| Qt.application.arguments.indexOf("--send-to") >= 0
diff --git a/desktop/app/qml/MirrorWindow.qml b/desktop/app/qml/MirrorWindow.qml
new file mode 100644
index 0000000..c0924e2
--- /dev/null
+++ b/desktop/app/qml/MirrorWindow.qml
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+import QtQuick
+import QtQuick.Window
+import app.nectarlink
+
+// A phone's screen in a window of its own, sized like the phone.
+Window {
+ id: win
+ readonly property string deviceName: Mirror.name
+
+ visible: Mirror.phase.length > 0
+ title: deviceName.length > 0 ? qsTr("%1 · Nectarlink").arg(deviceName) : qsTr("Phone screen · Nectarlink")
+ color: "black"
+ minimumWidth: 240
+ minimumHeight: 240
+
+ // A phone-shaped window the first time a picture arrives (portrait or
+ // landscape), within the screen.
+ readonly property size frame: video.frameSize
+ property bool sized: false
+ onFrameChanged: {
+ if (frame.width <= 0)
+ return
+ const maxH = Screen.desktopAvailableHeight * 0.85
+ const maxW = Screen.desktopAvailableWidth * 0.85
+ const scale = Math.min(maxH / frame.height, maxW / frame.width, 1)
+ if (!sized || Math.abs(width / height - frame.width / frame.height) > 0.05) {
+ width = Math.round(frame.width * scale)
+ height = Math.round(frame.height * scale)
+ sized = true
+ }
+ }
+ onVisibleChanged: {
+ if (visible) {
+ sized = false
+ width = 420
+ height = 860
+ }
+ }
+ onClosing: Mirror.stop()
+
+ VideoView {
+ id: video
+ anchors.fill: parent
+ stream: Mirror.device
+ }
+
+ // Before the picture: waiting for the phone, or why it ended.
+ Rectangle {
+ anchors.fill: parent
+ visible: Mirror.phase !== "showing" || video.frameSize.width <= 0
+ color: Theme.surface
+ Column {
+ anchors.centerIn: parent
+ width: Math.min(parent.width - 48, 320)
+ spacing: 14
+ Spinner {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: Mirror.phase !== "ended"
+ width: 28; height: 28
+ }
+ Icon {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: Mirror.phase === "ended"
+ width: 32; height: 32
+ path: Icons.mirror
+ color: Theme.surfaceContentVariant
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ role: "title"
+ text: Mirror.phase === "asking" ? qsTr("Allow it on your phone")
+ : Mirror.phase === "ended" ? qsTr("Mirroring stopped")
+ : qsTr("Starting…")
+ }
+ Txt {
+ width: parent.width
+ horizontalAlignment: Text.AlignHCenter
+ wrapMode: Text.WordWrap
+ role: "body"
+ muted: true
+ text: Mirror.phase === "asking"
+ ? qsTr("Tap the notification on %1, then choose to share the entire screen.").arg(win.deviceName)
+ : Mirror.phase === "ended" ? (Mirror.reason.length > 0 ? Mirror.reason : qsTr("The phone stopped sharing its screen."))
+ : ""
+ }
+ Button {
+ anchors.horizontalCenter: parent.horizontalCenter
+ visible: Mirror.phase === "ended"
+ variant: "tonal"
+ text: qsTr("Try again")
+ onClicked: Mirror.start(Mirror.device)
+ }
+ }
+ }
+}
diff --git a/desktop/app/qml/pages/HomePage.qml b/desktop/app/qml/pages/HomePage.qml
index 6c0979e..97e01b5 100644
--- a/desktop/app/qml/pages/HomePage.qml
+++ b/desktop/app/qml/pages/HomePage.qml
@@ -274,10 +274,11 @@ Item {
ActionTile {
width: actions.tileWidth
title: qsTr("Mirror screen")
- subtitle: qsTr("View and control")
+ subtitle: qsTr("See it on this PC")
iconPath: Icons.mirror
feature: home.feature("mirroring.view")
- ready: false
+ active: Mirror.device === home.deviceId && Mirror.phase !== "" && Mirror.phase !== "ended"
+ onClicked: Mirror.start(home.deviceId)
}
ActionTile {
width: actions.tileWidth
diff --git a/desktop/app/src/bridge/mirror.rs b/desktop/app/src/bridge/mirror.rs
new file mode 100644
index 0000000..9785614
--- /dev/null
+++ b/desktop/app/src/bridge/mirror.rs
@@ -0,0 +1,102 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! `Mirror`: the phone whose screen the mirror window shows, and how far
+//! along it is.
+
+use std::pin::Pin;
+
+use cxx_qt::{CxxQtType, Threading};
+use cxx_qt_lib::QString;
+use nectarlink_core::DeviceId;
+
+use crate::{
+ mirror::{self, Phase},
+ state::Changes,
+};
+
+#[cxx_qt::bridge]
+pub mod qobject {
+ unsafe extern "C++" {
+ include!("cxx-qt-lib/qstring.h");
+ type QString = cxx_qt_lib::QString;
+ }
+
+ unsafe extern "RustQt" {
+ #[qobject]
+ #[qml_element]
+ #[qml_singleton]
+ /// The phone shown ("" when the window is closed).
+ #[qproperty(QString, device)]
+ #[qproperty(QString, name)]
+ /// "asking", "showing" or "ended" ("" when closed).
+ #[qproperty(QString, phase)]
+ /// Why it ended, when there's something to say.
+ #[qproperty(QString, reason)]
+ type Mirror = super::MirrorRust;
+ }
+
+ impl cxx_qt::Threading for Mirror {}
+ impl cxx_qt::Initialize for Mirror {}
+
+ unsafe extern "RustQt" {
+ /// Asks a phone for its screen and opens the window.
+ #[qinvokable]
+ fn start(self: Pin<&mut Mirror>, device: &QString);
+ /// Closes the window and stops mirroring.
+ #[qinvokable]
+ fn stop(self: Pin<&mut Mirror>);
+ }
+}
+
+#[derive(Default)]
+pub struct MirrorRust {
+ device: QString,
+ name: QString,
+ phase: QString,
+ reason: QString,
+ shown: Option<DeviceId>,
+}
+
+impl cxx_qt::Initialize for qobject::Mirror {
+ fn initialize(self: Pin<&mut Self>) {
+ super::subscribe(self.qt_thread(), Changes::MIRROR, Self::refresh);
+ }
+}
+
+impl qobject::Mirror {
+ fn refresh(mut self: Pin<&mut Self>) {
+ let Some(device) = self.rust().shown else {
+ self.as_mut().set_phase(QString::default());
+ return;
+ };
+ let (phase, reason) = match mirror::phase(&device) {
+ None => ("", String::new()),
+ Some(Phase::Asking) => ("asking", String::new()),
+ Some(Phase::Showing) => ("showing", String::new()),
+ Some(Phase::Ended(reason)) => ("ended", reason.unwrap_or_default()),
+ };
+ self.as_mut().set_reason(QString::from(&reason));
+ self.as_mut().set_phase(QString::from(phase));
+ }
+
+ pub fn start(mut self: Pin<&mut Self>, device: &QString) {
+ let Some(id) = super::parse_device(device) else { return };
+ if let Some(previous) = self.rust().shown.filter(|p| *p != id) {
+ mirror::stop(previous);
+ }
+ self.as_mut().rust_mut().shown = Some(id);
+ self.as_mut().set_device(device.clone());
+ let name = crate::core_host::host().hub.read(|s| s.name_of(&id)).unwrap_or_default();
+ self.as_mut().set_name(QString::from(&name));
+ mirror::start(id);
+ self.refresh();
+ }
+
+ pub fn stop(mut self: Pin<&mut Self>) {
+ if let Some(id) = self.as_mut().rust_mut().shown.take() {
+ mirror::stop(id);
+ }
+ self.as_mut().set_device(QString::default());
+ self.as_mut().set_reason(QString::default());
+ self.set_phase(QString::default());
+ }
+}
diff --git a/desktop/app/src/bridge/mod.rs b/desktop/app/src/bridge/mod.rs
index bee0847..69a1dea 100644
--- a/desktop/app/src/bridge/mod.rs
+++ b/desktop/app/src/bridge/mod.rs
@@ -16,6 +16,8 @@ pub mod media;
#[allow(unsafe_code)]
pub mod messages;
#[allow(unsafe_code)]
+pub mod mirror;
+#[allow(unsafe_code)]
pub mod native;
#[allow(unsafe_code)]
pub mod notifications;
diff --git a/desktop/app/src/bridge/native.rs b/desktop/app/src/bridge/native.rs
index 601304d..8c33630 100644
--- a/desktop/app/src/bridge/native.rs
+++ b/desktop/app/src/bridge/native.rs
@@ -5,6 +5,13 @@
pub mod ffi {
unsafe extern "C++" {
include!("app_helpers.h");
+ include!("video_view.h");
+
+ /// The latest picture of a video stream (32-bit BGRX rows), for
+ /// `VideoView`s showing it. Any thread.
+ fn video_frame(stream: &str, width: u32, height: u32, bgrx: &[u8]);
+ /// The stream ended: its views go blank. Any thread.
+ fn video_clear(stream: &str);
/// Must run before `QGuiApplication` is created.
fn prepare_qt();
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 01291a8..65d71c7 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -101,6 +101,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
nectarlink_core::PHOTOS_SHOW.into(),
nectarlink_core::CALLS_SHOW.into(),
nectarlink_core::SMS_SHOW.into(),
+ nectarlink_core::MIRROR_VIEW.into(),
];
let node = match Node::start(config, platform).await {
Ok(node) => node,
@@ -150,6 +151,7 @@ async fn run(data_dir: PathBuf, platform: Arc<dyn Platform>) {
crate::photos::on_event(&event);
crate::calls::on_event(&event);
crate::messages::on_event(&event);
+ crate::mirror::on_event(&event);
crate::transfers::on_event(&event);
crate::send_to::on_event(&event);
crate::battery::on_event(&event);
diff --git a/desktop/app/src/main.rs b/desktop/app/src/main.rs
index b0292e6..2750868 100644
--- a/desktop/app/src/main.rs
+++ b/desktop/app/src/main.rs
@@ -21,6 +21,7 @@ mod logging;
mod mark;
mod media;
mod messages;
+mod mirror;
mod notification_store;
mod notifications;
mod palette;
@@ -86,6 +87,12 @@ impl Platform for DesktopPlatform {
) -> Result<(), MediaError> {
win::media_sessions::command(player, action, position)
}
+ fn mirror_sink(
+ &self,
+ peer: &nectarlink_core::DeviceId,
+ ) -> Option<std::sync::Arc<dyn nectarlink_core::MirrorSink>> {
+ mirror::sink(peer)
+ }
}
/// Command-line options (also used by shortcuts and autostart).
diff --git a/desktop/app/src/mirror.rs b/desktop/app/src/mirror.rs
new file mode 100644
index 0000000..56f2987
--- /dev/null
+++ b/desktop/app/src/mirror.rs
@@ -0,0 +1,270 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! A phone's screen on this PC (docs/protocol/mirror.md): asks the phone,
+//! decodes its video on a thread of its own and hands each picture to the
+//! mirror window's `VideoView`. Only the newest picture is shown; when the
+//! decoder falls behind or loses its place, the phone is asked for a
+//! keyframe.
+
+use std::{
+ collections::HashMap,
+ sync::{
+ Arc, Mutex,
+ atomic::{AtomicUsize, Ordering},
+ mpsc::{Receiver, SyncSender, TrySendError, sync_channel},
+ },
+ time::{Duration, Instant},
+};
+
+use nectarlink_core::{DeviceId, Error, MirrorConfig, MirrorSink, MirrorStart, NodeEvent};
+
+use crate::{
+ bridge::{app::describe, native::ffi},
+ core_host,
+ state::Changes,
+ win::h264::{Decoder, to_bgrx},
+};
+
+/// What the PC asks for: the phone scales its screen to fit.
+const OPTIONS: MirrorStart = MirrorStart { max_size: 1920, fps: 60, bitrate: 8_000_000 };
+/// Packets waiting for the decoder, at most (about two seconds).
+const BACKLOG: usize = 120;
+/// How often decode times are logged.
+const STATS_EVERY: Duration = Duration::from_secs(10);
+
+/// Where mirroring of a phone stands.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum Phase {
+ /// Waiting for the phone's user to agree.
+ Asking,
+ Showing,
+ /// It ended; the reason for the window, if any.
+ Ended(Option<String>),
+}
+
+#[derive(Debug, Default)]
+struct State {
+ phases: HashMap<DeviceId, Phase>,
+}
+
+static STATE: Mutex<Option<State>> = Mutex::new(None);
+
+fn state<T>(f: impl FnOnce(&mut State) -> T) -> T {
+ f(STATE.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert_default())
+}
+
+fn set_phase(device: DeviceId, phase: Phase) {
+ state(|s| s.phases.insert(device, phase));
+ core_host::host().hub.changed(Changes::MIRROR);
+}
+
+/// Where mirroring of `device` stands (`None`: not asked).
+pub fn phase(device: &DeviceId) -> Option<Phase> {
+ state(|s| s.phases.get(device).cloned())
+}
+
+/// Asks the phone for its screen.
+pub fn start(device: DeviceId) {
+ set_phase(device, Phase::Asking);
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move {
+ if let Err(e) = node.mirror_start(device, OPTIONS).await {
+ let reason = match e {
+ Error::Denied => "Mirroring is turned off for this phone.".to_owned(),
+ Error::Unsupported => {
+ "This phone's app doesn't share its screen yet. Update Nectarlink on the phone.".into()
+ }
+ Error::Offline | Error::NotPaired => "The phone isn't connected.".into(),
+ e => describe(&e),
+ };
+ set_phase(device, Phase::Ended(Some(reason)));
+ }
+ });
+}
+
+/// Stops showing the phone's screen (closing the window).
+pub fn stop(device: DeviceId) {
+ state(|s| s.phases.remove(&device));
+ ffi::video_clear(&device.to_string());
+ core_host::host().hub.changed(Changes::MIRROR);
+ let Some(node) = core_host::node() else { return };
+ core_host::spawn(async move { node.mirror_stop(device).await });
+}
+
+pub fn on_event(event: &NodeEvent) {
+ match event {
+ NodeEvent::Mirroring { device, on: true } => set_phase(*device, Phase::Showing),
+ // Closed here: nothing to say. Stopped on the phone: say so.
+ NodeEvent::Mirroring { device, on: false } if phase(device).is_some() => {
+ set_phase(*device, Phase::Ended(None));
+ }
+ _ => {}
+ }
+}
+
+/// Where the core puts a phone's video: only for phones this PC asked.
+pub fn sink(device: &DeviceId) -> Option<Arc<dyn MirrorSink>> {
+ matches!(phase(device), Some(Phase::Asking | Phase::Showing))
+ .then(|| Arc::new(Sink::start(*device)) as Arc<dyn MirrorSink>)
+}
+
+enum Item {
+ Config(MirrorConfig),
+ Packet { keyframe: bool, time_us: u64, data: Vec<u8> },
+ Ended,
+}
+
+/// Hands the core's packets to the decoder thread.
+struct Sink {
+ device: DeviceId,
+ queue: SyncSender<Item>,
+ /// Packets waiting for the decoder.
+ waiting: Arc<AtomicUsize>,
+}
+
+impl Sink {
+ fn start(device: DeviceId) -> Sink {
+ let (queue, items) = sync_channel(BACKLOG);
+ let waiting = Arc::new(AtomicUsize::new(0));
+ let counter = waiting.clone();
+ let started = std::thread::Builder::new()
+ .name("mirror-decoder".into())
+ .spawn(move || decode(device, &items, &counter));
+ if let Err(e) = started {
+ tracing::error!(error = %e, "can't start the video decoder");
+ }
+ Sink { device, queue, waiting }
+ }
+
+ fn keyframe_please(&self) {
+ let device = self.device;
+ if let Some(node) = core_host::node() {
+ core_host::spawn(async move { node.mirror_keyframe(device).await });
+ }
+ }
+}
+
+impl MirrorSink for Sink {
+ fn config(&self, config: MirrorConfig) {
+ // The format matters: wait for room rather than drop it.
+ let _ = self.queue.send(Item::Config(config));
+ }
+
+ fn packet(&self, keyframe: bool, time_us: u64, data: Vec<u8>) {
+ match self.queue.try_send(Item::Packet { keyframe, time_us, data }) {
+ Ok(()) => {
+ self.waiting.fetch_add(1, Ordering::AcqRel);
+ }
+ Err(TrySendError::Disconnected(_)) => {}
+ // The decoder is behind; it starts over at the next keyframe.
+ Err(TrySendError::Full(_)) => self.keyframe_please(),
+ }
+ }
+
+ fn ended(&self) {
+ let _ = self.queue.send(Item::Ended);
+ }
+}
+
+/// The decoder thread: decodes everything (later pictures depend on
+/// earlier ones), shows the newest picture of each batch.
+fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {
+ let stream = device.to_string();
+ let mut decoder = match Decoder::new() {
+ Ok(decoder) => decoder,
+ Err(e) => {
+ tracing::error!(error = %e, "no H.264 decoder");
+ set_phase(device, Phase::Ended(Some("This PC can't decode the phone's video.".into())));
+ return;
+ }
+ };
+ let keyframe_please = || {
+ if let Some(node) = core_host::node() {
+ core_host::spawn(async move { node.mirror_keyframe(device).await });
+ }
+ };
+ let mut size = (0, 0);
+ // After a gap, pictures are garbage until the next keyframe.
+ let mut need_keyframe = true;
+ let mut stats = Stats::new();
+ while let Ok(item) = items.recv() {
+ match item {
+ Item::Config(config) => {
+ size = (config.width, config.height);
+ need_keyframe = true;
+ }
+ Item::Packet { keyframe, time_us, data } => {
+ let behind = waiting.fetch_sub(1, Ordering::AcqRel) > 1;
+ if need_keyframe && !keyframe {
+ continue;
+ }
+ need_keyframe = false;
+ let started = Instant::now();
+ let pictures = match decoder.decode(&data, time_us) {
+ Ok(pictures) => pictures,
+ Err(e) => {
+ tracing::debug!(error = %e, "a video packet didn't decode");
+ decoder.flush();
+ need_keyframe = true;
+ keyframe_please();
+ continue;
+ }
+ };
+ let decoded = started.elapsed();
+ // Behind: skip showing this one, the next is already here.
+ if let (Some(picture), false) = (pictures.last(), behind) {
+ let converted = Instant::now();
+ let (w, h) = if size.0 > 0 { size } else { (picture.width, picture.height) };
+ let bgrx = to_bgrx(picture, w, h);
+ ffi::video_frame(&stream, w.min(picture.width), h.min(picture.height), &bgrx);
+ stats.shown(decoded, converted.elapsed());
+ } else {
+ stats.skipped();
+ }
+ }
+ Item::Ended => break,
+ }
+ }
+ ffi::video_clear(&stream);
+}
+
+/// Decode and conversion times, logged now and then.
+struct Stats {
+ since: Instant,
+ shown: u32,
+ skipped: u32,
+ decode: Duration,
+ convert: Duration,
+}
+
+impl Stats {
+ fn new() -> Stats {
+ Stats { since: Instant::now(), shown: 0, skipped: 0, decode: Duration::ZERO, convert: Duration::ZERO }
+ }
+
+ fn shown(&mut self, decode: Duration, convert: Duration) {
+ self.shown += 1;
+ self.decode += decode;
+ self.convert += convert;
+ self.maybe_log();
+ }
+
+ fn skipped(&mut self) {
+ self.skipped += 1;
+ self.maybe_log();
+ }
+
+ fn maybe_log(&mut self) {
+ let elapsed = self.since.elapsed();
+ if elapsed < STATS_EVERY || self.shown == 0 {
+ return;
+ }
+ tracing::info!(
+ fps = format!("{:.1}", f64::from(self.shown) / elapsed.as_secs_f64()),
+ skipped = self.skipped,
+ decode_ms = format!("{:.1}", self.decode.as_secs_f64() * 1000.0 / f64::from(self.shown)),
+ convert_ms = format!("{:.1}", self.convert.as_secs_f64() * 1000.0 / f64::from(self.shown)),
+ "mirroring"
+ );
+ *self = Stats::new();
+ }
+}
diff --git a/desktop/app/src/state.rs b/desktop/app/src/state.rs
index 46bde58..a16615b 100644
--- a/desktop/app/src/state.rs
+++ b/desktop/app/src/state.rs
@@ -38,6 +38,8 @@ impl Changes {
pub const UPDATE: Changes = Changes(1 << 11);
/// A phone's text messages (kept by crate::messages).
pub const MESSAGES: Changes = Changes(1 << 12);
+ /// Mirroring a phone's screen (kept by crate::mirror).
+ pub const MIRROR: Changes = Changes(1 << 13);
pub fn is_empty(self) -> bool {
self.0 == 0
@@ -383,11 +385,13 @@ impl AppState {
Changes::NOTIFICATIONS | self.remember(vec![gone])
}
// Feedback (crate::clipboard), notifications (crate::photos,
- // crate::calls) and state kept elsewhere (crate::messages).
+ // crate::calls) and state kept elsewhere (crate::messages,
+ // crate::mirror).
NodeEvent::ClipboardReceived { .. }
| NodeEvent::PhotoAdded { .. }
| NodeEvent::Call { .. }
- | NodeEvent::SmsChanged { .. } => Changes::NONE,
+ | NodeEvent::SmsChanged { .. }
+ | NodeEvent::Mirroring { .. } => Changes::NONE,
NodeEvent::Transfer(transfer) => self.update_transfer(transfer.clone(), Instant::now()),
// With artwork saved first (see crate::media).
NodeEvent::MediaChanged { .. } => Changes::NONE,
diff --git a/desktop/app/src/win/h264.rs b/desktop/app/src/win/h264.rs
new file mode 100644
index 0000000..6a9889d
--- /dev/null
+++ b/desktop/app/src/win/h264.rs
@@ -0,0 +1,308 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+//! H.264 decoding with Windows' own decoder (Media Foundation's H.264
+//! MFT, licensed with Windows), in low-latency mode: each access unit in,
+//! its picture out right away, as NV12.
+
+use std::mem::ManuallyDrop;
+
+use windows::{
+ Win32::{
+ Media::MediaFoundation::{
+ CLSID_MSH264DecoderMFT, IMF2DBuffer, IMFMediaType, IMFSample, IMFTransform, MF_E_NOTACCEPTING,
+ MF_E_TRANSFORM_NEED_MORE_INPUT, MF_E_TRANSFORM_STREAM_CHANGE, MF_LOW_LATENCY, MF_MT_FRAME_SIZE,
+ MF_MT_MAJOR_TYPE, MF_MT_SUBTYPE, MF_VERSION, MFCreateMediaType, MFCreateMemoryBuffer,
+ MFCreateSample, MFMediaType_Video, MFSTARTUP_NOSOCKET, MFStartup, MFT_MESSAGE_COMMAND_FLUSH,
+ MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM, MFT_OUTPUT_DATA_BUFFER,
+ MFT_OUTPUT_STREAM_PROVIDES_SAMPLES, MFVideoFormat_H264, MFVideoFormat_NV12,
+ },
+ System::Com::{CLSCTX_INPROC_SERVER, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx},
+ },
+ core::Interface,
+};
+
+/// A decoded picture: NV12, `stride` bytes per row, the chroma plane after
+/// `plane_rows` rows of luma (the decoder pads the height).
+#[derive(Debug)]
+pub struct Picture {
+ pub width: u32,
+ pub height: u32,
+ pub stride: usize,
+ pub plane_rows: usize,
+ pub nv12: Vec<u8>,
+}
+
+pub struct Decoder {
+ transform: IMFTransform,
+ /// The decoded size, as the output type says (padded).
+ coded: (u32, u32),
+ provides_samples: bool,
+ output_size: u32,
+}
+
+impl std::fmt::Debug for Decoder {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ f.debug_struct("Decoder").field("coded", &self.coded).finish_non_exhaustive()
+ }
+}
+
+impl Decoder {
+ /// A decoder for the calling thread (which it stays on).
+ pub fn new() -> windows::core::Result<Decoder> {
+ // SAFETY: plain COM and Media Foundation calls with owned values.
+ unsafe {
+ let _ = CoInitializeEx(None, COINIT_MULTITHREADED);
+ MFStartup(MF_VERSION, MFSTARTUP_NOSOCKET)?;
+ let transform: IMFTransform =
+ CoCreateInstance(&CLSID_MSH264DecoderMFT, None, CLSCTX_INPROC_SERVER)?;
+ // One picture in, one out: no reordering delay.
+ if let Ok(attributes) = transform.GetAttributes() {
+ let _ = attributes.SetUINT32(&MF_LOW_LATENCY, 1);
+ }
+ let input = MFCreateMediaType()?;
+ input.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;
+ input.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_H264)?;
+ transform.SetInputType(0, &input, 0)?;
+ let mut decoder = Decoder { transform, coded: (0, 0), provides_samples: false, output_size: 0 };
+ decoder.choose_output()?;
+ decoder.transform.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)?;
+ decoder.transform.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)?;
+ Ok(decoder)
+ }
+ }
+
+ /// Picks NV12 output (again after the stream's size changed).
+ fn choose_output(&mut self) -> windows::core::Result<()> {
+ // SAFETY: as above.
+ unsafe {
+ let mut index = 0;
+ let chosen: IMFMediaType = loop {
+ let candidate = self.transform.GetOutputAvailableType(0, index)?;
+ if candidate.GetGUID(&MF_MT_SUBTYPE)? == MFVideoFormat_NV12 {
+ break candidate;
+ }
+ index += 1;
+ };
+ self.transform.SetOutputType(0, &chosen, 0)?;
+ let size = chosen.GetUINT64(&MF_MT_FRAME_SIZE).unwrap_or(0);
+ self.coded = ((size >> 32) as u32, size as u32);
+ let info = self.transform.GetOutputStreamInfo(0)?;
+ self.provides_samples = info.dwFlags & MFT_OUTPUT_STREAM_PROVIDES_SAMPLES.0 as u32 != 0;
+ self.output_size = info.cbSize;
+ Ok(())
+ }
+ }
+
+ /// Decodes one access unit (Annex B); returns the pictures it completed.
+ pub fn decode(&mut self, data: &[u8], time_us: u64) -> windows::core::Result<Vec<Picture>> {
+ let sample = sample_of(data, time_us)?;
+ let mut pictures = Vec::new();
+ // SAFETY: as above.
+ loop {
+ match unsafe { self.transform.ProcessInput(0, &sample, 0) } {
+ Ok(()) => break,
+ // Full: take what's ready first, then try again.
+ Err(e) if e.code() == MF_E_NOTACCEPTING => pictures.extend(self.drain()?),
+ Err(e) => return Err(e),
+ }
+ }
+ pictures.extend(self.drain()?);
+ Ok(pictures)
+ }
+
+ /// Starts over (after lost packets): the next keyframe decodes cleanly.
+ pub fn flush(&mut self) {
+ // SAFETY: as above.
+ unsafe {
+ let _ = self.transform.ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);
+ }
+ }
+
+ fn drain(&mut self) -> windows::core::Result<Vec<Picture>> {
+ let mut pictures = Vec::new();
+ loop {
+ let provided = if self.provides_samples {
+ None
+ } else {
+ // SAFETY: as above.
+ let buffer = unsafe { MFCreateMemoryBuffer(self.output_size.max(1))? };
+ let sample = unsafe { MFCreateSample()? };
+ unsafe { sample.AddBuffer(&buffer)? };
+ Some(sample)
+ };
+ let mut output = [MFT_OUTPUT_DATA_BUFFER {
+ dwStreamID: 0,
+ pSample: ManuallyDrop::new(provided),
+ dwStatus: 0,
+ pEvents: ManuallyDrop::new(None),
+ }];
+ let mut status = 0;
+ // SAFETY: `output` holds a sample of the size the decoder asked
+ // for (or none when it provides its own); both fields are taken
+ // back below so they're released.
+ let result = unsafe { self.transform.ProcessOutput(0, &mut output, &mut status) };
+ let sample = unsafe { ManuallyDrop::take(&mut output[0].pSample) };
+ drop(unsafe { ManuallyDrop::take(&mut output[0].pEvents) });
+ match result {
+ Ok(()) => {
+ if let Some(sample) = sample {
+ pictures.push(self.picture(&sample)?);
+ }
+ }
+ Err(e) if e.code() == MF_E_TRANSFORM_NEED_MORE_INPUT => return Ok(pictures),
+ Err(e) if e.code() == MF_E_TRANSFORM_STREAM_CHANGE => self.choose_output()?,
+ Err(e) => return Err(e),
+ }
+ }
+ }
+
+ fn picture(&self, sample: &IMFSample) -> windows::core::Result<Picture> {
+ let (width, height) = self.coded;
+ // SAFETY: the buffer is locked while it's read and unlocked after.
+ unsafe {
+ let buffer = sample.ConvertToContiguousBuffer()?;
+ if let Ok(two_d) = buffer.cast::<IMF2DBuffer>() {
+ let mut scan0 = std::ptr::null_mut();
+ let mut pitch = 0;
+ two_d.Lock2D(&mut scan0, &mut pitch)?;
+ let stride = pitch.unsigned_abs() as usize;
+ let rows = height as usize;
+ let len = stride * rows * 3 / 2;
+ let nv12 = std::slice::from_raw_parts(scan0, len).to_vec();
+ two_d.Unlock2D()?;
+ return Ok(Picture { width, height, stride, plane_rows: rows, nv12 });
+ }
+ let mut data = std::ptr::null_mut();
+ let mut length = 0;
+ buffer.Lock(&mut data, None, Some(&mut length))?;
+ let nv12 = std::slice::from_raw_parts(data, length as usize).to_vec();
+ buffer.Unlock()?;
+ let stride = width as usize;
+ let plane_rows = (nv12.len() * 2 / 3) / stride.max(1);
+ Ok(Picture { width, height, stride, plane_rows, nv12 })
+ }
+ }
+}
+
+fn sample_of(data: &[u8], time_us: u64) -> windows::core::Result<IMFSample> {
+ // SAFETY: the buffer is at least `data.len()` long and locked while
+ // it's written.
+ unsafe {
+ let buffer = MFCreateMemoryBuffer(data.len() as u32)?;
+ let mut target = std::ptr::null_mut();
+ buffer.Lock(&mut target, None, None)?;
+ std::ptr::copy_nonoverlapping(data.as_ptr(), target, data.len());
+ buffer.Unlock()?;
+ buffer.SetCurrentLength(data.len() as u32)?;
+ let sample = MFCreateSample()?;
+ sample.AddBuffer(&buffer)?;
+ // In 100-nanosecond units.
+ sample.SetSampleTime(time_us as i64 * 10)?;
+ Ok(sample)
+ }
+}
+
+/// NV12 (BT.709, limited range, as phones encode) to 32-bit BGRX, the
+/// visible `width` x `height`, across a few threads.
+pub fn to_bgrx(picture: &Picture, width: u32, height: u32) -> Vec<u8> {
+ let (w, h) = (width.min(picture.width) as usize, height.min(picture.height) as usize);
+ let mut out = vec![0u8; w * h * 4];
+ if w == 0 || h == 0 {
+ return out;
+ }
+ let threads = std::thread::available_parallelism().map_or(4, |n| n.get()).clamp(1, 8);
+ // Whole row pairs per thread (each chroma row serves two luma rows).
+ let rows_per = h.div_ceil(threads).next_multiple_of(2);
+ std::thread::scope(|scope| {
+ for (chunk, rows) in out.chunks_mut(rows_per * w * 4).enumerate() {
+ let first = chunk * rows_per;
+ scope.spawn(move || convert_rows(picture, w, first, rows));
+ }
+ });
+ out
+}
+
+fn convert_rows(p: &Picture, w: usize, first: usize, out: &mut [u8]) {
+ let uv_plane = p.stride * p.plane_rows;
+ for (i, row) in out.chunks_exact_mut(w * 4).enumerate() {
+ let y_row = first + i;
+ let y_line = &p.nv12[y_row * p.stride..][..w];
+ let uv_line = &p.nv12[uv_plane + (y_row / 2) * p.stride..][..w.next_multiple_of(2).min(p.stride)];
+ for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() {
+ let c = (i32::from(y_line[x]) - 16) * 298;
+ let d = i32::from(uv_line[x & !1]) - 128;
+ let e = i32::from(uv_line[(x & !1) + 1]) - 128;
+ px[0] = clamp((c + 541 * d + 128) >> 8);
+ px[1] = clamp((c - 55 * d - 136 * e + 128) >> 8);
+ px[2] = clamp((c + 459 * e + 128) >> 8);
+ px[3] = 255;
+ }
+ }
+}
+
+fn clamp(v: i32) -> u8 {
+ v.clamp(0, 255) as u8
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn colors_convert() {
+ // 4x2: black, white, and BT.709 red and blue.
+ let (w, h) = (4usize, 2usize);
+ let mut nv12 = vec![0u8; w * h * 3 / 2];
+ nv12[..8].copy_from_slice(&[16, 235, 63, 32, 16, 235, 63, 32]);
+ // Chroma for pixel pairs (0,1) and (2,3): neutral; then red's... the
+ // second pair holds red's chroma (u=102, v=240).
+ nv12[8..12].copy_from_slice(&[128, 128, 102, 240]);
+ let picture = Picture { width: 4, height: 2, stride: 4, plane_rows: 2, nv12 };
+ let out = to_bgrx(&picture, 4, 2);
+ assert_eq!(&out[..4], &[0, 0, 0, 255], "black");
+ assert_eq!(&out[4..8], &[255, 255, 255, 255], "white");
+ let red = &out[8..12];
+ assert!(red[2] > 240 && red[1] < 20 && red[0] < 20, "red: {red:?}");
+ }
+
+ #[test]
+ fn odd_sizes_are_cropped_safely() {
+ let picture = Picture { width: 6, height: 4, stride: 8, plane_rows: 4, nv12: vec![128; 8 * 6] };
+ assert_eq!(to_bgrx(&picture, 5, 3).len(), 5 * 3 * 4);
+ assert_eq!(to_bgrx(&picture, 10, 10).len(), 6 * 4 * 4, "never larger than the picture");
+ }
+
+ /// Splits an Annex B stream into access units at its access unit
+ /// delimiters (a 4-byte start code, then NAL type 9).
+ fn access_units(stream: &[u8]) -> Vec<&[u8]> {
+ let starts: Vec<usize> =
+ (0..stream.len()).filter(|&i| stream[i..].starts_with(&[0, 0, 0, 1, 9])).collect();
+ starts
+ .iter()
+ .enumerate()
+ .map(|(n, &s)| &stream[s..*starts.get(n + 1).unwrap_or(&stream.len())])
+ .collect()
+ }
+
+ #[test]
+ fn a_stream_decodes_picture_by_picture() {
+ // 10 frames of FFmpeg's test pattern, 320x240, a keyframe every 5,
+ // no B-frames, as a phone's encoder sends them.
+ let stream = include_bytes!("testdata/testsrc.h264");
+ let units = access_units(stream);
+ assert_eq!(units.len(), 10);
+ let mut decoder = Decoder::new().unwrap();
+ let mut pictures = Vec::new();
+ for (i, unit) in units.iter().enumerate() {
+ let got = decoder.decode(unit, i as u64 * 33_333).unwrap();
+ // Low-latency mode: each picture comes out with its own unit.
+ assert_eq!(got.len(), 1, "unit {i}");
+ pictures.extend(got);
+ }
+ let first = &pictures[0];
+ assert_eq!((first.width, first.height), (320, 240));
+ let bgrx = to_bgrx(first, 320, 240);
+ // A colorful test pattern, not a blank picture.
+ let distinct: std::collections::HashSet<&[u8; 4]> = bgrx.as_chunks::<4>().0.iter().collect();
+ assert!(distinct.len() > 50, "{} colors", distinct.len());
+ }
+}
diff --git a/desktop/app/src/win/mod.rs b/desktop/app/src/win/mod.rs
index bee244c..f68e1dc 100644
--- a/desktop/app/src/win/mod.rs
+++ b/desktop/app/src/win/mod.rs
@@ -8,6 +8,7 @@
pub mod autostart;
pub mod clipboard;
pub mod doctor;
+pub mod h264;
pub mod http;
pub mod icon;
pub mod image;
diff --git a/desktop/app/src/win/testdata/testsrc.h264 b/desktop/app/src/win/testdata/testsrc.h264
new file mode 100644
index 0000000..b1d3c34
Binary files /dev/null and b/desktop/app/src/win/testdata/testsrc.h264 differ