Piik can now let one invited Viewer control the Host's shared desktop or window, using the existing media route and explicit source-scoped consent. This phase also finishes Viewer playback settings, the combined interaction window, the shared control/theme/icon polish, and concrete forwarding-feedback recovery fixes. Remote input stays off by default, uses one controller and releases held input on revocation, retirement or loss. Existing 2.x sharing remains compatible; new capabilities are negotiated with supporting App/Site/relay peers. No virtual input driver, new media listener or route planner is added. Validation: full Web check (97 files / 1,677 tests), Windows Go/native checks; seven real Browser/App lifecycle scenarios covering P2P, SFU and fallback-to-direct continuity; existing cross-version and physical Windows routed-input evidence; native macOS/Linux packaging, Go race/security and container checks through the publishing pipeline. Physical macOS/Linux permissions, mobile devices, mixed DPI and commercial games retain their documented limits. README/wiki keep deployment under the optional self-hosted Server chapters. Refs #472, #477, #479, #480. Issue follow-up happens after publication; unmatched field reports remain open. ## Release notes ### 中文 这是一次功能更新:一起看屏幕时,可以把键鼠交给一位朋友操作,聊天和表情也整合进了同一个互动窗口。本次还整理了分享与播放设置,并修复部分连接恢复和中转画质停滞的问题。 #### 新功能与体验 - **可选键鼠远控**:房主可以让一位朋友操作当前分享的桌面或窗口,随时撤回授权;换源或停播后关闭远控。提供手机触控、缩放和小键盘。当前实机验证覆盖 Windows App。 - **观众播放设置**:新增完整显示、等比铺满、拉伸铺满,以及自动/仅 P2P/仅 SFU 线路选择;站点和房主的线路限制仍然生效。 - **互动窗口**:聊天、参与者和表情放在同一窗口;可以从聊天头像选择接收者,新增点赞、倒彩等表情。支持的浏览器可以独立置顶,继续查看聊天和互动。全屏保留弹幕开关。 - **分享与播放设置更清楚**:暂停与停止相邻,画面、声音、连接和远控各有对应入口。观众播控在移动鼠标时显现,远控时收进画面边缘的小抽屉;点击画面不再意外暂停。没有声音输入时播控给出明确反馈,恢复输入后保留观众的音量设置。 #### 修复 - **连接与播放修复**:修正部分中转路径的媒体时钟、往返时间与重复反馈统计,改善这些错误导致的画质恢复停滞;重新进入房间后,SFU 连接仍可继续尝试直连。同步底层握手恢复修复。 - **界面修复**:修复浮窗返回后遮挡全屏、无法操作,窄屏控件错位、菜单超出边界等问题。虚拟键盘长按不会选中文字,拖出、取消或失焦后释放按键。页面和选源面板统一中性底色;App 图标与 favicon 保留小电视轮廓,精修对比度与底板层次。 - **兼容性修复**:新表情按站点支持情况显示,避免旧站点拒收后断开连接。补齐旧浏览器的浮层支持;修正 macOS `.app` 对包外启动文件的依赖。macOS 的 Finder、权限和远控仍需实机验证。 #### 更新说明 沿用 2.x 兼容边界。使用远控需要更新房主 App 和所连接的站点;要获得完整的中转修复,请同时更新 App 与自部署 Server。 ### English This feature update lets a Host hand keyboard and mouse control to one friend while sharing a screen. Chat and reactions now share one interaction window. It also clarifies sharing and playback settings and fixes specific connection-recovery and server-forwarding quality stalls. #### Features and experience - **Optional keyboard and mouse control:** the Host can let one friend control the shared desktop or window and revoke access at any time. Changing sources or stopping sharing disables control. Touch controls, zoom and an on-screen keyboard are included. Physical validation currently covers the Windows App. - **Viewer playback settings:** choose fit, crop or stretch, and Auto, P2P-only or SFU-only routing. Site and Host restrictions still apply. - **One interaction window:** chat, participants and reactions stay together. Choose a recipient from their chat avatar and use new reactions, including thumbs up and down. Supported browsers can detach the window and keep chat and reactions visible on top. Fullscreen retains the chat-overlay toggle. - **Clearer sharing and playback controls:** pause and stop stay together, with separate picture, sound, connection and remote-control settings. Pointer movement reveals the playback bar during viewing; remote control uses a small drawer at the picture edge. Clicking the picture no longer pauses it accidentally. Sound controls reflect missing input and retain the Viewer's volume when it returns. #### Fixes - **Connection and playback fixes:** correct media clocks, round-trip-time updates and duplicate feedback accounting on affected forwarding paths, improving recovery from the quality stalls caused by those errors. Rejoining a room restores direct-connection attempts while SFU playback continues. Incorporate upstream handshake-recovery fixes. - **Interface fixes:** returning a detached tool during fullscreen no longer leaves an inaccessible panel over the picture. Fix compact-layout shifts and overflowing menus. Holding a virtual key no longer selects its label; release, cancellation and focus loss clear held keys. Pages and the source picker use shared neutral surfaces. Refine App icons and favicons while retaining the familiar television outline. - **Compatibility fixes:** show new reactions only when the site supports them, preventing disconnects on older sites. Support popovers on older browsers and remove the macOS `.app` launcher's dependency on files outside the bundle. Finder, permissions and remote input still need physical macOS validation. #### Updating The existing 2.x compatibility boundary is retained. Remote control needs an updated Host App and site; update both App and self-hosted Server for the complete forwarding fix.
563 lines
21 KiB
Go
563 lines
21 KiB
Go
package nativehost
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"io"
|
|
"log/slog"
|
|
"os"
|
|
"slices"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/TNTcraftHIM/Piik/internal/app/mediaedge"
|
|
"github.com/TNTcraftHIM/Piik/internal/app/nativecapture"
|
|
)
|
|
|
|
func TestMain(tests *testing.M) {
|
|
if os.Getenv("PIIK_NATIVEHOST_PIPE_FIXTURE") == "backend" {
|
|
for _, key := range []string{"PIIK_CAPTURE_STARTING", "PIIK_CAPTURE_ACTIVE"} {
|
|
writeCaptureFixtureFrame(nativecapture.Frame{Kind: nativecapture.FrameStatus, Data: []byte(os.Getenv(key))})
|
|
if layer := os.Getenv("PIIK_CAPTURE_UNAVAILABLE"); key == "PIIK_CAPTURE_STARTING" && layer != "" {
|
|
value, _ := strconv.Atoi(layer)
|
|
writeCaptureFixtureFrame(nativecapture.Frame{Kind: nativecapture.FrameLayerUnavailable, Layer: value, Data: []byte("fixture")})
|
|
}
|
|
}
|
|
_, _ = io.Copy(io.Discard, os.Stdin)
|
|
os.Exit(0)
|
|
}
|
|
if os.Getenv("PIIK_NATIVEHOST_PIPE_FIXTURE") == "audio-recovery" {
|
|
runAudioRecoveryCapture()
|
|
os.Exit(0)
|
|
}
|
|
if os.Getenv("PIIK_NATIVEHOST_PIPE_FIXTURE") == "echo" {
|
|
_, _ = io.Copy(os.Stdout, os.Stdin)
|
|
os.Exit(0)
|
|
}
|
|
if os.Getenv("PIIK_NATIVEHOST_PIPE_FIXTURE") == "1" {
|
|
_, _ = io.Copy(io.Discard, os.Stdin)
|
|
os.Exit(0)
|
|
}
|
|
os.Exit(tests.Run())
|
|
}
|
|
|
|
func TestCaptureCommitWaitsForReaderMetadataOrTermination(t *testing.T) {
|
|
t.Setenv("PIIK_NATIVEHOST_PIPE_FIXTURE", "1")
|
|
executable, err := os.Executable()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, mode := range []string{"installed", "reader-failed", "closed"} {
|
|
t.Run(mode, func(t *testing.T) {
|
|
check := func(err error) {
|
|
t.Helper()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
defer cancel()
|
|
engine, err := mediaedge.NewEngine(mediaedge.EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})
|
|
check(err)
|
|
defer engine.Close()
|
|
options := nativecapture.VideoOptions{Target: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"}, Codec: "vp8",
|
|
Profile: nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 15, Bitrate: 2_000_000, Preference: "balanced"}, OutputGroups: 1}
|
|
previous, err := nativecapture.StartVideo(ctx, executable, options)
|
|
check(err)
|
|
defer previous.Close()
|
|
if len(previous.Outputs()) != 3 {
|
|
t.Fatal("capture did not retain its independent output group")
|
|
}
|
|
source, err := engine.NewSource("vp8", 1, 2, nil)
|
|
check(err)
|
|
defer source.Close()
|
|
check(configureCaptureOutputs(source, previous.Outputs()))
|
|
publication, err := engine.NewPublication(source, mediaedge.EdgeOptions{ConnectionID: "metadata-fixture"})
|
|
check(err)
|
|
session := &Session{ctx: ctx, cancel: cancel, engine: engine, source: source, stream: previous,
|
|
edgeCapacity: 1, ready: make(chan error, 1), done: make(chan error, 1), events: func(context.Context, Event) {}}
|
|
options.Profile.Width, options.Profile.Height = 854, 480
|
|
replacement, err := nativecapture.StartVideo(ctx, executable, options)
|
|
check(err)
|
|
defer replacement.Close()
|
|
committed := make(chan error, 1)
|
|
adapter, encoder := uint32(1), uint32(2)
|
|
go func() {
|
|
session.updateMu.Lock()
|
|
err := session.commitCapture(options, QualityProfile{Video: options.Profile, AudioBitrate: 64_000}, replacement,
|
|
CaptureState{AdapterIndex: &adapter, EncoderIndex: &encoder, unavailableLayers: []int{0}}, nil, false, nil)
|
|
session.updateMu.Unlock()
|
|
committed <- err
|
|
}()
|
|
select {
|
|
case <-previous.Done():
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("old fixture did not exit")
|
|
}
|
|
select {
|
|
case err := <-committed:
|
|
t.Fatalf("process exit acknowledged metadata before reader installation: %v", err)
|
|
default:
|
|
}
|
|
if len(publication.Media().Layers) != 2 || publication.Media().Layers[1].Width != 1280 {
|
|
t.Fatal("held reader unexpectedly changed source metadata")
|
|
}
|
|
if mode == "installed" {
|
|
// Hold the reader at its handoff, then run the same installation it uses.
|
|
check(session.installCapture(replacement))
|
|
select {
|
|
case err = <-committed:
|
|
check(err)
|
|
case <-time.After(time.Second):
|
|
t.Fatal("installed metadata did not acknowledge update")
|
|
}
|
|
media := publication.Media()
|
|
if session.videoOptions.AdapterIndex != adapter || session.videoOptions.EncoderIndex != encoder {
|
|
t.Fatal("capture replacement discarded its selected hardware backend")
|
|
}
|
|
if media.Layers[1].Width != 854 || media.Layers[1].Height != 480 || media.Layers[1].Bitrate != 2_000_000 {
|
|
t.Fatalf("acknowledged stale metadata: %+v", media)
|
|
}
|
|
plan, err := source.BeginFrame(time.Second)
|
|
check(err)
|
|
if plan.Bitrates[0] != 0 || plan.Bitrates[1] == 0 || session.captureUnavailable != nil {
|
|
t.Fatalf("replacement lost or retained pending failures: %+v", plan)
|
|
}
|
|
// The next healthy generation must not inherit the failed layer.
|
|
healthy, err := nativecapture.StartVideo(ctx, executable, options)
|
|
check(err)
|
|
defer healthy.Close()
|
|
go func() {
|
|
committed <- session.commitCapture(options, session.profile, healthy, CaptureState{}, nil, false, nil)
|
|
}()
|
|
select {
|
|
case <-replacement.Done():
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("replacement fixture did not exit")
|
|
}
|
|
check(session.installCapture(healthy))
|
|
select {
|
|
case err = <-committed:
|
|
check(err)
|
|
case <-time.After(time.Second):
|
|
t.Fatal("healthy replacement remained pending")
|
|
}
|
|
plan, err = source.BeginFrame(time.Second)
|
|
check(err)
|
|
if plan.Bitrates[0] == 0 || plan.Bitrates[1] == 0 {
|
|
t.Fatalf("healthy generation inherited a failed layer: %+v", plan)
|
|
}
|
|
return
|
|
}
|
|
go session.run()
|
|
closed := make(chan error, 1)
|
|
if mode == "closed" {
|
|
go func() { closed <- session.Close() }()
|
|
} else {
|
|
check(replacement.Close())
|
|
}
|
|
select {
|
|
case err = <-committed:
|
|
if err == nil {
|
|
t.Fatal("terminated reader acknowledged an uninstalled stream")
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("capture update remained latched after termination")
|
|
}
|
|
if mode == "closed" {
|
|
select {
|
|
case err = <-closed:
|
|
check(err)
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("Close deadlocked behind the capture update")
|
|
}
|
|
} else {
|
|
select {
|
|
case err = <-session.Done():
|
|
if err == nil {
|
|
t.Fatal("unexpected reader death did not fail the share")
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("reader death did not end the share")
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestCaptureFailureBelongsToSelectedStream(t *testing.T) {
|
|
for _, replace := range []bool{false, true} {
|
|
t.Run(strconv.FormatBool(replace), func(t *testing.T) {
|
|
check := func(err error) {
|
|
t.Helper()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
t.Setenv("PIIK_NATIVEHOST_PIPE_FIXTURE", "backend")
|
|
t.Setenv("PIIK_CAPTURE_STARTING", string(captureStatePayload(t,
|
|
`{"state":"starting","codec":"vp8","adapterIndex":0,"adapterName":"Fixture","adapterIdentity":"0:0","encoderName":"VP8","encoderIdentity":"vp8"}`)))
|
|
t.Setenv("PIIK_CAPTURE_ACTIVE", string(captureStatePayload(t, `{"state":"active","codec":"vp8","width":1280,"height":720,"fps":30}`)))
|
|
t.Setenv("PIIK_CAPTURE_UNAVAILABLE", "0")
|
|
executable, err := os.Executable()
|
|
check(err)
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
defer cancel()
|
|
options := nativecapture.VideoOptions{Target: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"}, Codec: "vp8",
|
|
Profile: nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 30, Bitrate: 3_000_000, Preference: "balanced"}, OutputGroups: 4}
|
|
previous, err := nativecapture.StartVideo(ctx, executable, options)
|
|
check(err)
|
|
defer previous.Close()
|
|
t.Setenv("PIIK_CAPTURE_UNAVAILABLE", "")
|
|
replacement, err := nativecapture.StartVideo(ctx, executable, options)
|
|
check(err)
|
|
defer replacement.Close()
|
|
engine, err := mediaedge.NewEngine(mediaedge.EngineOptions{BindAddress: "127.0.0.1:0", IncludeLoopback: true})
|
|
check(err)
|
|
defer engine.Close()
|
|
source, err := engine.NewSource("vp8", 4, 2, nil)
|
|
check(err)
|
|
defer source.Close()
|
|
check(configureCaptureOutputs(source, previous.Outputs()))
|
|
publication, err := engine.NewPublication(source, mediaedge.EdgeOptions{ConnectionID: "capture-failure-owner"})
|
|
check(err)
|
|
active := make(chan struct{}, 1)
|
|
session := &Session{ctx: ctx, cancel: cancel, engine: engine, source: source, stream: previous,
|
|
videoOptions: options, ready: make(chan error, 1), events: func(_ context.Context, event Event) {
|
|
if event.State == "active" {
|
|
select {
|
|
case active <- struct{}{}:
|
|
default:
|
|
}
|
|
}
|
|
}}
|
|
// Delay the actual reader after its first identity check, without a
|
|
// production hook. Log I/O and ordinary scheduling can delay it here.
|
|
entered, release := make(chan struct{}), make(chan struct{})
|
|
unblock := sync.OnceFunc(func() { close(release) })
|
|
previousLog := slog.Default()
|
|
defer slog.SetDefault(previousLog)
|
|
slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, &slog.HandlerOptions{
|
|
Level: slog.LevelDebug, ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
|
|
if attr.Key == "event" && attr.Value.String() == "capture-output-unavailable" {
|
|
close(entered)
|
|
<-release
|
|
}
|
|
return attr
|
|
},
|
|
})))
|
|
readerDone := make(chan error, 1)
|
|
go func() { readerDone <- session.runVideo() }()
|
|
defer func() {
|
|
unblock()
|
|
cancel()
|
|
_ = previous.Close()
|
|
_ = replacement.Close()
|
|
select {
|
|
case <-readerDone:
|
|
case <-time.After(5 * time.Second):
|
|
t.Error("capture reader did not retire")
|
|
}
|
|
}()
|
|
select {
|
|
case <-entered:
|
|
case err = <-readerDone:
|
|
readerDone <- err
|
|
t.Fatalf("reader stopped before output failure: %v", err)
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("old output failure did not reach the reader")
|
|
}
|
|
committed := make(chan error, 1)
|
|
if replace {
|
|
go func() {
|
|
committed <- session.commitCapture(options, QualityProfile{Video: options.Profile}, replacement, CaptureState{}, nil, false, nil)
|
|
}()
|
|
deadline := time.Now().Add(5 * time.Second)
|
|
for session.currentStream() != replacement {
|
|
if time.Now().After(deadline) {
|
|
t.Fatal("replacement was not selected")
|
|
}
|
|
time.Sleep(time.Millisecond)
|
|
}
|
|
}
|
|
unblock()
|
|
select {
|
|
case <-active:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("capture reader did not finish the failure or handoff")
|
|
}
|
|
if replace {
|
|
select {
|
|
case err = <-committed:
|
|
check(err)
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("replacement installation was not acknowledged")
|
|
}
|
|
}
|
|
if err = publication.SetActiveCount(1); (err == nil) != replace {
|
|
t.Fatalf("publication availability after replacement=%v: %v", replace, err)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestPreparedCaptureOutlivesItsPermissionOperation(t *testing.T) {
|
|
t.Setenv("PIIK_NATIVEHOST_PIPE_FIXTURE", "backend")
|
|
t.Setenv("PIIK_CAPTURE_STARTING", string(captureStatePayload(t,
|
|
`{"state":"starting","codec":"vp8","adapterIndex":0,"adapterName":"Fixture","adapterIdentity":"0:0","encoderName":"VP8","encoderIdentity":"vp8"}`)))
|
|
t.Setenv("PIIK_CAPTURE_ACTIVE", string(captureStatePayload(t, `{"state":"active","codec":"vp8","width":1280,"height":720,"fps":30}`)))
|
|
executable, err := os.Executable()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
shareContext, stopShare := context.WithCancel(t.Context())
|
|
defer stopShare()
|
|
operationContext, finishOperation := context.WithCancel(shareContext)
|
|
defer finishOperation()
|
|
session := &Session{ctx: shareContext, captureProcess: executable, edgeCapacity: 4}
|
|
stream, _, err := session.prepareVideo(operationContext, nativecapture.VideoOptions{
|
|
Target: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"}, Codec: "vp8",
|
|
Profile: nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 30, Bitrate: 3_000_000, Preference: "balanced"},
|
|
}, true, false)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer stream.Close()
|
|
finishOperation()
|
|
select {
|
|
case <-stream.Done():
|
|
t.Fatal("finishing permission preparation stopped its accepted picture")
|
|
case <-time.After(250 * time.Millisecond):
|
|
}
|
|
stopShare()
|
|
select {
|
|
case <-stream.Done():
|
|
case <-time.After(2 * time.Second):
|
|
t.Fatal("capture outlived its owning share")
|
|
}
|
|
}
|
|
|
|
func TestCaptureProfileRetainsSelectedBackendFromStarting(t *testing.T) {
|
|
t.Setenv("PIIK_NATIVEHOST_PIPE_FIXTURE", "backend")
|
|
t.Setenv("PIIK_CAPTURE_STARTING", string(captureStatePayload(t,
|
|
`{"state":"starting","hardwareOnly":true,"codec":"h264","adapterIndex":1,"adapterName":"GPU","adapterIdentity":"0:1","encoderIndex":2,"encoderName":"H264","encoderIdentity":"encoder"}`)))
|
|
t.Setenv("PIIK_CAPTURE_ACTIVE", string(captureStatePayload(t,
|
|
`{"state":"active","hardwareOnly":true,"codec":"h264","profileLevelId":"42c01f","width":1280,"height":720,"fps":30}`)))
|
|
executable, err := os.Executable()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
profile := nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 30, Bitrate: 3_000_000, Preference: "balanced"}
|
|
for _, failed := range []string{"", "0", "1", "5", "6"} {
|
|
t.Run("unavailable-"+failed, func(t *testing.T) {
|
|
t.Setenv("PIIK_CAPTURE_UNAVAILABLE", failed)
|
|
stream, err := nativecapture.StartVideo(t.Context(), executable, nativecapture.VideoOptions{
|
|
Target: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"}, Codec: "h264", Profile: profile, OutputGroups: 4,
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer stream.Close()
|
|
state, err := waitForCaptureProfile(t.Context(), stream, profile, "h264", false, false)
|
|
if failed == "1" || failed == "6" {
|
|
if err == nil {
|
|
t.Fatal("original or invalid output failure was accepted")
|
|
}
|
|
return
|
|
}
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if state.AdapterIndex == nil || *state.AdapterIndex != 1 || state.EncoderIndex == nil || *state.EncoderIndex != 2 {
|
|
t.Fatalf("active profile lost the actual hardware selection: %+v", state)
|
|
}
|
|
var unavailable []int
|
|
if failed != "" {
|
|
layer, _ := strconv.Atoi(failed)
|
|
unavailable = []int{layer}
|
|
}
|
|
if !slices.Equal(state.unavailableLayers, unavailable) {
|
|
t.Fatalf("preparation lost optional output failures: %+v", state.unavailableLayers)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestOutputPlanPreservesOriginalStartupAndIndependentActivation(t *testing.T) {
|
|
t.Setenv("PIIK_NATIVEHOST_PIPE_FIXTURE", "echo")
|
|
executable, err := os.Executable()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
|
defer cancel()
|
|
stream, err := nativecapture.StartVideo(ctx, executable, nativecapture.VideoOptions{
|
|
Target: nativecapture.CaptureTarget{Kind: "display", SourceID: "1", Title: "Fixture"}, Codec: "vp8",
|
|
Profile: nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 15,
|
|
Bitrate: 2_000_000, Preference: "balanced"}, OutputGroups: 2,
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer stream.Close()
|
|
plan := mediaedge.OutputPlan{Active: []bool{false, true, true, false}, Bitrates: []uint32{0, 0, 250_000, 0}}
|
|
if err = applyOutputPlan(stream, plan, false); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
plan.RecoveryLayers = []int{2}
|
|
if err = applyOutputPlan(stream, plan, true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
clear(plan.Active)
|
|
plan.RecoveryLayers = nil
|
|
if err = applyOutputPlan(stream, plan, true); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for _, command := range []string{"B 2 250000", "K 2", "A 0 0", "A 2 1", "A 1 0", "A 2 0"} {
|
|
frame, readErr := stream.Read()
|
|
if readErr != nil || frame.Kind != nativecapture.FrameControl || string(frame.Data) != command {
|
|
t.Fatalf("expected control %q, received %+v, %v", command, frame, readErr)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCaptureStateKeepsStartingAndActiveContractsDistinct(t *testing.T) {
|
|
starting, err := decodeCaptureState(captureStatePayload(t,
|
|
`{"state":"starting","hardwareOnly":true,"codec":"h264","adapterIndex":0,"adapterName":"GPU","adapterIdentity":"0:1","encoderIndex":0,"encoderName":"H264","encoderIdentity":"encoder"}`,
|
|
))
|
|
if err != nil || starting.State != "starting" || starting.AdapterIndex == nil {
|
|
t.Fatalf("starting = %+v, %v", starting, err)
|
|
}
|
|
active, err := decodeCaptureState(captureStatePayload(t,
|
|
`{"state":"active","hardwareOnly":true,"codec":"h264","profileLevelId":"42c01f","width":1280,"height":720,"fps":30}`,
|
|
))
|
|
if err != nil || active.State != "active" || active.ProfileLevelID != "42c01f" {
|
|
t.Fatalf("active = %+v, %v", active, err)
|
|
}
|
|
for _, payload := range []string{
|
|
`{"state":"starting","hardwareOnly":false,"codec":"vp8","adapterIndex":0,"adapterName":"GPU","adapterIdentity":"0:1","encoderName":"libvpx VP8","encoderIdentity":"libvpx/v1.17.0"}`,
|
|
`{"state":"active","hardwareOnly":false,"codec":"vp8","width":1280,"height":720,"fps":30}`,
|
|
`{"state":"active","hardwareOnly":true,"codec":"h264","profileLevelId":"42c01e","width":854,"height":480,"fps":15}`,
|
|
`{"state":"active","hardwareOnly":true,"codec":"h264","profileLevelId":"42c033","width":2560,"height":1440,"fps":60,"restoreToken":"portal-token"}`,
|
|
} {
|
|
if _, err = decodeCaptureState(captureStatePayload(t, payload)); err != nil {
|
|
t.Fatalf("valid profile state was rejected: %s: %v", payload, err)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCaptureStateRejectsUnknownOrUnattributedState(t *testing.T) {
|
|
for _, payload := range []string{
|
|
`{"state":"active","hardwareOnly":true,"codec":"vp8","width":1280,"height":720,"fps":30}`,
|
|
`{"state":"active","hardwareOnly":false,"codec":"vp8","profileLevelId":"42c01f","width":1280,"height":720,"fps":30}`,
|
|
`{"state":"active","hardwareOnly":false}`,
|
|
`{"state":"ready","hardwareOnly":true}`,
|
|
`{"state":"active","hardwareOnly":true,"codec":"h264","extra":true}`,
|
|
} {
|
|
if _, err := decodeCaptureState(captureStatePayload(t, payload)); err == nil {
|
|
t.Fatalf("invalid state was accepted: %s", payload)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCaptureStateValidatesH264ToolsRatherThanConstraintSpelling(t *testing.T) {
|
|
for _, profile := range []string{"42c01f", "42e01f", "42E033", "4d801f", "58c02a", "42c00a", "42c016", "42c034"} {
|
|
state, err := decodeCaptureState(captureStatePayload(t,
|
|
`{"state":"active","hardwareOnly":true,"codec":"h264","profileLevelId":"`+profile+`","width":1280,"height":720,"fps":30}`))
|
|
if err != nil || state.ProfileLevelID != profile {
|
|
t.Fatalf("equivalent Constrained Baseline %q was rejected or rewritten: %+v, %v", profile, state, err)
|
|
}
|
|
}
|
|
for _, profile := range []string{"42001f", "4d001f", "64001f", "42e11f", "42e01", "42e01fg", "42e0gg", "42e000", "42e035", "42e03c"} {
|
|
if _, err := decodeCaptureState(captureStatePayload(t,
|
|
`{"state":"active","hardwareOnly":true,"codec":"h264","profileLevelId":"`+profile+`","width":1280,"height":720,"fps":30}`)); err == nil {
|
|
t.Fatalf("incompatible profile/level %q was admitted", profile)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCaptureStateUsesOriginalSlotAndBoundsPhysicalGroups(t *testing.T) {
|
|
state, err := decodeCaptureState(captureStatePayload(t,
|
|
`{"state":"active","hardwareOnly":false,"codec":"vp8","width":1280,"height":720,"fps":30}`))
|
|
if err != nil || len(state.Outputs) != 6 || state.Outputs[5] != state.Outputs[0] {
|
|
t.Fatalf("independent output groups = %+v, %v", state, err)
|
|
}
|
|
wrongOriginal := state
|
|
wrongOriginal.Width = state.Outputs[5].Width
|
|
tooMany := state
|
|
tooMany.Outputs = append(tooMany.Outputs, tooMany.Outputs[0])
|
|
for _, invalid := range []CaptureState{wrongOriginal, tooMany} {
|
|
payload, err := json.Marshal(invalid)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err = decodeCaptureState(payload); err == nil {
|
|
t.Fatal("invalid original slot or output count was accepted")
|
|
}
|
|
}
|
|
}
|
|
|
|
func captureStatePayload(t *testing.T, payload string) []byte {
|
|
t.Helper()
|
|
var fields map[string]json.RawMessage
|
|
if err := json.Unmarshal([]byte(payload), &fields); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
profile := nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 30, Bitrate: 3_000_000}
|
|
for key, field := range map[string]*uint32{"width": &profile.Width, "height": &profile.Height, "fps": &profile.Framerate} {
|
|
if value, ok := fields[key]; ok {
|
|
if err := json.Unmarshal(value, field); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
}
|
|
slots := nativecapture.ScreenShareOutputs(profile)
|
|
for range 4 {
|
|
slots = append(slots, slots[0])
|
|
}
|
|
outputs, err := json.Marshal(slots)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
fields["outputs"] = outputs
|
|
result, err := json.Marshal(fields)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return result
|
|
}
|
|
|
|
func TestCandidateForRetiredEdgeIsIgnored(t *testing.T) {
|
|
session := &Session{}
|
|
if err := session.AddCandidate("retired-edge", nil); err != nil {
|
|
t.Fatalf("stale candidate stopped the session: %v", err)
|
|
}
|
|
}
|
|
|
|
func TestCaptureProfileFailurePreservesCauseWithoutCredentials(t *testing.T) {
|
|
previous := slog.Default()
|
|
t.Cleanup(func() { slog.SetDefault(previous) })
|
|
var output bytes.Buffer
|
|
slog.SetDefault(slog.New(slog.NewJSONHandler(&output, &slog.HandlerOptions{Level: slog.LevelDebug})))
|
|
failure := errors.New("profile failed: hresult=0x887a0005 token=private-capture-token")
|
|
profile := nativecapture.VideoProfile{Width: 1280, Height: 720, Framerate: 30, Bitrate: 3_000_000}
|
|
if captureProfileFailure(t.Context(), profile, "wait-timeout", failure) != failure {
|
|
t.Fatal("diagnostic changed the failure result")
|
|
}
|
|
var record map[string]any
|
|
if err := json.Unmarshal(output.Bytes(), &record); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if record["event"] != "capture-profile-rejected" || record["stage"] != "wait-timeout" ||
|
|
record["width"] != float64(1280) || record["height"] != float64(720) ||
|
|
record["fps"] != float64(30) || record["bitrate"] != float64(3_000_000) ||
|
|
!strings.Contains(output.String(), "0x887a0005") || strings.Contains(output.String(), "private-capture-token") {
|
|
t.Fatalf("profile diagnostic changed or leaked: %s", output.String())
|
|
}
|
|
}
|