Skip to content

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

feat: HEVC for screen sharing (#66)

AS014c8860d866
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
index 0ef13dd..44c7e81 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/core/Core.kt
@@ -1089,6 +1089,12 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
return runCatching { node?.webcamCodecs(pcId) }.getOrNull() ?: listOf("h264")
}
+ /** Accepted screen codecs from the connected PC; unknown receivers use H.264. */
+ suspend fun mirrorCodecs(pcId: String): List<String> {
+ startJob?.join()
+ return runCatching { node?.mirrorCodecs(pcId) }.getOrNull() ?: listOf("h264")
+ }
+
/** Opens this phone's camera stream to a PC (`webcam`), or emits a message on failure. */
suspend fun webcamOpenOrMessage(pcId: String): MirrorStream? {
startJob?.join()
@@ -1869,7 +1875,8 @@ class Core(context: Context, private val scope: CoroutineScope) : EventListener
// Apps in windows of their own run on displays the Elevated helper makes.
(if (Elevated.running && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) listOf("mirror.virtual_display") else emptyList()) +
// Asked for when a PC wants the sound, or streamed via Elevated helper.
- (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q || Elevated.running) listOf("mirror.audio.playback") else emptyList())
+ (if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q || Elevated.running) listOf("mirror.audio.playback") else emptyList()) +
+ (if (app.nectarlink.android.mirror.ScreenEncoder.supportsHevcDecoder()) listOf("mirror.decode.hevc") else emptyList())
/**
* Triggers an immediate network/presence reconnect (e.g. when woken by
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.kt b/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.kt
index dfd761f..5528fce 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/elevated/AppDisplay.kt
@@ -18,10 +18,10 @@ import java.io.OutputStream
/**
* An app in a window of its own (Elevated): a virtual display of its own,
* made by the shell-side helper (apps may not put other apps on their
- * displays), with an H.264 encoder drawing from it, and the app started on
- * it. The encoded video goes to [out] as packets:
- * `u32 length | u8 kind | u64 time µs | data` (kind 0: config, as
- * `u32 width | u32 height | u32 display id`; 1: frame; 2: keyframe).
+ * displays). A surface encoder captures that display, and the app starts on it.
+ * Packets written to [out] use `u32 length | u8 kind | u64 time_us | data`.
+ * Kind 0 carries four u32 fields: width, height, display ID, and codec ID
+ * (1: H.264, 2: H.265, 3: AV1). Kinds 1 and 2 carry frames and keyframes.
*/
@SuppressLint("PrivateApi", "DiscouragedPrivateApi", "BlockedPrivateApi")
class AppDisplay(
@@ -32,6 +32,12 @@ class AppDisplay(
private val fps: Int,
private val codecName: String = "h264",
) {
+ private data class EncodedSurface(
+ val codecName: String,
+ val codec: MediaCodec,
+ val surface: Surface,
+ )
+
@Volatile private var running = true
@Volatile private var nextSize: Triple<Int, Int, Int>? = null
private var display: VirtualDisplay? = null
@@ -50,25 +56,21 @@ class AppDisplay(
var surface: Surface? = null
val data = DataOutputStream(out.buffered(1 shl 16))
try {
- val (firstCodec, firstSurface) = createEncoder(curW, curH)
- codec = firstCodec
- surface = firstSurface
+ val first = createEncoder(curW, curH)
+ codec = first.codec
+ surface = first.surface
val made = if (fullScreen) {
- createMirrorDisplay(curW, curH, curDpi, firstSurface)
+ createMirrorDisplay(curW, curH, curDpi, first.surface)
} else {
- createDisplay(curW, curH, curDpi, firstSurface)
+ createDisplay(curW, curH, curDpi, first.surface)
}
display = made
displayId = if (fullScreen) 0 else made.display.displayId
if (!fullScreen) {
hideIme(displayId)
}
- firstCodec.start()
- codecForKeyframes = firstCodec
- write(data, KIND_CONFIG, 0, ByteArray(12).also {
- java.nio.ByteBuffer.wrap(it).putInt(curW).putInt(curH).putInt(displayId)
- })
- data.flush()
+ codecForKeyframes = first.codec
+ writeConfig(data, curW, curH, displayId, first.codecName)
if (!fullScreen) {
launch(pkg, displayId)
watchActivities(displayId)
@@ -87,20 +89,16 @@ class AppDisplay(
codec = null
runCatching { surface?.release() }
surface = null
- val (nextCodec, nextSurface) = createEncoder(newW, newH)
- codec = nextCodec
- surface = nextSurface
- nextCodec.start()
- codecForKeyframes = nextCodec
+ val next = createEncoder(newW, newH)
+ codec = next.codec
+ surface = next.surface
+ codecForKeyframes = next.codec
made.resize(newW, newH, newDpi)
- made.surface = nextSurface
+ made.surface = next.surface
curW = newW
curH = newH
curDpi = newDpi
- write(data, KIND_CONFIG, 0, ByteArray(12).also {
- java.nio.ByteBuffer.wrap(it).putInt(curW).putInt(curH).putInt(displayId)
- })
- data.flush()
+ writeConfig(data, curW, curH, displayId, next.codecName)
}
} finally {
running = false
@@ -137,7 +135,8 @@ class AppDisplay(
else -> MediaFormat.MIMETYPE_VIDEO_AVC
}
- private fun createEncoderForMime(mime: String, w: Int, h: Int): Pair<MediaCodec, Surface> {
+ private fun createEncoderForCodec(name: String, w: Int, h: Int): EncodedSurface {
+ val mime = mimeForCodec(name)
val format = MediaFormat.createVideoFormat(mime, w, h).apply {
setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
setInteger(MediaFormat.KEY_BIT_RATE, bitrate)
@@ -157,16 +156,47 @@ class AppDisplay(
}
}
val codec = MediaCodec.createEncoderByType(mime)
- codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
- return codec to codec.createInputSurface()
+ var surface: Surface? = null
+ try {
+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
+ surface = codec.createInputSurface()
+ codec.start()
+ return EncodedSurface(name, codec, surface)
+ } catch (error: Exception) {
+ runCatching { surface?.release() }
+ runCatching { codec.release() }
+ throw error
+ }
+ }
+
+ private fun createEncoder(w: Int, h: Int): EncodedSurface {
+ if (codecName != "h264") {
+ try {
+ return createEncoderForCodec(codecName, w, h)
+ } catch (error: Exception) {
+ android.util.Log.i("AppDisplay", "$codecName screen encoder unavailable; using H.264", error)
+ }
+ }
+ return createEncoderForCodec("h264", w, h)
}
- private fun createEncoder(w: Int, h: Int): Pair<MediaCodec, Surface> {
- val preferredMime = mimeForCodec(codecName)
- if (preferredMime != MediaFormat.MIMETYPE_VIDEO_AVC) {
- runCatching { return createEncoderForMime(preferredMime, w, h) }
+ private fun writeConfig(
+ out: DataOutputStream,
+ width: Int,
+ height: Int,
+ displayId: Int,
+ codec: String,
+ ) {
+ val codecId = when (codec) {
+ "h264" -> CODEC_ID_H264
+ "h265" -> CODEC_ID_H265
+ "av1" -> CODEC_ID_AV1
+ else -> error("Unsupported screen codec: $codec")
}
- return createEncoderForMime(MediaFormat.MIMETYPE_VIDEO_AVC, w, h)
+ write(out, KIND_CONFIG, 0, ByteArray(16).also {
+ java.nio.ByteBuffer.wrap(it).putInt(width).putInt(height).putInt(displayId).putInt(codecId)
+ })
+ out.flush()
}
private fun drain(codec: MediaCodec, out: DataOutputStream) {
@@ -382,6 +412,9 @@ class AppDisplay(
const val KIND_CONFIG = 0
const val KIND_FRAME = 1
const val KIND_KEYFRAME = 2
+ const val CODEC_ID_H264 = 1
+ const val CODEC_ID_H265 = 2
+ const val CODEC_ID_AV1 = 3
/** How often an open window counts as activity; well under any screen timeout. */
private const val KEEP_ACTIVE_MS = 4_000L
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt
index 8f939ba..46593af 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/MirrorService.kt
@@ -22,6 +22,7 @@ import androidx.core.content.ContextCompat
import androidx.core.content.IntentCompat
import app.nectarlink.android.NectarlinkApplication
import app.nectarlink.android.R
+import app.nectarlink.android.elevated.AppDisplay
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
@@ -133,13 +134,14 @@ class MirrorService : Service() {
main.post { stopSharing() }
return@launch
}
+ val preferredCodec = core.mirrorCodecs(pc).firstOrNull() ?: "h264"
main.post {
val running = projection
if (running == null) {
stream.end()
return@post
}
- encoder = ScreenEncoder(this@MirrorService, running, stream, maxSize, fps, bitrate) {
+ encoder = ScreenEncoder(this@MirrorService, running, stream, maxSize, fps, bitrate, preferredCodec) {
main.post { stopSharing() }
}.also { it.start() }
applyPower()
@@ -160,7 +162,8 @@ class MirrorService : Service() {
val (initW, initH, initDpi) = ScreenEncoder.computeScreenSize(this@MirrorService, request.maxSize)
// With the screen off (phone in a pocket) there's nothing to show yet.
app.nectarlink.android.elevated.Elevated.wakeScreen()
- val codec = ScreenEncoder.selectCodec("h264")
+ val preferredCodec = core.mirrorCodecs(pc).firstOrNull() ?: "h264"
+ val codec = ScreenEncoder.selectCodec(preferredCodec)
val socket = app.nectarlink.android.elevated.Elevated.openScreen(
initW,
initH,
@@ -179,7 +182,7 @@ class MirrorService : Service() {
}
elevatedSocket = socket
main.post { watchDisplay(socket, request, initW, initH) }
- streamElevated(core, pc, pcName, request, socket, codec)
+ streamElevated(core, pc, pcName, request, socket)
}
/** Resizes the helper's picture when the phone's screen turns. */
@@ -223,7 +226,6 @@ class MirrorService : Service() {
pcName: String,
request: MirrorRequest,
socket: java.net.Socket,
- codec: String,
) {
val stream = runCatching { core.mirrorOpen(pc) }.getOrElse {
Log.w(TAG, "can't stream to the PC", it)
@@ -241,17 +243,25 @@ class MirrorService : Service() {
val time = input.readLong().toULong()
val data = ByteArray(length - 9).also { input.readFully(it) }
val result = when (kind) {
- app.nectarlink.android.elevated.AppDisplay.KIND_CONFIG -> {
- gotConfig = true
+ AppDisplay.KIND_CONFIG -> {
+ if (data.size != 16) throw java.io.IOException("Invalid screen configuration length")
val fields = java.nio.ByteBuffer.wrap(data)
val (w, h) = fields.int to fields.int
+ fields.int // display id
+ val activeCodec = when (fields.int) {
+ AppDisplay.CODEC_ID_H264 -> "h264"
+ AppDisplay.CODEC_ID_H265 -> "h265"
+ AppDisplay.CODEC_ID_AV1 -> "av1"
+ else -> throw java.io.IOException("Unsupported screen codec")
+ }
+ gotConfig = true
stream.send(
app.nectarlink.core.VideoPacketKind.CONFIG,
0u,
- app.nectarlink.core.mirrorConfigCodec(codec, w.toUInt(), h.toUInt(), 0u),
+ app.nectarlink.core.mirrorConfigCodec(activeCodec, w.toUInt(), h.toUInt(), 0u),
)
}
- app.nectarlink.android.elevated.AppDisplay.KIND_KEYFRAME ->
+ AppDisplay.KIND_KEYFRAME ->
stream.send(app.nectarlink.core.VideoPacketKind.KEYFRAME, time, data)
else ->
stream.send(app.nectarlink.core.VideoPacketKind.FRAME, time, data)
diff --git a/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt b/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt
index 0f4125e..1754bd9 100644
--- a/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt
+++ b/android/app/src/main/kotlin/app/nectarlink/android/mirror/ScreenEncoder.kt
@@ -14,6 +14,7 @@ import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.Display
+import android.view.Surface
import android.view.WindowManager
import app.nectarlink.core.MirrorSendResult
import app.nectarlink.core.MirrorStream
@@ -51,6 +52,8 @@ internal class ScreenEncoder(
private data class Size(val width: Int, val height: Int, val dpi: Int)
+ private data class Encoder(val name: String, val codec: MediaCodec, val surface: Surface)
+
private val rotation = object : DisplayManager.DisplayListener {
override fun onDisplayChanged(displayId: Int) {
if (displayId != Display.DEFAULT_DISPLAY) return
@@ -82,28 +85,30 @@ internal class ScreenEncoder(
while (running) {
size = screenSize()
resizeWanted = false
- val (activeCodecName, codec) = encoder(size)
- val surface = codec.createInputSurface()
- codec.start()
- val current = display
- if (current == null) {
- display = projection.createVirtualDisplay(
- "Nectarlink", size.width, size.height, size.dpi,
- DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, surface, null, null,
- )
- } else {
- current.resize(size.width, size.height, size.dpi)
- current.surface = surface
+ val active = encoder(size)
+ try {
+ val current = display
+ if (current == null) {
+ display = projection.createVirtualDisplay(
+ "Nectarlink", size.width, size.height, size.dpi,
+ DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, active.surface, null, null,
+ )
+ } else {
+ current.resize(size.width, size.height, size.dpi)
+ current.surface = active.surface
+ }
+ val closed = stream.send(
+ VideoPacketKind.CONFIG,
+ 0u,
+ mirrorConfigCodec(active.name, size.width.toUInt(), size.height.toUInt(), 0u),
+ ) == MirrorSendResult.CLOSED || drain(active.codec)
+ if (closed) break
+ } finally {
+ runCatching { display?.surface = null }
+ runCatching { active.codec.stop() }
+ runCatching { active.codec.release() }
+ active.surface.release()
}
- val closed = stream.send(
- VideoPacketKind.CONFIG,
- 0u,
- mirrorConfigCodec(activeCodecName, size.width.toUInt(), size.height.toUInt(), 0u),
- ) == MirrorSendResult.CLOSED || drain(codec)
- runCatching { codec.stop() }
- codec.release()
- surface.release()
- if (closed) break
}
} catch (e: Exception) {
Log.w(TAG, "screen sharing failed", e)
@@ -157,7 +162,8 @@ internal class ScreenEncoder(
return !running
}
- private fun createCodecForMime(mime: String, size: Size): MediaCodec {
+ private fun createEncoder(name: String, size: Size): Encoder {
+ val mime = mimeForCodec(name)
val format = MediaFormat.createVideoFormat(mime, size.width, size.height).apply {
setInteger(MediaFormat.KEY_COLOR_FORMAT, MediaCodecInfo.CodecCapabilities.COLOR_FormatSurface)
setInteger(MediaFormat.KEY_BIT_RATE, bitrate)
@@ -176,16 +182,28 @@ internal class ScreenEncoder(
setInteger(MediaFormat.KEY_COLOR_TRANSFER, MediaFormat.COLOR_TRANSFER_SDR_VIDEO)
}
val codec = MediaCodec.createEncoderByType(mime)
- codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
- return codec
+ var surface: Surface? = null
+ try {
+ codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE)
+ surface = codec.createInputSurface()
+ codec.start()
+ return Encoder(name, codec, surface)
+ } catch (error: Exception) {
+ runCatching { surface?.release() }
+ runCatching { codec.release() }
+ throw error
+ }
}
- private fun encoder(size: Size): Pair<String, MediaCodec> {
- val preferredMime = mimeForCodec(codecName)
- if (preferredMime != MediaFormat.MIMETYPE_VIDEO_AVC) {
- runCatching { return codecName to createCodecForMime(preferredMime, size) }
+ private fun encoder(size: Size): Encoder {
+ if (codecName != "h264") {
+ try {
+ return createEncoder(codecName, size)
+ } catch (error: Exception) {
+ Log.i(TAG, "$codecName screen encoder unavailable; using H.264", error)
+ }
}
- return "h264" to createCodecForMime(MediaFormat.MIMETYPE_VIDEO_AVC, size)
+ return createEncoder("h264", size)
}
/** The screen's size scaled to fit `maxSize`, in multiples of 16 (what encoders like). */
@@ -197,6 +215,17 @@ internal class ScreenEncoder(
companion object {
private const val TAG = "ScreenEncoder"
private const val WAIT_US = 50_000L
+ private val hevcDecoderSupported by lazy(LazyThreadSafetyMode.PUBLICATION) {
+ runCatching {
+ android.media.MediaCodecList(android.media.MediaCodecList.REGULAR_CODECS)
+ .codecInfos
+ .any { info ->
+ !info.isEncoder && info.supportedTypes.any {
+ it.equals(MediaFormat.MIMETYPE_VIDEO_HEVC, ignoreCase = true)
+ }
+ }
+ }.getOrDefault(false)
+ }
fun mimeForCodec(name: String): String = when (name.lowercase()) {
"h265", "hevc" -> MediaFormat.MIMETYPE_VIDEO_HEVC
@@ -218,6 +247,8 @@ internal class ScreenEncoder(
return if (supported) want else "h264"
}
+ fun supportsHevcDecoder(): Boolean = hevcDecoderSupported
+
fun computeScreenSize(context: Context, maxSize: Int): Triple<Int, Int, Int> {
val windows = context.getSystemService(WindowManager::class.java)
val (w, h) = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
diff --git a/core/nectarlink-core/src/lib.rs b/core/nectarlink-core/src/lib.rs
index 20e53c1..0a0393b 100644
--- a/core/nectarlink-core/src/lib.rs
+++ b/core/nectarlink-core/src/lib.rs
@@ -109,9 +109,10 @@ pub use nectarlink_protocol::{
mic::{LISTEN as MIC_LISTEN, STREAM as MIC_STREAM},
mirror::{
AUDIO as MIRROR_AUDIO, AUDIO_PLAYBACK as MIRROR_AUDIO_PLAYBACK, AV1 as MIRROR_AV1,
- CAPTURE as MIRROR_CAPTURE, H264 as MIRROR_H264, H265 as MIRROR_H265, INPUT as MIRROR_INPUT,
- LISTEN as MIRROR_LISTEN, MAX_TEXT_BYTES as MIRROR_MAX_TEXT_BYTES, PCM as MIRROR_PCM,
- SCREEN as MIRROR_SCREEN, VIEW as MIRROR_VIEW, VIRTUAL_DISPLAY as MIRROR_VIRTUAL_DISPLAY,
+ CAPTURE as MIRROR_CAPTURE, H264 as MIRROR_H264, H265 as MIRROR_H265, HEVC as MIRROR_HEVC,
+ INPUT as MIRROR_INPUT, LISTEN as MIRROR_LISTEN, MAX_TEXT_BYTES as MIRROR_MAX_TEXT_BYTES,
+ PCM as MIRROR_PCM, SCREEN as MIRROR_SCREEN, VIEW as MIRROR_VIEW,
+ VIRTUAL_DISPLAY as MIRROR_VIRTUAL_DISPLAY,
},
mirror_keys, notify_limits, parse_mac,
photos::{
diff --git a/core/nectarlink-core/src/node.rs b/core/nectarlink-core/src/node.rs
index 0ed8d72..5953a21 100644
--- a/core/nectarlink-core/src/node.rs
+++ b/core/nectarlink-core/src/node.rs
@@ -2691,6 +2691,19 @@ impl Node {
Ok(codecs)
}
+ /// Screen codecs accepted by the connected receiver, in preference order.
+ /// Older receivers do not advertise HEVC and continue to use H.264.
+ pub fn mirror_codecs(&self, peer: DeviceId) -> Result<Vec<String>> {
+ let _ = self.connected(&peer)?;
+ let record = self.shared.store.get_peer(&peer)?.ok_or(Error::NotPaired)?;
+ let mut codecs = Vec::new();
+ if record.caps.contains(crate::MIRROR_HEVC) {
+ codecs.push(crate::MIRROR_H265.into());
+ }
+ codecs.push(crate::MIRROR_H264.into());
+ Ok(codecs)
+ }
+
/// Asks a paired phone to start streaming its camera as a webcam.
/// Video then arrives through [`Platform::webcam_sink`](crate::Platform::webcam_sink).
pub async fn webcam_start(&self, peer: DeviceId, options: crate::WebcamStart) -> Result<()> {
diff --git a/core/nectarlink-core/tests/two_devices.rs b/core/nectarlink-core/tests/two_devices.rs
index aca45e1..eb85132 100644
--- a/core/nectarlink-core/tests/two_devices.rs
+++ b/core/nectarlink-core/tests/two_devices.rs
@@ -3399,6 +3399,25 @@ async fn the_phone_negotiates_hevc_only_with_an_advertising_receiver() {
webcam_round_trip(true).await;
}
+#[tokio::test(flavor = "multi_thread")]
+async fn screen_mirroring_prefers_hevc_only_when_the_receiver_advertises_it() {
+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[nectarlink_core::MIRROR_HEVC]).await;
+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[]).await;
+ pair_qr(&mut pc, &mut phone).await;
+ let pc_id = pc.node.device_id();
+
+ assert_eq!(phone.node.mirror_codecs(pc_id).unwrap(), ["h265", "h264"]);
+}
+
+#[tokio::test(flavor = "multi_thread")]
+async fn screen_mirroring_uses_h264_for_receivers_without_hevc_support() {
+ let mut pc = device_with("Desktop", DeviceKind::Desktop, &[]).await;
+ let mut phone = device_with("Pixel", DeviceKind::Phone, &[]).await;
+ pair_qr(&mut pc, &mut phone).await;
+
+ assert_eq!(phone.node.mirror_codecs(pc.node.device_id()).unwrap(), ["h264"]);
+}
+
async fn webcam_round_trip(hevc: bool) {
use nectarlink_core::{MirrorSend, PacketKind};
let mut caps = vec![nectarlink_core::WEBCAM_VIRTUAL];
diff --git a/core/nectarlink-ffi/src/lib.rs b/core/nectarlink-ffi/src/lib.rs
index c4c6d5c..c603688 100644
--- a/core/nectarlink-ffi/src/lib.rs
+++ b/core/nectarlink-ffi/src/lib.rs
@@ -4077,6 +4077,11 @@ impl NectarlinkNode {
Ok(self.node.webcam_codecs(parse_id(&pc_id)?)?)
}
+ /// Screen codecs accepted by the connected receiver, with H.264 fallback.
+ pub fn mirror_codecs(&self, pc_id: String) -> Result<Vec<String>> {
+ Ok(self.node.mirror_codecs(parse_id(&pc_id)?)?)
+ }
+
/// Opens this phone's camera stream to a paired PC (`docs/protocol/webcam.md`).
pub async fn webcam_open(&self, pc_id: String) -> Result<Arc<MirrorStream>> {
let id = parse_id(&pc_id)?;
diff --git a/core/nectarlink-protocol/src/messages.rs b/core/nectarlink-protocol/src/messages.rs
index 39207a8..bac8a05 100644
--- a/core/nectarlink-protocol/src/messages.rs
+++ b/core/nectarlink-protocol/src/messages.rs
@@ -1322,6 +1322,8 @@ pub mod mirror {
pub const H264: &str = "h264";
pub const H265: &str = "h265";
pub const AV1: &str = "av1";
+ /// Offered by a device that can decode HEVC video streams.
+ pub const HEVC: &str = "mirror.decode.hevc";
/// Offered by phones that stream all their sound while mirrored.
pub const AUDIO: &str = "mirror.audio";
/// Offered by phones that stream the sound of apps that allow it.
@@ -1578,7 +1580,7 @@ impl MirrorInput {
/// The format of a mirroring stream (a config packet's data, in CBOR).
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MirrorConfig {
- /// `h264`.
+ /// `h264`, `h265`, or `av1`.
pub codec: String,
pub width: u32,
pub height: u32,
diff --git a/desktop/app/src/core_host.rs b/desktop/app/src/core_host.rs
index 8d3c1f9..81edd2a 100644
--- a/desktop/app/src/core_host.rs
+++ b/desktop/app/src/core_host.rs
@@ -129,6 +129,7 @@ pub fn compute_capabilities(
caps.push(nectarlink_core::WEBCAM_VIRTUAL.into());
if crate::webcam::supports_hevc() {
caps.push(nectarlink_core::WEBCAM_HEVC.into());
+ caps.push(nectarlink_core::MIRROR_HEVC.into());
}
caps.push(nectarlink_core::MEDIA_STREAM.into());
}
diff --git a/desktop/app/src/pc_mirror.rs b/desktop/app/src/pc_mirror.rs
index f09817e..24dff88 100644
--- a/desktop/app/src/pc_mirror.rs
+++ b/desktop/app/src/pc_mirror.rs
@@ -1,8 +1,7 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-//! Reverse Mirroring ("Your PC in Your Pocket"): captures the PC's primary
-//! display, encodes it to low-latency H.264 via Windows Media Foundation, and
-//! streams it over `mirror` / `video` (`session = 0`) to a paired phone, while
-//! injecting touch, scroll, key, and text input back into Windows (`docs/PLAN.md` §8.6).
+//! Shares the PC's display with a paired phone over `mirror` / `video` (session 0).
+//! Encodes H.264 or HEVC using Media Foundation on Windows, or H.264 using OpenH264
+//! on Linux, and handles remote touch, keyboard, and pointer input.
#[cfg(any(windows, target_os = "linux"))]
mod imp {
@@ -23,7 +22,7 @@ mod imp {
use nectarlink_core::{MirrorConfig, MirrorSend, PacketKind};
#[cfg(windows)]
use windows::Win32::{
- Foundation::{POINT, RECT},
+ Foundation::{E_INVALIDARG, E_NOTIMPL, ERROR_TIMEOUT, POINT, RECT},
Graphics::Gdi::{
BI_RGB, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleBitmap, CreateCompatibleDC, DESKTOPHORZRES,
DESKTOPVERTRES, DeleteDC, DeleteObject, GetDC, GetDIBits, GetDeviceCaps, HALFTONE, ReleaseDC,
@@ -31,17 +30,22 @@ mod imp {
},
Media::MediaFoundation::{
CODECAPI_AVEncCommonMeanBitRate, CODECAPI_AVEncMPVGOPSize, CODECAPI_AVEncVideoForceKeyFrame,
- CODECAPI_AVLowLatencyMode, ICodecAPI, IMFMediaBuffer, IMFMediaType, IMFSample, IMFTransform,
- MF_E_NOTACCEPTING, MF_E_TRANSFORM_NEED_MORE_INPUT, MF_E_TRANSFORM_STREAM_CHANGE, MF_LOW_LATENCY,
- MF_MT_AVG_BITRATE, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE, MF_MT_INTERLACE_MODE, MF_MT_MAJOR_TYPE,
- MF_MT_MPEG_SEQUENCE_HEADER, MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE, MFCreateMediaType,
+ CODECAPI_AVLowLatencyMode, ICodecAPI, IMFActivate, IMFAsyncCallback, IMFAsyncCallback_Impl,
+ IMFAsyncResult, IMFAttributes, IMFMediaBuffer, IMFMediaEventGenerator, IMFMediaType, IMFSample,
+ IMFTransform, MEError, METransformHaveOutput, METransformNeedInput, MF_E_NOTACCEPTING,
+ MF_E_OPERATION_CANCELLED, MF_E_TRANSFORM_NEED_MORE_INPUT, MF_E_TRANSFORM_STREAM_CHANGE,
+ MF_LOW_LATENCY, MF_MT_AVG_BITRATE, MF_MT_FRAME_RATE, MF_MT_FRAME_SIZE, MF_MT_INTERLACE_MODE,
+ MF_MT_MAJOR_TYPE, MF_MT_MPEG_SEQUENCE_HEADER, MF_MT_PIXEL_ASPECT_RATIO, MF_MT_SUBTYPE,
+ MF_TRANSFORM_ASYNC, MF_TRANSFORM_ASYNC_UNLOCK, MFCreateAttributes, MFCreateMediaType,
MFCreateMemoryBuffer, MFCreateSample, MFMediaType_Video, MFSampleExtension_CleanPoint,
- MFT_CATEGORY_VIDEO_ENCODER, MFT_MESSAGE_COMMAND_FLUSH, MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,
+ MFT_CATEGORY_VIDEO_ENCODER, MFT_ENUM_ADAPTER_LUID, MFT_ENUM_FLAG_ASYNCMFT,
+ MFT_ENUM_FLAG_HARDWARE, MFT_ENUM_FLAG_LOCALMFT, MFT_ENUM_FLAG_SORTANDFILTER,
+ MFT_ENUM_FLAG_SYNCMFT, MFT_MESSAGE_COMMAND_FLUSH, MFT_MESSAGE_NOTIFY_BEGIN_STREAMING,
MFT_MESSAGE_NOTIFY_END_STREAMING, MFT_MESSAGE_NOTIFY_START_OF_STREAM, MFT_OUTPUT_DATA_BUFFER,
- MFT_OUTPUT_STREAM_PROVIDES_SAMPLES, MFVideoFormat_H264, MFVideoFormat_NV12,
- MFVideoInterlace_Progressive,
+ MFT_OUTPUT_STREAM_PROVIDES_SAMPLES, MFT_REGISTER_TYPE_INFO, MFTEnum2, MFVideoFormat_H264,
+ MFVideoFormat_HEVC, MFVideoFormat_NV12, MFVideoInterlace_Progressive,
},
- System::Variant::VARIANT,
+ System::{Com::CoTaskMemFree, Variant::VARIANT},
UI::WindowsAndMessaging::{
CURSOR_SHOWING, CURSORINFO, DI_NORMAL, DrawIconEx, GetCursorInfo, GetSystemMetrics, SM_CXSCREEN,
SM_CYSCREEN,
@@ -49,7 +53,7 @@ mod imp {
};
#[cfg(windows)]
- use crate::win::h264::{create_mft, ensure_mf_started};
+ use crate::win::h264::{ensure_mf_started, video_adapters};
use crate::{core_host, win};
struct ActiveSession {
@@ -94,8 +98,7 @@ mod imp {
/// Whether this PC's display session supports screen capture for `mirror.capture`.
///
- /// On Linux, `pc_mirror` captures the screen via X11 (`XGetImage`) or Wayland
- /// (`org.freedesktop.portal.ScreenCast` + PipeWire) and encodes via `libopenh264`.
+ /// Linux needs an H.264 encoder and either X11 or the ScreenCast portal with PipeWire.
pub fn is_capture_available() -> bool {
#[cfg(windows)]
{
@@ -337,8 +340,212 @@ mod imp {
}
#[cfg(windows)]
- pub(crate) struct H264Encoder {
+ fn video_encoder_activations(
+ output_subtype: windows::core::GUID,
+ adapter: Option<u64>,
+ ) -> windows::core::Result<Vec<IMFActivate>> {
+ let input_info =
+ MFT_REGISTER_TYPE_INFO { guidMajorType: MFMediaType_Video, guidSubtype: MFVideoFormat_NV12 };
+ let output_info =
+ MFT_REGISTER_TYPE_INFO { guidMajorType: MFMediaType_Video, guidSubtype: output_subtype };
+ let flags = if adapter.is_some() {
+ MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER
+ } else {
+ MFT_ENUM_FLAG_SYNCMFT
+ | MFT_ENUM_FLAG_ASYNCMFT
+ | MFT_ENUM_FLAG_LOCALMFT
+ | MFT_ENUM_FLAG_SORTANDFILTER
+ };
+ let mut activates: *mut Option<IMFActivate> = std::ptr::null_mut();
+ let mut count = 0u32;
+ // SAFETY: MFTEnum2 returns a CoTaskMemAlloc array; take each interface before freeing it.
+ unsafe {
+ let mut attributes: Option<IMFAttributes> = None;
+ if let Some(adapter) = adapter {
+ MFCreateAttributes(&mut attributes, 1)?;
+ attributes
+ .as_ref()
+ .ok_or_else(|| windows::core::Error::from(E_INVALIDARG))?
+ .SetBlob(&MFT_ENUM_ADAPTER_LUID, &adapter.to_le_bytes())?;
+ }
+ MFTEnum2(
+ MFT_CATEGORY_VIDEO_ENCODER,
+ flags,
+ Some(&input_info),
+ Some(&output_info),
+ attributes.as_ref(),
+ &mut activates,
+ &mut count,
+ )?;
+ let mut candidates = Vec::new();
+ if !activates.is_null() {
+ let entries = std::slice::from_raw_parts_mut(activates, count as usize);
+ for entry in entries {
+ if let Some(activation) = entry.take() {
+ candidates.push(activation);
+ }
+ }
+ CoTaskMemFree(Some(activates.cast()));
+ }
+ Ok(candidates)
+ }
+ }
+
+ #[cfg(windows)]
+ fn create_video_encoder(
+ subtype: windows::core::GUID,
+ configure: impl FnMut(IMFTransform) -> windows::core::Result<ScreenEncoder>,
+ ) -> windows::core::Result<ScreenEncoder> {
+ let mut candidates = Vec::new();
+ if let Ok(adapters) = video_adapters() {
+ for adapter in adapters {
+ match video_encoder_activations(subtype, Some(adapter.luid)) {
+ Ok(found) => candidates.extend(found),
+ Err(error) => {
+ tracing::debug!(%error, adapter = adapter.luid, "GPU encoder enumeration failed")
+ }
+ }
+ }
+ }
+ match video_encoder_activations(subtype, None) {
+ Ok(found) => candidates.extend(found),
+ Err(error) if candidates.is_empty() => return Err(error),
+ Err(error) => tracing::debug!(%error, "Software encoder enumeration failed"),
+ }
+ try_video_encoders(candidates, configure)
+ }
+
+ #[cfg(windows)]
+ fn try_video_encoders(
+ candidates: Vec<IMFActivate>,
+ mut configure: impl FnMut(IMFTransform) -> windows::core::Result<ScreenEncoder>,
+ ) -> windows::core::Result<ScreenEncoder> {
+ let mut last_error = windows::core::Error::from(E_INVALIDARG);
+ let mut candidates = candidates.into_iter();
+ while let Some(activation) = candidates.next() {
+ // SAFETY: each activation owns an encoder; fully configure it before selecting it.
+ let result = unsafe { activation.ActivateObject::<IMFTransform>() }.and_then(&mut configure);
+ match result {
+ Ok(mut encoder) => {
+ encoder.alternatives = candidates.collect();
+ return Ok(encoder);
+ }
+ Err(error) => {
+ tracing::debug!(%error, "Video encoder candidate unavailable");
+ last_error = error;
+ // SAFETY: this failed candidate will not be used again.
+ let _ = unsafe { activation.ShutdownObject() };
+ }
+ }
+ }
+ Err(last_error)
+ }
+
+ #[cfg(windows)]
+ #[windows::core::implement(IMFAsyncCallback)]
+ struct EncoderEventCallback {
+ cookie: u32,
+ sender: std::sync::mpsc::Sender<windows::core::Result<u32>>,
+ }
+
+ #[cfg(windows)]
+ impl IMFAsyncCallback_Impl for EncoderEventCallback_Impl {
+ fn GetParameters(&self, _: *mut u32, _: *mut u32) -> windows::core::Result<()> {
+ Err(E_NOTIMPL.into())
+ }
+
+ fn Invoke(&self, result: windows::core::Ref<IMFAsyncResult>) -> windows::core::Result<()> {
+ // SAFETY: the global interface table marshals the generator into this callback's apartment.
+ let event = unsafe {
+ global_interface_table().and_then(|table| {
+ let mut raw = std::ptr::null_mut();
+ table.GetInterfaceFromGlobal(
+ self.cookie,
+ &<IMFMediaEventGenerator as windows::core::Interface>::IID,
+ &mut raw,
+ )?;
+ let generator = <IMFMediaEventGenerator as windows::core::Interface>::from_raw(raw);
+ result.ok().and_then(|result| generator.EndGetEvent(result)).and_then(|event| {
+ let kind = event.GetType()?;
+ if kind == MEError.0 as u32 {
+ event.GetStatus()?.ok()?;
+ }
+ Ok(kind)
+ })
+ })
+ };
+ let _ = self.sender.send(event);
+ Ok(())
+ }
+ }
+
+ #[cfg(windows)]
+ unsafe fn global_interface_table()
+ -> windows::core::Result<windows::Win32::System::Com::IGlobalInterfaceTable> {
+ use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
+ const CLSID_STD_GLOBAL_INTERFACE_TABLE: windows::core::GUID =
+ windows::core::GUID::from_u128(0x00000323_0000_0000_c000_000000000046);
+ unsafe { CoCreateInstance(&CLSID_STD_GLOBAL_INTERFACE_TABLE, None, CLSCTX_INPROC_SERVER) }
+ }
+
+ #[cfg(windows)]
+ struct EncoderEvents {
+ generator: IMFMediaEventGenerator,
+ table: windows::Win32::System::Com::IGlobalInterfaceTable,
+ cookie: u32,
+ callback: IMFAsyncCallback,
+ receiver: std::sync::mpsc::Receiver<windows::core::Result<u32>>,
+ pending: bool,
+ }
+
+ #[cfg(windows)]
+ impl EncoderEvents {
+ fn new(generator: IMFMediaEventGenerator) -> windows::core::Result<Self> {
+ // SAFETY: registers the interface so the callback can retrieve it in its own apartment.
+ let table = unsafe { global_interface_table()? };
+ let cookie = unsafe {
+ table.RegisterInterfaceInGlobal(
+ &generator,
+ &<IMFMediaEventGenerator as windows::core::Interface>::IID,
+ )?
+ };
+ let (sender, receiver) = std::sync::mpsc::channel();
+ let callback = EncoderEventCallback { cookie, sender }.into();
+ Ok(Self { generator, table, cookie, callback, receiver, pending: false })
+ }
+
+ fn receive(&mut self, timeout: Duration) -> windows::core::Result<Option<u32>> {
+ if !self.pending {
+ // SAFETY: only one event request is pending at a time.
+ unsafe { self.generator.BeginGetEvent(&self.callback, None)? };
+ self.pending = true;
+ }
+ match self.receiver.recv_timeout(timeout) {
+ Ok(event) => {
+ self.pending = false;
+ event.map(Some)
+ }
+ Err(std::sync::mpsc::RecvTimeoutError::Timeout) => Ok(None),
+ Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => Err(E_INVALIDARG.into()),
+ }
+ }
+ }
+
+ #[cfg(windows)]
+ impl Drop for EncoderEvents {
+ fn drop(&mut self) {
+ // SAFETY: this cookie is owned by this registration and is revoked once.
+ let _ = unsafe { self.table.RevokeInterfaceFromGlobal(self.cookie) };
+ }
+ }
+
+ #[cfg(windows)]
+ pub(crate) struct ScreenEncoder {
+ codec: String,
transform: IMFTransform,
+ async_events: Option<EncoderEvents>,
+ pending_input: u32,
+ pending_output: u32,
/// The encoder's settings interface, when it has one: keyframes on demand and live
/// bitrate changes without rebuilding the encoder.
codec_api: Option<ICodecAPI>,
@@ -348,10 +555,11 @@ mod imp {
output_size: u32,
seq_header: Vec<u8>,
sent_first_frame: bool,
+ alternatives: Vec<IMFActivate>,
}
#[cfg(windows)]
- impl Drop for H264Encoder {
+ impl Drop for ScreenEncoder {
fn drop(&mut self) {
// SAFETY: flushes and ends streaming on the MFT before drop.
unsafe {
@@ -362,24 +570,68 @@ mod imp {
}
#[cfg(windows)]
- impl H264Encoder {
- pub(crate) fn new(width: u32, height: u32, fps: u32, bitrate: u32) -> windows::core::Result<Self> {
+ impl ScreenEncoder {
+ pub(crate) fn new_for_codec(
+ codec: &str,
+ width: u32,
+ height: u32,
+ fps: u32,
+ bitrate: u32,
+ ) -> windows::core::Result<Self> {
ensure_mf_started()?;
+ let subtype = match codec {
+ "h264" => MFVideoFormat_H264,
+ "h265" => MFVideoFormat_HEVC,
+ _ => return Err(windows::core::Error::from(E_INVALIDARG)),
+ };
+ create_video_encoder(subtype, |transform| {
+ Self::from_transform(codec, transform, width, height, fps, bitrate)
+ })
+ }
+
+ fn from_transform(
+ codec: &str,
+ transform: IMFTransform,
+ width: u32,
+ height: u32,
+ fps: u32,
+ bitrate: u32,
+ ) -> windows::core::Result<Self> {
// SAFETY: Media Foundation COM calls with valid parameters.
unsafe {
- let transform =
- create_mft(MFT_CATEGORY_VIDEO_ENCODER, MFVideoFormat_NV12, MFVideoFormat_H264)?;
- if let Ok(attrs) = transform.GetAttributes() {
+ let subtype = match codec {
+ "h264" => MFVideoFormat_H264,
+ "h265" => MFVideoFormat_HEVC,
+ _ => return Err(windows::core::Error::from(E_INVALIDARG)),
+ };
+ let attributes = transform.GetAttributes().ok();
+ let is_async = attributes
+ .as_ref()
+ .is_some_and(|attrs| attrs.GetUINT32(&MF_TRANSFORM_ASYNC).is_ok_and(|value| value != 0));
+ if is_async {
+ attributes
+ .as_ref()
+ .ok_or_else(|| windows::core::Error::from(E_INVALIDARG))?
+ .SetUINT32(&MF_TRANSFORM_ASYNC_UNLOCK, 1)?;
+ }
+ if let Some(attrs) = attributes.as_ref() {
let _ = attrs.SetUINT32(&MF_LOW_LATENCY, 1);
}
let out_type: IMFMediaType = MFCreateMediaType()?;
out_type.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;
- out_type.SetGUID(&MF_MT_SUBTYPE, &MFVideoFormat_H264)?;
- let _ = out_type.SetUINT32(
- &windows::Win32::Media::MediaFoundation::MF_MT_MPEG2_PROFILE,
- windows::Win32::Media::MediaFoundation::eAVEncH264VProfile_Base.0 as u32,
- );
+ out_type.SetGUID(&MF_MT_SUBTYPE, &subtype)?;
+ if codec == "h264" {
+ let _ = out_type.SetUINT32(
+ &windows::Win32::Media::MediaFoundation::MF_MT_MPEG2_PROFILE,
+ windows::Win32::Media::MediaFoundation::eAVEncH264VProfile_Base.0 as u32,
+ );
+ } else {
+ let _ = out_type.SetUINT32(
+ &windows::Win32::Media::MediaFoundation::MF_MT_MPEG2_PROFILE,
+ windows::Win32::Media::MediaFoundation::eAVEncH265VProfile_Main_420_8.0 as u32,
+ );
+ }
out_type.SetUINT32(&MF_MT_AVG_BITRATE, bitrate.clamp(500_000, 20_000_000))?;
out_type.SetUINT32(&MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive.0 as u32)?;
out_type.SetUINT64(&MF_MT_FRAME_SIZE, (u64::from(width) << 32) | u64::from(height))?;
@@ -411,19 +663,27 @@ mod imp {
let provides_samples = (info.dwFlags & (MFT_OUTPUT_STREAM_PROVIDES_SAMPLES.0 as u32)) != 0;
let output_size = info.cbSize.max(256 * 1024);
- // A keyframe every two seconds keeps late joiners and lost packets recoverable
- // without rebuilding the encoder, and low-latency mode stops it holding frames back.
+ // Periodic keyframes allow recovery after packet loss without restarting the encoder.
let codec_api: Option<ICodecAPI> = windows::core::Interface::cast(&transform).ok();
+ let async_events = if is_async {
+ Some(EncoderEvents::new(windows::core::Interface::cast(&transform)?)?)
+ } else {
+ None
+ };
if let Some(api) = codec_api.as_ref() {
let _ = api.SetValue(&CODECAPI_AVLowLatencyMode, &VARIANT::from(true));
let _ = api.SetValue(&CODECAPI_AVEncMPVGOPSize, &VARIANT::from(fps.max(1) * 2));
}
- let _ = transform.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0);
- let _ = transform.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
+ transform.ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0)?;
+ transform.ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0)?;
Ok(Self {
+ codec: codec.to_owned(),
transform,
+ async_events,
+ pending_input: 0,
+ pending_output: 0,
codec_api,
width,
height,
@@ -431,10 +691,24 @@ mod imp {
output_size,
seq_header,
sent_first_frame: false,
+ alternatives: Vec::new(),
})
}
}
+ fn next_encoder(&mut self, codec: &str, width: u32, height: u32, fps: u32, bitrate: u32) -> bool {
+ let candidates = std::mem::take(&mut self.alternatives);
+ match try_video_encoders(candidates, |transform| {
+ Self::from_transform(codec, transform, width, height, fps, bitrate)
+ }) {
+ Ok(encoder) => {
+ *self = encoder;
+ true
+ }
+ Err(_) => false,
+ }
+ }
+
/// Asks for the next frame to be a keyframe. False when the encoder can't, so the
/// caller must rebuild it instead.
pub(crate) fn request_keyframe(&self) -> bool {
@@ -453,26 +727,34 @@ mod imp {
}
/// Feeds one NV12 frame (`width * height * 3 / 2` bytes) and drains encoded
- /// Annex-B H.264 access units `(is_keyframe, bytes)`.
+ /// Annex-B H.264 or H.265 access units `(is_keyframe, bytes)`.
pub(crate) fn encode(
&mut self,
nv12: &[u8],
hns: i64,
dur_hns: i64,
+ stop: &AtomicBool,
) -> windows::core::Result<Vec<(bool, Vec<u8>)>> {
let expected = (self.width as usize) * (self.height as usize) * 3 / 2;
if nv12.len() < expected {
return Ok(Vec::new());
}
+ self.wait_for_async_event(METransformNeedInput.0 as u32, stop)?;
// SAFETY: Media Foundation sample creation and MFT ProcessInput/ProcessOutput.
unsafe {
let sample = make_sample(&nv12[..expected], hns, dur_hns)?;
let mut out = Vec::new();
match self.transform.ProcessInput(0, &sample, 0) {
- Ok(()) => self.drain(&mut out)?,
+ Ok(()) => {
+ self.wait_for_async_event(METransformHaveOutput.0 as u32, stop)?;
+ self.drain(&mut out)?;
+ }
Err(e) if e.code() == MF_E_NOTACCEPTING => {
+ self.wait_for_async_event(METransformHaveOutput.0 as u32, stop)?;
self.drain(&mut out)?;
+ self.wait_for_async_event(METransformNeedInput.0 as u32, stop)?;
self.transform.ProcessInput(0, &sample, 0)?;
+ self.wait_for_async_event(METransformHaveOutput.0 as u32, stop)?;
self.drain(&mut out)?;
}
Err(e) => return Err(e),
@@ -481,6 +763,39 @@ mod imp {
}
}
+ fn wait_for_async_event(&mut self, expected: u32, stop: &AtomicBool) -> windows::core::Result<()> {
+ let Some(events) = self.async_events.as_mut() else {
+ return Ok(());
+ };
+ let deadline = Instant::now() + Duration::from_secs(2);
+ loop {
+ if stop.load(Ordering::Relaxed) {
+ return Err(windows::core::Error::from(MF_E_OPERATION_CANCELLED));
+ }
+ let pending = if expected == METransformNeedInput.0 as u32 {
+ &mut self.pending_input
+ } else {
+ &mut self.pending_output
+ };
+ if *pending > 0 {
+ *pending -= 1;
+ return Ok(());
+ }
+ if Instant::now() >= deadline {
+ return Err(windows::core::Error::from(ERROR_TIMEOUT.to_hresult()));
+ }
+ let remaining = deadline.saturating_duration_since(Instant::now());
+ let Some(kind) = events.receive(remaining.min(Duration::from_millis(20)))? else {
+ continue;
+ };
+ if kind == METransformNeedInput.0 as u32 {
+ self.pending_input += 1;
+ } else if kind == METransformHaveOutput.0 as u32 {
+ self.pending_output += 1;
+ }
+ }
+ }
+
unsafe fn drain(&mut self, out: &mut Vec<(bool, Vec<u8>)>) -> windows::core::Result<()> {
loop {
// SAFETY: MFT output draining with allocated or MFT-provided sample.
@@ -516,9 +831,18 @@ mod imp {
let mut len = 0u32;
buf.Lock(&mut ptr, None, Some(&mut len))?;
let slice = std::slice::from_raw_parts(ptr, len as usize);
- let is_idr = !self.sent_first_frame || clean || has_h264_idr(slice);
+ let is_idr = !self.sent_first_frame
+ || clean
+ || match self.codec.as_str() {
+ "h265" => has_h265_irap(slice),
+ _ => has_h264_idr(slice),
+ };
let mut bytes = Vec::new();
- if is_idr && !has_h264_sps(slice) {
+ let has_parameters = match self.codec.as_str() {
+ "h265" => has_h265_parameters(slice),
+ _ => has_h264_sps(slice),
+ };
+ if is_idr && !has_parameters {
if self.seq_header.is_empty()
&& let Ok(cur_out) = self.transform.GetOutputCurrentType(0)
&& let Ok(hdr_len) = cur_out.GetBlobSize(&MF_MT_MPEG_SEQUENCE_HEADER)
@@ -543,6 +867,10 @@ mod imp {
out.push((is_idr, bytes));
}
}
+ // Each METransformHaveOutput event permits one ProcessOutput call.
+ if self.async_events.is_some() {
+ return Ok(());
+ }
}
Err(e) if e.code() == MF_E_TRANSFORM_NEED_MORE_INPUT => return Ok(()),
Err(e) if e.code() == MF_E_TRANSFORM_STREAM_CHANGE => {
@@ -593,6 +921,32 @@ mod imp {
data.windows(4).any(|w| w[..3] == [0, 0, 1] && (w[3] & 0x1f) == 7)
}
+ #[cfg(any(windows, test))]
+ fn hevc_nal_types(data: &[u8]) -> impl Iterator<Item = u8> + '_ {
+ data.windows(4).filter_map(|w| (w[..3] == [0, 0, 1]).then_some((w[3] >> 1) & 0x3f))
+ }
+
+ #[cfg(any(windows, test))]
+ fn has_h265_irap(data: &[u8]) -> bool {
+ hevc_nal_types(data).any(|kind| (16..=21).contains(&kind))
+ }
+
+ #[cfg(any(windows, test))]
+ fn has_h265_parameters(data: &[u8]) -> bool {
+ let mut vps = false;
+ let mut sps = false;
+ let mut pps = false;
+ for kind in hevc_nal_types(data) {
+ match kind {
+ 32 => vps = true,
+ 33 => sps = true,
+ 34 => pps = true,
+ _ => {}
+ }
+ }
+ vps && sps && pps
+ }
+
#[cfg(target_os = "linux")]
#[repr(C)]
struct SEncParamBase {
@@ -748,7 +1102,7 @@ mod imp {
}
#[cfg(target_os = "linux")]
- pub(crate) struct H264Encoder {
+ pub(crate) struct ScreenEncoder {
encoder: *mut std::ffi::c_void,
width: u32,
height: u32,
@@ -758,7 +1112,7 @@ mod imp {
}
#[cfg(target_os = "linux")]
- impl Drop for H264Encoder {
+ impl Drop for ScreenEncoder {
fn drop(&mut self) {
if !self.encoder.is_null() {
unsafe {
@@ -775,7 +1129,20 @@ mod imp {
}
#[cfg(target_os = "linux")]
- impl H264Encoder {
+ impl ScreenEncoder {
+ pub(crate) fn new_for_codec(
+ codec: &str,
+ width: u32,
+ height: u32,
+ fps: u32,
+ bitrate: u32,
+ ) -> Result<Self, String> {
+ if codec != "h264" {
+ return Err("Linux screen encoding supports H.264 only".into());
+ }
+ Self::new(width, height, fps, bitrate)
+ }
+
pub(crate) fn new(width: u32, height: u32, fps: u32, bitrate: u32) -> Result<Self, String> {
let api = openh264_enc_api().ok_or_else(|| "libopenh264 encoder unavailable".to_owned())?;
unsafe {
@@ -887,13 +1254,14 @@ mod imp {
nv12: &[u8],
hns: i64,
_dur_hns: i64,
+ stop: &AtomicBool,
) -> Result<Vec<(bool, Vec<u8>)>, String> {
let w = self.width as usize;
let h = self.height as usize;
let y_size = w * h;
let uv_size = y_size / 2;
let expected = y_size + uv_size;
- if nv12.len() < expected || self.encoder.is_null() {
+ if stop.load(Ordering::Relaxed) || nv12.len() < expected || self.encoder.is_null() {
return Ok(Vec::new());
}
@@ -1026,6 +1394,47 @@ mod imp {
}
}
+ #[cfg(windows)]
+ fn new_pc_encoder(
+ codec: &str,
+ width: u32,
+ height: u32,
+ fps: u32,
+ bitrate: u32,
+ ) -> Result<ScreenEncoder, String> {
+ ScreenEncoder::new_for_codec(codec, width, height, fps, bitrate).map_err(|error| error.to_string())
+ }
+
+ #[cfg(target_os = "linux")]
+ fn new_pc_encoder(
+ codec: &str,
+ width: u32,
+ height: u32,
+ fps: u32,
+ bitrate: u32,
+ ) -> Result<ScreenEncoder, String> {
+ ScreenEncoder::new_for_codec(codec, width, height, fps, bitrate)
+ }
+
+ #[cfg(any(windows, target_os = "linux"))]
+ fn new_pc_encoder_with_fallback(
+ codec: &mut String,
+ width: u32,
+ height: u32,
+ fps: u32,
+ bitrate: u32,
+ ) -> Result<ScreenEncoder, String> {
+ match new_pc_encoder(codec, width, height, fps, bitrate) {
+ Ok(encoder) => Ok(encoder),
+ Err(error) if codec == "h265" => {
+ tracing::info!(%error, "HEVC screen encoder unavailable; using H.264");
+ *codec = "h264".into();
+ new_pc_encoder(codec, width, height, fps, bitrate)
+ }
+ Err(error) => Err(error),
+ }
+ }
+
#[cfg(windows)]
fn primary_screen_dimensions() -> (u32, u32) {
// SAFETY: Win32 GDI device context and system metrics calls with balanced ReleaseDC.
@@ -1899,10 +2308,16 @@ mod imp {
let frame_interval = Duration::from_micros(1_000_000 / u64::from(fps));
let dur_hns = (10_000_000 / u64::from(fps)) as i64;
+ let mut codec = if node.mirror_codecs(peer).is_ok_and(|codecs| codecs.iter().any(|c| c == "h265")) {
+ "h265".to_owned()
+ } else {
+ "h264".to_owned()
+ };
+
let mut bgra = Vec::new();
let mut nv12 = Vec::new();
let mut stream_dims: Option<(u32, u32)> = None;
- let mut encoder: Option<H264Encoder> = None;
+ let mut encoder: Option<ScreenEncoder> = None;
let started = Instant::now();
let mut last_reinit = Instant::now() - Duration::from_secs(5);
let mut last_drop: Option<Instant> = None;
@@ -1977,17 +2392,17 @@ mod imp {
// stream config plus a full keyframe) is the fallback for encoders that can't.
let requested_kf = force_keyframe.swap(false, Ordering::SeqCst);
let keyframe_in_place =
- requested_kf && encoder.as_ref().is_some_and(H264Encoder::request_keyframe);
+ requested_kf && encoder.as_ref().is_some_and(ScreenEncoder::request_keyframe);
let need_reinit = encoder.is_none()
|| (requested_kf
&& !keyframe_in_place
&& last_reinit.elapsed() >= Duration::from_millis(1400));
if need_reinit {
- match H264Encoder::new(dst_w, dst_h, fps, bitrate) {
+ match new_pc_encoder_with_fallback(&mut codec, dst_w, dst_h, fps, bitrate) {
Ok(enc) => {
let cfg = MirrorConfig {
- codec: nectarlink_core::MIRROR_H264.into(),
+ codec: codec.clone(),
width: dst_w,
height: dst_h,
session: nectarlink_core::MIRROR_SCREEN,
@@ -2000,7 +2415,7 @@ mod imp {
stats.rebuilds += 1;
}
Err(e) => {
- tracing::warn!(error = %e, "PC mirror H.264 encoder init failed");
+ tracing::warn!(error = %e, codec, "PC mirror encoder init failed");
break;
}
}
@@ -2017,7 +2432,7 @@ mod imp {
bgra_to_nv12(&bgra, dst_w as usize, dst_h as usize, &mut nv12);
let time_us = started.elapsed().as_micros() as u64;
let hns = (time_us * 10) as i64;
- match enc.encode(&nv12, hns, dur_hns) {
+ match enc.encode(&nv12, hns, dur_hns, &stop) {
Ok(packets) => {
let mut send_failed = false;
for (is_keyframe, bytes) in packets {
@@ -2068,7 +2483,21 @@ mod imp {
}
}
Err(e) => {
- tracing::warn!(error = %e, "PC mirror frame encode error; rebuilding the encoder");
+ if stop.load(Ordering::Relaxed) {
+ break;
+ }
+ #[cfg(windows)]
+ if enc.next_encoder(&codec, dst_w, dst_h, fps, bitrate) {
+ tracing::warn!(error = %e, codec, "Video encoding failed; trying another encoder");
+ stats.rebuilds += 1;
+ continue;
+ }
+ if codec == "h265" {
+ tracing::warn!(error = %e, "HEVC screen encoding failed; using H.264");
+ codec = "h264".into();
+ } else {
+ tracing::warn!(error = %e, "PC mirror frame encode error; rebuilding the encoder");
+ }
encoder = None;
}
}
@@ -2168,6 +2597,44 @@ mod imp {
mod tests {
use super::*;
+ #[cfg(windows)]
+ #[test]
+ fn encoder_failures_advance_to_the_next_candidate() {
+ ensure_mf_started().unwrap();
+ let first = video_encoder_activations(MFVideoFormat_H264, None).unwrap().remove(0);
+ let second = video_encoder_activations(MFVideoFormat_H264, None).unwrap().remove(0);
+ let third = video_encoder_activations(MFVideoFormat_H264, None).unwrap().remove(0);
+ let mut attempts = 0;
+ let mut encoder = try_video_encoders(vec![first, second, third], |transform| {
+ attempts += 1;
+ if attempts == 1 {
+ return Err(windows::core::Error::from(E_INVALIDARG));
+ }
+ ScreenEncoder::from_transform("h264", transform, 320, 240, 30, 2_000_000)
+ })
+ .unwrap();
+ assert_eq!(attempts, 2);
+ let input = vec![128; 320 * 240 * 3 / 2];
+ let stop = AtomicBool::new(false);
+ let mut packets = 0;
+ for i in 0..8 {
+ packets += encoder.encode(&input, i * 333_333, 333_333, &stop).unwrap().len();
+ }
+ assert!(packets > 0);
+ assert!(encoder.next_encoder("h264", 320, 240, 30, 2_000_000));
+ let mut keys = 0;
+ for i in 0..8 {
+ keys += encoder
+ .encode(&input, i * 333_333, 333_333, &stop)
+ .unwrap()
+ .iter()
+ .filter(|(keyframe, _)| *keyframe)
+ .count();
+ }
+ assert!(keys > 0, "a replacement encoder starts with a keyframe");
+ assert!(!encoder.next_encoder("h264", 320, 240, 30, 2_000_000));
+ }
+
#[cfg(target_os = "linux")]
#[test]
fn wayland_capture_reads_the_stream_through_the_portal_connection() {
@@ -2190,6 +2657,85 @@ mod imp {
assert_eq!(nv12.len(), (w as usize) * (h as usize) * 3 / 2);
}
+ #[test]
+ fn recognizes_hevc_random_access_frames_and_parameter_sets() {
+ let headers = [
+ 0, 0, 0, 1, 0x40, 1, // VPS
+ 0, 0, 1, 0x42, 1, // SPS
+ 0, 0, 0, 1, 0x44, 1, // PPS
+ ];
+ let idr = [0, 0, 1, 0x26, 1]; // IDR_W_RADL, type 19
+ assert!(has_h265_parameters(&headers));
+ assert!(!has_h265_irap(&headers));
+ assert!(has_h265_irap(&idr));
+ assert!(!has_h265_parameters(&idr));
+ }
+
+ #[cfg(windows)]
+ #[test]
+ fn async_encoder_waits_time_out_and_honor_cancellation() {
+ let mut encoder = match ScreenEncoder::new_for_codec("h265", 1280, 720, 30, 2_000_000) {
+ Ok(encoder) if encoder.async_events.is_some() => encoder,
+ _ => {
+ eprintln!("No asynchronous HEVC encoder available");
+ return;
+ }
+ };
+ let stop = AtomicBool::new(false);
+ let cancelled = std::thread::scope(|scope| {
+ scope.spawn(|| {
+ std::thread::sleep(Duration::from_millis(50));
+ stop.store(true, Ordering::Relaxed);
+ });
+ encoder.wait_for_async_event(METransformHaveOutput.0 as u32, &stop).unwrap_err()
+ });
+ assert_eq!(cancelled.code(), MF_E_OPERATION_CANCELLED);
+
+ stop.store(false, Ordering::Relaxed);
+ // No frame has been submitted, so an output event cannot arrive.
+ let timeout = encoder.wait_for_async_event(METransformHaveOutput.0 as u32, &stop).unwrap_err();
+ assert_eq!(timeout.code(), ERROR_TIMEOUT.to_hresult());
+ }
+
+ #[test]
+ fn hevc_encoder_round_trips_when_available() {
+ let (w, h) = target_dimensions(1280, 720, 1280);
+ let mut enc = match ScreenEncoder::new_for_codec("h265", w, h, 30, 2_000_000) {
+ Ok(encoder) => encoder,
+ Err(error) => {
+ eprintln!("HEVC encoder unavailable: {error}");
+ return;
+ }
+ };
+ let mut dec = match crate::win::h264::Decoder::new_for_codec("h265") {
+ Ok(decoder) => decoder,
+ Err(error) => {
+ eprintln!("HEVC decoder unavailable: {error}");
+ return;
+ }
+ };
+ let nv12 = vec![128u8; (w as usize) * (h as usize) * 3 / 2];
+ let mut produced_packets = 0usize;
+ let mut decoded_picture = false;
+ let stop = AtomicBool::new(false);
+ for i in 0..8 {
+ for (keyframe, data) in enc
+ .encode(&nv12, i * 333_333, 333_333, &stop)
+ .unwrap_or_else(|error| panic!("encode HEVC frame {i}: {error}"))
+ {
+ produced_packets += 1;
+ if keyframe {
+ assert!(has_h265_irap(&data), "keyframes must contain an HEVC IRAP NAL");
+ assert!(has_h265_parameters(&data), "keyframes must carry VPS, SPS and PPS");
+ }
+ decoded_picture |=
+ !dec.decode(&data, i as u64 * 33_333).expect("decode packet").is_empty();
+ }
+ }
+ assert!(produced_packets > 0, "encoder must emit H.265 access units");
+ assert!(decoded_picture, "decoder must reconstruct an H.265 picture");
+ }
+
#[cfg(any(windows, target_os = "linux"))]
#[test]
fn encodes_nv12_frames_and_decodes_back() {
@@ -2197,7 +2743,7 @@ mod imp {
assert_eq!(w % 16, 0);
assert_eq!(h % 16, 0);
- let mut enc = H264Encoder::new(w, h, 30, 4_000_000).expect("H264Encoder");
+ let mut enc = new_pc_encoder("h264", w, h, 30, 4_000_000).expect("ScreenEncoder");
let mut dec = crate::win::h264::Decoder::new_for_codec("h264").expect("H264 Decoder");
let mut bgra = vec![0u8; (w as usize) * (h as usize) * 4];
@@ -2212,8 +2758,9 @@ mod imp {
let mut decoded_any = false;
let mut produced_packets = 0usize;
+ let stop = AtomicBool::new(false);
for i in 0..8 {
- let packets = enc.encode(&nv12, i * 333_333, 333_333).expect("encode frame");
+ let packets = enc.encode(&nv12, i * 333_333, 333_333, &stop).expect("encode frame");
for (_keyframe, data) in packets {
produced_packets += 1;
let pics = dec.decode(&data, (i as u64) * 33_333).expect("decode packet");
@@ -2225,7 +2772,7 @@ mod imp {
}
}
assert!(produced_packets > 0, "encoder must emit H.264 access units");
- assert!(decoded_any, "decoder must reconstruct at least one frame from H264Encoder");
+ assert!(decoded_any, "decoder must reconstruct at least one frame from ScreenEncoder");
}
/// With a Chromium browser showing a video on a page whose title has
@@ -2260,13 +2807,17 @@ mod imp {
#[test]
fn keyframes_come_on_request_without_rebuilding_the_encoder() {
let (w, h) = target_dimensions(1280, 720, 1280);
- let mut enc = H264Encoder::new(w, h, 30, 2_000_000).expect("H264Encoder");
+ #[cfg(windows)]
+ let mut enc = new_pc_encoder("h264", w, h, 30, 2_000_000).expect("ScreenEncoder");
+ #[cfg(target_os = "linux")]
+ let mut enc = ScreenEncoder::new(w, h, 30, 2_000_000).expect("OpenH264");
let mut nv12 = Vec::new();
bgra_to_nv12(&vec![128u8; (w as usize) * (h as usize) * 4], w as usize, h as usize, &mut nv12);
+ let stop = AtomicBool::new(false);
- let keyframes_after = |enc: &mut H264Encoder, start: i64, count: i64| {
+ let keyframes_after = |enc: &mut ScreenEncoder, start: i64, count: i64| {
(start..start + count)
- .flat_map(|i| enc.encode(&nv12, i * 333_333, 333_333).expect("encode frame"))
+ .flat_map(|i| enc.encode(&nv12, i * 333_333, 333_333, &stop).expect("encode frame"))
.filter(|(keyframe, data)| *keyframe && has_h264_idr(data))
.count()
};
diff --git a/desktop/app/src/webcam.rs b/desktop/app/src/webcam.rs
index ee85bc8..834d02b 100644
--- a/desktop/app/src/webcam.rs
+++ b/desktop/app/src/webcam.rs
@@ -1,25 +1,11 @@
// SPDX-License-Identifier: GPL-3.0-or-later
-//! Phone as a webcam (`docs/protocol/webcam.md`): decodes a phone's H.264
-//! camera stream on a dedicated thread, publishes shared GPU NV12 textures or
-//! fallback BGRX frames into the mapping read by `nectarlink_vcam.dll` (the global one the
-//! camera creates inside Windows' Frame Server, or this session's while it
-//! isn't there), and feeds the live preview `VideoView` (`stream:
-//! "webcam"`) in Settings.
+//! Decodes a phone's H.264 or HEVC camera stream on a dedicated thread.
+//! Publishes NV12 GPU textures or BGRX frames to the virtual camera and feeds
+//! the Settings preview through `VideoView` (stream `webcam`).
//!
-//! ## 4K (3840×2160) Support & Why 10-bit HDR Is Omitted
-//!
-//! End-to-end 4K UHD (`3840×2160` @ 30 fps) is supported across the phone
-//! camera encoder, the desktop H.264 decoder, the shared-memory frame
-//! transport (`nectarlink-vcam` v2), and the Media Foundation virtual camera
-//! source (`RGB32` and `NV12`).
-//!
-//! 10-bit HDR (`P010` / BT.2020 PQ or HLG) is intentionally omitted: Windows'
-//! inbox H.264 Media Foundation Transform (`CLSID_CMSH264DecoderMFT`) decodes
-//! 8-bit 4:2:0 profiles into 8-bit `NV12` (`MFVideoFormat_NV12`), and the
-//! shared-memory virtual camera pipeline operates in 8-bit-per-channel SDR
-//! Rec.709 (`BGRX` / `MFVideoFormat_RGB32` and `MFVideoFormat_NV12` with
-//! `MFVideoTransferMatrix_BT709`) for universal compatibility with conferencing
-//! apps.
+//! The transport supports up to 3840×2160 in 8-bit SDR. HDR would require
+//! P010 surfaces, BT.2020 color handling, and HDR metadata throughout the pipeline.
+//! See `docs/protocol/webcam.md`.
use std::{
sync::{
@@ -717,19 +703,17 @@ pub fn supports_hevc() -> bool {
*SUPPORTED.get_or_init(|| match Decoder::new_gpu("h265") {
Ok(decoder) => {
let supported = decoder.on_gpu();
- tracing::info!(supported, "HEVC webcam decoder probe");
+ tracing::info!(supported, "HEVC decoder probe");
supported
}
Err(error) => {
- tracing::info!(%error, "HEVC webcam decoder unavailable; advertising H.264 only");
+ tracing::info!(%error, "HEVC decoder unavailable");
false
}
})
}
fn decode(device: DeviceId, items: &Receiver<Item>, waiting: &AtomicUsize) {
- // On the GPU when there is one: 4K takes about 24 ms a frame in software
- // and 11 ms on a GPU, against 33 ms per frame at 30 fps.
let mut decoder = match Decoder::new_gpu("h264") {
Ok(decoder) => decoder,
Err(e) => {
diff --git a/desktop/app/src/win/h264.rs b/desktop/app/src/win/h264.rs
index 436bf48..f927d68 100644
--- a/desktop/app/src/win/h264.rs
+++ b/desktop/app/src/win/h264.rs
@@ -10,13 +10,19 @@ use windows::{
Win32::{
Foundation::E_FAIL,
Graphics::{
- Direct3D::D3D_DRIVER_TYPE_HARDWARE,
+ Direct3D::D3D_DRIVER_TYPE_UNKNOWN,
Direct3D11::{
- D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_VIDEO_SUPPORT, D3D11_MAP_READ,
- D3D11_MAPPED_SUBRESOURCE, D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING,
- D3D11CreateDevice, ID3D11Device, ID3D11Multithread, ID3D11Texture2D,
+ D3D11_CPU_ACCESS_READ, D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
+ D3D11_DECODER_PROFILE_AV1_VLD_PROFILE0, D3D11_DECODER_PROFILE_H264_VLD_NOFGT,
+ D3D11_DECODER_PROFILE_HEVC_VLD_MAIN, D3D11_MAP_READ, D3D11_MAPPED_SUBRESOURCE,
+ D3D11_SDK_VERSION, D3D11_TEXTURE2D_DESC, D3D11_USAGE_STAGING, D3D11CreateDevice,
+ ID3D11Device, ID3D11Multithread, ID3D11Texture2D, ID3D11VideoDevice,
+ },
+ Dxgi::{
+ Common::{DXGI_FORMAT_NV12, DXGI_SAMPLE_DESC},
+ CreateDXGIFactory1, DXGI_ADAPTER_FLAG_SOFTWARE, DXGI_ERROR_NOT_FOUND, IDXGIAdapter1,
+ IDXGIFactory1,
},
- Dxgi::Common::DXGI_SAMPLE_DESC,
},
Media::MediaFoundation::{
CLSID_MSH264DecoderMFT, CODECAPI_AVDecNumWorkerThreads, IMF2DBuffer, IMFActivate, IMFDXGIBuffer,
@@ -151,14 +157,53 @@ pub(crate) fn create_mft(
}
}
-/// A Direct3D 11 device on the default GPU, shared with Media Foundation.
-fn gpu_device_manager() -> windows::core::Result<IMFDXGIDeviceManager> {
+pub(crate) struct VideoAdapter {
+ pub luid: u64,
+ pub adapter: IDXGIAdapter1,
+}
+
+struct GpuDevice {
+ adapter_luid: u64,
+ manager: IMFDXGIDeviceManager,
+}
+
+pub(crate) fn video_adapters() -> windows::core::Result<Vec<VideoAdapter>> {
+ // SAFETY: enumeration returns owned COM interfaces; no raw pointers escape.
+ unsafe {
+ let factory: IDXGIFactory1 = CreateDXGIFactory1()?;
+ let mut adapters = Vec::new();
+ for index in 0.. {
+ let adapter = match factory.EnumAdapters1(index) {
+ Ok(adapter) => adapter,
+ Err(error) if error.code() == DXGI_ERROR_NOT_FOUND => break,
+ Err(error) => return Err(error),
+ };
+ let desc = match adapter.GetDesc1() {
+ Ok(desc) => desc,
+ Err(error) => {
+ tracing::debug!(%error, index, "Video adapter description unavailable");
+ continue;
+ }
+ };
+ if desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32 != 0 {
+ continue;
+ }
+ adapters.push(VideoAdapter {
+ luid: u64::from(desc.AdapterLuid.LowPart) | ((desc.AdapterLuid.HighPart as u64) << 32),
+ adapter,
+ });
+ }
+ Ok(adapters)
+ }
+}
+
+fn gpu_device_manager(adapter: &VideoAdapter, codec: &str) -> windows::core::Result<IMFDXGIDeviceManager> {
// SAFETY: plain Direct3D and Media Foundation calls with owned values.
unsafe {
let mut device: Option<ID3D11Device> = None;
D3D11CreateDevice(
- None,
- D3D_DRIVER_TYPE_HARDWARE,
+ &adapter.adapter,
+ D3D_DRIVER_TYPE_UNKNOWN,
Default::default(),
D3D11_CREATE_DEVICE_VIDEO_SUPPORT,
None,
@@ -168,6 +213,15 @@ fn gpu_device_manager() -> windows::core::Result<IMFDXGIDeviceManager> {
None,
)?;
let device = device.ok_or_else(|| windows::core::Error::from(E_FAIL))?;
+ let video: ID3D11VideoDevice = device.cast()?;
+ let profile = match codec {
+ "h265" => D3D11_DECODER_PROFILE_HEVC_VLD_MAIN,
+ "av1" => D3D11_DECODER_PROFILE_AV1_VLD_PROFILE0,
+ _ => D3D11_DECODER_PROFILE_H264_VLD_NOFGT,
+ };
+ if !video.CheckVideoDecoderFormat(&profile, DXGI_FORMAT_NV12)?.as_bool() {
+ return Err(windows::core::Error::from(E_FAIL));
+ }
// The decoder uses the device from its own threads.
if let Ok(multithread) = device.cast::<ID3D11Multithread>() {
let _ = multithread.SetMultithreadProtected(true);
@@ -194,7 +248,8 @@ pub struct Decoder {
codec: String,
transform: IMFTransform,
/// The GPU the decoder uses, kept alive with it; `None` when it decodes in software.
- gpu: Option<IMFDXGIDeviceManager>,
+ gpu: Option<GpuDevice>,
+ failed_adapters: Vec<u64>,
/// Where GPU pictures are copied to be read, reused while the size stays.
staging: Option<(ID3D11Texture2D, D3D11_TEXTURE2D_DESC)>,
/// The decoded size, as the output type says (padded).
@@ -227,15 +282,12 @@ impl Decoder {
/// A low-latency software decoder for `"h264"`, `"h265"`, or `"av1"`, for
/// the calling thread (which it stays on).
pub fn new_for_codec(codec: &str) -> windows::core::Result<Decoder> {
- Self::create(codec, false)
+ Self::create_with_manager(codec, None)
}
- /// As [`Decoder::new_for_codec`], decoding on the GPU when the PC can
- /// (4K H.264 takes about 60 ms a frame in software, far over a 30 fps
- /// frame's 33 ms). Falls back to software when it can't, here or later
- /// in the stream (see [`Decoder::decode`]).
+ /// Tries hardware adapters in DXGI order, then falls back to software.
pub fn new_gpu(codec: &str) -> windows::core::Result<Decoder> {
- Self::create(codec, true).or_else(|e| {
+ Self::create_hardware(codec, &[]).or_else(|e| {
tracing::info!(error = %e, "no GPU video decoding; decoding in software");
Self::new_for_codec(codec)
})
@@ -246,7 +298,45 @@ impl Decoder {
self.gpu.is_some()
}
- fn create(codec: &str, gpu: bool) -> windows::core::Result<Decoder> {
+ fn create_hardware(codec: &str, excluded: &[u64]) -> windows::core::Result<Decoder> {
+ ensure_mf_started()?;
+ let mut last_error = windows::core::Error::from(E_FAIL);
+ for adapter in video_adapters()? {
+ if excluded.contains(&adapter.luid) {
+ continue;
+ }
+ let result = gpu_device_manager(&adapter, codec).and_then(|manager| {
+ Self::create_with_manager(codec, Some(GpuDevice { adapter_luid: adapter.luid, manager }))
+ });
+ match result {
+ Ok(mut decoder) => {
+ decoder.failed_adapters = excluded.to_vec();
+ tracing::info!(codec, adapter = adapter.luid, "GPU video decoder initialized");
+ return Ok(decoder);
+ }
+ Err(error) => {
+ tracing::debug!(%error, codec, adapter = adapter.luid, "GPU decoder unavailable on adapter");
+ last_error = error;
+ }
+ }
+ }
+ Err(last_error)
+ }
+
+ fn recover_gpu(&mut self) {
+ let Some(gpu) = &self.gpu else { return };
+ let mut excluded = self.failed_adapters.clone();
+ excluded.push(gpu.adapter_luid);
+ let replacement = Self::create_hardware(&self.codec, &excluded).or_else(|_| {
+ tracing::info!(codec = self.codec, "GPU adapters exhausted; decoding in software");
+ Self::new_for_codec(&self.codec)
+ });
+ if let Ok(decoder) = replacement {
+ *self = decoder;
+ }
+ }
+
+ fn create_with_manager(codec: &str, gpu: Option<GpuDevice>) -> windows::core::Result<Decoder> {
// SAFETY: plain COM and Media Foundation calls with owned values.
unsafe {
ensure_mf_started()?;
@@ -264,26 +354,22 @@ impl Decoder {
CoCreateInstance(&CLSID_MSH264DecoderMFT, None, CLSCTX_INPROC_SERVER)?,
),
};
- // One picture in, one out: no reordering delay, single worker thread.
+ // Avoid decoder worker-thread and buffering overhead for low-latency streams.
let attributes = transform.GetAttributes().ok();
if let Some(attributes) = &attributes {
let _ = attributes.SetUINT32(&MF_LOW_LATENCY, 1);
let _ = attributes.SetUINT32(&CODECAPI_AVDecNumWorkerThreads, 1);
}
- // The GPU, before any media type is set.
- let gpu = if gpu {
+ // Media Foundation needs the D3D manager before media types are set.
+ if let Some(gpu) = &gpu {
let aware = attributes
.as_ref()
.is_some_and(|a| a.GetUINT32(&MF_SA_D3D11_AWARE).is_ok_and(|v| v != 0));
if !aware {
return Err(windows::core::Error::from(E_FAIL));
}
- let manager = gpu_device_manager()?;
- transform.ProcessMessage(MFT_MESSAGE_SET_D3D_MANAGER, manager.as_raw() as usize)?;
- Some(manager)
- } else {
- None
- };
+ transform.ProcessMessage(MFT_MESSAGE_SET_D3D_MANAGER, gpu.manager.as_raw() as usize)?;
+ }
let input = MFCreateMediaType()?;
input.SetGUID(&MF_MT_MAJOR_TYPE, &MFMediaType_Video)?;
input.SetGUID(&MF_MT_SUBTYPE, &subtype)?;
@@ -298,6 +384,7 @@ impl Decoder {
codec: codec.to_owned(),
transform,
gpu,
+ failed_adapters: Vec::new(),
staging: None,
coded: (0, 0),
provides_samples: false,
@@ -347,9 +434,8 @@ impl Decoder {
}
/// Decodes one access unit (Annex B); returns the pictures it completed.
- /// If decoding on the GPU fails, the decoder switches to software for the
- /// rest of the stream and returns the error: the caller starts over from
- /// the next keyframe, as after any decoding error.
+ /// On a GPU failure, tries another adapter before software. The error is
+ /// returned so the caller can request a keyframe for the replacement decoder.
pub fn decode(&mut self, data: &[u8], time_us: u64) -> windows::core::Result<Vec<Picture>> {
let frames = self.decode_frames(data, time_us)?;
frames.iter().map(|frame| self.read_frame(frame)).collect()
@@ -359,12 +445,8 @@ impl Decoder {
/// decoded even when the caller discards their output to catch up.
pub fn decode_frames(&mut self, data: &[u8], time_us: u64) -> windows::core::Result<Vec<DecodedFrame>> {
let result = self.decode_on(data, time_us);
- if result.is_err()
- && self.gpu.is_some()
- && let Ok(software) = Self::create(&self.codec, false)
- {
- tracing::info!("GPU video decoding failed; decoding in software");
- *self = software;
+ if result.is_err() && self.gpu.is_some() {
+ self.recover_gpu();
}
result
}
@@ -457,12 +539,8 @@ impl Decoder {
pub fn read_frame(&mut self, frame: &DecodedFrame) -> windows::core::Result<Picture> {
let result = self.picture(frame);
- if result.is_err()
- && self.gpu.is_some()
- && let Ok(software) = Self::create(&self.codec, false)
- {
- tracing::info!("GPU video readback failed; decoding in software");
- *self = software;
+ if result.is_err() && self.gpu.is_some() {
+ self.recover_gpu();
}
result
}
@@ -657,6 +735,22 @@ fn clamp(v: i32) -> u8 {
mod tests {
use super::*;
+ #[test]
+ fn gpu_recovery_excludes_the_failed_adapter_and_resumes_at_a_keyframe() {
+ let Ok(mut decoder) = Decoder::create_hardware("h264", &[]) else { return };
+ let failed = decoder.gpu.as_ref().unwrap().adapter_luid;
+ decoder.recover_gpu();
+ if let Some(gpu) = &decoder.gpu {
+ assert_ne!(gpu.adapter_luid, failed);
+ assert!(decoder.failed_adapters.contains(&failed));
+ }
+ let mut pictures = 0;
+ for (i, unit) in test_stream("h264").iter().enumerate() {
+ pictures += decoder.decode(unit, i as u64 * 33_333).unwrap().len();
+ }
+ assert_eq!(pictures, 10);
+ }
+
#[test]
fn gpu_frames_can_be_discarded_without_readback_then_materialized() {
let mut decoder = Decoder::new_gpu("h264").unwrap();
diff --git a/docs/protocol/capabilities.md b/docs/protocol/capabilities.md
index e4b9287..9580add 100644
--- a/docs/protocol/capabilities.md
+++ b/docs/protocol/capabilities.md
@@ -57,6 +57,7 @@ capability is missing.
| `photos.read` | Announces new photos and screenshots, lists albums and items, serves thumbnails, and sends files on request ([photos](photos.md)) | photos permission |
| `elevated.usb` | Starts a USB-connected phone's Elevated helper over adb ([Elevated over USB](elevated-usb.md)) | adb on the PC |
| `mirror.capture` | Streams its screen (with the system's capture prompt at Basic; [mirroring](mirror.md)) | app update |
+| `mirror.decode.hevc` | Decodes H.265 screen-mirroring streams | app update |
| `mirror.input` | Accepts touch, key and scroll input while mirrored | Assist |
| `mirror.virtual_display` | Runs apps on displays of their own, shown in windows on the PC ([mirroring](mirror.md)) | Elevated, Android 11+ |
| `mirror.audio` | Streams all audio while mirrored | Elevated |
diff --git a/docs/protocol/mirror.md b/docs/protocol/mirror.md
index 4f34df9..916c482 100644
--- a/docs/protocol/mirror.md
+++ b/docs/protocol/mirror.md
@@ -4,7 +4,8 @@
> allowed until v1. License: CC BY 4.0.
A PC shows a phone's screen. The phone's user agrees each time (Android
-asks); the phone then streams its screen as H.264 on a stream of its own,
+asks); the phone then streams its screen as H.264 or, when both sides support
+it, H.265 on a stream of its own,
and its sound, when the PC asks, on another (§5). The PC can also use the
phone with its mouse and keyboard (§4), and open the phone's apps in
windows of their own (§6).
@@ -15,6 +16,7 @@ windows of their own (§6).
|---|---|---|
| `mirror.capture` | phone | Shares its screen when its user agrees |
| `mirror.view` | PC | Shows a phone's screen |
+| `mirror.decode.hevc` | PC or phone | Decodes H.265 screen-mirroring streams |
| `mirror.input` | phone | Takes the PC's mouse and keyboard while mirrored (Assist: an accessibility service the user turns on; Elevated: injected input) |
| `mirror.audio.playback` | phone | Shares the sound of apps that allow it while mirrored (Android 10+) |
| `mirror.audio` | phone | Shares all its sound while mirrored (planned, Elevated) |
@@ -84,14 +86,19 @@ u64 time // capture time in microseconds, big-endian (only differences mean
data
```
-- **config**: the stream's format, CBOR `{ codec: "h264", width: uint,
+- **config**: the stream's format, CBOR `{ codec: "h264" | "h265", width: uint,
height: uint }`. First, and again whenever it changes (the phone turned).
-- **frame**: one H.264 access unit (Annex B) that depends on earlier ones.
-- **keyframe**: an access unit that starts fresh (an IDR picture), with its
- SPS and PPS before it.
+- **frame**: one H.264 or H.265 access unit (Annex B) that depends on earlier ones.
+- **keyframe**: an access unit that starts fresh (an IDR/IRAP picture), with
+ the codec's parameter sets before it (SPS/PPS for H.264; VPS/SPS/PPS for H.265).
Packets are at most 8 MiB. Video is BT.709, limited range.
+The PC can also send its screen to the phone using the same packet format.
+It uses H.265 when the phone advertises `mirror.decode.hevc` and the PC's
+HEVC encoder starts successfully; otherwise it uses H.264. If the codec changes
+during a stream, the sender sends a new config packet.
+
## 4. Input
```
diff --git a/docs/technical/screen-video.md b/docs/technical/screen-video.md
new file mode 100644
index 0000000..d7ad662
--- /dev/null
+++ b/docs/technical/screen-video.md
@@ -0,0 +1,9 @@
+# Screen video implementation
+
+Windows uses Media Foundation for screen encoding and video decoding. It checks
+each adapter's decoder profile and enumerates screen encoders for that adapter's
+LUID. Screen mirroring and the webcam share decoder selection; webcam textures
+retain their producer's adapter LUID when passed to the virtual camera.
+
+When decoding switches devices, the receiver requests a keyframe before
+resuming.