This release adds microphone processing controls and local chat controls, expands platform packages, and synchronizes the website and guides. It also fixes native H.264 input/format handling, signaling recovery, fresh STUN discovery, and UDP ownership during overlapping connections. This is **v1.8.0**. Browser/Server v23, Native control v9 and capture v7 remain unchanged, with the existing 1440p ceiling. Additional resolutions, capability negotiation and Magicsock are separate follow-up work. ## Validation - Full local Web check: 79 files / 1,317 tests, TypeScript and production build. - Full Go checks, platform builds and Windows native capture regressions/probe. - Native H.264 Host lifecycle, Browser-to-App fanout and App-exit recovery, and Native H.264 through embedded SFU: all passed with owned process/port/profile cleanup. - Website build, documentation and repository hygiene passed. Existing UI acceptance covers narrow screens, both languages/themes, architecture downloads and all 23 film checks; final packaging and Go race checks run on the merged revision in CI. - Physical macOS/Linux capture, representative public networks and unmatched field reports retain their documented evidence limits. No claim that every blur/disconnection report is resolved. ## Release notes ### 中文 这是一次功能与兼容性更新:麦克风和聊天增加了实用的小选项,App 与 Server 支持更多设备,同时修复了原生分享和连接恢复中的若干问题。现有 1.x 协议保持不变。 #### 新增与改进 - 浏览器麦克风新增「降噪与回声消除」开关,默认开启回声消除、降噪和自动增益;分享音乐或使用虚拟音频输入时,可按需关闭。 - 可调整弹幕字号和透明度,并将当前保留的聊天记录导出为 TXT。当前会话最多保留 1,000 条文字消息,刷新页面后清空;需要保存时请先导出。 - 新增 Intel Mac、Linux ARM64 App,以及 Linux ARM64 Server 和容器镜像。官网下载区可直接选择对应架构,并显示最新版本和发布时间。 - 更新官网演示、README 截图和中英文教程,明确浏览器分享也可选择窗口或屏幕;开始分享前显示房间号占位,保持底栏控件位置稳定。 - 官网新增直达问题排查的入口,补充浏览器 WebRTC 限制、校园网和 Windows 显卡相关的排查步骤。 - App 模式选择页显示免费开源说明、作者与贡献者署名,以及官方网站和源码链接。 #### 修复 - 修正部分 H.264 原生分享的格式兼容性校验,以及 Windows 编码器输入长度和输出缓冲区对齐问题。 - 清理已失效的重连任务和 Native 接收信令,避免旧连接继续影响当前会话。 - 修复 App 重连时可能复用过期公网地址的问题;重新探测使用当前地址,并处理探测丢包和过期响应,保留其他正常连接。 - 修复 App 新旧媒体连接重叠时共用端口造成的冲突,避免准备或撤销新连接打断仍在使用的画面;关闭连接时及时取消未完成的端口映射请求。 - 无站点密码时,连接恢复不再误引导用户输入站点密码。 - 房间失效或会话终止时,开播前后的原因提示统一显示在电视状态图标中,避免额外提示条。 - 修正 Linux 原生采集的时间戳与关键帧时间基准。感谢 Pedro Antonio 在 [#449](https://github.com/TNTcraftHIM/Piik/pull/449) 的贡献。 #### 使用说明 下载对应平台的完整压缩包,退出旧 App 后解压使用。Windows 继续提供 x64;macOS 提供 Apple 芯片与 Intel 版本,原生采集需要 macOS 13 或更新版本。Linux 提供 x64 与 ARM64,原生采集还需安装[系统组件](https://github.com/TNTcraftHIM/Piik/blob/main/native/capture/linux/README.md)。macOS 和 Linux 的实机覆盖仍有限,欢迎反馈。 ### English This update adds useful microphone and chat controls, brings Piik to more devices, and fixes several native-sharing and connection-recovery issues. The existing 1.x protocols remain unchanged. #### New and improved - Browser microphones now have a “Noise & echo reduction” toggle. Echo cancellation, noise suppression and automatic gain control are on by default; turn them off when appropriate for music or virtual audio inputs. - Adjust chat-overlay text size and opacity, and export retained messages as TXT. The current session keeps up to 1,000 text messages and clears on page refresh; export first if you want to keep them. - Added Intel Mac and Linux ARM64 App packages, plus Linux ARM64 Server and container images. The website provides architecture selectors and shows the latest release and publication date. - Updated the website demonstration, README screenshots and bilingual guides, clarifying that browser capture can also select windows or screens. A room-code placeholder keeps the bottom bar stable before sharing starts. - Added direct website links to troubleshooting, with steps for browser WebRTC restrictions, campus networks and Windows graphics issues. - The App mode-selection page now shows its free and open-source status, author and contributor credit, and links to the official website and source. #### Fixes - Corrected H.264 format compatibility checks and Windows encoder input-length and output-buffer alignment handling. - Retired stale reconnect tasks and Native receive signals so they cannot continue affecting the current session. - Fixed App reconnection reusing an expired public address. Fresh discovery handles lost probes and stale responses while preserving other working connections. - Fixed UDP socket conflicts between overlapping App media connections so preparing or canceling a replacement preserves the active picture. Closing a connection now cancels unfinished gateway mapping requests. - Connection recovery on passwordless sites no longer incorrectly asks for a site passphrase. - Expired-room and session-termination reasons now use the same TV status indicator before and during sharing, without an extra notice strip. - Corrected Linux native capture timestamps and keyframe time bases. Thanks to Pedro Antonio for [#449](https://github.com/TNTcraftHIM/Piik/pull/449). #### Updating Download the complete archive for your platform, quit the old App, and extract the new package. Windows remains x64-only. macOS packages support Apple silicon and Intel; native capture requires macOS 13 or newer. Linux supports x64 and ARM64 and requires additional [system components](https://github.com/TNTcraftHIM/Piik/blob/main/native/capture/linux/README.md) for native capture. Physical-device coverage on macOS and Linux remains limited; feedback is welcome. ## Attribution Co-authored-by: Pedro Antonio <wrenchwastaken@gmail.com>
527 lines
20 KiB
Go
527 lines
20 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)
|
|
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)
|
|
}()
|
|
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)
|
|
}()
|
|
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 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"} {
|
|
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", "42e034", "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())
|
|
}
|
|
}
|