Files
piik/internal/app/nativecontrol/session_test.go
T
AAA 499789671c feat(app): bring Android sharing and touch control into the shared runtime (#504)
## Problem and outcome / 问题与结果

Bring Android into Piik's shared App workflow and make phone control usable without a separate Web UI. One signed APK covers ARM64 and x64; screen capture, room authority, routing, voice and site approval reuse the existing Go and Browser owners. Android opens the user's system browser rather than shipping an embedded browser.

This phase also fixes capture replacement and encoding-clock failures, improves source-audio startup, contains recoverable input and transport failures, adds a bounded relay-volunteer setting and supports hostnames in `SFU_PUBLIC_IP`. The website separates desktop and mobile downloads, gives iOS users an online entry and aligns the bilingual installation guides.

Related reports: #495, #499, #500, #501, #502 and #503. For #502, input execution failures now preserve authorization, and temporary target observations suspend rather than revoke it; the original Windows report remains open for candidate feedback.

## Release notes

**Piik, now in your pocket.**

Piik App now supports Android screen sharing, with touch controls for a friend's computer.

**手机,也能开播。**

Piik App 现已支持 Android 屏幕分享,也能用手机控制朋友的电脑。

### English

Piik v2.5.0 brings the App to Android and improves capture reliability, touch control and everyday startup. The existing 2.x compatibility baseline is unchanged.

- **Android App:** share your screen, join room voice or control a supported computer. One APK supports ARM64 and x64, using your own browser and the same Piik interface.
- **Phone controls:** use direct touch or a compact floating mouse with dragging, left/right buttons and a scroll wheel. Pinch to zoom and pan the picture while controlling.
- **More reliable sharing:** keep video progressing through source and encoder-output changes, and improve low-bitrate recovery and stationary-screen keyframes. Correct Windows window-size handling and Linux NVENC settings; start optional source sound after video is ready.
- **Smoother App entry:** retry failed startup in place, reopen the running room and retain the correct App connection when returning from the browser. Compress shared page assets to reduce loading traffic and keep microphone choices stable during ordinary page updates.
- **Recovery stays local:** a rejected input or canceled source replacement no longer revokes remote-control permission. Full ICE candidate queues and failed audio-parameter updates retain healthy connections. A failed local room leaves the App and unrelated approved sites running.
- **Connection settings:** relay volunteers can cap their downstream viewers. Self-hosted SFU setups can use a DNS hostname in `SFU_PUBLIC_IP`.
- **Clearer help:** refine sharing-error guidance, preserve input-failure diagnostics without recording input content, and update the bilingual platform and network guides.

Update both the App and your self-hosted site to use the new features. Android can control a supported computer; the Android device itself is not a controlled endpoint.

If you previously installed a test APK, uninstall it once before installing this release: the official signing key is different. Uninstalling clears App-local site approvals and starred-site choices; browser settings remain in the browser. Later official releases can be installed over this one.

### 中文

Piik v2.5.0 带来 Android App,并改善采集稳定性、手机远控与日常启动体验。沿用现有 2.x 兼容基线。

- **Android App:** 分享手机画面、加入房间语音,或控制支持远控的电脑。一个安装包同时支持 ARM64 与 x64,使用自己的浏览器和熟悉的 Piik 界面。
- **手机远控:** 直接触摸操作,或展开小巧的悬浮鼠标,使用拖拽、左右键与滚轮;控制时也能双指缩放、移动画面。
- **分享更稳定:** 修复切换采集来源、编码输出时画面停止推进的问题,改善低码率恢复与静止画面的关键帧响应。修正 Windows 窗口尺寸处理和 Linux NVENC 设置,来源声音会在画面就绪后启动。
- **App 进出更顺畅:** 启动失败可原地重试,再次打开会回到正在运行的房间;从浏览器返回时保持连接到正确的 App。共用页面资源启用压缩,减少加载流量,麦克风选项不再随普通页面更新反复加载。
- **局部问题就地恢复:** 单次操作失败或取消换源不再撤销远控授权;ICE 候选队列满或音频参数调整失败时保留健康连接。本地房间故障不会连带停止 App 和其他已授权站点的分享。
- **连接设置:** 帮助转发的观众可设置承接人数上限;自部署 SFU 的 `SFU_PUBLIC_IP` 现在支持 DNS 主机名。
- **排查更直接:** 打磨分享失败提示,补充不记录输入内容的远控故障诊断,并更新中英文平台说明与网络指南。

使用新功能时,请一起更新 App 与自部署站点。Android 可作为控制端操作电脑,手机本身不作为被控端。

曾安装测试 APK 的用户需先卸载一次,再安装正式版,两者签名不同。卸载会清除 App 内的站点授权和收藏,浏览器设置仍保留在浏览器中;后续正式版可直接覆盖安装。

## Verification / 验证

- Local full Web/type/build checks passed: 104 test files, 1,848 tests; the website and documentation builds passed.
- Android full-App emulator acceptance covered real decoded screen sharing, concurrent 1080p/540p encoder allocation, live bitrate changes, stationary keyframes, Viewer departure, consent reuse/reentry and final capture-resource retirement.
- A local universal release APK passed signing, package identity, version-code, ABI and non-debuggable checks using the permanent release key. GitHub Actions receives the same key through encrypted Secrets; manual candidate runs use a disposable candidate signer.
- Windows real capture checks covered H264/VP8 window resizing and restoration. Source-audio startup and failure/close ordering passed focused runtime checks; Linux race checks passed.
- Desktop/mobile website layouts were reviewed in English and Chinese, both themes, including grouped downloads, the iOS online entry and self-hosting links.
- All three Server and six App candidate targets, including the signed Android universal APK, passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40350004792. This uses the same release packaging path with publication disabled.
- The complete network laboratory passed in https://github.com/TNTcraftHIM/Piik/actions/runs/40354253735: 43 expected scenario outcomes (37 media connections, six expected-unavailable controls), six negative controls, and complete process/network cleanup.
- Recoverable-error checks cover real encrypted input replies and legacy opt-in, retained grants and held-key cleanup, real Windows target geometry recovery, candidate queue overflow, and audio-parameter retry on the existing edge. Android room failure and full shutdown use real launcher, control WebSocket and supervised-process checks; unrelated site resources remain intact.
- The lifecycle fixes at `7eb04de373567cfe7aff2db6c93adf2a38e0b1aa` passed all nine package targets and Go/vulnerability/race/Web checks in https://github.com/TNTcraftHIM/Piik/actions/runs/40362794088, including macOS x64/ARM64 cgo and Android. Publication was skipped.
- Final cross-review found and fixed the same candidate-overflow false failure in the SFU voice owner. Its real-Pion regression verifies the first 64 candidates remain queued, a valid answer drains them, and renegotiation succeeds. Independent reviews confirmed real SDP and authorization failures still propagate.
- A real-browser before/after check reduced microphone enumeration from nine calls to one across eight ordinary Host rerenders. Changing the native client or switching to Browser capture still enumerates the new devices. The separate focused contribution #507 preserves input focus during queued floating-panel opening and is not attributed to this phase.
- The verified Windows candidate and reproduction steps have been updated in #502. macOS/Linux physical-device coverage and iOS device acceptance keep their documented boundaries.

## Impact / 影响

- Planned release: **v2.5.0**; no public wire or storage version bump.
- Android is a sharing and controlling endpoint, not a remotely controlled Android device. iOS is held outside this release.
- New Android release target joins the existing complete-target, checksum, GitHub and Gitee artifact pipeline. Signing material stays outside Git; optional input SDKs/drivers are not bundled.
- The owner authorized closure and publication after the final design review and acceptance checks. Restore the publication gate after the held focused contribution and merge this complete phase once; CI publishes only after its full checks and registered packages pass.
- Current TODO, platform guidance, media/routing evidence and release operations retain their existing document owners; no additional audit ledger or changelog archive is introduced.
2026-10-26 13:37:33 -04:00

848 lines
33 KiB
Go

package nativecontrol
import (
"bytes"
"context"
"encoding/binary"
"encoding/json"
"io"
"log/slog"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"testing"
"time"
"github.com/TNTcraftHIM/Piik/internal/app/loopback"
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
"github.com/TNTcraftHIM/Piik/internal/app/nativehost"
"github.com/TNTcraftHIM/Piik/internal/app/remoteinput"
"github.com/TNTcraftHIM/Piik/internal/server/protocol"
"github.com/pion/webrtc/v4"
)
// Production responses may arrive through Events while the command loop keeps
// processing ICE, ping and stop. Tests wait only for this exact request ID.
func deliveredControlValue(value any) any {
if event, ok := value.(loopback.ControlEvent); ok {
if event.Current != nil && !event.Current() {
return nil
}
if event.BeforeWrite != nil {
event.BeforeWrite()
}
return event.Value
}
return value
}
func awaitControlResponse(t *testing.T, session *Session, payload []byte) (any, error) {
t.Helper()
value, err := session.Handle(t.Context(), payload)
if value != nil || err != nil {
return value, err
}
var request requestEnvelope
if err := json.Unmarshal(payload, &request); err != nil {
t.Fatal(err)
}
deadline := time.NewTimer(5 * time.Second)
defer deadline.Stop()
for {
select {
case value := <-session.Events():
value = deliveredControlValue(value)
encoded, _ := json.Marshal(value)
var envelope responseEnvelope
_ = json.Unmarshal(encoded, &envelope)
if envelope.ID == request.ID {
return value, nil
}
case <-deadline.C:
t.Fatalf("request %s lost its response", request.ID)
}
}
}
func TestReceiveOfferReusePreservesLegacyResponseShape(t *testing.T) {
peer, err := webrtc.NewPeerConnection(webrtc.Configuration{})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = peer.Close() })
if _, err = peer.AddTransceiverFromKind(webrtc.RTPCodecTypeVideo,
webrtc.RTPTransceiverInit{Direction: webrtc.RTPTransceiverDirectionSendonly}); err != nil {
t.Fatal(err)
}
offer, err := peer.CreateOffer(nil)
if err != nil {
t.Fatal(err)
}
session := New("", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
for _, reuse := range []bool{false, true} {
request := receiveOfferRequest{Version: 10, ID: "request_offer", Type: "receive-offer", ShareID: "viewer_session",
ConnectionID: "connection_1234", EdgeCapacity: 2, SDP: offer.SDP, ReuseReceiver: reuse}
payload, _ := json.Marshal(request)
value, err := session.Handle(t.Context(), payload)
if err != nil {
t.Fatal(err)
}
answer, ok := value.(receiveAnswerResponse)
if !ok {
t.Fatalf("receive offer returned %#v", value)
}
encoded, _ := json.Marshal(answer)
if bytes.Contains(encoded, []byte(`"reused"`)) != reuse {
t.Fatalf("new response field leaked across opt-in: %s", encoded)
}
if reuse && (answer.Reused == nil || !*answer.Reused) {
t.Fatal("opted-in answer did not retain its receiver")
}
}
}
func TestRemoteStopShortcutRequiresAnOwnedShare(t *testing.T) {
session := New("", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
for _, command := range []string{"get-remote-stop-shortcut", "set-remote-stop-shortcut"} {
key := 0
if command == "set-remote-stop-shortcut" {
key = 9
}
request := remoteStopShortcutRequest{requestEnvelope: requestEnvelope{Version: 10, ID: "request_shortcut", Type: command}, ShareID: "retired_share", Key: key}
payload, _ := json.Marshal(request)
result, err := session.Handle(t.Context(), payload)
if _, ok := result.(requestFailedResponse); !ok || err != nil {
t.Fatalf("missing share must fail the operation, not the connection: %#v, %v", result, err)
}
}
}
func TestMain(tests *testing.M) {
if path := os.Getenv("PIIK_SOURCE_LIST_FIXTURE"); path != "" {
payload, err := os.ReadFile(path)
if err != nil {
os.Exit(1)
}
_, _ = os.Stdout.Write(payload)
os.Exit(0)
}
if marker := os.Getenv("PIIK_SOURCE_PROBE_FIXTURE"); marker != "" {
if err := os.WriteFile(marker, nil, 0600); err != nil {
os.Exit(1)
}
time.Sleep(10 * time.Second)
os.Exit(0)
}
if directory := os.Getenv("PIIK_QUIET_CAPTURE_FIXTURE"); directory != "" {
runQuietCaptureFixture(directory)
os.Exit(0)
}
// Self-exec capture fixtures inherit this before their race runtime starts.
// Real native helpers have no race detector's default one-second exit sleep.
if err := os.Setenv("GORACE", os.Getenv("GORACE")+" atexit_sleep_ms=0"); err != nil {
panic(err)
}
os.Exit(tests.Run())
}
func TestSourceListFitsTheControlEnvelope(t *testing.T) {
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
for _, check := range []struct {
title string
count int
}{
{strings.Repeat("界", 512), 64},
{strings.Repeat("<", 512), 100},
} {
targets := make([]nativecapture.CaptureTarget, check.count)
for index := range targets {
targets[index] = nativecapture.CaptureTarget{Kind: "window", SourceID: strconv.Itoa(index + 1),
PID: 1, CreationTime: "1", Title: check.title}
}
var payload bytes.Buffer
encoder := json.NewEncoder(&payload)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(targets); err != nil {
t.Fatal(err)
}
path := filepath.Join(t.TempDir(), "sources.json")
if err := os.WriteFile(path, payload.Bytes(), 0600); err != nil {
t.Fatal(err)
}
t.Setenv("PIIK_SOURCE_LIST_FIXTURE", path)
session := New(executable, nativecapture.Capabilities{}, false, nil)
defer session.Close()
value, err := awaitControlResponse(t, session,
[]byte(`{"version":10,"id":"request_sources","type":"list-sources"}`))
if err != nil {
t.Fatal(err)
}
response, ok := value.(sourceListResponse)
if !ok || len(response.Sources) == 0 {
t.Fatalf("usable sources were lost: %#v", value)
}
if check.count == 64 && len(response.Sources) != 64 {
t.Fatalf("localized windows were truncated: %d", len(response.Sources))
}
encoded, err := json.Marshal(response)
if err != nil || len(encoded) > loopback.MaxControlMessageBytes {
t.Fatalf("valid enumeration would close control: %d bytes, %v", len(encoded), err)
}
}
}
func runQuietCaptureFixture(directory string) {
arguments, _ := json.Marshal(os.Args[1:])
if err := os.WriteFile(filepath.Join(directory, "arguments.json"), arguments, 0600); err != nil {
os.Exit(1)
}
if os.Getenv("PIIK_PENDING_CAPTURE_FIXTURE") == "true" {
_ = os.WriteFile(filepath.Join(directory, "prepared"), nil, 0600)
_, _ = io.Copy(io.Discard, os.Stdin)
return
}
var state nativehost.CaptureState
state.State, state.Codec = "starting", "vp8"
var adapter uint32
state.AdapterIndex = &adapter
state.AdapterName, state.AdapterIdentity, state.EncoderName, state.EncoderIdentity = "fixture", "fixture", "fixture", "fixture"
number := func(value string) uint32 { parsed, _ := strconv.ParseUint(value, 10, 32); return uint32(parsed) }
for index := 1; index < len(os.Args)-1; index++ {
switch os.Args[index] {
case "--width":
state.Width = number(os.Args[index+1])
case "--height":
state.Height = number(os.Args[index+1])
case "--fps":
state.FPS = number(os.Args[index+1])
case "--output":
state.Outputs = append(state.Outputs, nativecapture.OutputProfile{Width: number(os.Args[index+1]),
Height: number(os.Args[index+2]), Framerate: number(os.Args[index+3]), Bitrate: number(os.Args[index+4])})
}
}
write := func(kind nativecapture.FrameKind, payload []byte, timestamp uint64) {
var header [32]byte
copy(header[:], "SMED")
header[4], header[5] = 2, byte(kind)
if kind == nativecapture.FrameBegin {
binary.BigEndian.PutUint64(header[8:16], timestamp)
binary.BigEndian.PutUint64(header[16:24], 333_333)
}
binary.BigEndian.PutUint32(header[28:32], uint32(len(payload)))
_, _ = os.Stdout.Write(header[:])
_, _ = os.Stdout.Write(payload)
}
status := func() { payload, _ := json.Marshal(state); write(nativecapture.FrameStatus, payload, 0) }
if len(os.Args) == 2 && os.Args[1] == "--capture-microphone" {
write(nativecapture.FrameStatus, []byte(`{"state":"active","audio":true}`), 0)
_, _ = io.Copy(io.Discard, os.Stdin)
return
}
status()
closed := make(chan struct{})
go func() { _, _ = io.Copy(io.Discard, os.Stdin); close(closed) }()
if state.Width == 1280 {
_ = os.WriteFile(filepath.Join(directory, "prepared"), nil, 0600)
ticker := time.NewTicker(20 * time.Millisecond)
defer ticker.Stop()
var input uint64
for {
select {
case <-closed:
return
case <-ticker.C:
value, _ := os.ReadFile(filepath.Join(directory, "release"))
if string(value) == "active" {
write(nativecapture.FrameBegin, nil, input+333_333)
state.State = "active"
status()
<-closed
return
}
if string(value) == "input" {
input += 333_333
write(nativecapture.FrameBegin, nil, input)
}
}
}
}
state.State = "active"
status()
<-closed
}
func TestMicrophoneOptInPreservesLegacyAndOrdersStateBeforeCompletion(t *testing.T) {
for _, capabilities := range []struct{ optIn, microphone bool }{{false, true}, {true, true}, {true, false}} {
optIn, microphone := capabilities.optIn, capabilities.microphone
t.Run(strconv.FormatBool(optIn)+"/microphone="+strconv.FormatBool(microphone), func(t *testing.T) {
t.Setenv("PIIK_QUIET_CAPTURE_FIXTURE", t.TempDir())
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
session := New(executable, nativecapture.Capabilities{VideoCapture: true, SoftwareVP8: true, Microphone: microphone}, false, nil)
defer session.Close()
request := startShareRequest{Version: 10, ID: "request_start", Type: "start-share", ShareID: "share_123456",
Source: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"},
MicrophoneMixing: optIn, EdgeCapacity: 1, Codec: "vp8",
Profile: qualitySettings{Resolution: protocol.QualityResolution{Width: 1920, Height: 1080}, MaxFramerate: 30, MaxBitrate: 5_000_000, DegradationPreference: "balanced"}}
payload, _ := json.Marshal(request)
result, err := awaitControlResponse(t, session, payload)
started, ok := result.(shareStartedResponse)
if err != nil || !ok {
t.Fatalf("start failed: %v %#v", err, result)
}
encoded, _ := json.Marshal(started)
if started.Audio != optIn || bytes.Contains(encoded, []byte(`"sourceAudio"`)) != optIn {
t.Fatalf("mixed output leaked across opt-in: %s", encoded)
}
result, err = session.Handle(t.Context(), []byte(`{"version":10,"id":"request_volume","type":"set-share-volume","shareId":"share_123456","volume":2}`))
if optIn {
if ack, ok := result.(responseEnvelope); err != nil || !ok || ack.Type != "share-volume-set" {
t.Fatalf("source volume failed: %v %#v", err, result)
}
} else if _, failed := result.(requestFailedResponse); err != nil || !failed {
t.Fatalf("volume accepted without an audio source: %v %#v", err, result)
}
if !microphone {
return // Source gain must work without requesting an unavailable device.
}
result, err = session.Handle(t.Context(), []byte(`{"version":10,"id":"request_mic","type":"set-microphone","shareId":"share_123456","enabled":true,"volume":1}`))
if !optIn {
if _, failed := result.(requestFailedResponse); err != nil || !failed {
t.Fatalf("non-opted share admitted mic: %v %#v", err, result)
}
return
}
if err != nil || result != nil {
t.Fatalf("device setup was not asynchronous: %v %#v", err, result)
}
stateSeen := false
for {
select {
case event := <-session.Events():
event = deliveredControlValue(event)
switch value := event.(type) {
case audioStateEvent:
stateSeen = value.Microphone && !value.SourceAudio
case responseEnvelope:
if value.Type == "microphone-set" {
if !stateSeen {
t.Fatal("completion overtook microphone state")
}
return
}
case requestFailedResponse:
t.Fatalf("microphone failed: %#v", value)
}
case <-time.After(2 * time.Second):
t.Fatal("microphone did not complete")
}
}
})
}
}
func TestRemoteInputRequiresPageOptIn(t *testing.T) {
for _, optIn := range []bool{false, true} {
t.Run(strconv.FormatBool(optIn), func(t *testing.T) {
t.Setenv("PIIK_QUIET_CAPTURE_FIXTURE", t.TempDir())
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
// No OS sink or approved controller: only exercise event ownership.
session := New(executable, nativecapture.Capabilities{VideoCapture: true, SoftwareVP8: true}, false, &remoteinput.Manager{})
defer session.Close()
request := startShareRequest{Version: 10, ID: "request_start", Type: "start-share", ShareID: "share_123456",
Source: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"},
RemoteInput: optIn, EdgeCapacity: 1, Codec: "vp8",
Profile: qualitySettings{Resolution: protocol.QualityResolution{Width: 1920, Height: 1080}, MaxFramerate: 30, MaxBitrate: 5_000_000, DegradationPreference: "balanced"}}
payload, _ := json.Marshal(request)
result, err := awaitControlResponse(t, session, payload)
if _, ok := result.(shareStartedResponse); err != nil || !ok {
t.Fatalf("start failed: %v %#v", err, result)
}
if (session.current(request.ShareID).RemoteInputChanges() != nil) != optIn {
t.Fatal("input events did not respect page opt-in")
}
// Browser quality candidates relay through this same preview bridge.
offer, err := session.current(request.ShareID).PrepareLocalEdge("preview_input", "preview_offer", false)
if err != nil {
t.Fatal(err)
}
if strings.Contains(offer.SDP, "m=application ") != optIn {
t.Fatal("preview bridge did not preserve the opted-in input channel")
}
})
}
}
func TestCaptureBorderPreferenceFollowsSourceAndProfile(t *testing.T) {
for _, supported := range []bool{false, true} {
t.Run(strconv.FormatBool(supported), func(t *testing.T) {
directory := t.TempDir()
t.Setenv("PIIK_QUIET_CAPTURE_FIXTURE", directory)
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
session := New(executable, nativecapture.Capabilities{VideoCapture: true, SoftwareVP8: true, CaptureBorderControl: supported}, false, nil)
t.Cleanup(func() { _ = session.Close() })
handle := func(request any) {
t.Helper()
payload, err := json.Marshal(request)
if err != nil {
t.Fatal(err)
}
value, err := awaitControlResponse(t, session, payload)
if _, failed := value.(requestFailedResponse); err != nil || failed {
t.Fatalf("capture request failed: %v, %#v", err, value)
}
}
assertBorder := func(expected bool) {
t.Helper()
data, err := os.ReadFile(filepath.Join(directory, "arguments.json"))
var arguments []string
if err != nil || json.Unmarshal(data, &arguments) != nil {
t.Fatalf("capture arguments missing: %v", err)
}
if slices.Contains(arguments, "--show-capture-border") != expected {
t.Fatalf("capture border intent lost: %v", arguments)
}
}
start := startShareRequest{Version: 10, ID: "request_start", Type: "start-share", ShareID: "share_123456",
Source: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"},
ShowCaptureBorder: true, EdgeCapacity: 1, Codec: "vp8",
Profile: qualitySettings{Resolution: protocol.QualityResolution{Width: 1920, Height: 1080}, MaxFramerate: 30, MaxBitrate: 5_000_000, DegradationPreference: "balanced"}}
handle(start)
assertBorder(supported)
profile := start.Profile
profile.Resolution = protocol.QualityResolution{Width: 854, Height: 480}
handle(updateShareRequest{Version: 10, ID: "request_update", Type: "update-share", ShareID: start.ShareID, Profile: profile})
session.mu.Lock()
done := session.updateDone
session.mu.Unlock()
if done != nil {
select {
case <-done:
case <-time.After(3 * time.Second):
t.Fatal("profile update did not settle")
}
}
assertBorder(supported)
for _, show := range []bool{false, true} {
handle(replaceShareSourceRequest{Version: 10, ID: "request_replace", Type: "replace-share-source", ShareID: start.ShareID,
Source: nativecapture.CaptureTarget{Kind: "display", SourceID: "2", Title: "Other fixture"}, ShowCaptureBorder: show})
assertBorder(show && supported)
}
handle(stopShareRequest{Version: 10, ID: "request_stop", Type: "stop-share", ShareID: start.ShareID})
})
}
}
func TestQuietHostUpdatePreservesControlAndCancelsCleanly(t *testing.T) {
for _, outcome := range []string{"complete", "stop", "disconnect", "first-input-timeout", "backpressure-stop"} {
t.Run(outcome, func(t *testing.T) {
var trace bytes.Buffer
if outcome == "complete" {
previous := slog.Default()
t.Cleanup(func() { slog.SetDefault(previous) })
slog.SetDefault(slog.New(slog.NewJSONHandler(&trace, &slog.HandlerOptions{Level: slog.LevelDebug})))
}
directory := t.TempDir()
t.Setenv("PIIK_QUIET_CAPTURE_FIXTURE", directory)
executable, err := os.Executable()
if err != nil {
t.Fatal(err)
}
session := New(executable, nativecapture.Capabilities{SoftwareVP8: true}, false, nil)
t.Cleanup(func() { _ = session.Close() })
handle := func(payload string) any {
t.Helper()
var value any
var err error
if strings.Contains(payload, `"type":"start-share"`) {
value, err = awaitControlResponse(t, session, []byte(payload))
} else {
value, err = session.Handle(t.Context(), []byte(payload))
}
if err != nil {
t.Fatal(err)
}
return value
}
const start = `{"version":10,"id":"request_start","type":"start-share","shareId":"share_123456","source":{"kind":"display","sourceId":"1","title":"Fixture"},"audio":false,"adapterIndex":0,"encoderIndex":0,"edgeCapacity":1,"codec":"vp8","profile":{"resolution":{"width":1920,"height":1080},"maxFramerate":30,"maxBitrate":5000000,"degradationPreference":"balanced"}}`
handle(start)
const update = `{"version":10,"id":"request_update","type":"update-share","shareId":"share_123456","profile":{"resolution":{"width":1280,"height":720},"maxFramerate":30,"maxBitrate":3000000,"degradationPreference":"balanced"}}`
if value := handle(update); value != nil {
t.Fatalf("Host update did not defer: %#v", value)
}
session.mu.Lock()
done := session.updateDone
session.mu.Unlock()
deadline := time.Now().Add(2 * time.Second)
for {
if _, err = os.Stat(filepath.Join(directory, "prepared")); err == nil {
break
}
if time.Now().After(deadline) {
t.Fatal("replacement did not reach its starting state")
}
time.Sleep(10 * time.Millisecond)
}
for _, payload := range []string{
strings.Replace(update, "request_update", "request_duplicate", 1),
`{"version":10,"id":"request_replace","type":"replace-share-source","shareId":"share_123456","source":{"kind":"display","sourceId":"1","title":"Fixture"},"audio":false,"adapterIndex":0,"encoderIndex":0}`,
} {
if _, ok := handle(payload).(requestFailedResponse); !ok {
t.Fatal("conflicting capture mutation was not rejected")
}
}
for _, payload := range []string{
`{"version":10,"id":"request_pause","type":"pause-share","shareId":"share_123456","paused":true}`,
`{"version":10,"id":"request_ice","type":"edge-candidate","shareId":"share_123456","connectionId":"retired_edge","candidate":null}`,
} {
started := time.Now()
handle(payload)
if time.Since(started) > time.Second {
t.Fatal("quality preparation blocked control")
}
}
switch outcome {
case "complete":
select {
case <-done:
t.Fatal("quiet source update ended before a frame arrived")
case <-time.After(5200 * time.Millisecond):
}
if err = os.WriteFile(filepath.Join(directory, "release"), []byte("active"), 0600); err != nil {
t.Fatal(err)
}
case "first-input-timeout":
if err = os.WriteFile(filepath.Join(directory, "release"), []byte("input"), 0600); err != nil {
t.Fatal(err)
}
case "backpressure-stop":
fill:
for {
select {
case session.events <- struct{}{}:
default:
break fill
}
}
if err = os.WriteFile(filepath.Join(directory, "release"), []byte("active"), 0600); err != nil {
t.Fatal(err)
}
case "stop":
handle(`{"version":10,"id":"request_stop","type":"stop-share","shareId":"share_123456"}`)
case "disconnect":
if err = session.Close(); err != nil {
t.Fatal(err)
}
}
select {
case <-done:
case <-time.After(6 * time.Second):
t.Fatal("update did not finish after input or cancellation")
}
if outcome == "disconnect" {
return
}
if outcome == "backpressure-stop" {
stopped := make(chan any, 1)
go func() {
value, err := session.Handle(t.Context(), []byte(`{"version":10,"id":"request_stop","type":"stop-share","shareId":"share_123456"}`))
if err != nil {
stopped <- err
} else {
stopped <- value
}
}()
select {
case value := <-stopped:
if _, ok := value.(responseEnvelope); !ok {
t.Fatalf("backpressured stop failed: %#v", value)
}
case <-time.After(2 * time.Second):
t.Fatal("completion backpressure blocked stop")
}
return
}
ctx, cancel := context.WithTimeout(t.Context(), time.Second)
defer cancel()
responseFor := func(id string) any {
for {
select {
case value := <-session.Events():
value = deliveredControlValue(value)
if response, ok := value.(shareUpdatedResponse); ok && response.ID == id {
return value
}
if response, ok := value.(requestFailedResponse); ok && response.ID == id {
return value
}
case <-ctx.Done():
t.Fatal("deferred update lost its response")
}
}
}
_, success := responseFor("request_update").(shareUpdatedResponse)
if success != (outcome == "complete") {
t.Fatal("deferred response did not match capture outcome")
}
if outcome == "stop" {
if _, ok := handle(strings.ReplaceAll(start, "share_123456", "share_restart")).(shareStartedResponse); !ok {
t.Fatal("stopped update blocked a new share")
}
}
if outcome == "complete" {
if value := handle(strings.Replace(update, "request_update", "request_followup", 1)); value != nil {
t.Fatal("acknowledged update still blocked its successor")
}
if _, ok := responseFor("request_followup").(shareUpdatedResponse); !ok {
t.Fatal("later update could not complete")
}
_ = session.Close()
var started, ended int
decoder := json.NewDecoder(&trace)
for decoder.More() {
var record map[string]any
if err := decoder.Decode(&record); err != nil {
t.Fatal(err)
}
if record["requestId"] != "request_update" {
continue
}
switch record["event"] {
case "native-request-started":
started++
case "native-request-ended":
ended++
if record["durationMs"].(float64) < 5_000 || record["failed"] != false || record["share"] == "share_123456" {
t.Fatalf("asynchronous request lost duration, outcome or private identity handling: %+v", record)
}
}
}
if started != 1 || ended != 1 {
t.Fatalf("async update logged %d starts and %d completions", started, ended)
}
}
})
}
}
func TestSTUNURLsUseTheCurrentBoundedWire(t *testing.T) {
servers, err := pionICEServers([]iceServer{{URLs: []string{
"stun:example.test:3478",
"stun:example.test:3479",
}}})
if err != nil || len(servers) != 1 || len(servers[0].URLs) != 2 {
t.Fatalf("servers = %+v, %v", servers, err)
}
for _, value := range []string{
"turn:example.com:3478",
"stun:user@example.com:3478",
"stun:example.com:0",
"stun:example.com/path",
} {
if validSTUNURL(value) {
t.Fatalf("invalid STUN URL accepted: %s", value)
}
}
}
func TestControlMessagesRejectUnknownFieldsAndStaleVersions(t *testing.T) {
session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
for _, payload := range []string{
`{"version":10,"id":"request_sources","type":"list-sources","extra":true}`,
`{"version":4,"id":"request_sources","type":"list-sources"}`,
`{"version":5,"id":"short","type":"stop-share","shareId":"share_123456"}`,
} {
if _, err := session.Handle(t.Context(), []byte(payload)); err == nil {
t.Fatalf("invalid control message accepted: %s", payload)
}
}
}
func TestResponseKeepsTheRequestIdentity(t *testing.T) {
value := response(requestEnvelope{
Version: loopback.ProtocolVersion,
ID: "request_123456",
Type: "stop-share",
}, "share-stopped")
if value.Version != loopback.ProtocolVersion || value.ID != "request_123456" ||
value.Type != "share-stopped" {
t.Fatalf("response = %+v", value)
}
failed := operationFailure(requestEnvelope{
Version: loopback.ProtocolVersion, ID: "request_update", Type: "update-share",
})
if failed.Version != loopback.ProtocolVersion || failed.ID != "request_update" ||
failed.Type != "request-failed" || failed.Code != "operation-failed" {
t.Fatalf("operation failure lost its request identity: %+v", failed)
}
}
func TestPrepareLocalEdgeOwnsOneStrictRequestShape(t *testing.T) {
session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
valid := `{"version":10,"id":"request_local_edge","type":"prepare-local-edge","shareId":"share_123456","connectionId":"edge_1234567"}`
assertOperationFailure(t, session, valid)
invalid := `{"version":10,"id":"request_local_edge","type":"prepare-local-edge","shareId":"share_123456","connectionId":"edge_1234567","iceServers":[]}`
if _, err := session.Handle(t.Context(), []byte(invalid)); err == nil || err.Error() != "native prepare-local-edge request is invalid" {
t.Fatalf("extended local-edge request was accepted: %v", err)
}
}
func TestPreviewFailureReturnsAnAdvisoryResponse(t *testing.T) {
session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
value, err := session.Handle(t.Context(), []byte(
`{"version":10,"id":"request_preview","type":"source-preview","source":{"kind":"display","sourceId":"65537","title":"Display 1"}}`,
))
if err != nil {
t.Fatal(err)
}
response, ok := value.(sourcePreviewResponse)
if !ok || response.Data != "" || response.SourceKey != "display:65537" {
t.Fatalf("preview response = %#v", value)
}
}
func TestSourceEnumerationFailureDoesNotCloseControl(t *testing.T) {
session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
value, err := session.Handle(t.Context(), []byte(
`{"version":10,"id":"request_sources","type":"list-sources"}`,
))
if err != nil || value != operationFailure(requestEnvelope{
Version: loopback.ProtocolVersion, ID: "request_sources", Type: "list-sources",
}) {
t.Fatalf("source list failure ended its control session: %#v, %v", value, err)
}
if _, err := session.Handle(t.Context(), []byte(
`{"version":10,"id":"request_options","type":"capture-options"}`,
)); err != nil {
t.Fatalf("control was unusable after source enumeration failed: %v", err)
}
}
func TestQualitySettingsMapOnceIntoNativeMedia(t *testing.T) {
settings := qualitySettings{
Resolution: protocol.QualityResolution{Width: 2560, Height: 1440}, MaxFramerate: 60, MaxBitrate: 12_000_000,
DegradationPreference: "maintain-framerate",
MaxAudioBitrate: 192000,
}
profile := nativeQualityProfile(settings)
if !profile.Valid() || profile.Video.Width != 2560 ||
profile.Video.Height != 1440 || profile.Video.Framerate != 60 ||
profile.Video.Bitrate != 12_000_000 ||
profile.Video.Preference != "maintain-framerate" ||
profile.AudioBitrate != 192_000 {
t.Fatalf("native profile = %+v", profile)
}
settings.Resolution = protocol.QualityResolution{Width: 1920, Height: 1200}
if profile := nativeQualityProfile(settings); !profile.Valid() || profile.Video.Height != 1200 {
t.Fatalf("numeric size outside UI presets was not preserved: %+v", profile)
}
settings.Resolution = protocol.QualityResolution{Width: 3840, Height: 2160}
if !nativeQualityProfile(settings).Valid() {
t.Fatal("4K60 was rejected")
}
settings.MaxFramerate = 30
if !nativeQualityProfile(settings).Valid() {
t.Fatal("4K30 was rejected")
}
for _, fps := range []protocol.Num{30.5, 65, 120, 0x1_0000_0000 + 30} {
settings.MaxFramerate = fps
if nativeQualityProfile(settings).Valid() {
t.Fatalf("unsupported fps %v was narrowed into a valid profile", fps)
}
}
}
func TestUpdateShareRequiresTheCurrentStrictProfile(t *testing.T) {
session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
valid := `{"version":10,"id":"request_update","type":"update-share","shareId":"share_123456","profile":{"resolution":{"width":1920,"height":1080},"maxFramerate":30,"maxBitrate":5000000,"degradationPreference":"balanced","maxAudioBitrate":128000}}`
assertOperationFailure(t, session, valid)
// Opus permits this numeric request, but the current 20 ms sender does not.
// Keep the control session usable and let the caller keep its current share.
assertOperationFailure(t, session, strings.Replace(valid, `"maxAudioBitrate":128000`, `"maxAudioBitrate":510000`, 1))
assertOperationFailure(t, session, strings.Replace(valid,
`"resolution":{"width":1920,"height":1080}`,
`"resolution":{"width":7680,"height":4320}`, 1))
for _, replace := range [][2]string{
{`"width":1920`, `"width":32768`}, {`"width":1920`, `"width":1921`},
{`"maxFramerate":30`, `"maxFramerate":480`}, {`"maxFramerate":30`, `"maxFramerate":30.5`},
{`"maxFramerate":30`, `"maxFramerate":4294967326`}, {`"maxFramerate":30`, `"maxFramerate":0.5`},
{`"maxBitrate":5000000`, `"maxBitrate":240000001`}, {`"maxBitrate":5000000`, `"maxBitrate":1000`},
} {
assertOperationFailure(t, session, strings.Replace(valid, replace[0], replace[1], 1))
}
if _, err := session.Handle(t.Context(), []byte(`{"version":10,"id":"request_options","type":"capture-options"}`)); err != nil {
t.Fatalf("unsupported media setting retired control: %v", err)
}
invalid := `{"version":10,"id":"request_update","type":"update-share","shareId":"share_123456","profile":{"resolution":{"width":1920,"height":1080},"maxFramerate":30,"maxBitrate":5000000,"degradationPreference":"balanced","maxAudioBitrate":128000,"extra":true}}`
if _, err := session.Handle(t.Context(), []byte(invalid)); err == nil ||
err.Error() != "native update-share request is invalid" {
t.Fatalf("extended update was accepted: %v", err)
}
}
func TestReplaceShareSourceKeepsOneStrictTargetShape(t *testing.T) {
session := New("missing-capture-process", nativecapture.Capabilities{}, false, nil)
t.Cleanup(func() { _ = session.Close() })
valid := `{"version":10,"id":"request_source","type":"replace-share-source","shareId":"share_123456","source":{"kind":"picker","sourceId":"1","title":"Portal"},"audio":false,"adapterIndex":0,"encoderIndex":0}`
assertOperationFailure(t, session, valid)
invalid := `{"version":10,"id":"request_source","type":"replace-share-source","shareId":"share_123456","source":{"kind":"picker","sourceId":"1","title":"Portal"},"audio":false,"adapterIndex":0,"encoderIndex":0,"extra":true}`
if _, err := session.Handle(t.Context(), []byte(invalid)); err == nil ||
err.Error() != "native replace-share-source request is invalid" {
t.Fatalf("extended source replacement was accepted: %v", err)
}
invalid = strings.Replace(valid, `"kind":"picker"`, `"kind":"unknown"`, 1)
if _, err := session.Handle(t.Context(), []byte(invalid)); err == nil ||
err.Error() != "native replace-share-source request is invalid" {
t.Fatalf("malformed target was treated as an operational failure: %v", err)
}
}
func TestAudioExclusionValidatesScopeWithoutDroppingRequestedPolicy(t *testing.T) {
session := &Session{capabilities: nativecapture.Capabilities{Microphone: true, SystemAudio: true, ProcessAudioExclusion: true}}
display := nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Screen"}
window := nativecapture.CaptureTarget{Kind: "window", SourceID: "2", PID: 123, CreationTime: "456", Title: "Voice fixture"}
if err := session.validateAudioExclusion(display, true, &window); err != nil {
t.Fatal(err)
}
for _, invalid := range []struct {
source nativecapture.CaptureTarget
audio bool
excluded nativecapture.CaptureTarget
}{
{display, false, window}, {window, true, window}, {display, true, display},
{display, true, nativecapture.CaptureTarget{Kind: "window", SourceID: "2", PID: 123, Title: "Missing lifetime"}},
} {
if _, ok := session.validateAudioExclusion(invalid.source, invalid.audio, &invalid.excluded).(protocolViolation); !ok {
t.Fatal("malformed audio exclusion was not rejected")
}
}
session.capabilities.ProcessAudioExclusion = false
err := session.validateAudioExclusion(display, true, &window)
if _, malformed := err.(protocolViolation); err == nil || malformed {
t.Fatal("unsupported audio exclusion must fail the operation, not silently widen capture or close control")
}
if err := session.validateAudioExclusion(display, true, nil); err != nil {
t.Fatal("legacy capture became dependent on exclusion support")
}
}