diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a05b2a9..562f42d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,6 @@ name: Release -# Builds the pet's installers with nsgo build (go tool nsgo, the version go.mod pins) and publishes them on the GitHub release of the tag: the macOS disk images on a macOS runner, signed with YLDM's Developer ID and notarized so Gatekeeper opens them without a warning, and the Linux packages and AppImages on Ubuntu, with nsgo build's install scripts. Windows is left out until the pet runs there (see the README). +# Builds the pet's installers with nsgo build (go tool nsgo, the version go.mod pins) and publishes them on the GitHub release of the tag: the macOS disk images on a macOS runner, signed with YLDM's Developer ID and notarized so Gatekeeper opens them without a warning, the Linux packages and AppImages on Ubuntu, with nsgo build's install scripts, and the Windows installers on Ubuntu too, with NSIS, as NSGo's desktop builds need no cgo. The Windows installers carry no signature yet, for which SmartScreen warns; that needs a code signing certificate. # # Push a tag v, matching version in nsgo.yaml, to release. The release's notes are CHANGELOG.md's section for the version (tools/release-notes.sh), followed by GitHub's list of the pull requests since the last release; a tag without that section fails before anything builds. A pull request that changes this file, or a run by hand (Actions › Release › Run workflow), builds and signs the same packages without publishing them, keeping them as the run's artifacts. # @@ -34,12 +34,17 @@ jobs: # installers: what each target must make, after nsgo-pet--, so that a package nsgo build leaves out fails the row rather than going missing from the release. scripts: install.sh and install.ps1, kept from one row. - { name: macOS, os: macos-latest, targets: "macos_arm64,macos_x64", installers: ".dmg" } - { name: Linux, os: ubuntu-latest, targets: "linux_x64,linux_arm64", installers: ".deb .pkg.tar.gz .AppImage", scripts: true } + - { name: Windows, os: ubuntu-latest, targets: "windows_x64", installers: "-setup.exe" } env: MACOS_SIGNING_IDENTITY: ${{ vars.MACOS_SIGNING_IDENTITY }} steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false + # Without NSIS nsgo build leaves the Windows installer out, which Collect the packages then fails on. + - name: Install NSIS, for the Windows installers + if: matrix.name == 'Windows' + run: sudo apt-get update && sudo apt-get install -y --no-install-recommends nsis # A tag that does not match the version in nsgo.yaml would publish packages named for another version, one without notes a release that says nothing, and one without the updates key installers no pet updates to. - name: Check the version if: startsWith(github.ref, 'refs/tags/') diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 19406a4..819e634 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -19,6 +19,7 @@ nsgo-pet is two things in one repository: the pet engine, a Go module any NSGo a - The engine is a module of its own so that importing it downloads no pets: `resources/` is about 175 MB and belongs to the app alone. The root `go.mod` replaces the engine with `./pet`, so both change together in one commit. - The engine ships no assets and no app policy. It opens no tray, checks for no updates, writes no storage, shows no text of its own and never calls `cx.Quit()`; menus, labels and lifecycle are the host's. +- On Windows, whose NSGo player refuses video with alpha ([nsgo#862](https://github.com/nsgo-dev/nsgo/issues/862)), the engine plays the WebM clips in its own decoder over libvpx, which the host ships in `resources/windows`; elsewhere it plays them with `core.Video`. - Everything that moves a window is behind `Options.Window`. A pet in a host's view plays walking clips in place and dangles where it is, as it has no window to move. - What the user is doing reaches the clips through `Context` alone: the host's `Options.Context`, or the app in front without one. Clip rules never read the host's state another way. - The engine's exported API is public: changing or removing any of it breaks hosts, so it needs the user's agreement first. @@ -38,7 +39,7 @@ The engine keeps no state beyond the pet it plays. The app stores the ID of the ## Verification -Both test suites run headless on `nsgotest`, which loads no media. The app's tests check every shipped pet's manifest and clip files, the policy's weights and the menus; the engine's cover loading, host state, playing by ID and leaving against fixture packs. Real playback, transparency, floating, walking at a screen's edge and Linux's X11 and Wayland differences need a manual run with `go tool nsgo dev`. +Both test suites run headless on `nsgotest`, which loads no media. The app's tests check every shipped pet's manifest and clip files, the policy's weights and the menus; the engine's cover loading, host state, playing by ID and leaving against fixture packs, and its Windows decoder against the app's clips where libvpx loads. Real playback, transparency, floating, walking at a screen's edge and Linux's X11 and Wayland differences need a manual run with `go tool nsgo dev`. ## Subjects diff --git a/CHANGELOG.md b/CHANGELOG.md index 95a67c3..d3fc8f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## [Unreleased] +- Run on Windows x64, decoding the WebM clips with libvpx, which NSGo's Windows player cannot play with their alpha. (#13 by @houko) - Make the docs' search a command palette driven by the arrow keys, mark the reader's place in the table of contents and drop the code blocks' title bars. ## [0.1.0] - 2026-11-22 diff --git a/README.md b/README.md index 17245f5..061fa2b 100644 --- a/README.md +++ b/README.md @@ -120,7 +120,7 @@ Your app owns the windows, menus and lifecycle. The engine opens no tray, checks | --- | --- | | macOS | Runs, playing the HEVC-with-alpha clips. | | Linux | Plays the WebM clips. The window floats on X11; on Wayland it cannot float or move itself. | -| Windows | Not yet: NSGo's Windows player refuses clips with alpha. | +| Windows | Runs on x64. NSGo's Windows player refuses clips with alpha, so the engine decodes the WebM clips itself with libvpx, which the app ships in `resources/windows` ([NOTICE](resources/windows/NOTICE.md)), and shows the frames in an image. | Lunar festivals, hit testing by the clip's alpha ([nsgo#599](https://github.com/nsgo-dev/nsgo/issues/599)), speech bubbles and weather are not done yet. @@ -134,6 +134,8 @@ go tool nsgo test . # the app's headless tests, which check every pet in (cd pet && go test ./...) # the engine's tests ``` +The tests of the Windows decoder run where libvpx loads: on macOS with Homebrew's (`brew install libvpx`), on Linux with the distribution's; elsewhere they are skipped. + The website is in `website/` and its docs in `docs/public/`; with [Bun](https://bun.sh), `bun install && bun run dev` there serves them and `bun run build` builds them. To release, move `CHANGELOG.md`'s `Unreleased` bullets under `## [] - `, set `version` in `nsgo.yaml` to the same version and push the tag `v`. [The release workflow](.github/workflows/release.yml) builds, signs and publishes the installers with that section as the notes. @@ -142,4 +144,4 @@ Read [ARCHITECTURE.md](ARCHITECTURE.md) before changing code, and [AGENTS.md](AG ## License -The code, the app and the engine, is MIT, Copyright (c) 2026 nsgo-dev: see [LICENSE](LICENSE). Each pet keeps its own license, listed under [Pets](#pets) and in its `NOTICE.md`. NSGo-chan's art is CC BY-NC 4.0 and Big Blue Fish's character CC BY-NC-SA 4.0, so a build that includes either may not be used commercially. +The code, the app and the engine, is MIT, Copyright (c) 2026 nsgo-dev: see [LICENSE](LICENSE). Each pet keeps its own license, listed under [Pets](#pets) and in its `NOTICE.md`. NSGo-chan's art is CC BY-NC 4.0 and Big Blue Fish's character CC BY-NC-SA 4.0, so a build that includes either may not be used commercially. The libvpx and winpthreads libraries in `resources/windows` keep theirs, BSD-3-Clause and MIT, in [its NOTICE](resources/windows/NOTICE.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index f60755d..d7e0a32 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -120,7 +120,7 @@ desktop.OpenWindow(cx, pet.WindowOptions(pack), func(cx *core.Scope) core.Node { | --- | --- | | macOS | 可运行,播放带透明通道的 HEVC 动画。 | | Linux | 播放 WebM 动画。X11 下窗口可浮动;Wayland 下不能浮动,也不能自己移动。 | -| Windows | 暂不支持:NSGo 的 Windows 播放器拒绝带透明通道的视频。 | +| Windows | 可在 x64 上运行。NSGo 的 Windows 播放器拒绝带透明通道的视频,所以引擎用 libvpx 自己解码 WebM 动画并显示在图片里;libvpx 由应用放在 `resources/windows` 中分发([NOTICE](resources/windows/NOTICE.md))。 | 农历节日、按动画透明度判定点击([nsgo#599](https://github.com/nsgo-dev/nsgo/issues/599))、对话气泡和天气还没做。 @@ -134,6 +134,8 @@ go tool nsgo test . # the app's headless tests, which check every pet in (cd pet && go test ./...) # the engine's tests ``` +Windows 解码器的测试只在能加载 libvpx 的地方运行:macOS 上用 Homebrew 的(`brew install libvpx`),Linux 上用发行版的;其他情况下跳过。 + 网站在 `website/`,文档在 `docs/public/`;装好 [Bun](https://bun.sh) 后,在那里运行 `bun install && bun run dev` 启动预览,`bun run build` 构建。 发布时,把 `CHANGELOG.md` 里 `Unreleased` 下的条目移到 `## [<版本>] - <日期>` 下,把 `nsgo.yaml` 的 `version` 设为同一版本,然后推送标签 `v<版本>`。[发布工作流](.github/workflows/release.yml) 会构建、签名并发布安装包,以该节作为发布说明。 @@ -142,4 +144,4 @@ go tool nsgo test . # the app's headless tests, which check every pet in ## 许可证 -代码(应用和引擎)采用 MIT 许可,Copyright (c) 2026 nsgo-dev,见 [LICENSE](LICENSE)。每只宠物保留各自的许可,列在 [宠物](#宠物) 和各自的 `NOTICE.md` 中。NSGo 酱的美术采用 CC BY-NC 4.0,大蓝鱼的角色采用 CC BY-NC-SA 4.0,因此包含其中任一只的构建都不得商用。 +代码(应用和引擎)采用 MIT 许可,Copyright (c) 2026 nsgo-dev,见 [LICENSE](LICENSE)。每只宠物保留各自的许可,列在 [宠物](#宠物) 和各自的 `NOTICE.md` 中。NSGo 酱的美术采用 CC BY-NC 4.0,大蓝鱼的角色采用 CC BY-NC-SA 4.0,因此包含其中任一只的构建都不得商用。`resources/windows` 中的 libvpx 和 winpthreads 库保留各自的许可(BSD-3-Clause 和 MIT),见[其 NOTICE](resources/windows/NOTICE.md)。 diff --git a/app_test.go b/app_test.go index a991734..4fa8af5 100644 --- a/app_test.go +++ b/app_test.go @@ -322,3 +322,39 @@ func TestStatsAgentNamesThePlatform(t *testing.T) { t.Errorf("web agent = %q, want none", a) } } + +var windows = nsgotest.Environment(core.Environment{OS: core.OSWindows, Idiom: core.IdiomDesktop}) + +// On Windows a pet chosen in the settings' grid replaces the one playing, as the app's window does, and plays in the engine's own player, an image rather than a video; the engine's tests decode its frames. +func TestWindowsSettingsSwitchPets(t *testing.T) { + ps := packs(t) + find := func(id string) *pet.Pack { + for _, p := range ps { + if p.ID == id { + return p + } + } + t.Fatalf("no %s pet", id) + return nil + } + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + chosen := core.NewSignal(cx, "nsgo-chan") + return core.View{Style: core.Style{Direction: core.Row}, Children: []core.Node{ + core.View{Style: core.Style{Width: core.Pt(620), Height: core.Pt(500)}, Children: []core.Node{Settings(cx, prefs(t, cx, chosen, core.NewSignal(cx, true)))}}, + core.Dynamic(func(cx *core.Scope) core.Node { + p := pet.New(cx, find(chosen.Get()), pet.Options{}) + cx.Post(p.Start) + return p.View() + }), + }} + }, windows) + player := func(name string) bool { + v := app.FindMounted("id:slot1") + return v.Kind.String() == "image" && v.Props.Label == name + } + if !player(find("nsgo-chan").Name) { + t.Fatalf("NSGo-chan plays in a %s labeled %q, want the engine's image", app.FindMounted("id:slot1").Kind, app.FindMounted("id:slot1").Props.Label) + } + app.Press("id:pet-bigbluefish") + app.WaitUntil(10*time.Second, func() bool { return player(find("bigbluefish").Name) }) +} diff --git a/docs/public/en/embedding.md b/docs/public/en/embedding.md index d254776..410753c 100644 --- a/docs/public/en/embedding.md +++ b/docs/public/en/embedding.md @@ -27,6 +27,8 @@ func loadPacks() ([]*pet.Pack, error) { } ``` +On Windows, whose NSGo player refuses clips with alpha, the engine decodes the WebM clips itself with libvpx, which your app ships: copy `libvpx-1.dll` and `libwinpthread-1.dll` from nsgo-pet's [`resources/windows/`](https://github.com/nsgo-dev/nsgo-pet/tree/main/resources/windows) into your app's `resources/windows/`, with their licenses. + ## Show a pet As a view in your own layout: diff --git a/docs/public/zh/embedding.md b/docs/public/zh/embedding.md index 2caef1b..6b1992f 100644 --- a/docs/public/zh/embedding.md +++ b/docs/public/zh/embedding.md @@ -27,6 +27,8 @@ func loadPacks() ([]*pet.Pack, error) { } ``` +Windows 上 NSGo 的播放器拒绝带透明通道的动画,引擎会用 libvpx 自己解码 WebM 动画,而 libvpx 由你的应用分发:把 nsgo-pet 的 [`resources/windows/`](https://github.com/nsgo-dev/nsgo-pet/tree/main/resources/windows) 里的 `libvpx-1.dll` 和 `libwinpthread-1.dll` 连同它们的许可复制到你的应用的 `resources/windows/`。 + ## 展示宠物 作为一个视图放进你自己的布局: diff --git a/go.mod b/go.mod index a9929b9..e388954 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( require ( github.com/andybalholm/brotli v1.3.0 // indirect + github.com/at-wat/ebml-go v0.19.4 // indirect github.com/dop251/goja v0.0.0-20261027234916-5f913d1693d9 // indirect github.com/ebitengine/purego v0.11.3 // indirect github.com/evanw/esbuild v0.28.2 // indirect diff --git a/go.sum b/go.sum index 57ae64d..00d75b8 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,7 @@ github.com/andybalholm/brotli v1.3.0 h1:IdkhjSe/+34U+fP7FSR2Q6Poj1hnHUa2GoWmzXJd6qY= github.com/andybalholm/brotli v1.3.0/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY= +github.com/at-wat/ebml-go v0.19.4 h1:6F767ThzH/JqNUsF79PwRFP0pwUF5ALXWJ6pXuiolI8= +github.com/at-wat/ebml-go v0.19.4/go.mod h1:wu3fQj+DWo6SOOl9c4yDi+gFs9Oa96Z2B5qxo1OxFYY= github.com/dlclark/regexp2/v2 v2.11.0 h1:z5uRPHav+eTVpoffDSuUP2KPS4f1ONZaPDK73S8HA0w= github.com/dlclark/regexp2/v2 v2.11.0/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= github.com/dop251/goja v0.0.0-20261027234916-5f913d1693d9 h1:K1R7adPxJGLfojyUBe6TuuqcvS6YqQAdg2HujQ9Il+Y= diff --git a/nsgo.yaml b/nsgo.yaml index 012b781..147d969 100644 --- a/nsgo.yaml +++ b/nsgo.yaml @@ -29,8 +29,8 @@ build: output: dist # true opens the output directory after building. open: true - # Desktop only, the targets the release publishes; Windows waits until the pet plays there (see the README). - targets: [macos_arm64, macos_x64, linux_x64, linux_arm64] + # Desktop only, the targets the release publishes. + targets: [macos_arm64, macos_x64, linux_x64, linux_arm64, windows_x64] # The repository whose latest release holds the appcasts installed pets read. release: diff --git a/pet/clip.go b/pet/clip.go new file mode 100644 index 0000000..ea49b46 --- /dev/null +++ b/pet/clip.go @@ -0,0 +1,212 @@ +package pet + +import ( + "bytes" + "cmp" + "errors" + "fmt" + "image" + "slices" + "time" + + "github.com/at-wat/ebml-go" +) + +// clip is a WebM clip's VP9 frames as its file stores them: each frame's color picture and, in the block's additions, its alpha picture, a second VP9 stream. +type clip struct { + width, height int + frames []clipFrame + // duration is how long the clip plays, its last frame included. + duration time.Duration +} + +// clipFrame is one frame: when it shows, and its compressed color and alpha pictures; alpha is nil for a frame without one, which is opaque. +type clipFrame struct { + at time.Duration + color, alpha []byte +} + +// webmFile is what demuxClip reads of a WebM file. A video frame with alpha is a BlockGroup, as only a BlockGroup has additions; one without may be a SimpleBlock. +type webmFile struct { + Segment struct { + Info struct { + TimecodeScale uint64 `ebml:"TimecodeScale"` + Duration float64 `ebml:"Duration"` + } `ebml:"Info"` + Tracks struct { + TrackEntry []struct { + TrackNumber uint64 `ebml:"TrackNumber"` + TrackType uint64 `ebml:"TrackType"` + CodecID string `ebml:"CodecID"` + DefaultDuration uint64 `ebml:"DefaultDuration"` + Video *struct { + PixelWidth uint64 `ebml:"PixelWidth"` + PixelHeight uint64 `ebml:"PixelHeight"` + } `ebml:"Video"` + } `ebml:"TrackEntry"` + } `ebml:"Tracks"` + Cluster []struct { + Timecode uint64 `ebml:"Timecode"` + SimpleBlock []ebml.Block `ebml:"SimpleBlock"` + BlockGroup []struct { + Block ebml.Block `ebml:"Block"` + BlockAdditions struct { + BlockMore []struct { + BlockAddID uint64 `ebml:"BlockAddID"` + BlockAdditional []byte `ebml:"BlockAdditional"` + } `ebml:"BlockMore"` + } `ebml:"BlockAdditions"` + } `ebml:"BlockGroup"` + } `ebml:"Cluster"` + } `ebml:"Segment"` +} + +// trackVideo is Matroska's TrackType of a video track. +const trackVideo = 1 + +// alphaAddID is the BlockAddID of the additions that hold a frame's alpha picture, as Matroska's AlphaMode 1 says. It is also BlockAddID's default, which a muxer may leave out; ebml-go fills in no defaults, so an absent BlockAddID reads as 0, which no BlockMore may have. +const alphaAddID = 1 + +// demuxClip reads the VP9 video track of a WebM file. +func demuxClip(data []byte) (*clip, error) { + var f webmFile + if err := ebml.Unmarshal(bytes.NewReader(data), &f, ebml.WithIgnoreUnknown(true)); err != nil { + return nil, err + } + s := &f.Segment + scale := s.Info.TimecodeScale + if scale == 0 { + // Matroska's default: timecodes in milliseconds. + scale = 1_000_000 + } + c := &clip{} + var track, frameDuration uint64 + for _, t := range s.Tracks.TrackEntry { + if t.TrackType == trackVideo && t.Video != nil { + if t.CodecID != "V_VP9" { + return nil, fmt.Errorf("the video is %s, not VP9", t.CodecID) + } + track, frameDuration = t.TrackNumber, t.DefaultDuration + c.width, c.height = int(t.Video.PixelWidth), int(t.Video.PixelHeight) + break + } + } + if track == 0 { + return nil, errors.New("no video track") + } + add := func(cluster uint64, b ebml.Block, alpha []byte) error { + if b.TrackNumber != track { + return nil + } + if len(b.Data) != 1 { + return fmt.Errorf("a video block holds %d frames, not one", len(b.Data)) + } + ticks := int64(cluster) + int64(b.Timecode) + c.frames = append(c.frames, clipFrame{at: time.Duration(ticks * int64(scale)), color: b.Data[0], alpha: alpha}) + return nil + } + for _, cl := range s.Cluster { + for _, b := range cl.SimpleBlock { + if err := add(cl.Timecode, b, nil); err != nil { + return nil, err + } + } + for _, g := range cl.BlockGroup { + var alpha []byte + for _, m := range g.BlockAdditions.BlockMore { + if m.BlockAddID == alphaAddID || m.BlockAddID == 0 { + alpha = m.BlockAdditional + } + } + if err := add(cl.Timecode, g.Block, alpha); err != nil { + return nil, err + } + } + } + if len(c.frames) == 0 { + return nil, errors.New("no video frames") + } + // A cluster's SimpleBlocks and BlockGroups come apart above; VP9 in WebM decodes in the order frames show, as its hidden frames travel inside the shown ones. + slices.SortStableFunc(c.frames, func(a, b clipFrame) int { return cmp.Compare(a.at, b.at) }) + last := c.frames[len(c.frames)-1].at + switch { + case s.Info.Duration > 0: + c.duration = time.Duration(s.Info.Duration * float64(scale)) + case frameDuration > 0: + c.duration = last + time.Duration(frameDuration) + case len(c.frames) > 1: + c.duration = last + last/time.Duration(len(c.frames)-1) + } + c.duration = max(c.duration, last) + return c, nil +} + +// yuvPlanes is a decoded 8-bit 4:2:0 picture: y at full size, u and v at half the width and height, rounded up. +type yuvPlanes struct { + width, height int + y, u, v []byte + yStride, uStride, vStride int + // bt709 picks BT.709's matrix over BT.601's, and fullRange Y and chroma over 0 to 255 instead of 16 to 235 and 240. + bt709, fullRange bool +} + +// yuvMatrix is a YUV to RGB matrix in 8.8 fixed point: y is Y's factor, rv V's in red, gu and gv U's and V's in green, bu U's in blue. +type yuvMatrix struct{ y, rv, gu, gv, bu int32 } + +var ( + bt601Limited = yuvMatrix{298, 409, 100, 208, 516} + bt709Limited = yuvMatrix{298, 459, 55, 136, 541} + bt601Full = yuvMatrix{256, 359, 88, 183, 454} + bt709Full = yuvMatrix{256, 403, 48, 120, 475} +) + +// toRGBA writes the picture into dst, premultiplied as image.RGBA is, with alpha from the luma of a, the alpha stream's picture, or opaque where a is nil. dst and a are the picture's size. +func (p *yuvPlanes) toRGBA(dst *image.RGBA, a *yuvPlanes) { + m := bt601Limited + switch { + case p.bt709 && p.fullRange: + m = bt709Full + case p.bt709: + m = bt709Limited + case p.fullRange: + m = bt601Full + } + var black int32 = 16 + if p.fullRange { + black = 0 + } + w, h := dst.Rect.Dx(), dst.Rect.Dy() + for row := range h { + ys := p.y[row*p.yStride:] + us := p.u[(row/2)*p.uStride:] + vs := p.v[(row/2)*p.vStride:] + var as []byte + if a != nil { + as = a.y[row*a.yStride:] + } + out := dst.Pix[row*dst.Stride : row*dst.Stride+4*w] + for col := range w { + alpha := int32(255) + if as != nil { + alpha = int32(as[col]) + } + px := out[4*col : 4*col+4 : 4*col+4] + if alpha == 0 { + px[0], px[1], px[2], px[3] = 0, 0, 0, 0 + continue + } + c := m.y * (int32(ys[col]) - black) + d := int32(us[col/2]) - 128 + e := int32(vs[col/2]) - 128 + r := clamp8((c + m.rv*e + 128) >> 8) + g := clamp8((c - m.gu*d - m.gv*e + 128) >> 8) + b := clamp8((c + m.bu*d + 128) >> 8) + if alpha < 255 { + r, g, b = (r*alpha+127)/255, (g*alpha+127)/255, (b*alpha+127)/255 + } + px[0], px[1], px[2], px[3] = uint8(r), uint8(g), uint8(b), uint8(alpha) + } + } +} + +func clamp8(v int32) int32 { return min(max(v, 0), 255) } diff --git a/pet/clip_test.go b/pet/clip_test.go new file mode 100644 index 0000000..399e4f1 --- /dev/null +++ b/pet/clip_test.go @@ -0,0 +1,369 @@ +package pet + +import ( + "bytes" + "image" + "os" + "path/filepath" + "testing" + "time" + + "github.com/at-wat/ebml-go" + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// The tests run in the engine's folder, which ships no clips: they play nsgo-pet's, and on Windows its libvpx, from the app's resources beside it rather than beside the test's executable. +func init() { resourceRoot = filepath.Join("..", "resources") } + +// appPets is where nsgo-pet's pets are. +var appPets = filepath.Join("..", "resources", "pets") + +func readClip(t *testing.T, path string) *clip { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + c, err := demuxClip(data) + if err != nil { + t.Fatalf("%s: %v", path, err) + } + return c +} + +// Big Blue Fish's clips are 640 by 360 at 24 frames a second, each frame with its alpha picture, and play for their Duration. +func TestDemuxBigBlueFish(t *testing.T) { + c := readClip(t, filepath.Join(appPets, "bigbluefish", "webm", "待机呼吸休闲.webm")) + if c.width != 640 || c.height != 360 { + t.Fatalf("size %dx%d, want 640x360", c.width, c.height) + } + if len(c.frames) < 24 { + t.Fatalf("%d frames", len(c.frames)) + } + for i, f := range c.frames { + if len(f.color) == 0 || len(f.alpha) == 0 { + t.Fatalf("frame %d: %d bytes of color, %d of alpha", i, len(f.color), len(f.alpha)) + } + if i > 0 && f.at <= c.frames[i-1].at { + t.Fatalf("frame %d at %v after frame %d at %v", i, f.at, i-1, c.frames[i-1].at) + } + } + if c.frames[0].at != 0 { + t.Fatalf("the first frame shows at %v", c.frames[0].at) + } + step := c.frames[1].at - c.frames[0].at + if step < 41*time.Millisecond || step > 42*time.Millisecond { + t.Fatalf("frames %v apart, want 1/24 s", step) + } + last := c.frames[len(c.frames)-1].at + if c.duration < last || c.duration > last+2*step { + t.Fatalf("duration %v with the last frame at %v", c.duration, last) + } +} + +// Every one of nsgo-pet's WebM clips demuxes, so the Windows player can open all of them. +func TestDemuxEveryClip(t *testing.T) { + packs, err := LoadDir(appPets) + if err != nil { + t.Fatal(err) + } + for _, pk := range packs { + for _, r := range pk.Policy.Rules { + c := readClip(t, clipPath(pk.Base+"/webm/"+r.File)) + if c.width <= 0 || c.height <= 0 || c.duration <= 0 { + t.Errorf("%s %s: %dx%d for %v", pk.ID, r.ID, c.width, c.height, c.duration) + } + for i, f := range c.frames { + if f.alpha == nil { + t.Errorf("%s %s: frame %d has no alpha", pk.ID, r.ID, i) + break + } + } + } + } +} + +// A BlockMore without a BlockAddID holds the alpha picture, as BlockAddID's default is 1: muxers that leave out elements at their default write it so. +func TestDemuxAlphaWithoutBlockAddID(t *testing.T) { + type blockMore struct { + BlockAdditional []byte `ebml:"BlockAdditional"` + } + type blockGroup struct { + Block ebml.Block `ebml:"Block"` + BlockAdditions struct { + BlockMore []blockMore `ebml:"BlockMore"` + } `ebml:"BlockAdditions"` + } + type video struct { + PixelWidth uint64 `ebml:"PixelWidth"` + PixelHeight uint64 `ebml:"PixelHeight"` + } + type trackEntry struct { + TrackNumber uint64 `ebml:"TrackNumber"` + TrackType uint64 `ebml:"TrackType"` + CodecID string `ebml:"CodecID"` + Video video `ebml:"Video"` + } + type cluster struct { + Timecode uint64 `ebml:"Timecode"` + BlockGroup []blockGroup `ebml:"BlockGroup"` + } + var f struct { + Segment struct { + Tracks struct { + TrackEntry []trackEntry `ebml:"TrackEntry"` + } `ebml:"Tracks"` + Cluster []cluster `ebml:"Cluster"` + } `ebml:"Segment"` + } + f.Segment.Tracks.TrackEntry = []trackEntry{{TrackNumber: 1, TrackType: trackVideo, CodecID: "V_VP9", Video: video{PixelWidth: 2, PixelHeight: 2}}} + g := blockGroup{Block: ebml.Block{TrackNumber: 1, Keyframe: true, Data: [][]byte{{0xc0}}}} + g.BlockAdditions.BlockMore = []blockMore{{BlockAdditional: []byte{0xa0}}} + f.Segment.Cluster = []cluster{{BlockGroup: []blockGroup{g}}} + var buf bytes.Buffer + if err := ebml.Marshal(&f, &buf); err != nil { + t.Fatal(err) + } + c, err := demuxClip(buf.Bytes()) + if err != nil { + t.Fatal(err) + } + if len(c.frames) != 1 || !bytes.Equal(c.frames[0].alpha, []byte{0xa0}) { + t.Fatalf("frames %+v, want one with its alpha", c.frames) + } +} + +// planes makes a 2 by 2 picture of one Y, U and V. +func planes(y, u, v byte, fullRange bool) *yuvPlanes { + return &yuvPlanes{width: 2, height: 2, y: []byte{y, y, y, y}, u: []byte{u}, v: []byte{v}, yStride: 2, uStride: 1, vStride: 1, fullRange: fullRange} +} + +func alphaPlanes(a ...byte) *yuvPlanes { + return &yuvPlanes{width: 2, height: 2, y: a, yStride: 2} +} + +func TestToRGBA(t *testing.T) { + for _, c := range []struct { + name string + p, a *yuvPlanes + want0 [4]uint8 + want3 [4]uint8 + }{ + {"limited white, opaque", planes(235, 128, 128, false), nil, [4]uint8{255, 255, 255, 255}, [4]uint8{255, 255, 255, 255}}, + {"limited black", planes(16, 128, 128, false), alphaPlanes(255, 255, 255, 255), [4]uint8{0, 0, 0, 255}, [4]uint8{0, 0, 0, 255}}, + {"full white", planes(255, 128, 128, true), nil, [4]uint8{255, 255, 255, 255}, [4]uint8{255, 255, 255, 255}}, + // BT.601 red is Y 81, U 90, V 240 in limited range. + {"red, then transparent", planes(81, 90, 240, false), alphaPlanes(255, 255, 255, 0), [4]uint8{255, 0, 0, 255}, [4]uint8{0, 0, 0, 0}}, + // Half-transparent white is premultiplied. + {"half white", planes(235, 128, 128, false), alphaPlanes(128, 128, 128, 128), [4]uint8{128, 128, 128, 128}, [4]uint8{128, 128, 128, 128}}, + } { + dst := image.NewRGBA(image.Rect(0, 0, 2, 2)) + c.p.toRGBA(dst, c.a) + got0, got3 := [4]uint8(dst.Pix[0:4]), [4]uint8(dst.Pix[12:16]) + if far(got0, c.want0) || far(got3, c.want3) { + t.Errorf("%s: %v and %v, want %v and %v", c.name, got0, got3, c.want0, c.want3) + } + } +} + +// far reports whether a and b differ by more than rounding. +func far(a, b [4]uint8) bool { + for i := range a { + if d := int(a[i]) - int(b[i]); d < -2 || d > 2 { + return true + } + } + return false +} + +// A real clip decodes with libvpx into a picture whose corners are transparent and whose middle, where the pet is, is not. It needs libvpx: on Windows nsgo-pet's DLL in its resources/windows, elsewhere the system's. +func TestDecodeClip(t *testing.T) { + if err := loadVPX(); err != nil { + t.Skip(err) + } + c := readClip(t, filepath.Join(appPets, "bigbluefish", "webm", "待机呼吸休闲.webm")) + color, err := newVP9Decoder() + if err != nil { + t.Fatal(err) + } + defer color.close() + alpha, err := newVP9Decoder() + if err != nil { + t.Fatal(err) + } + defer alpha.close() + dst := image.NewRGBA(image.Rect(0, 0, c.width, c.height)) + for i, f := range c.frames { + p, ok, err := color.decode(f.color) + if err != nil || !ok { + t.Fatalf("frame %d: %v, %v", i, ok, err) + } + a, ok, err := alpha.decode(f.alpha) + if err != nil || !ok { + t.Fatalf("frame %d's alpha: %v, %v", i, ok, err) + } + if p.width != c.width || p.height != c.height || a.width != c.width || a.height != c.height { + t.Fatalf("frame %d is %dx%d with alpha %dx%d", i, p.width, p.height, a.width, a.height) + } + p.toRGBA(dst, &a) + } + // The alpha stream is lossy, so transparent parts may keep an alpha of a few levels. + if corner := dst.RGBAAt(0, 0); corner.A > 8 { + t.Errorf("the corner is %v, want transparent", corner) + } + opaque := 0 + for y := c.height / 4; y < 3*c.height/4; y++ { + for x := c.width / 3; x < 2*c.width/3; x++ { + if dst.RGBAAt(x, y).A == 255 { + opaque++ + } + } + } + if opaque < c.width*c.height/30 { + t.Errorf("%d opaque pixels in the middle, want the fish", opaque) + } +} + +// BenchmarkDecodeFrame measures one of Big Blue Fish's 640 by 360 frames: decoding its color and alpha pictures and writing them as RGBA, what the Windows player does 24 times a second. +func BenchmarkDecodeFrame(b *testing.B) { + if err := loadVPX(); err != nil { + b.Skip(err) + } + data, err := os.ReadFile(filepath.Join(appPets, "bigbluefish", "webm", "待机呼吸休闲.webm")) + if err != nil { + b.Fatal(err) + } + c, err := demuxClip(data) + if err != nil { + b.Fatal(err) + } + dst := image.NewRGBA(image.Rect(0, 0, c.width, c.height)) + var color, alpha *vp9Decoder + for i := 0; b.Loop(); i++ { + n := i % len(c.frames) + if n == 0 { + color.close() + alpha.close() + if color, err = newVP9Decoder(); err != nil { + b.Fatal(err) + } + if alpha, err = newVP9Decoder(); err != nil { + b.Fatal(err) + } + } + p, _, err := color.decode(c.frames[n].color) + if err != nil { + b.Fatal(err) + } + a, _, err := alpha.decode(c.frames[n].alpha) + if err != nil { + b.Fatal(err) + } + p.toRGBA(dst, &a) + } + color.close() + alpha.close() +} + +var windows = nsgotest.Environment(core.Environment{OS: core.OSWindows, Idiom: core.IdiomDesktop}) + +// appPack is one of nsgo-pet's pets, loaded from its directory, so the Windows player reads its clips from their files. +func appPack(t *testing.T, id string) *Pack { + t.Helper() + packs, err := LoadDir(appPets) + for _, p := range packs { + if p.ID == id { + return p + } + } + t.Fatalf("no %s pet: %v", id, err) + return nil +} + +// showing is whether the slot id shows a decoded picture. +func showing(app *nsgotest.App, id string) bool { + v := app.FindMounted("id:" + id) + return v.Image.Source.Pixels != nil && v.Style.Opacity == 1 +} + +// On Windows the clips play in the engine's own decoder: the greeting's first picture shows in an image, and once the greeting ends an idle clip takes over in the other slot. It needs libvpx, as TestDecodeClip does. +func TestWindowsPlaysClipsItself(t *testing.T) { + if err := loadVPX(); err != nil { + t.Skip(err) + } + pack := appPack(t, "nsgo-chan") + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + p := New(cx, pack, Options{}) + cx.Post(p.Start) + return p.View() + }, windows) + app.WaitUntil(10*time.Second, func() bool { return showing(app, "slot1") }) + if showing(app, "slot0") { + t.Fatal("both slots show") + } + // The fake clock moves on while the decoder keeps up in real time. + deadline := time.Now().Add(30 * time.Second) + for !showing(app, "slot0") { + if time.Now().After(deadline) { + t.Fatal("no idle clip after the greeting") + } + app.Advance(40 * time.Millisecond) + } + if showing(app, "slot1") { + t.Fatal("the greeting still shows over the idle clip") + } +} + +// A host switching pets on Windows, as nsgo-pet's settings do, starts the new pet's own players, which show its greeting. +func TestWindowsSwitchesPets(t *testing.T) { + if err := loadVPX(); err != nil { + t.Skip(err) + } + nsgoChan, fish := appPack(t, "nsgo-chan"), appPack(t, "bigbluefish") + var chosen *core.Signal[*Pack] + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + chosen = core.NewSignal(cx, nsgoChan) + return core.Dynamic(func(cx *core.Scope) core.Node { + p := New(cx, chosen.Get(), Options{}) + cx.Post(p.Start) + return p.View() + }) + }, windows) + app.WaitUntil(10*time.Second, func() bool { return showing(app, "slot1") }) + app.Post(func() { chosen.Set(fish) }) + app.WaitUntil(10*time.Second, func() bool { + v := app.FindMounted("id:slot1") + return v.Props.Label == fish.Name && showing(app, "slot1") && v.Image.Source.Pixels.Rect.Dx() == 640 + }) +} + +// A clip chosen again while the hidden slot still holds it shows only once Windows' player has decoded it anew, not with the frame the slot last showed. +func TestWindowsReplaysAClipFromItsStart(t *testing.T) { + if err := loadVPX(); err != nil { + t.Skip(err) + } + pack := appPack(t, "nsgo-chan") + var p *Pet + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + p = New(cx, pack, Options{}) + cx.Post(p.Start) + return p.View() + }, windows) + app.WaitUntil(10*time.Second, func() bool { return showing(app, "slot1") }) + app.Post(func() { p.Play("idle") }) + app.WaitUntil(10*time.Second, func() bool { return showing(app, "slot0") && !showing(app, "slot1") }) + stale := app.FindMounted("id:slot1").Image.Source.Version + app.Post(func() { p.Play(pack.Clips.Greeting) }) + app.Settle() + if v := app.FindMounted("id:slot1"); v.Style.Opacity == 1 && v.Image.Source.Version == stale { + t.Fatal("the slot shows the greeting's old frame") + } + app.WaitUntil(10*time.Second, func() bool { + v := app.FindMounted("id:slot1") + return showing(app, "slot1") && v.Image.Source.Version > stale + }) + if showing(app, "slot0") { + t.Fatal("both slots show") + } +} diff --git a/pet/clipplayer.go b/pet/clipplayer.go new file mode 100644 index 0000000..e1532be --- /dev/null +++ b/pet/clipplayer.go @@ -0,0 +1,325 @@ +package pet + +import ( + "context" + "fmt" + "image" + "os" + "path/filepath" + "strings" + "time" + + "github.com/nsgo-dev/nsgo/core" +) + +// NSGo refuses alpha video on Windows (internal/platform/windows/video.go): whether Media Foundation keeps the alpha of VP9 in WebM was never checked there, so its player reports VideoErrorAlphaUnsupported and asks the app to decode such clips itself. clipPlayer does that for the pet on Windows: it demuxes the WebM clip, decodes its color and alpha streams with libvpx on a goroutine of its own, and shows each frame in a core.Image through ImageSource.Pixels at the frame's time. It gives slot.view what core.Video gives it elsewhere: a load once the first picture is up, progress, the end, pausing and restarting. +// TODO(nsgo#862): once NSGo plays VP9-with-alpha WebM on Windows, go back to core.Video there and drop clipPlayer, libvpx and ebml-go https://github.com/nsgo-dev/nsgo/issues/862 +type clipPlayer struct { + cx *core.Scope + // version counts the frames shown, the image's Version of shown. + version *core.Signal[uint64] + + onLoad func() + onProgress func(position time.Duration) + onEnd func() + onError func(error) + + source string + // load counts the loads, so a frame a stopped decoder posted late is dropped. + load int + cancel context.CancelFunc + // free are the buffers the decoder may write the next frames into, ready the frames it decoded in order and that wait for their time. + free chan *image.RGBA + ready []readyFrame + // shown is the buffer on screen, given back to the decoder once the next frame shows: the core copies a buffer in the commit that carries it, and a later frame replaces one that has not been committed yet. + shown *image.RGBA + shownLoad int + + loaded, ended, decoded bool + duration time.Duration + // playing is whether the clock runs: from start, the graph time of the clip's position 0, else held at position. + paused, playing bool + start time.Time + position time.Duration + lastProgress time.Duration + stopTimer func() bool +} + +// readyFrame is a decoded frame and when it shows. +type readyFrame struct { + at time.Duration + buf *image.RGBA +} + +// clipBuffers is how many frames the decoder may be ahead of the screen, the one shown included. +const clipBuffers = 3 + +// clipProgressInterval is how often a playing clip reports its position, as slot.view asks of core.Video. +const clipProgressInterval = 33 * time.Millisecond + +// clipView is slot.view's player on Windows: an image, sized and styled as the video would be, that plays the clip src names and that the slot restarts through *player. +type clipView struct { + src func() string + paused func() bool + style func() core.Style + onLoad func() + onProgress func(position time.Duration) + onEnd func() + onError func(error) + player **clipPlayer + label string + testID string +} + +// Render implements core.Node. +func (v clipView) Render(cx *core.Scope) core.Node { + pl := &clipPlayer{cx: cx, version: core.NewSignal(cx, uint64(0)), onLoad: v.onLoad, onProgress: v.onProgress, onEnd: v.onEnd, onError: v.onError} + *v.player = pl + cx.Effect(func() { pl.open(v.src()) }) + cx.Effect(func() { pl.setPaused(v.paused()) }) + cx.Cleanup(pl.stop) + frame := func() core.ImageSource { + v := pl.version.Get() + if pl.shown == nil { + return core.ImageSource{} + } + return core.ImageSource{Pixels: pl.shown, Version: v} + } + return core.Image{SourceFunc: frame, ResizeMode: core.Contain, StyleFunc: v.style, Label: v.label, TestID: v.testID} +} + +// open starts playing source from its start, keeping the frame on screen until the first of source's shows. +func (pl *clipPlayer) open(source string) { + pl.stop() + pl.source = source + pl.loaded, pl.ended, pl.decoded, pl.playing = false, false, false, false + // The first tick reports the start. + pl.position, pl.lastProgress, pl.duration = 0, -clipProgressInterval, 0 + pl.load++ + if source == "" { + return + } + load := pl.load + ctx, cancel := context.WithCancel(context.Background()) + pl.cancel = cancel + pl.free = make(chan *image.RGBA, clipBuffers) + go pl.decode(ctx, load, pl.free, clipPath(source)) +} + +// restart plays the clip again from its start, as a seek to 0 does a video's. +func (pl *clipPlayer) restart() { pl.open(pl.source) } + +// stop stops the decoder and the clock; the frame on screen stays. +func (pl *clipPlayer) stop() { + if pl.cancel != nil { + pl.cancel() + pl.cancel = nil + } + if pl.stopTimer != nil { + pl.stopTimer() + pl.stopTimer = nil + } + pl.ready = nil +} + +func (pl *clipPlayer) setPaused(paused bool) { + if paused == pl.paused { + return + } + pl.paused = paused + if paused { + pl.hold() + return + } + pl.run() +} + +// run starts the clock from the position it holds, once the first frame is up and while not paused. +func (pl *clipPlayer) run() { + if pl.playing || pl.paused || !pl.loaded || pl.ended { + return + } + pl.playing = true + pl.start = pl.cx.Now().Add(-pl.position) + // run may be called from the effect that follows paused: the first tick, which may call the slot's handlers and arms the timer, runs under the player's own scope instead, which keeps the timer when that effect runs again. + pl.cx.Post(pl.tick) +} + +// hold stops the clock at the position it reached. +func (pl *clipPlayer) hold() { + if !pl.playing { + return + } + pl.position = pl.now() + pl.playing = false + if pl.stopTimer != nil { + pl.stopTimer() + pl.stopTimer = nil + } +} + +// now is the clip's position. +func (pl *clipPlayer) now() time.Duration { + if !pl.playing { + return pl.position + } + return pl.cx.Now().Sub(pl.start) +} + +// decode runs on a goroutine of its own: it reads and demuxes the clip, then decodes its frames in order into the free buffers and posts each to the graph, until the clip ends or ctx is cancelled. +func (pl *clipPlayer) decode(ctx context.Context, load int, free chan *image.RGBA, path string) { + fail := func(err error) { + pl.cx.Post(func() { + if load == pl.load { + pl.onError(fmt.Errorf("%s: %w", filepath.Base(path), err)) + } + }) + } + data, err := os.ReadFile(path) + if err != nil { + fail(err) + return + } + c, err := demuxClip(data) + if err != nil { + fail(err) + return + } + color, err := newVP9Decoder() + if err != nil { + fail(err) + return + } + defer color.close() + alpha, err := newVP9Decoder() + if err != nil { + fail(err) + return + } + defer alpha.close() + for range clipBuffers { + free <- image.NewRGBA(image.Rect(0, 0, c.width, c.height)) + } + for i, f := range c.frames { + var buf *image.RGBA + select { + case buf = <-free: + case <-ctx.Done(): + return + } + p, ok, err := color.decode(f.color) + if err != nil { + fail(fmt.Errorf("frame %d: %w", i, err)) + return + } + var a *yuvPlanes + if f.alpha != nil { + ap, aok, err := alpha.decode(f.alpha) + if err != nil { + fail(fmt.Errorf("frame %d's alpha: %w", i, err)) + return + } + if aok && ap.width >= c.width && ap.height >= c.height { + a = &ap + } + } + if !ok || p.width < c.width || p.height < c.height { + free <- buf + continue + } + p.toRGBA(buf, a) + at := f.at + pl.cx.Post(func() { pl.deliver(load, readyFrame{at: at, buf: buf}) }) + } + pl.cx.Post(func() { + if load == pl.load { + pl.decoded, pl.duration = true, c.duration + pl.tick() + } + }) +} + +// deliver takes a decoded frame on the graph: the first shows at once and loads the clip; the others wait for their time. +func (pl *clipPlayer) deliver(load int, f readyFrame) { + if load != pl.load { + return + } + if !pl.loaded { + pl.show(load, f.buf) + pl.loaded = true + pl.position = f.at + pl.onLoad() + pl.run() + return + } + pl.ready = append(pl.ready, f) + // A frame that arrives while none waited may be due before the next report. + if pl.playing && len(pl.ready) == 1 { + pl.tick() + } +} + +// show puts buf, a frame of load, on screen, and gives the buffer it replaces back to the decoder when that buffer is of the same load: one of an earlier load is left to the collector. +func (pl *clipPlayer) show(load int, buf *image.RGBA) { + if old := pl.shown; old != nil && pl.shownLoad == load { + pl.free <- old + } + pl.shown, pl.shownLoad = buf, load + pl.version.Set(pl.version.GetUntracked() + 1) +} + +// tick shows the frames that are due, reports the position and the end, and arms the timer for the next frame or report. +func (pl *clipPlayer) tick() { + if pl.stopTimer != nil { + pl.stopTimer() + pl.stopTimer = nil + } + if !pl.playing { + return + } + pos := pl.now() + // A decoder that falls behind skips to the latest frame that is due. + for len(pl.ready) > 0 && pl.ready[0].at <= pos { + f := pl.ready[0] + pl.ready = pl.ready[1:] + pl.show(pl.load, f.buf) + } + if pl.decoded && len(pl.ready) == 0 && pos >= pl.duration { + pl.position, pl.playing, pl.ended = pl.duration, false, true + pl.onProgress(pl.duration) + pl.onEnd() + return + } + if pos-pl.lastProgress >= clipProgressInterval { + pl.lastProgress = pos + pl.onProgress(pos) + } + next := pl.lastProgress + clipProgressInterval + if len(pl.ready) > 0 { + next = min(next, pl.ready[0].at) + } else if pl.decoded { + next = min(next, pl.duration) + } + pl.stopTimer = pl.cx.AfterFunc(max(next-pos, time.Millisecond), func() { + pl.stopTimer = nil + pl.tick() + }) +} + +// resourceRoot is the folder NSGo resolves "asset:" paths against on Windows and Linux, the executable's, where its packages put the host's resources; the tests point it at the app's resources in this repository. +var resourceRoot = func() string { + exe, err := os.Executable() + if err != nil { + return "." + } + return filepath.Dir(exe) +}() + +// clipPath is where a clip is on disk: an "asset:" clip under resourceRoot, the clip of a pack loaded from a directory (LoadDir) at its own path. +func clipPath(source string) string { + rel, ok := strings.CutPrefix(source, "asset:") + if !ok { + return filepath.FromSlash(source) + } + return filepath.Join(resourceRoot, filepath.FromSlash(rel)) +} diff --git a/pet/go.mod b/pet/go.mod index 6568cd3..3dd4b2d 100644 --- a/pet/go.mod +++ b/pet/go.mod @@ -2,6 +2,10 @@ module github.com/nsgo-dev/nsgo-pet/pet go 1.27.3 -require github.com/nsgo-dev/nsgo v0.1.1-0.20261117115553-09ec9a909738 +require ( + github.com/at-wat/ebml-go v0.19.4 + github.com/ebitengine/purego v0.11.3 + github.com/nsgo-dev/nsgo v0.1.1-0.20261117115553-09ec9a909738 +) require go.yaml.in/yaml/v3 v3.0.6 // indirect diff --git a/pet/go.sum b/pet/go.sum index 8a1aae2..140d72c 100644 --- a/pet/go.sum +++ b/pet/go.sum @@ -1,3 +1,5 @@ +github.com/at-wat/ebml-go v0.19.4 h1:6F767ThzH/JqNUsF79PwRFP0pwUF5ALXWJ6pXuiolI8= +github.com/at-wat/ebml-go v0.19.4/go.mod h1:wu3fQj+DWo6SOOl9c4yDi+gFs9Oa96Z2B5qxo1OxFYY= github.com/ebitengine/purego v0.11.3 h1:OB+JLpdm7ioymhyA+6s5kbb/uOuYycAgL8NNTFc5MLg= github.com/ebitengine/purego v0.11.3/go.mod h1:DCHPP08djqhNSoTfImcnHYQRZmd0qhakvrozqaEYhGQ= github.com/nsgo-dev/nsgo v0.1.1-0.20261117115553-09ec9a909738 h1:3Jn5vk54oVdEM+oxXaSTMgI4MRi5ydVLhog4d8Z3WCg= diff --git a/pet/pet.go b/pet/pet.go index dada62e..c0ad259 100644 --- a/pet/pet.go +++ b/pet/pet.go @@ -121,7 +121,7 @@ func fill() core.Style { return core.Style{Position: core.Absolute, Top: core.Pt(0), Right: core.Pt(0), Bottom: core.Pt(0), Left: core.Pt(0)} } -// clipSource is where this platform's clips are: HEVC with alpha on macOS, whose player opens no WebM, VP9 with alpha in WebM elsewhere. +// clipSource is where this platform's clips are: HEVC with alpha on macOS, whose player opens no WebM, VP9 with alpha in WebM elsewhere, which Windows decodes itself (clipPlayer). func clipSource(cx *core.Scope, pack *Pack, r Rule) string { name := strings.TrimSuffix(r.File, ".webm") switch cx.Env().OS() { @@ -136,47 +136,68 @@ type slot struct { src *core.Signal[string] mirrored *core.Signal[bool] ref *core.Ref + // player plays the clips on Windows instead of a video, nil elsewhere. + player *clipPlayer } func (s *slot) view(p *Pet, i int) core.Node { + paused := func() bool { return p.front.Get() != i && p.pending.Get() != i } + style := func() core.Style { + st := fill() + st.Opacity = core.Alpha(0) + if p.front.Get() == i { + st.Opacity = core.Alpha(1) + } + if s.mirrored.Get() { + st.Transform = core.Transform{ScaleX: -1} + } + return st + } + loaded := func() { + if p.pending.GetUntracked() == i { + p.front.Set(i) + p.pending.Set(-1) + } + } + progress := func(position time.Duration) { + if p.front.GetUntracked() == i { + p.progress(position) + } + } + ended := func() { + if p.front.GetUntracked() == i && p.pending.GetUntracked() < 0 { + p.finished() + } + } + failed := func(err error) { log.Printf("clip %s: %v", s.src.GetUntracked(), err) } + if p.cx.Env().OS() == core.OSWindows { + return clipView{src: s.src.Get, paused: paused, style: style, onLoad: loaded, onProgress: progress, onEnd: ended, onError: failed, player: &s.player, label: p.pack.Name, testID: slotIDs[i]} + } return core.Video{ - SourceFunc: s.src.Get, - PausedFunc: func() bool { return p.front.Get() != i && p.pending.Get() != i }, - Muted: true, - ResizeMode: core.Contain, - Ref: s.ref, - StyleFunc: func() core.Style { - st := fill() - st.Opacity = core.Alpha(0) - if p.front.Get() == i { - st.Opacity = core.Alpha(1) - } - if s.mirrored.Get() { - st.Transform = core.Transform{ScaleX: -1} - } - return st - }, - OnLoad: func(core.VideoInfo) { - if p.pending.GetUntracked() == i { - p.front.Set(i) - p.pending.Set(-1) - } - }, - OnProgress: func(position, _ time.Duration) { - if p.front.GetUntracked() == i { - p.progress(position) - } - }, + SourceFunc: s.src.Get, + PausedFunc: paused, + Muted: true, + ResizeMode: core.Contain, + Ref: s.ref, + StyleFunc: style, + OnLoad: func(core.VideoInfo) { loaded() }, + OnProgress: func(position, _ time.Duration) { progress(position) }, ProgressInterval: 33 * time.Millisecond, - OnEnd: func() { - if p.front.GetUntracked() == i && p.pending.GetUntracked() < 0 { - p.finished() - } - }, - OnError: func(err error) { log.Printf("clip %s: %v", s.src.GetUntracked(), err) }, - Label: p.pack.Name, - TestID: slotIDs[i], + OnEnd: ended, + OnError: failed, + Label: p.pack.Name, + TestID: slotIDs[i], + } +} + +// rewind plays the slot's clip again from the start and says whether the slot may show at once. A video seeks in the player it has open; Windows' player reads and decodes the clip again, and until its first frame is up shows the frame it last showed, so the slot waits for the load as for a new clip. +func (s *slot) rewind() (now bool) { + if s.player != nil { + s.player.restart() + return false } + s.ref.Seek(0) + return true } // slotIDs name the two players for tests. @@ -236,9 +257,12 @@ func (p *Pet) play(r Rule, phase string, mirrored bool) { s.mirrored.Set(mirrored) if s.src.GetUntracked() == src { // The hidden player has this clip already: play it again from the start and show it. - s.ref.Seek(0) - p.pending.Set(-1) - p.front.Set(back) + if s.rewind() { + p.pending.Set(-1) + p.front.Set(back) + } else { + p.pending.Set(back) + } return } s.src.Set(src) diff --git a/pet/vpx.go b/pet/vpx.go new file mode 100644 index 0000000..9b6fd07 --- /dev/null +++ b/pet/vpx.go @@ -0,0 +1,121 @@ +package pet + +import ( + "errors" + "fmt" + "runtime" + "sync" + "unsafe" + + "github.com/ebitengine/purego" +) + +// libvpx's decoder functions, bound by loadVPX through purego, so the engine needs no cgo. +var vpx struct { + vp9 func() uintptr + initVer func(ctx unsafe.Pointer, iface uintptr, cfg unsafe.Pointer, flags int, ver int32) int32 + decode func(ctx unsafe.Pointer, data unsafe.Pointer, size uint32, userPriv uintptr, deadline int) int32 + getFrame func(ctx unsafe.Pointer, iter *uintptr) unsafe.Pointer + destroy func(ctx unsafe.Pointer) int32 + errText func(err int32) string +} + +var ( + vpxOnce sync.Once + vpxErr error +) + +// loadVPX opens libvpx (openVPXLibrary) and binds its functions, once. +func loadVPX() error { + vpxOnce.Do(func() { + lib, err := openVPXLibrary() + if err != nil { + vpxErr = fmt.Errorf("loading libvpx: %w", err) + return + } + purego.RegisterLibFunc(&vpx.vp9, lib, "vpx_codec_vp9_dx") + purego.RegisterLibFunc(&vpx.initVer, lib, "vpx_codec_dec_init_ver") + purego.RegisterLibFunc(&vpx.decode, lib, "vpx_codec_decode") + purego.RegisterLibFunc(&vpx.getFrame, lib, "vpx_codec_get_frame") + purego.RegisterLibFunc(&vpx.destroy, lib, "vpx_codec_destroy") + purego.RegisterLibFunc(&vpx.errText, lib, "vpx_codec_err_to_string") + }) + return vpxErr +} + +// vpxDecoderABI is VPX_DECODER_ABI_VERSION of libvpx's headers, 3 + VPX_CODEC_ABI_VERSION (4 + VPX_IMAGE_ABI_VERSION, 5), which libvpx checks so a mismatched vpxImage below fails to open rather than misreads. +const vpxDecoderABI = 3 + 4 + 5 + +// vpxImgI420 is VPX_IMG_FMT_I420, 8-bit 4:2:0, the only format the clips use. +const vpxImgI420 = 0x102 + +// vpxCS709 and vpxFullRange are VPX_CS_BT_709 and VPX_CR_FULL_RANGE. +const ( + vpxCS709 = 2 + vpxFullRange = 1 +) + +// vpxImage is the start of vpx_image_t, up to the planes and their strides. +type vpxImage struct { + fmt, cs, colorRange uint32 + w, h, bitDepth uint32 + dw, dh uint32 + rw, rh uint32 + xChromaShift, yChromaShift uint32 + planes [4]*byte + stride [4]int32 +} + +// vp9Decoder is one libvpx VP9 decoder; a clip with alpha takes two, one for each stream. It is used on one goroutine. +type vp9Decoder struct { + // ctx is a vpx_codec_ctx_t, 56 bytes on 64-bit Windows and Unix, with room to spare; Go's collector does not move it. + ctx *[16]uint64 +} + +func newVP9Decoder() (*vp9Decoder, error) { + if err := loadVPX(); err != nil { + return nil, err + } + d := &vp9Decoder{ctx: new([16]uint64)} + if e := vpx.initVer(unsafe.Pointer(d.ctx), vpx.vp9(), nil, 0, vpxDecoderABI); e != 0 { + return nil, fmt.Errorf("opening a VP9 decoder: %s", vpx.errText(e)) + } + return d, nil +} + +// decode decodes one frame and returns its picture, valid until the next call; ok is false when the frame shows nothing. +func (d *vp9Decoder) decode(frame []byte) (p yuvPlanes, ok bool, err error) { + if len(frame) == 0 { + return p, false, errors.New("an empty frame") + } + if e := vpx.decode(unsafe.Pointer(d.ctx), unsafe.Pointer(&frame[0]), uint32(len(frame)), 0, 0); e != 0 { + return p, false, fmt.Errorf("decoding: %s", vpx.errText(e)) + } + runtime.KeepAlive(frame) + var iter uintptr + ptr := vpx.getFrame(unsafe.Pointer(d.ctx), &iter) + if ptr == nil { + return p, false, nil + } + img := (*vpxImage)(ptr) + if img.fmt != vpxImgI420 { + return p, false, fmt.Errorf("the picture's format is %#x, not 8-bit 4:2:0", img.fmt) + } + h, ch := int(img.dh), int(img.dh+1)/2 + p = yuvPlanes{ + width: int(img.dw), height: h, + y: unsafe.Slice(img.planes[0], int(img.stride[0])*h), yStride: int(img.stride[0]), + u: unsafe.Slice(img.planes[1], int(img.stride[1])*ch), uStride: int(img.stride[1]), + v: unsafe.Slice(img.planes[2], int(img.stride[2])*ch), vStride: int(img.stride[2]), + bt709: img.cs == vpxCS709, fullRange: img.colorRange == vpxFullRange, + } + return p, true, nil +} + +// close frees the decoder. +func (d *vp9Decoder) close() { + if d != nil && d.ctx != nil { + vpx.destroy(unsafe.Pointer(d.ctx)) + d.ctx = nil + } +} diff --git a/pet/vpx_other.go b/pet/vpx_other.go new file mode 100644 index 0000000..35e1b20 --- /dev/null +++ b/pet/vpx_other.go @@ -0,0 +1,22 @@ +//go:build !windows + +package pet + +import ( + "errors" + + "github.com/ebitengine/purego" +) + +// openVPXLibrary opens the system's libvpx. The engine plays the clips with core.Video on macOS and Linux, so only the decoder's tests come here, to run against a libvpx such as Homebrew's or a distribution's. +func openVPXLibrary() (uintptr, error) { + var errs []error + for _, name := range []string{"libvpx.dylib", "/opt/homebrew/lib/libvpx.dylib", "/usr/local/lib/libvpx.dylib", "libvpx.so", "libvpx.so.9", "libvpx.so.8", "libvpx.so.7"} { + h, err := purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_LOCAL) + if err == nil { + return h, nil + } + errs = append(errs, err) + } + return 0, errors.Join(errs...) +} diff --git a/pet/vpx_windows.go b/pet/vpx_windows.go new file mode 100644 index 0000000..f2bddf9 --- /dev/null +++ b/pet/vpx_windows.go @@ -0,0 +1,33 @@ +package pet + +import ( + "path/filepath" + "syscall" + "unsafe" +) + +// loadLibraryExW is kernel32's LoadLibraryExW, which syscall.LoadDLL does not offer with flags. +var loadLibraryExW = syscall.NewLazyDLL("kernel32.dll").NewProc("LoadLibraryExW") + +// The flags of LoadLibraryExW that look for a library's own dependencies in its folder and then in System32 only. +const ( + loadLibrarySearchDLLLoadDir = 0x100 + loadLibrarySearchSystem32 = 0x800 +) + +// openVPXLibrary opens the libvpx the host ships in its resources/windows, as nsgo-pet does, which NSGo's Windows packages put beside the executable (resourceRoot). Its winpthreads library is beside it, and the flags find it there rather than one of the same name elsewhere on PATH. +func openVPXLibrary() (uintptr, error) { + dir, err := filepath.Abs(filepath.Join(resourceRoot, "windows")) + if err != nil { + return 0, err + } + path, err := syscall.UTF16PtrFromString(filepath.Join(dir, "libvpx-1.dll")) + if err != nil { + return 0, err + } + h, _, err := loadLibraryExW.Call(uintptr(unsafe.Pointer(path)), 0, loadLibrarySearchDLLLoadDir|loadLibrarySearchSystem32) + if h == 0 { + return 0, err + } + return h, nil +} diff --git a/resources/windows/NOTICE.md b/resources/windows/NOTICE.md new file mode 100644 index 0000000..e468361 --- /dev/null +++ b/resources/windows/NOTICE.md @@ -0,0 +1,10 @@ +# libvpx for Windows + +The Windows build decodes the WebM clips with libvpx, which NSGo's Windows player cannot do with their alpha. These files come unchanged from MSYS2's mingw64 packages, fetched by `tools/fetch-libvpx.sh`: + +| File | Package | License | +| --- | --- | --- | +| `libvpx-1.dll` | [mingw-w64-x86_64-libvpx-1.16.0-1-any.pkg.tar.zst](https://mirror.msys2.org/mingw/mingw64/mingw-w64-x86_64-libvpx-1.16.0-1-any.pkg.tar.zst), libvpx 1.16.0 by the WebM Project | BSD-3-Clause, with Google's patent grant: [libvpx-LICENSE](libvpx-LICENSE), [libvpx-PATENTS](libvpx-PATENTS) | +| `libwinpthread-1.dll` | [mingw-w64-x86_64-libwinpthread-14.0.0.r92.g818fa6510-1-any.pkg.tar.zst](https://mirror.msys2.org/mingw/mingw64/mingw-w64-x86_64-libwinpthread-14.0.0.r92.g818fa6510-1-any.pkg.tar.zst), winpthreads by the mingw-w64 project, which libvpx-1.dll links | MIT and others: [libwinpthread-COPYING](libwinpthread-COPYING) | + +The libvpx license and patent grant are those of its [v1.16.0](https://github.com/webmproject/libvpx/tree/v1.16.0) tag, which the package does not carry. diff --git a/resources/windows/libvpx-1.dll b/resources/windows/libvpx-1.dll new file mode 100755 index 0000000..65b5b92 Binary files /dev/null and b/resources/windows/libvpx-1.dll differ diff --git a/resources/windows/libvpx-LICENSE b/resources/windows/libvpx-LICENSE new file mode 100644 index 0000000..1ce4434 --- /dev/null +++ b/resources/windows/libvpx-LICENSE @@ -0,0 +1,31 @@ +Copyright (c) 2010, The WebM Project authors. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in + the documentation and/or other materials provided with the + distribution. + + * Neither the name of Google, nor the WebM Project, nor the names + of its contributors may be used to endorse or promote products + derived from this software without specific prior written + permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + diff --git a/resources/windows/libvpx-PATENTS b/resources/windows/libvpx-PATENTS new file mode 100644 index 0000000..caedf60 --- /dev/null +++ b/resources/windows/libvpx-PATENTS @@ -0,0 +1,23 @@ +Additional IP Rights Grant (Patents) +------------------------------------ + +"These implementations" means the copyrightable works that implement the WebM +codecs distributed by Google as part of the WebM Project. + +Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge, +royalty-free, irrevocable (except as stated in this section) patent license to +make, have made, use, offer to sell, sell, import, transfer, and otherwise +run, modify and propagate the contents of these implementations of WebM, where +such license applies only to those patent claims, both currently owned by +Google and acquired in the future, licensable by Google that are necessarily +infringed by these implementations of WebM. This grant does not include claims +that would be infringed only as a consequence of further modification of these +implementations. If you or your agent or exclusive licensee institute or order +or agree to the institution of patent litigation or any other patent +enforcement activity against any entity (including a cross-claim or +counterclaim in a lawsuit) alleging that any of these implementations of WebM +or any code incorporated within any of these implementations of WebM +constitute direct or contributory patent infringement, or inducement of +patent infringement, then any patent rights granted to you under this License +for these implementations of WebM shall terminate as of the date such +litigation is filed. diff --git a/resources/windows/libwinpthread-1.dll b/resources/windows/libwinpthread-1.dll new file mode 100755 index 0000000..67d3b9f Binary files /dev/null and b/resources/windows/libwinpthread-1.dll differ diff --git a/resources/windows/libwinpthread-COPYING b/resources/windows/libwinpthread-COPYING new file mode 100644 index 0000000..3507701 --- /dev/null +++ b/resources/windows/libwinpthread-COPYING @@ -0,0 +1,57 @@ +Copyright (c) 2011 mingw-w64 project + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. + + +/* + * Parts of this library are derived by: + * + * Posix Threads library for Microsoft Windows + * + * Use at own risk, there is no implied warranty to this code. + * It uses undocumented features of Microsoft Windows that can change + * at any time in the future. + * + * (C) 2010 Lockless Inc. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, + * are permitted provided that the following conditions are met: + * + * + * * Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright notice, + * this list of conditions and the following disclaimer in the documentation + * and/or other materials provided with the distribution. + * * Neither the name of Lockless Inc. nor the names of its contributors may be + * used to endorse or promote products derived from this software without + * specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AN + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ diff --git a/tools/fetch-libvpx.sh b/tools/fetch-libvpx.sh new file mode 100755 index 0000000..aebe4ae --- /dev/null +++ b/tools/fetch-libvpx.sh @@ -0,0 +1,45 @@ +#!/bin/bash +# Fetches the libvpx DLL the Windows build decodes the WebM clips with, and the winpthreads DLL it links, from MSYS2's signed mingw64 packages (pinned by their SHA-256), into resources/windows with their licenses. Needs curl and a tar that reads zstd. +set -euo pipefail + +mirror=https://mirror.msys2.org/mingw/mingw64 +vpx=mingw-w64-x86_64-libvpx-1.16.0-1-any.pkg.tar.zst +vpx_sum=e1c166239223d1f723971d89b932bf6fdfaaa175e1908f07f09d673188c6bab2 +pthread=mingw-w64-x86_64-libwinpthread-14.0.0.r92.g818fa6510-1-any.pkg.tar.zst +pthread_sum=c426ba9ef8870b4342d5c0843efa7a9b360361994c7556f3d18f23fd30734194 +# The packages carry winpthreads' license but not libvpx's, which comes from the tag the package was built from. +libvpx_tag=v1.16.0 +root=$(cd "$(dirname "$0")/.." && pwd) +out=$root/resources/windows +tmp=$(mktemp -d) +trap 'rm -rf "$tmp"' EXIT + +fetch() { + curl -fsSL --max-time 300 -o "$tmp/$1" "$mirror/$1" + if [ "$(shasum -a 256 "$tmp/$1" | cut -d' ' -f1)" != "$2" ]; then + echo "$1 does not match its SHA-256" >&2 + exit 1 + fi + tar --zstd -xf "$tmp/$1" -C "$tmp" +} +fetch "$vpx" "$vpx_sum" +fetch "$pthread" "$pthread_sum" + +mkdir -p "$out" +cp "$tmp/mingw64/bin/libvpx-1.dll" "$tmp/mingw64/bin/libwinpthread-1.dll" "$out/" +for f in LICENSE PATENTS; do + curl -fsS --max-time 60 -o "$out/libvpx-$f" "https://raw.githubusercontent.com/webmproject/libvpx/$libvpx_tag/$f" +done +cp "$tmp/mingw64/share/licenses/libwinpthread/COPYING" "$out/libwinpthread-COPYING" +cat >"$out/NOTICE.md" <