diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f84b3e5af..cb02f5be8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -97,6 +97,11 @@ jobs: # it, and a symbol that needs one usually needs a typed one instead. - name: API discipline run: go run ./tools/apicheck ./ui ./components ./app ./gfx + # Nothing keeps the framework busy while an application is idle: no ticker, + # no file access while painting, no frame asked for forever. A line that + # needs one says why with //appaudit:allow. + - name: Idle and window-thread audit + run: go run ./tools/appaudit ./... # The attribute rules (ADR 0089 stage 3) exist only in the dev build: they # report a generic attribute that an element cannot use instead of letting it @@ -388,6 +393,16 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } $passed = $events | ConvertFrom-Json | Where-Object { $_.Action -eq 'pass' -and $_.Test -eq $test } if (-not $passed) { throw "$test did not pass on the Windows runner" } + # Shared media textures are opened on the WARP device and sampled under + # their keyed mutex. The tests skip when the offscreen renderer or a + # shared NT handle is unavailable on the runner. + - name: Offscreen shared video textures + run: go test ./internal/platform/windows -run '^TestOffscreen(DrawsASharedTexture|ClipsASharedTexture|SweepsAgedSharedTexture)$' -count=1 -v -timeout=2m + # The media engine's notify object, its shared texture registry and the + # renderer adapter choice need no codec; a runner without Media + # Foundation skips the first, and one without a Direct3D device the last. + - name: Media engine references and adapter + run: go test ./internal/media -run '^Test(NotifyRefCountAndDetach|SharedTextureErrorReporting|NewVideoDevice)$' -count=1 -v -timeout=2m - name: Web view partitions run: go test ./internal/platform/windows -run '^Test(APageWithoutAPartitionAsksForNoProfileOfItsOwn|APartitionNamesTheWebView2Profile|AnEphemeralPartitionIsAnOffTheRecordProfile|EphemeralPagesWithoutAPartitionEachGetAProfileOfTheirOwn)$' -count=1 -v - name: Terminal keyboard routing diff --git a/app/painter.go b/app/painter.go index 20cd6c450..ba42e9ed8 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1635,6 +1635,15 @@ func (painter *painter) applyTextEvent(event platform.TextEvent) (platform.TextS return painter.nativeText.State, nil } } + if active.Paste != nil && !explicit && + (event.Kind == platform.TextPasteNoText || event.Kind == platform.TextPaste && appEvent.Text != "") && + active.Paste(appEvent.Text) { + // The field took the paste itself: what it shows has not changed, but + // what it took may change the page, so the window paints again. + native := painter.nativeText.State + native.Redraw = true + return native, nil + } if !explicit && !painter.nativeText.Multiline && !painter.nativeText.Terminal && event.Kind == platform.TextCommandEvent && (event.Command == platform.TextInsertNewline || event.Command == platform.TextInsertLineBreak) { diff --git a/base/edit_menu.go b/base/edit_menu.go index 8f67b9039..8d2ba2616 100644 --- a/base/edit_menu.go +++ b/base/edit_menu.go @@ -121,13 +121,21 @@ func (p *Page) declareEditMenu(c C, entry editMenuEntry, labels EditMenuLabels) } } if menu.Item(labels.Paste).Keys(Primary, "v").Disabled(!editable).Clicked() && chosen() { - if value, err := ClipboardText(); err == nil { - if !entry.area { - value = text.SingleLine(value) - } - if value != "" { - editor.Paste(value) - } + value, err := ClipboardText() + if err != nil { + value = "" + } + folded := value + if !entry.area { + folded = text.SingleLine(value) + } + switch paste := p.fieldPaste(id); { + case value != "" && folded == "": + // None of the text is left on one line: there is nothing to paste. + case paste != nil && paste(folded): + // Box.OnPaste took it, as it takes a paste from the keyboard. + case folded != "": + editor.Paste(folded) } } menu.Separator() diff --git a/base/field.go b/base/field.go index 6a8020e30..42885db6d 100644 --- a/base/field.go +++ b/base/field.go @@ -313,6 +313,69 @@ func (b Box) OnKey(handler func(gfx.KeyEvent) gfx.EventResult) Box { panic("ui: OnKey must be chained on a TextField") } +// OnPaste gives a TextField or a TextArea a look at every paste into it before +// the field takes it, from the keyboard, the edit menu or the system's menu. +// The handler gets the text the paste would insert (a TextField's with its +// lines folded into one), or nothing when the clipboard holds something else, +// such as a picture or the files a file manager copied. +// Returning true takes the paste and leaves the field as it was; returning +// false lets the text paste as usual. A chat box uses it to attach what was +// copied: +// +// prompt := ui.TextArea(c, &m.prompt, "Message", "").Height(80) +// prompt.OnPaste(func(text string) bool { +// if files, err := app.ClipboardFiles(); err == nil { +// m.attach(files...) +// return true +// } +// if text != "" { +// return false +// } +// if png, err := app.ClipboardImagePNG(); err == nil { +// m.attachPicture(png) +// return true +// } +// return false +// }) +// +// Ask for the files first: most file managers put the file names on the +// clipboard as text too. A cut is not a paste and is not offered. +// +// Not inside a Memo, whose copied fields are not declared. +func (b Box) OnPaste(handler func(text string) bool) Box { + n := b.N() + if n.Kind != kindInput && n.Kind != kindTextarea { + panic("ui: OnPaste is for a TextField or a TextArea") + } + if handler == nil { + panic("ui: OnPaste needs a handler") + } + if b.f.memoDepth > 0 { + panic("ui: OnPaste in a Memo: a copied field is not declared, so its handler would disappear; declare it outside the Memo") + } + p := b.f.page + if p == nil { + panic("ui: OnPaste is for a field of a page") + } + for i := len(p.fields) - 1; i >= 0; i-- { + if p.fields[i].ID == n.ID { + p.fields[i].paste = handler + return b + } + } + panic("ui: OnPaste must be chained on a TextField or a TextArea") +} + +// fieldPaste is the Box.OnPaste handler of the field id, or nil. +func (p *Page) fieldPaste(id gfx.ID) func(string) bool { + for i := len(p.fields) - 1; i >= 0; i-- { + if p.fields[i].ID == id { + return p.fields[i].paste + } + } + return nil +} + // Fields answers Config.TextInput for the fields: the platform asks which editor // belongs to the focused control, and gets the one of the field declared with that // identity. diff --git a/base/flex_test.go b/base/flex_test.go index 8264e32e8..e18cbd2c0 100644 --- a/base/flex_test.go +++ b/base/flex_test.go @@ -837,3 +837,41 @@ func TestViewTrimReleasesLargePageNodes(t *testing.T) { t.Fatalf("nodes capacity after a large page = %d, want the spike released", got) } } + +// A container as wide as it measured gives its child the whole width, even where +// float32 sums the sizes to a few ulps less when it shares them out: a label that +// fits exactly is not cut to an ellipsis, with or without padding of its own, +// whether the container flows along the label's width or across it. +func TestAContainerAtItsMeasuredWidthKeepsAnEllipsizedLabelWhole(t *testing.T) { + for _, across := range []bool{false, true} { + for _, pad := range []float32{0, 3} { + for i := range 2000 { + scale := 0.5 + float32(i)*0.000731 + canvas := &gfx.Canvas{} + canvas.SetTree(&tree) + canvas.SetMeasurer(func(Value string, Size, Weight float32) float32 { return float32(len(Value)) * Size * scale }) + var view View + var label Box + f := view.Begin(canvas, gfx.LightTheme(), gfx.Rect{Width: 400, Height: 40}) + f.Row().Height(40).Gap(6).Children(func() { + f.Spacer() + if across { + f.Column().PadX(9).Children(func() { + label = f.Text("High").FontSize(12).PadX(pad).Ellipsis() + }) + return + } + f.Row().PadX(9).Gap(5).Children(func() { + f.Slot().Width(12) + label = f.Text("High").FontSize(12).PadX(pad).Ellipsis() + f.Slot().Width(11) + }) + }) + f.End() + if got := f.Lines[f.Nodes[label.GetI()].LineFirst]; got != "High" { + t.Fatalf("across=%v, glyph %v wide and padding %v, the label reads %q in %v, want High", across, 12*scale, pad, got, label.Rect().Width) + } + } + } + } +} diff --git a/base/layout.go b/base/layout.go index 6f43979ee..e4752a92a 100644 --- a/base/layout.go +++ b/base/layout.go @@ -87,8 +87,12 @@ func (f *Frame) measure(axis int) { n.TextDecor &^= textTruncated first := int32(len(f.Lines)) // An empty text has no line at all, as WrapLines gives it none; anything - // else that fits is one line and needs no breaking. - if n.Text != "" && n.Natural <= n.Rect.Width-n.PadX() && strings.IndexByte(n.Text, '\n') < 0 { + // else that fits is one line and needs no breaking. The width it needs is + // summed as its preferred width was, so a text given exactly that fits. A + // container across the flow derives the room by subtracting its insets, so + // float32 can leave the text a few ulps short of the same sum; that is + // rounding, not a lack of room. + if n.Text != "" && n.Natural+n.PadX() <= n.Rect.Width+roundingSlack(n.Rect.Width, 1) && strings.IndexByte(n.Text, '\n') < 0 { f.Lines = append(f.Lines, n.Text) } else { f.Lines = f.wrapText(f.Lines, n) @@ -378,6 +382,15 @@ func shrinksToRoom(n *Node, extra *Extra) bool { return breaksAnywhere(n, extra) && n.Size[AxisX].Kind == dimAuto && n.Flags&flagBasis == 0 } +// roundingSlack is the most that summing terms sizes of a container of the given +// size can be off by in float32: two ulps of the size for each term, the insets and +// gaps included. It is far below a device pixel, so a shortfall within it is never a +// real lack of room. +func roundingSlack(size float32, terms int) float32 { + const ulp = 1.0 / (1 << 23) // the float32 machine epsilon + return float32(2*(terms+3)) * ulp * max(size, 1) +} + func offset(align Align, free float32) float32 { switch align { case Center: @@ -455,6 +468,13 @@ func (f *Frame) solveFlow(n *Node, First, stop int32, axis int, start, avail flo room = max(avail, baseSum+frozenSize+fixed) } free := room - frozenSize - baseSum - fixed + if free < 0 && -free <= roundingSlack(room, count) { + // A container placed at the size it measured sums the same sizes again here, + // in another order, and float32 can leave it a few ulps short. That is + // rounding, not a lack of room: taking it from a child would cut a text that + // fits exactly down to an ellipsis. + free = 0 + } var violation float32 for c := First; c != stop; c = f.Nodes[c].Next { child := &f.Nodes[c] diff --git a/base/names.go b/base/names.go index eed41a0ae..c07510d26 100644 --- a/base/names.go +++ b/base/names.go @@ -148,4 +148,5 @@ type fieldEntry struct { field *Field box int32 // the field's element, for routing inside a wheel panel key func(gfx.KeyEvent) gfx.EventResult // Box.OnKey, while this field has the keyboard + paste func(string) bool // Box.OnPaste, offered every paste into this field } diff --git a/base/page.go b/base/page.go index c08403b3b..9fe13af7e 100644 --- a/base/page.go +++ b/base/page.go @@ -1209,6 +1209,7 @@ func (p *Page) TextInput(context window.TextInputContext) *window.TextInput { if entry.ID == context.ID && !context.ID.IsZero() { entry.field.input.Alignment = context.Alignment entry.field.input.Editor = entry.field.ensure() + entry.field.input.Paste = entry.paste return &entry.field.input } } diff --git a/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index fb8147105..049529b4e 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -229,7 +229,7 @@ func (m *model) page(c ui.C) { `ui/chart`, `ui/sidebar`. Its state type is named by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`. Use `cal`, `msg`, `pic` for locals; a model field may keep the noun (`m.calendar`) because a selector never shadows a package. -- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/video`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, @@ -263,6 +263,10 @@ func (m *model) page(c ui.C) { repaint that delivers Enter, not for a click; `OnKey` is not needed). The label (first string) is never empty. - Several rows: `ui.TextArea(c, &m.notes, "Notes", "").Height(120)` (Enter is a new line). Arrow keys and Page Up/Down move by row while the platform edits it, and the page routes them; no `OnKey` is needed. +- A field that takes more than text (a chat box that attaches copied files or a screenshot) chains + `.OnPaste(func(text string) bool { ... })` on its TextField or TextArea: it sees every paste first, with the text the + paste would insert or "" when the clipboard has none; return true to take it (read `app.ClipboardFiles()` before the + text, then `app.ClipboardImagePNG()`), false to let the text paste. - Other fields: `ui.TextField(...).Icon(plus)` puts an icon before the text, `.Action(cross, "Clear")` a button at its end (`.ActionClicked()` reads it), `.AutoFocus()` takes the focus as it appears and `.Secure()` makes it a password field. A search box is a TextField with `.Icon(search)` and `.Action(cross, "Clear")`, as above. diff --git a/components/markdown_index_test.go b/components/markdown_index_test.go index b1fb94d10..ce7059651 100644 --- a/components/markdown_index_test.go +++ b/components/markdown_index_test.go @@ -119,10 +119,7 @@ func linearCaretAtReference(v *MarkdownView, offset int) (gfx.Rect, bool) { } func TestMarkdownIndexMatchesLinearReferenceOnGrid(t *testing.T) { - // Parse-built document combining blank lines inside code blocks, horizontal - // rules, tables (including empty and wrapped cells), nested quotes, lists, - // links, inline code, and multi-byte UTF-8. - parsedSrc := strings.Join([]string{ + fullSrc := strings.Join([]string{ "# Overview", "", "before text with [link](https://example.com) and `code` 中文", @@ -157,10 +154,33 @@ func TestMarkdownIndexMatchesLinearReferenceOnGrid(t *testing.T) { "", "1. First item", "2. Second item with **bold** and *italic*", + "", + "- Unordered bullet", + }, "\n") + + edgeSrc := strings.Join([]string{ + "lead paragraph", + "", + "---", + "", + "---", + "", + "```", + "", + "", + "", + "```", + "", + "| A | B |", + "| - | - |", + "| | |", + "", + "tail paragraph", }, "\n") - var parsedDoc markdown.Document - parsedDoc.Parse(parsedSrc) + var fullDoc, edgeDoc markdown.Document + fullDoc.Parse(fullSrc) + edgeDoc.Parse(edgeSrc) // Programmatic document with Labeled blocks and mixed block kinds. var labeledDoc markdown.Document @@ -184,7 +204,8 @@ func TestMarkdownIndexMatchesLinearReferenceOnGrid(t *testing.T) { doc *markdown.Document width float32 }{ - {name: "parsed-full-features", doc: &parsedDoc, width: 320}, + {name: "parsed-full-features", doc: &fullDoc, width: 320}, + {name: "parsed-empty-blocks-and-rules", doc: &edgeDoc, width: 260}, {name: "programmatic-labeled", doc: &labeledDoc, width: 300}, } @@ -262,6 +283,87 @@ func TestMarkdownEmptyCodeLinesStayInCodeBlock(t *testing.T) { } } +func TestMarkdownViewTallTableCellClippedPaintAndHitTest(t *testing.T) { + // Single-row table where one cell wraps into >500 visual lines: clipped + // Paint emits only the visible cell lines and OffsetAt/CaretAt round-trip. + var sb strings.Builder + sb.WriteString("| Header A | Header B |\n| --- | --- |\n| Short | ") + for i := 0; i < 1200; i++ { + if i > 0 { + sb.WriteByte(' ') + } + fmt.Fprintf(&sb, "cellword%04d", i) + } + sb.WriteString(" |\n") + + var doc markdown.Document + doc.Parse(sb.String()) + + canvas := markdownCanvas() + var view MarkdownView + h := view.Layout(canvas, MarkdownStyle{Size: 13, LineHeight: 20}, &doc, 320) + if h < 8000 { + t.Fatalf("expected tall table height >= 8000, got %v", h) + } + + clipTop := h / 2 + canvas.Reset() + view.Paint(canvas, MarkdownPaint{ + Look: MarkdownLookFor(gfx.Theme{}), + X: 0, + Y: -clipTop, + Clip: gfx.Rect{X: 0, Y: 0, Width: 320, Height: 200}, + }) + if drawn := len(canvas.Texts()); drawn == 0 || drawn > 30 { + t.Fatalf("clipped Paint emitted %d texts for 200px slice of tall cell, want 1..30", drawn) + } + + off, ok := view.OffsetAt(gfx.Point{X: 200, Y: 100}) + if !ok { + t.Fatal("OffsetAt in tall cell returned ok=false") + } + rect, ok := view.CaretAt(off) + if !ok { + t.Fatalf("CaretAt(%d) returned ok=false", off) + } + if rect.Y < -25 || rect.Y > 225 { + t.Fatalf("CaretAt(%d) Y=%v outside painted slice [0, 200]", off, rect.Y) + } +} + +func TestMarkdownViewLongQuoteBarClippedPaint(t *testing.T) { + // One continuous quote bar spanning hundreds of blocks must still paint + // inside a mid-document clip while skipping off-screen paragraphs. + var sb strings.Builder + for i := 0; i < 400; i++ { + fmt.Fprintf(&sb, "> Quoted paragraph %d\n>\n", i) + } + var doc markdown.Document + doc.Parse(sb.String()) + + canvas := markdownCanvas() + var view MarkdownView + h := view.Layout(canvas, MarkdownStyle{Size: 13, LineHeight: 20}, &doc, 420) + if h < 6000 { + t.Fatalf("expected tall quoted doc, got %v", h) + } + + clipTop := h / 2 + canvas.Reset() + view.Paint(canvas, MarkdownPaint{ + Look: MarkdownLookFor(gfx.Theme{}), + X: 0, + Y: -clipTop, + Clip: gfx.Rect{X: 0, Y: 0, Width: 420, Height: 200}, + }) + if drawn := len(canvas.Texts()); drawn == 0 || drawn > 25 { + t.Fatalf("clipped Paint emitted %d texts for 200px slice of 400-block quote, want 1..25", drawn) + } + if rects := len(canvas.Rectangles()); rects != 1 { + t.Fatalf("expected 1 spanning quote bar rectangle inside clip, got %d", rects) + } +} + func TestMarkdownBuilderLabeledAndOpaqueLinks(t *testing.T) { var doc markdown.Document doc.Reset() @@ -418,16 +520,13 @@ func TestMarkdownViewLongQuoteBarAndShortBlocksIndex(t *testing.T) { } func BenchmarkMarkdownViewClippedPaintSteady(b *testing.B) { - var doc markdown.Document + var sb strings.Builder for i := 0; i < 400; i++ { - doc.AppendParagraph(1, 0, []markdown.Span{ - {Text: "Iterators returned by "}, - {Text: "iterator", Style: markdown.Mono, Link: "symbol:#iterator()"}, - {Text: " are "}, - {Text: "fail-fast", Style: markdown.Italic}, - {Text: " in paragraph."}, - }) + sb.WriteString("> Iterators returned by [`iterator`](https://example.com) are *fail-fast* in paragraph.\n\n") } + var doc markdown.Document + doc.Parse(sb.String()) + canvas := markdownCanvas() var view MarkdownView view.Layout(canvas, MarkdownStyle{Size: 13, LineHeight: 20}, &doc, 500) diff --git a/docs/README.md b/docs/README.md index 231e2b9d2..995a6e74b 100644 --- a/docs/README.md +++ b/docs/README.md @@ -41,6 +41,8 @@ mentions every exported method and theme field. file drops, and the rest of the native surface. - [audio.md](audio.md) — PCM output on the three native targets, what it does not do, and its measured cost. +- [video.md](video.md) — playing video as pictures: the Media Foundation + engine and its shared textures, Go-decoded GIF and APNG, and the player API. - [web-deployment.md](web-deployment.md) — the browser build, its capability matrix, lifecycle mapping, static-hosting headers and security limits. - [diagnostics.md](diagnostics.md) — the structured event stream, its slog diff --git a/docs/maintaining-controls.md b/docs/maintaining-controls.md index e53520591..3d94df09a 100644 --- a/docs/maintaining-controls.md +++ b/docs/maintaining-controls.md @@ -48,7 +48,7 @@ Opt-in page packages live under `ui/` (`ui/codeeditor`, `ui/textview`, `ui `ui/calendar`, `ui/carousel`, `ui/markdown`, `ui/columnresize`, `ui/avatareditor`, `ui/reordergrid`, `ui/avatar`, `ui/attachment`, `ui/message`, `ui/messagescroller`, `ui/command`, `ui/menubar`, -`ui/navigationmenu`, `ui/hovercard`, `ui/image`, `ui/aspectratio`, +`ui/navigationmenu`, `ui/hovercard`, `ui/image`, `ui/video`, `ui/aspectratio`, `ui/skeleton`, `ui/inputgroup`, `ui/inputotp`, `ui/questionnaire`, `ui/metriccard`, `ui/marker`, `ui/sidebar`, `ui/buttongroup`, `ui/togglegroup`, `ui/multiselect`, diff --git a/docs/skills/building-with-viva/SKILL.md b/docs/skills/building-with-viva/SKILL.md index c09092bdf..e1bd4269d 100644 --- a/docs/skills/building-with-viva/SKILL.md +++ b/docs/skills/building-with-viva/SKILL.md @@ -89,7 +89,7 @@ func (m *model) page(c ui.C) { ### Optional page packages and custom surfaces - A heavy or stateful page control lives in an opt-in package under `ui/`; import it only when the page uses it. -- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/video`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid`. Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard`. Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`. - Read-only words the user may copy (an error, a fingerprint, a detail page) go in `ui.TextSelectionArea(c, &m.details).Children(...)`: the `Text`, `Paragraph` and `Wrap` inside can be dragged across, double-clicked and copied, while buttons and fields inside keep their presses. `Box.Unselectable()` takes a decorative text out. - For read-only selectable output, keep a `textview.View` in the model and call `m.output.Declare(c, textview.Spec{Source: lines, Scroll: true})`. The caller owns lines, spans and actions; `ui/textview` owns selection and drawing without an editing model. - The package name is the capability, never a `view` suffix. Name its state type by role, not by repeating the package: `calendar.State`, `message.Row`, `attachment.Card`, `hovercard.Card`. Keep locals out of the package name (`cal`, `msg`, `pic`); a model field may keep the domain noun (`m.calendar`). diff --git a/docs/video.md b/docs/video.md new file mode 100644 index 000000000..b8daff60e --- /dev/null +++ b/docs/video.md @@ -0,0 +1,112 @@ +# Video + +`ui/video` plays video as pictures. The application declares a player in its +model, opens it on a file, a URL or bytes, and shows a `View` where the +picture goes. The application gives the player its own controls: there is no +built-in control bar, and nothing plays until `Play` is called. + +```go +//go:embed trailer.mp4 +var trailer []byte + +m.player, err = video.OpenData(trailer) +if err != nil { + // ErrUnsupported on a system with no media framework: show a GIF instead. +} +m.player.Fit(video.Cover).SetLoop(false) +... +video.View(c, "Trailer", m.player).Fill().Height(240) +if ui.Button(c, "Pause").Clicked() { + m.player.Pause() +} +``` + +A player opens paused and loads in the background: `Size` is 0×0 and `State` +is `Loading` until its first picture, which wakes the page through the +window's invalidator. `Play` starts it; `Pause` stops it where it is. `Seek` +starts it at the nearest frame at or before the time, `Position` says where it +is, and `Duration` how long it is, 0 while unknown. `State` reports `Ended` +when it played to its end, and `Err` what stopped it. `SetLoop` makes it play +again by itself, `SetRate` sets how fast, and `SetVolume` and `SetMuted` its +sound. + +`Fit` chooses how the picture fills the view's box, and returns the player for +chaining: `Contain` (the default) fits the whole picture inside and leaves the +rest empty, `Cover` fills the box and clips the overflow, and `Fill` stretches +the picture to the box. + +## Sources + +- `Open(path)` opens a file. +- `OpenURL(url)` opens a `file:`, `http:` or `https:` URL, as the system's + media framework accepts it. +- `OpenData(data)` plays bytes in memory. Windows copies them into a memory + stream (`SHCreateMemStream`); on macOS AVFoundation reads a file, so the + engine writes them to a temporary file, which it removes when the player + closes. The caller may reuse or modify `data` after `OpenData` returns. + +The system's media framework decodes: Media Foundation on Windows, where +H.264 in MP4 and MOV play with their sound, in hardware where the machine +has it; AVFoundation on macOS, which plays what the system plays. Their +pictures reach the window's renderer where the decoder left them, on the GPU. +On Windows the engine shares an NT handle of a Direct3D texture, and the +renderer opens it on its own device, the two synchronizing with a keyed +mutex. On macOS the engine hands over a `CVPixelBuffer`'s IOSurface, and the +renderer wraps it as a Metal texture. Either way a frame is drawn without a +copy through memory. A build for another system, a Windows without Media +Foundation, or a macOS built without cgo, returns `ErrUnsupported` from all +three Open functions. + +## GIF and APNG + +`NewGIFDecoder(data)` and `NewAPNGDecoder(data)` decode animated images in Go, +so they play on every system. Their frames are composed as they play, as +browsers show them: a frame whose delay is 10 ms or less shows for 100 ms, a +GIF's disposal and an APNG's dispose and blend are honored, and a GIF that ends +early plays the frames it has whole. Pass one to `NewDecoder`: + +```go +d, err := video.NewGIFDecoder(wavesGIF) +... +waves := video.NewDecoder(d).Fit(video.Cover) +waves.SetLoop(true) +waves.Play() +``` + +A decoder's frames have no sound, so `SetVolume` and `SetMuted` do nothing. +Both decoders know how many frames come before the one showing at a time, so +`Seek` starts there and composes the frames before it; a decoder that cannot +seek ignores `Seek`, and `Position` stays where it was. A GIF decodes into +memory at once, a byte a pixel for each frame; an APNG keeps each frame +compressed and decodes it as it plays. Neither makes its composed picture +until the first frame is asked for, and an animation whose frames and +pictures would need more memory than the decoder allows is an error rather +than a small file that pins hundreds of megabytes. + +## Shapes + +`Decoder` is the contract behind `NewDecoder`, so an application may bring its +own picture source: `Next` returns each frame, premultiplied BGRA, and +`Rewind` starts over. `Seeker`, a `Decoder` that also has `Seek`, lets the +player jump without replaying; a `Duration` method of its own tells the +player's `Duration` before the end is reached. The player decodes a couple of +frames ahead on its own goroutine and shows each frame when the canvas clock +passes its time, so the page paints once per frame of the clip and not at all +between frames. + +## Lifetime and threading + +A player's methods are called on the UI thread. Keep one in the model, declare +its view in the page's own paint (not inside a `Memo`, or the view may not be +there when the picture wakes the page), and do not copy the player after it +has been shown. `Close` stops the video, frees the decoder or engine, and +closes the textures the engine shared; it is safe to call more than once. A +view of a closed player paints nothing. + +## What it is not + +- It shows pictures, not controls, subtitles or a playlist. +- It plays what the system plays. A codec the machine's media framework does + not have is an error the page can show with `Err`, not something Viva + decodes itself. +- It is not a camera or a capture API. \ No newline at end of file diff --git a/examples/guides/video/colors.mp4 b/examples/guides/video/colors.mp4 new file mode 100644 index 000000000..359037b89 Binary files /dev/null and b/examples/guides/video/colors.mp4 differ diff --git a/examples/guides/video/main.go b/examples/guides/video/main.go new file mode 100644 index 000000000..772be2bf4 --- /dev/null +++ b/examples/guides/video/main.go @@ -0,0 +1,174 @@ +// Video plays video in a Viva window, as a launcher's store page does: a +// short color-wave GIF loops behind the window's content, and a five-second +// color clip plays over it, with controls to pause it, seek and close it. +// +// go run ./examples/guides/video +// +// The GIF decodes in Go, on every system: package video.NewGIFDecoder's +// frames decode on a goroutine a few ahead, and each reaches the screen as it +// comes due, so the window draws one frame for each of the clip's and none +// between. +// +// The color clip is a 640×360 MP4 embedded in the application, made for this +// example: five seconds of full-frame color changes at 30 frames a second. It +// plays with the system's media framework, Media Foundation on Windows and +// AVFoundation on macOS, and its pictures reach the window's renderer where +// the decoder left them, on the GPU. Elsewhere OpenData reports +// ErrUnsupported: the example says so and keeps the GIF playing. +package main + +import ( + _ "embed" + "fmt" + "log" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/video" +) + +var ( + //go:embed waves.gif + wavesGIF []byte + //go:embed colors.mp4 + clipMP4 []byte +) + +// model is the state the window shows. +type model struct { + waves *video.Player + // clip is the color clip's player once opened, and clipErr what stopped it + // from opening, as a system without a media framework. + clip *video.Player + clipErr error + seek ui.SliderState +} + +func newModel() (*model, error) { + d, err := video.NewGIFDecoder(wavesGIF) + if err != nil { + return nil, err + } + waves := video.NewDecoder(d) + waves.Fit(video.Cover) + waves.SetLoop(true) + waves.Play() + return &model{waves: waves}, nil +} + +// openClip opens the color clip, which plays once its view shows it. The +// background holds still while the clip plays. +func (m *model) openClip() { + m.clip, m.clipErr = video.OpenData(clipMP4) + if m.clip != nil { + m.clip.Fit(video.Contain) + m.waves.Pause() + } +} + +// closeClip stops the clip and goes back to the background. +func (m *model) closeClip() { + m.clip.Close() + m.clip = nil + m.seek.Value = 0 + m.waves.Play() +} + +// page builds the interface from the state, on the main thread, whenever the +// window needs a frame. +func (m *model) page(c ui.C) { + white := ui.RGB(255, 255, 255) + ui.Stack(c).Fill().Children(func() { + video.View(c, "Waves", m.waves).Fill() + // Over the clip, which takes the window. + ui.Column(c).Absolute().Inset(0).Center().Gap(16).Children(func() { + if m.clip != nil { + m.clipView(c) + return + } + ui.Text(c, "Wavelength").FontSize(44).Bold().Color(white) + ui.Row(c).Gap(8).Children(func() { + label := "Pause" + if !m.waves.Playing() { + label = "Play" + } + if ui.Button(c, label).Width(96).Clicked() { + if m.waves.Playing() { + m.waves.Pause() + } else { + m.waves.Play() + } + } + if ui.Button(c, "Watch the clip").Clicked() { + m.openClip() + } + }) + if m.clipErr != nil { + ui.Text(c, m.clipErr.Error()).Color(white) + } + }) + }) +} + +// clipView shows the color clip and its controls. +func (m *model) clipView(c ui.C) { + p := m.clip + white := ui.RGB(255, 255, 255) + ui.Column(c).Width(480).Gap(8).Pad(12).Background(ui.RGBA(0, 0, 0, 0.78)).Radius(12).Children(func() { + ui.Stack(c).Width(456).Height(256).Children(func() { + video.View(c, "Clip", p).Fill() + if p.Err() != nil { + ui.Text(c, p.Err().Error()).Color(white) + } + }) + ui.Row(c).Gap(8).Items(ui.Center).Children(func() { + label := "Pause" + if !p.Playing() { + label = "Play" + } + if ui.Button(c, label).Width(72).Clicked() { + if p.Playing() { + p.Pause() + } else { + p.Play() + } + } + duration := float32(p.Duration().Seconds()) + if duration <= 0 { + duration = 0.001 + } + if !m.seek.Dragging() { + m.seek.Value = float32(p.Position().Seconds()) + } + if ui.Slider(c, &m.seek).Range(0, duration).Grow(1).Label("Position").Changed() { + p.Seek(time.Duration(float64(m.seek.Value) * float64(time.Second))) + } + ui.Text(c, clock(p.Position())+" / "+clock(p.Duration())).Color(white) + if ui.Button(c, "Close").Clicked() { + m.closeClip() + } + }) + }) +} + +// clock is a time as minutes and seconds. +func clock(d time.Duration) string { + sec := int(d.Round(time.Second) / time.Second) + return fmt.Sprintf("%d:%02d", sec/60, sec%60) +} + +func main() { + m, err := newModel() + if err != nil { + log.Fatal(err) + } + err = ui.Run(app.Config{Title: "Video", Width: 640, Height: 400}, ui.PageConfig{View: m.page}) + m.waves.Close() + if m.clip != nil { + m.clip.Close() + } + if err != nil { + log.Fatal(err) + } +} diff --git a/examples/guides/video/main_test.go b/examples/guides/video/main_test.go new file mode 100644 index 000000000..67de8af9e --- /dev/null +++ b/examples/guides/video/main_test.go @@ -0,0 +1,123 @@ +package main + +import ( + "errors" + "strings" + "testing" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/video" +) + +// open runs the page in a headless window: the real painter, router and focus +// rules, driven by explicit calls. +func open(t *testing.T, m *model) *app.Driver { + t.Helper() + page := ui.NewPage(ui.PageConfig{View: m.page}) + driver, err := app.NewDriver(ui.Configure(page, app.Config{Width: 640, Height: 400}), nil) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + driver.Close() + m.waves.Close() + if m.clip != nil { + m.clip.Close() + } + }) + return driver +} + +// control is the element a user finds by its name. +func control(t *testing.T, driver *app.Driver, name string) gfx.Hit { + t.Helper() + hits := driver.Snapshot().Hits + for i := len(hits) - 1; i >= 0; i-- { + hit := hits[i] + if hit.Label == name && !hit.IsLabel { + return hit + } + } + t.Fatalf("no control named %q on screen", name) + return gfx.Hit{} +} + +// click presses the middle of the named control. +func click(t *testing.T, driver *app.Driver, name string) { + t.Helper() + b := control(t, driver, name).Bounds + if err := driver.Click(b.X+b.Width/2, b.Y+b.Height/2); err != nil { + t.Fatal(err) + } +} + +func shows(driver *app.Driver, want string) bool { + for _, label := range driver.Snapshot().Labels { + if strings.Contains(label.Value, want) { + return true + } + } + return false +} + +// The page opens on the clip: its title, and the controls that play it or +// open the clip over it. +func TestThePageOpensOnTheClip(t *testing.T) { + m, err := newModel() + if err != nil { + t.Fatal(err) + } + driver := open(t, m) + if !shows(driver, "Wavelength") { + t.Fatal("the clip's title is not on screen") + } + if !m.waves.Playing() { + t.Fatal("the background clip starts paused") + } + click(t, driver, "Pause") + if m.waves.Playing() { + t.Fatal("Pause did not pause the clip") + } + if !shows(driver, "Play") { + t.Fatal("the button does not offer to play the clip again") + } +} + +// Watching opens the color clip over the background, plays it, and closing it +// goes back. +func TestWatchingTheClip(t *testing.T) { + m, err := newModel() + if err != nil { + t.Fatal(err) + } + driver := open(t, m) + click(t, driver, "Watch the clip") + if m.clip == nil { + if errors.Is(m.clipErr, video.ErrUnsupported) { + // No media framework here: the page says so and keeps the clip. + if !shows(driver, video.ErrUnsupported.Error()) { + t.Fatal("the page does not say why the clip did not open") + } + if !m.waves.Playing() { + t.Fatal("a platform without video stopped the background") + } + return + } + t.Fatalf("the clip did not open: %v", m.clipErr) + } + if m.waves.Playing() { + t.Fatal("the background kept playing behind the clip") + } + if !shows(driver, "Close") { + t.Fatal("the clip's controls are not on screen") + } + click(t, driver, "Close") + if m.clip != nil { + t.Fatal("Close kept the clip open") + } + if !m.waves.Playing() || !shows(driver, "Wavelength") { + t.Fatal("closing the clip did not go back to the background") + } +} diff --git a/examples/guides/video/waves.gif b/examples/guides/video/waves.gif new file mode 100644 index 000000000..4cd28da47 Binary files /dev/null and b/examples/guides/video/waves.gif differ diff --git a/gfx/canvas.go b/gfx/canvas.go index f0413f1b8..6f59dc917 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -317,10 +317,30 @@ type Bitmap struct { Version uint32 } -// Image is one bitmap draw. Source is measured in bitmap pixels. ClipOf and -// HasClip capture the active clip intersection at paint time. +// NativeTexture is a texture a platform engine decoded a picture into, shared +// with the renderer: an NT handle on Windows, an IOSurface on macOS. ID is +// stable while the texture lives, Handle is how the platform's renderer opens +// it, and Version says how often its contents changed, so a renderer can tell +// a new frame from a repeat. The engine keeps the texture alive while it shows +// it; a canvas records only the fields it was given. +type NativeTexture struct { + ID uint64 + Handle uintptr + Width int + Height int + Version uint32 +} + +// Image is one bitmap or shared-texture draw. Source is measured in bitmap +// pixels. ClipOf and HasClip capture the active clip intersection at paint +// time. When Texture is set the whole texture is the image: Bitmap and Source +// are ignored. type Image struct { - Bitmap Bitmap + Bitmap Bitmap + // Texture, when set, is a GPU texture from a platform engine. The Windows + // and macOS renderers draw it; a frame built for another platform drops + // the image. + Texture *NativeTexture Source Rect Bounds Rect Layer uint16 @@ -1261,6 +1281,28 @@ func (canvas *Canvas) DrawBitmapShaded(bitmap Bitmap, source, bounds Rect, radiu canvas.images = append(canvas.images, image) } +// DrawTexture appends a shared texture sampled into bounds, faded by fade +// (1-opacity), with square corners. The texture is drawn where the engine +// decoded it, without a copy through memory. A nil texture, one with no +// identity or no handle, one with a non-positive size, and bounds with no +// area are ignored. The canvas records a copy of the texture's fields, so the +// caller may reuse its value and later changes to it are not seen. +func (canvas *Canvas) DrawTexture(texture *NativeTexture, bounds Rect, fade float32) { + if texture == nil || texture.ID == 0 || texture.Handle == 0 || texture.Width <= 0 || texture.Height <= 0 || bounds.Width <= 0 || bounds.Height <= 0 { + return + } + recorded := *texture + image := Image{ + Texture: &recorded, + Bounds: bounds, + Fade: min(max(fade, 0), 1), + Layer: canvas.currentLayer(), + Order: canvas.nextOrder(), + } + image.ClipOf, image.HasClip = canvas.clipSnapshot() + canvas.images = append(canvas.images, image) +} + // DrawBackdrop appends a source region of bitmap sampled into bounds beneath // everything else the frame paints: every rectangle, text and image of every // layer, so that translucent surfaces let it show through. It is not clipped and diff --git a/gfx/texture_test.go b/gfx/texture_test.go new file mode 100644 index 000000000..b4559b1ee --- /dev/null +++ b/gfx/texture_test.go @@ -0,0 +1,66 @@ +package gfx + +import "testing" + +func TestDrawTextureRecordsItsBounds(t *testing.T) { + var canvas Canvas + texture := NativeTexture{ID: 7, Handle: 0x1234, Width: 640, Height: 360, Version: 3} + canvas.DrawTexture(&texture, Rect{X: 10, Y: 20, Width: 80, Height: 45}, 0.25) + images := canvas.Images() + if len(images) != 1 { + t.Fatalf("recorded %d images, want 1", len(images)) + } + image := images[0] + if image.Texture == nil { + t.Fatal("the image has no texture") + } + if *image.Texture != texture { + t.Fatalf("texture = %+v, want %+v", *image.Texture, texture) + } + if image.Bounds != (Rect{X: 10, Y: 20, Width: 80, Height: 45}) { + t.Errorf("bounds = %+v", image.Bounds) + } + if image.Fade != 0.25 { + t.Errorf("fade = %g, want 0.25", image.Fade) + } + // The recorded image is immutable: changing the caller's value does not + // change what the canvas holds. + texture.Version = 99 + if images[0].Texture.Version != 3 { + t.Error("the canvas kept a pointer to the caller's texture") + } +} + +func TestDrawTextureIgnoresInvalidInput(t *testing.T) { + var canvas Canvas + valid := NativeTexture{ID: 1, Handle: 2, Width: 4, Height: 4} + noHandle := valid + noHandle.Handle = 0 + noWidth := valid + noWidth.Width = 0 + noID := valid + noID.ID = 0 + canvas.DrawTexture(nil, Rect{Width: 4, Height: 4}, 0) + canvas.DrawTexture(&noHandle, Rect{Width: 4, Height: 4}, 0) + canvas.DrawTexture(&noID, Rect{Width: 4, Height: 4}, 0) + canvas.DrawTexture(&noWidth, Rect{Width: 4, Height: 4}, 0) + canvas.DrawTexture(&valid, Rect{Width: 0, Height: 4}, 0) + canvas.DrawTexture(&valid, Rect{Width: 4, Height: -1}, 0) + if got := len(canvas.Images()); got != 0 { + t.Fatalf("recorded %d images, want 0", got) + } +} + +func TestDrawTextureClampsItsFade(t *testing.T) { + var canvas Canvas + texture := NativeTexture{ID: 1, Handle: 2, Width: 4, Height: 4} + canvas.DrawTexture(&texture, Rect{Width: 4, Height: 4}, -1) + canvas.DrawTexture(&texture, Rect{Width: 4, Height: 4}, 2) + images := canvas.Images() + if len(images) != 2 { + t.Fatalf("recorded %d images, want 2", len(images)) + } + if images[0].Fade != 0 || images[1].Fade != 1 { + t.Errorf("fades = %g, %g, want 0, 1", images[0].Fade, images[1].Fade) + } +} diff --git a/internal/devreload/watcher.go b/internal/devreload/watcher.go index 742a076b4..ef54f4c5e 100644 --- a/internal/devreload/watcher.go +++ b/internal/devreload/watcher.go @@ -30,7 +30,7 @@ func (watcher *watcher) run(ctx context.Context) error { if err != nil { return err } - ticker := time.NewTicker(watcher.interval) + ticker := time.NewTicker(watcher.interval) //appaudit:allow the development reload host scans the source tree it rebuilds from defer ticker.Stop() for { select { diff --git a/internal/framebuild/framebuild.go b/internal/framebuild/framebuild.go index 269a0fd85..9a1cd1e6a 100644 --- a/internal/framebuild/framebuild.go +++ b/internal/framebuild/framebuild.go @@ -362,6 +362,22 @@ func (builder *Builder) appendImage(image gfx.Image) { if RoundPixel(image.Bounds.Width) <= 0 || RoundPixel(image.Bounds.Height) <= 0 { return } + if image.Texture != nil { + // A shared texture has no pixels in Go to cut: the renderer scissors + // the whole texture to the clip instead. A platform without shared + // textures drops it rather than paint a picture it cannot read. + if !platform.NativeTextures { + return + } + if image.HasClip { + if _, ok := intersectVisible(image.Bounds, image.ClipOf); !ok { + return + } + } + builder.clippedImages = append(builder.clippedImages, image) + builder.clippedImageBefores = append(builder.clippedImageBefores, uint32(len(builder.order))) + return + } if image.Backdrop { // A backdrop is beneath every layer, before any shape: it carries no // place among them. @@ -730,6 +746,10 @@ func (builder *Builder) syncLabels() { // frame's labels, after shapesBefore shapes. func (builder *Builder) appendImageLabel(index int, shapesBefore uint32) { image := builder.clippedImages[index] + if image.Texture != nil { + builder.appendTextureLabel(image, index, shapesBefore) + return + } bitmap := image.Bitmap left := max(int(image.Source.X), 0) top := max(int(image.Source.Y), 0) @@ -770,6 +790,32 @@ func (builder *Builder) appendImageLabel(index int, shapesBefore uint32) { builder.labelImage = append(builder.labelImage, int32(index)) } +// appendTextureLabel adds a shared-texture image to the frame's labels, after +// shapesBefore shapes. It carries no pixels: the renderer opens the texture, +// and scissors it to image.ClipOf when the clip cuts it. +func (builder *Builder) appendTextureLabel(image gfx.Image, index int, shapesBefore uint32) { + texture := image.Texture + width := RoundPixel(image.Bounds.Width) + height := RoundPixel(image.Bounds.Height) + if width <= 0 || height <= 0 { + return + } + entry := platform.TextLabel{ + X: float32(RoundPosition(image.Bounds.X)), Y: float32(RoundPosition(image.Bounds.Y)), + Width: float32(width), Height: float32(height), + Layer: builder.PlatformLayer(image.Layer), + ShapesBefore: shapesBefore, + TextureHandle: texture.Handle, TextureID: texture.ID, + TextureWidth: texture.Width, TextureHeight: texture.Height, TextureVersion: texture.Version, + ImageRadius: image.Radius, ImageFade: image.Fade, + } + if image.HasClip { + entry.Clip, entry.Clipped = image.ClipOf, true + } + builder.labels = append(builder.labels, entry) + builder.labelImage = append(builder.labelImage, int32(index)) +} + // bitmapUpload reports whether image number index must carry its pixels to the // platform. It may omit them only when the label it is about to become showed // the same picture in the frame last sent: the platform then reuses that @@ -1167,6 +1213,9 @@ func sameImages(left, right []gfx.Image) bool { } for index := range left { a, b := left[index], right[index] + if !sameTexture(a.Texture, b.Texture) { + return false + } if a.Bounds != b.Bounds || a.Source != b.Source || a.Layer != b.Layer || a.Order != b.Order || a.Backdrop != b.Backdrop || a.Radius != b.Radius || a.Fade != b.Fade || a.Bitmap.Width != b.Bitmap.Width || a.Bitmap.Height != b.Bitmap.Height || a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || a.Bitmap.Version != b.Bitmap.Version || len(a.Bitmap.Pix) != len(b.Bitmap.Pix) { @@ -1183,6 +1232,11 @@ func sameImages(left, right []gfx.Image) bool { // identity and version, source region and storage. A bitmap with no identity // (ID 0) is never the same: nothing says its pixels did not change. func SameImageBitmap(a, b gfx.Image) bool { + if a.Texture != nil || b.Texture != nil { + // A shared texture never reaches here as bytes: it is the same + // picture only when both draws name the same texture and version. + return sameTexture(a.Texture, b.Texture) + } if a.Source != b.Source || a.Bitmap.Width != b.Bitmap.Width || a.Bitmap.Height != b.Bitmap.Height || a.Bitmap.Stride != b.Bitmap.Stride || a.Bitmap.ID != b.Bitmap.ID || a.Bitmap.Version != b.Bitmap.Version || len(a.Bitmap.Pix) != len(b.Bitmap.Pix) || a.Bitmap.ID == 0 { @@ -1191,6 +1245,15 @@ func SameImageBitmap(a, b gfx.Image) bool { return len(a.Bitmap.Pix) == 0 || &a.Bitmap.Pix[0] == &b.Bitmap.Pix[0] } +// sameTexture reports whether two draws name the same shared texture, with the +// same handle, size and version. Two nil textures are the same picture. +func sameTexture(a, b *gfx.NativeTexture) bool { + if a == nil || b == nil { + return a == b + } + return *a == *b +} + // saveContent remembers this frame's texts for the next comparison. Their runs // live in the canvas, which is rewritten by the next paint, so they are copied. func (builder *Builder) saveContent() { diff --git a/internal/framebuild/texture_native_test.go b/internal/framebuild/texture_native_test.go new file mode 100644 index 000000000..5ad61213c --- /dev/null +++ b/internal/framebuild/texture_native_test.go @@ -0,0 +1,97 @@ +//go:build windows || darwin + +package framebuild + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +func TestTextureImageBecomesALabel(t *testing.T) { + var canvas gfx.Canvas + texture := gfx.NativeTexture{ID: 5, Handle: 0x99, Width: 64, Height: 32, Version: 4} + canvas.DrawTexture(&texture, gfx.Rect{X: 10, Y: 20, Width: 80, Height: 40}, 0.5) + builder := New(&canvas) + frame, err := builder.Build() + if err != nil { + t.Fatal(err) + } + if len(frame.TextLabels) != 1 { + t.Fatalf("frame has %d labels, want 1", len(frame.TextLabels)) + } + label := frame.TextLabels[0] + if label.TextureID != 5 || label.TextureHandle != 0x99 || label.TextureWidth != 64 || label.TextureHeight != 32 || label.TextureVersion != 4 { + t.Fatalf("label texture = %+v", label) + } + if label.Bitmap != nil || label.BitmapUpload { + t.Fatalf("a texture label carried pixels: %+v", label) + } + if label.X != 10 || label.Y != 20 || label.Width != 80 || label.Height != 40 || label.ImageFade != 0.5 { + t.Fatalf("label = %+v", label) + } +} + +func TestClippedTextureKeepsItsBounds(t *testing.T) { + var canvas gfx.Canvas + texture := gfx.NativeTexture{ID: 5, Handle: 0x99, Width: 64, Height: 32} + clip := gfx.Rect{X: 20, Y: 20, Width: 40, Height: 20} + canvas.Clip(clip) + canvas.DrawTexture(&texture, gfx.Rect{X: 10, Y: 20, Width: 80, Height: 40}, 0) + canvas.Unclip() + builder := New(&canvas) + frame, err := builder.Build() + if err != nil { + t.Fatal(err) + } + if len(frame.TextLabels) != 1 { + t.Fatalf("frame has %d labels, want 1", len(frame.TextLabels)) + } + label := frame.TextLabels[0] + if label.X != 10 || label.Width != 80 || label.Height != 40 { + t.Fatalf("a clipped texture was cut in Go: %+v", label) + } + if !label.Clipped || label.Clip != clip { + t.Fatalf("clip = %v %+v, want %+v", label.Clipped, label.Clip, clip) + } +} + +func TestClippedAwayTextureIsDropped(t *testing.T) { + var canvas gfx.Canvas + texture := gfx.NativeTexture{ID: 5, Handle: 0x99, Width: 64, Height: 32} + canvas.Clip(gfx.Rect{X: 200, Y: 200, Width: 10, Height: 10}) + canvas.DrawTexture(&texture, gfx.Rect{X: 10, Y: 20, Width: 80, Height: 40}, 0) + canvas.Unclip() + builder := New(&canvas) + frame, err := builder.Build() + if err != nil { + t.Fatal(err) + } + if len(frame.TextLabels) != 0 { + t.Fatalf("a texture outside its clip was kept: %+v", frame.TextLabels) + } +} + +func TestSameImageBitmapComparesTextures(t *testing.T) { + a := gfx.Image{Texture: &gfx.NativeTexture{ID: 1, Handle: 2, Width: 4, Height: 4, Version: 1}} + b := gfx.Image{Texture: &gfx.NativeTexture{ID: 1, Handle: 2, Width: 4, Height: 4, Version: 1}} + if !SameImageBitmap(a, b) { + t.Fatal("the same texture is not the same picture") + } + b.Texture.Version = 2 + if SameImageBitmap(a, b) { + t.Fatal("a new texture version is not a new picture") + } + b.Texture.Version = 1 + b.Texture.Handle = 3 + if SameImageBitmap(a, b) { + t.Fatal("a reopened texture is not a new picture") + } + if SameImageBitmap(a, gfx.Image{}) { + t.Fatal("a texture and no image are the same picture") + } + bitmap := gfx.Image{Bitmap: opaqueBitmap(3, 1, 4, 4)} + if SameImageBitmap(a, bitmap) || SameImageBitmap(bitmap, a) { + t.Fatal("a texture and a bitmap are the same picture") + } +} diff --git a/internal/media/av_darwin.go b/internal/media/av_darwin.go new file mode 100644 index 000000000..0f9df6777 --- /dev/null +++ b/internal/media/av_darwin.go @@ -0,0 +1,550 @@ +//go:build darwin && cgo && (amd64 || arm64) + +package media + +// On macOS, AVFoundation plays the video. An AVPlayerItemVideoOutput decodes +// each frame into a BGRA CVPixelBuffer whose memory is an IOSurface; the +// engine keeps the pixel buffers it shows and hands their surfaces to the +// renderer, which wraps them as Metal textures, so a picture reaches the +// window where it was decoded, without a copy through Go. +// +// The engine polls, at the player's frame interval, for a new picture, a +// finished seek and a state change, and wakes the window from that goroutine. + +/* +#cgo darwin LDFLAGS: -framework AVFoundation -framework CoreMedia -framework CoreVideo -framework Foundation -framework IOSurface +#include +#include "av_darwin.h" +*/ +import "C" + +import ( + "errors" + "fmt" + "sync" + "sync/atomic" + "time" + "unsafe" +) + +// frameSlots is the number of pictures the engine keeps, leaving the +// renderer time to read one while the engine shows the next. +const frameSlots = 3 + +// sharedIDs numbers the pictures, for the renderer to tell one from another. +var sharedIDs atomic.Uint64 + +// avSlot is one picture the engine keeps alive: the pixel buffer AVFoundation +// decoded, and the IOSurface of it the renderer wraps as a texture. +type avSlot struct { + buffer unsafe.Pointer // CVPixelBufferRef + handle uintptr // its IOSurface + width int + height int +} + +// avEngine plays one video with AVFoundation. +type avEngine struct { + engine *C.viva_media_engine + id uint64 // stable texture identity for this engine's renderer layer + stop chan struct{} + poke chan struct{} + + mu sync.Mutex + wake func() + state State // Loading until the first picture, then Ready + failure error + loop bool + rate float64 + playing bool + ended bool + seeking bool + seekAt time.Duration + seekNotified bool + consumed bool // a view has asked for a picture with Frame + shown int // the slot showing, -1 before the first picture + width int + height int + closed bool + + // watchPolls counts the watcher's looks. It lets a test prove that a + // player with no view, and a paused one, let the watcher park. + watchPolls atomic.Uint64 + + slots [frameSlots]avSlot +} + +// Open opens a video with AVFoundation. +func Open(s Source) (Engine, error) { + e := &avEngine{id: sharedIDs.Add(1), shown: -1, state: Loading, rate: 1} + if err := e.open(s); err != nil { + e.release() + return nil, err + } + e.stop = make(chan struct{}) + e.poke = make(chan struct{}, 1) + go e.watch() + return e, nil +} + +func (e *avEngine) open(s Source) error { + var cErr *C.char + var engine *C.viva_media_engine + switch { + case s.Path != "": + path := C.CString(s.Path) + engine = C.viva_media_open_path(path, &cErr) + C.free(unsafe.Pointer(path)) + case s.URL != "": + url := C.CString(s.URL) + engine = C.viva_media_open_url(url, &cErr) + C.free(unsafe.Pointer(url)) + case len(s.Data) > 0: + engine = C.viva_media_open_data(unsafe.Pointer(&s.Data[0]), C.size_t(len(s.Data)), &cErr) + default: + return errors.New("video: no source") + } + if engine == nil { + if cErr != nil { + err := fmt.Errorf("video: %s", C.GoString(cErr)) + C.viva_media_free_error(cErr) + return err + } + return errors.New("video: AVFoundation could not open the video") + } + e.engine = engine + return nil +} + +// watch polls the player while it is playing or while a seek a view asked for +// is landing, and parks without an active timer otherwise: a paused player +// has nothing to wait for, and a player no view has drawn has no picture to +// wake. Play, Seek and SetLoop poke it awake again. +func (e *avEngine) watch() { + timer := time.NewTimer(10 * time.Millisecond) + defer timer.Stop() + active := true + for { + if active { + select { + case <-e.stop: + return + case <-e.poke: + if !timer.Stop() { + select { + case <-timer.C: + default: + } + } + case <-timer.C: + } + } else { + select { + case <-e.stop: + return + case <-e.poke: + } + } + wake, keepActive := e.observe() + active = keepActive + if active { + timer.Reset(10 * time.Millisecond) + } + if wake { + e.wakeWindow() + } + } +} + +func (e *avEngine) pokeWatcher() { + if e.poke == nil { + return + } + select { + case e.poke <- struct{}{}: + default: + } +} + +// watcherActive reports whether the watcher has something to wait for: +// playback in progress, or a seek a view asked for still landing. A paused +// player has nothing to wait for, whether or not it has a picture, and a +// player no view has drawn does not poll for a seek either: its first paint +// asks for the picture and the seek lands then. +func watcherActive(playing, seeking, consumed bool) bool { + if playing { + return true + } + return seeking && consumed +} + +// observe reports whether the window should paint again and whether the +// watcher should keep polling. +func (e *avEngine) observe() (changed bool, active bool) { + e.watchPolls.Add(1) + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return false, false + } + ended := C.viva_media_ended(e.engine) != 0 + if ended && e.loop && e.playing { + // Loop: play again from the start, as browsers do. + C.viva_media_clear_ended(e.engine) + C.viva_media_seek(e.engine, 0) + C.viva_media_play(e.engine, C.double(e.playRate())) + e.ended, e.seeking, e.seekAt, e.seekNotified = false, true, 0, false + return true, true + } + if ended != e.ended { + e.ended = ended + changed = true + } + if e.failure == nil { + e.checkFailure() + } + state := e.stateNow() + if state != e.state { + e.state = state + changed = true + } + if state == Failed || state == Ended { + // Terminal state until Play/Seek: wake once on transition, then park. + return changed, false + } + if e.seeking { + if C.viva_media_seek_landed(e.engine) != 0 { + if !e.seekNotified { + e.seekNotified = true + changed = true + } + if e.playing && C.viva_media_has_new_frame(e.engine, C.viva_media_position(e.engine)) != 0 { + changed = true + } + // One wake is enough for a paused player: a view pulls the landed + // picture, and a player nobody drew has none to pull. A playing + // one keeps its watcher, which must see the frames after it and, + // with SetLoop, the end. + return changed, e.playing + } + return changed, watcherActive(e.playing, true, e.consumed) + } + if e.playing { + if C.viva_media_has_new_frame(e.engine, C.viva_media_position(e.engine)) != 0 { + changed = true + } + } + return changed, watcherActive(e.playing, false, e.consumed) +} + +// Frame returns the picture showing now, and whether it is newer than the one +// Frame returned before. +func (e *avEngine) Frame() (Picture, bool, bool) { + changed := e.pull() + e.mu.Lock() + defer e.mu.Unlock() + if e.closed || e.shown < 0 { + return Picture{}, false, false + } + slot := &e.slots[e.shown] + return Picture{Handle: slot.handle, ID: e.id, W: slot.width, H: slot.height}, changed, true +} + +// pull takes the picture due into the next slot. It forces the picture when +// the output does not call it new yet: the first picture after Open, and the +// frame a seek lands on once AVFoundation reports the seek complete. +func (e *avEngine) pull() bool { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return false + } + e.consumed = true + if e.seeking && C.viva_media_seek_landed(e.engine) == 0 { + // Wait for AVFoundation's seek completionHandler before pulling a + // frame so we never mistake a pre-seek buffered frame for the target. + // The watcher may have parked before a view asked for the picture; + // now that one has, wake it to poll for the landing. + e.pokeWatcher() + return false + } + force := C.int(0) + if e.seeking { + force = 1 + e.seeking = false + e.seekAt = 0 + e.seekNotified = false + } else if e.shown < 0 { + force = 1 + } + var w, h C.int + var surface unsafe.Pointer + // Once a seek has landed, query AVPlayer's live currentTime (not the old + // seek target): when playing, the clock has already moved past seekAt and + // AVPlayerItemVideoOutput drops frames for stale timestamps. + buffer := C.viva_media_copy_frame(e.engine, C.viva_media_position(e.engine), force, &w, &h, &surface) + if buffer == nil || w <= 0 || h <= 0 { + if buffer != nil { + C.viva_media_release_frame(buffer) + } + return false + } + next := (e.shown + 1) % frameSlots + slot := &e.slots[next] + if slot.buffer != nil { + C.viva_media_release_frame(slot.buffer) + } + slot.buffer = buffer + slot.handle = uintptr(surface) + slot.width, slot.height = int(w), int(h) + e.shown = next + e.width, e.height = int(w), int(h) + if e.state == Loading { + e.state = Ready + } + return true +} + +// playRate is the rate Play plays at. +func (e *avEngine) playRate() float64 { + if e.rate <= 0 { + return 1 + } + return e.rate +} + +// checkFailure records the item's failure, if it failed. +func (e *avEngine) checkFailure() { + if e.engine == nil || C.viva_media_status(e.engine) != 2 { + return + } + if message := C.viva_media_error(e.engine); message != nil { + e.failure = fmt.Errorf("video: %s", C.GoString(message)) + C.viva_media_free_error(message) + return + } + e.failure = errors.New("video: the video failed to play") +} + +// stateNow is where the engine is, in the report the player uses. +func (e *avEngine) stateNow() State { + if e.failure != nil { + return Failed + } + if e.ended { + return Ended + } + if e.shown < 0 { + return Loading + } + if e.playing && C.viva_media_waiting(e.engine) != 0 { + return Buffering + } + return Ready +} + +func (e *avEngine) SetWake(wake func()) { + e.mu.Lock() + e.wake = wake + e.mu.Unlock() +} + +func (e *avEngine) wakeWindow() { + e.mu.Lock() + wake := e.wake + e.mu.Unlock() + if wake != nil { + wake() + } +} + +func (e *avEngine) Interval() time.Duration { return time.Second / 60 } + +func (e *avEngine) State() (State, error) { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return Ended, nil + } + if e.failure == nil { + e.checkFailure() + } + if e.failure != nil { + return Failed, e.failure + } + if e.ended { + return Ended, nil + } + if e.shown < 0 { + return Loading, nil + } + if e.playing && C.viva_media_waiting(e.engine) != 0 { + return Buffering, nil + } + return Ready, nil +} + +func (e *avEngine) Size() (int, int) { + e.mu.Lock() + defer e.mu.Unlock() + return e.width, e.height +} + +func (e *avEngine) Duration() time.Duration { + e.mu.Lock() + defer e.mu.Unlock() + seconds := float64(C.viva_media_duration(e.engine)) + return time.Duration(seconds * float64(time.Second)) +} + +func (e *avEngine) Position() time.Duration { + e.mu.Lock() + defer e.mu.Unlock() + if e.seeking && C.viva_media_seek_landed(e.engine) == 0 { + return e.seekAt + } + return time.Duration(float64(C.viva_media_position(e.engine)) * float64(time.Second)) +} + +func (e *avEngine) Playing() bool { + e.mu.Lock() + defer e.mu.Unlock() + return !e.closed && e.engine != nil && e.playing && !e.ended +} + +func (e *avEngine) Play() { + e.mu.Lock() + if e.closed { + e.mu.Unlock() + return + } + if e.ended { + // Play after the end starts over, as the decoder player does. + C.viva_media_clear_ended(e.engine) + C.viva_media_seek(e.engine, 0) + e.ended, e.seeking, e.seekAt, e.seekNotified = false, true, 0, false + } + e.playing = true + C.viva_media_play(e.engine, C.double(e.playRate())) + e.mu.Unlock() + e.pokeWatcher() + e.wakeWindow() +} + +func (e *avEngine) Pause() { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return + } + e.playing = false + C.viva_media_pause(e.engine) +} + +func (e *avEngine) Seek(d time.Duration) { + if d < 0 { + d = 0 + } + e.mu.Lock() + if e.closed { + e.mu.Unlock() + return + } + e.ended = false + e.seeking = true + e.seekAt = d + e.seekNotified = false + C.viva_media_clear_ended(e.engine) + C.viva_media_seek(e.engine, C.double(d.Seconds())) + e.mu.Unlock() + e.pokeWatcher() + e.wakeWindow() +} + +func (e *avEngine) SetLoop(loop bool) { + e.mu.Lock() + e.loop = loop + e.mu.Unlock() + if loop { + e.pokeWatcher() + } +} + +func (e *avEngine) SetRate(rate float64) { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return + } + e.rate = rate + if e.playing { + C.viva_media_set_rate(e.engine, C.double(e.playRate())) + } +} + +func (e *avEngine) SetVolume(volume float64) { + if volume < 0 { + volume = 0 + } + if volume > 1 { + volume = 1 + } + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return + } + C.viva_media_set_volume(e.engine, C.double(volume)) +} + +func (e *avEngine) SetMuted(muted bool) { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return + } + value := C.int(0) + if muted { + value = 1 + } + C.viva_media_set_muted(e.engine, value) +} + +// Close stops the player and frees what it made. +func (e *avEngine) Close() error { + e.mu.Lock() + if e.closed { + e.mu.Unlock() + return nil + } + e.closed = true + e.wake = nil + stop := e.stop + e.mu.Unlock() + if stop != nil { + close(stop) + } + e.mu.Lock() + e.release() + e.mu.Unlock() + return nil +} + +// release frees the pictures and the player. It is called with the engine +// closed, so no other call can reach the player while it goes. +func (e *avEngine) release() { + for i := range e.slots { + e.freeSlot(&e.slots[i]) + } + if e.engine != nil { + C.viva_media_close(e.engine) + e.engine = nil + } +} + +func (e *avEngine) freeSlot(slot *avSlot) { + if slot.buffer != nil { + C.viva_media_release_frame(slot.buffer) + } + *slot = avSlot{} +} diff --git a/internal/media/av_darwin.h b/internal/media/av_darwin.h new file mode 100644 index 000000000..5b7437def --- /dev/null +++ b/internal/media/av_darwin.h @@ -0,0 +1,59 @@ +// The AVFoundation side of the macOS media engine: an AVPlayer decodes the +// video into IOSurface-backed BGRA pixel buffers, and the Go engine hands +// their surfaces to the renderer, which wraps them as Metal textures. +#ifndef VIVA_INTERNAL_MEDIA_AV_DARWIN_H +#define VIVA_INTERNAL_MEDIA_AV_DARWIN_H + +#include +#include + +typedef struct viva_media_engine viva_media_engine; + +// viva_media_open_url opens a URL AVFoundation accepts, viva_media_open_path +// a file, and viva_media_open_data bytes written to a temporary file that is +// removed when the engine closes. On failure they return NULL and, when +// error is not NULL, an error message the caller frees with +// viva_media_free_error. +viva_media_engine *viva_media_open_url(const char *url, char **error); +viva_media_engine *viva_media_open_path(const char *path, char **error); +viva_media_engine *viva_media_open_data(const void *data, size_t length, char **error); +void viva_media_free_error(char *error); +void viva_media_close(viva_media_engine *engine); + +// viva_media_status is the item's status: 0 unknown, 1 ready to play, 2 +// failed. viva_media_error describes a failure, malloc'd, or NULL. +int viva_media_status(viva_media_engine *engine); +char *viva_media_error(viva_media_engine *engine); + +// viva_media_ended reports whether the item played to its end, until +// viva_media_clear_ended takes the report away. viva_media_waiting reports +// whether the player is playing but waiting for data. +int viva_media_ended(viva_media_engine *engine); +void viva_media_clear_ended(viva_media_engine *engine); +int viva_media_waiting(viva_media_engine *engine); + +void viva_media_play(viva_media_engine *engine, double rate); +void viva_media_pause(viva_media_engine *engine); +void viva_media_seek(viva_media_engine *engine, double seconds); +// viva_media_seek_landed reports whether the latest viva_media_seek has +// completed in AVFoundation. +int viva_media_seek_landed(viva_media_engine *engine); +void viva_media_set_rate(viva_media_engine *engine, double rate); +void viva_media_set_volume(viva_media_engine *engine, double volume); +void viva_media_set_muted(viva_media_engine *engine, int muted); +double viva_media_position(viva_media_engine *engine); +double viva_media_duration(viva_media_engine *engine); + +// viva_media_has_new_frame reports whether the video output has a picture for +// seconds that viva_media_copy_frame has not returned yet. +int viva_media_has_new_frame(viva_media_engine *engine, double seconds); + +// viva_media_copy_frame returns the picture for seconds as a retained +// CVPixelBuffer, or NULL when there is none yet. force takes the picture even +// when the output does not call it new, which is how a paused seek and the +// first picture are read. width and height receive its size, and surface its +// IOSurface, which stays valid until the caller releases the pixel buffer. +void *viva_media_copy_frame(viva_media_engine *engine, double seconds, int force, int *width, int *height, void **surface); +void viva_media_release_frame(void *frame); + +#endif \ No newline at end of file diff --git a/internal/media/av_darwin.m b/internal/media/av_darwin.m new file mode 100644 index 000000000..69bb4fd7b --- /dev/null +++ b/internal/media/av_darwin.m @@ -0,0 +1,449 @@ +// The AVFoundation side of the macOS media engine. It is written in manual +// retain/release, like the rest of the native backends, and every function +// that makes Objective-C objects drains its own autorelease pool: the Go +// caller has none. +#include "av_darwin.h" + +#import +#import +#import +#import +#import + +#include +#include +#include +#include + +// VivaMediaEngine plays one item through an AVPlayer and reads the pictures +// the video output decodes into IOSurface-backed pixel buffers. +@interface VivaMediaEngine : NSObject { +@public + AVPlayer *_player; + AVPlayerItem *_item; + AVPlayerItemVideoOutput *_output; + NSString *_tempPath; // the file memory-held data was written to, or nil + atomic_bool _ended; + atomic_uint_least64_t _seekSeq; + atomic_uint_least64_t _seekDone; +} +- (instancetype)initWithURL:(NSURL *)url error:(NSError **)error; +@end + +@implementation VivaMediaEngine + +- (instancetype)initWithURL:(NSURL *)url error:(NSError **)error { + self = [super init]; + if (self == nil) { + return nil; + } + atomic_init(&_ended, false); + atomic_init(&_seekSeq, 0); + atomic_init(&_seekDone, 0); + AVPlayerItem *item = [AVPlayerItem playerItemWithURL:url]; + if (item == nil) { + if (error != NULL) { + *error = [NSError errorWithDomain:@"viva.media" + code:1 + userInfo:@{NSLocalizedDescriptionKey: @"the video could not be opened"}]; + } + [self release]; + return nil; + } + NSDictionary *attributes = @{ + (NSString *)kCVPixelBufferPixelFormatTypeKey: @(kCVPixelFormatType_32BGRA), + (NSString *)kCVPixelBufferIOSurfacePropertiesKey: @{}, + (NSString *)kCVPixelBufferMetalCompatibilityKey: @YES, + }; + AVPlayerItemVideoOutput *output = [[AVPlayerItemVideoOutput alloc] initWithPixelBufferAttributes:attributes]; + if (output == nil) { + if (error != NULL) { + *error = [NSError errorWithDomain:@"viva.media" + code:2 + userInfo:@{NSLocalizedDescriptionKey: @"the video output could not be made"}]; + } + [self release]; + return nil; + } + [item addOutput:output]; + AVPlayer *player = [[AVPlayer alloc] initWithPlayerItem:item]; + if (player == nil) { + [output release]; + if (error != NULL) { + *error = [NSError errorWithDomain:@"viva.media" + code:3 + userInfo:@{NSLocalizedDescriptionKey: @"the player could not be made"}]; + } + [self release]; + return nil; + } + // The item's clock stops at its end; the Go engine seeks back and plays + // again when it loops. + player.actionAtItemEnd = AVPlayerActionAtItemEndPause; + _item = [item retain]; + _output = output; + _player = player; + [[NSNotificationCenter defaultCenter] addObserver:self + selector:@selector(itemDidPlayToEnd:) + name:AVPlayerItemDidPlayToEndTimeNotification + object:item]; + return self; +} + +- (void)itemDidPlayToEnd:(NSNotification *)notification { + atomic_store(&_ended, true); +} + +- (void)close { + [[NSNotificationCenter defaultCenter] removeObserver:self]; + [_player pause]; + [_player replaceCurrentItemWithPlayerItem:nil]; + if (_tempPath != nil) { + [[NSFileManager defaultManager] removeItemAtPath:_tempPath error:NULL]; + [_tempPath release]; + _tempPath = nil; + } +} + +- (void)dealloc { + [self close]; + [_output release]; + [_item release]; + [_player release]; + [super dealloc]; +} + +@end + +// viva_media_engine is the opaque handle Go holds: the Objective-C engine +// and nothing else. +struct viva_media_engine { + void *object; +}; + +static void viva_report_failure(char **error, NSError *failure, NSString *fallback) { + if (error == NULL) { + return; + } + NSString *message = failure != nil ? failure.localizedDescription : fallback; + if (message == nil || message.UTF8String == NULL) { + message = @"the video could not be opened"; + } + *error = strdup(message.UTF8String); +} + +static viva_media_engine *viva_media_open(NSURL *url, char **error) { + char *message = NULL; + viva_media_engine *engine = NULL; + @autoreleasepool { + NSError *failure = nil; + VivaMediaEngine *object = [[VivaMediaEngine alloc] initWithURL:url error:&failure]; + if (object == nil) { + viva_report_failure(&message, failure, @"the video could not be opened"); + } else { + engine = calloc(1, sizeof(*engine)); + if (engine == NULL) { + [object release]; + viva_report_failure(&message, nil, @"memory for the video engine ran out"); + } else { + engine->object = object; + } + } + } + if (error != NULL) { + *error = message; + } else if (message != NULL) { + free(message); + } + return engine; +} + +viva_media_engine *viva_media_open_url(const char *url, char **error) { + @autoreleasepool { + NSString *string = url != NULL ? [NSString stringWithUTF8String:url] : nil; + NSURL *location = string != nil ? [NSURL URLWithString:string] : nil; + if (location == nil) { + viva_report_failure(error, nil, @"the video's URL is not valid"); + return NULL; + } + return viva_media_open(location, error); + } +} + +viva_media_engine *viva_media_open_path(const char *path, char **error) { + @autoreleasepool { + if (path == NULL) { + viva_report_failure(error, nil, @"the video's path is empty"); + return NULL; + } + NSString *string = [NSString stringWithUTF8String:path]; + if (string == nil) { + viva_report_failure(error, nil, @"the video's path is not valid"); + return NULL; + } + return viva_media_open([NSURL fileURLWithPath:string], error); + } +} + +viva_media_engine *viva_media_open_data(const void *data, size_t length, char **error) { + @autoreleasepool { + if (data == NULL || length == 0) { + viva_report_failure(error, nil, @"the video's data is empty"); + return NULL; + } + // AVFoundation plays files, so data goes to a temporary file beside + // the others the system keeps, and Close takes it away again. Pick + // the container extension from magic bytes so MOV/M4V/WebM are not + // misidentified as MP4. + NSString *ext = @"mp4"; + const uint8_t *raw = (const uint8_t *)data; + if (length >= 12 && memcmp(raw + 4, "ftyp", 4) == 0) { + if (memcmp(raw + 8, "qt ", 4) == 0) { + ext = @"mov"; + } else if (memcmp(raw + 8, "M4V ", 4) == 0 || memcmp(raw + 8, "m4v ", 4) == 0) { + ext = @"m4v"; + } + } else if (length >= 4 && memcmp(raw, "\x1a\x45\xdf\xa3", 4) == 0) { + ext = @"webm"; + } + NSString *name = [[[NSUUID UUID] UUIDString] stringByAppendingPathExtension:ext]; + NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:name]; + NSData *bytes = [NSData dataWithBytesNoCopy:(void *)data length:length freeWhenDone:NO]; + NSError *failure = nil; + if (![bytes writeToFile:path options:NSDataWritingAtomic error:&failure]) { + viva_report_failure(error, failure, @"the video's data could not be written"); + return NULL; + } + viva_media_engine *engine = viva_media_open([NSURL fileURLWithPath:path], error); + if (engine == NULL) { + [[NSFileManager defaultManager] removeItemAtPath:path error:NULL]; + return NULL; + } + ((VivaMediaEngine *)engine->object)->_tempPath = [path copy]; + return engine; + } +} + +void viva_media_free_error(char *error) { + free(error); +} + +void viva_media_close(viva_media_engine *engine) { + if (engine == NULL) { + return; + } + @autoreleasepool { + VivaMediaEngine *me = (VivaMediaEngine *)engine->object; + [me close]; + [me release]; + free(engine); + } +} + +int viva_media_status(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return 0; + } + @autoreleasepool { + VivaMediaEngine *me = (VivaMediaEngine *)engine->object; + if (me->_player.status == AVPlayerStatusFailed) { + return 2; + } + AVPlayerItemStatus status = me->_item.status; + switch (status) { + case AVPlayerItemStatusReadyToPlay: + return 1; + case AVPlayerItemStatusFailed: + return 2; + default: + return 0; + } + } +} + +char *viva_media_error(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return NULL; + } + @autoreleasepool { + VivaMediaEngine *me = (VivaMediaEngine *)engine->object; + NSError *failure = me->_item.error != nil ? me->_item.error : me->_player.error; + if (failure == nil) { + return NULL; + } + const char *message = failure.localizedDescription.UTF8String; + if (message == NULL) { + message = "the video failed to play"; + } + return strdup(message); + } +} + +int viva_media_ended(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return 0; + } + return atomic_load(&((VivaMediaEngine *)engine->object)->_ended) ? 1 : 0; +} + +void viva_media_clear_ended(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return; + } + atomic_store(&((VivaMediaEngine *)engine->object)->_ended, false); +} + +int viva_media_waiting(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return 0; + } + @autoreleasepool { + return ((VivaMediaEngine *)engine->object)->_player.timeControlStatus == AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate ? 1 : 0; + } +} + +void viva_media_play(viva_media_engine *engine, double rate) { + if (engine == NULL || engine->object == NULL) { + return; + } + @autoreleasepool { + AVPlayer *player = ((VivaMediaEngine *)engine->object)->_player; + [player play]; + player.rate = (float)rate; + } +} + +void viva_media_pause(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return; + } + @autoreleasepool { + ((VivaMediaEngine *)engine->object)->_player.rate = 0; + } +} + +void viva_media_seek(viva_media_engine *engine, double seconds) { + if (engine == NULL || engine->object == NULL) { + return; + } + @autoreleasepool { + VivaMediaEngine *me = (VivaMediaEngine *)engine->object; + uint64_t seq = atomic_fetch_add(&me->_seekSeq, 1) + 1; + CMTime time = CMTimeMakeWithSeconds(seconds, 600); + [me->_player seekToTime:time + toleranceBefore:kCMTimeZero + toleranceAfter:kCMTimeZero + completionHandler:^(BOOL finished) { + // Only mark landed when this seek completed or is still the + // latest seek (superseding seeks cancel earlier ones). + if (finished || atomic_load(&me->_seekSeq) == seq) { + uint64_t prev = atomic_load(&me->_seekDone); + while (prev < seq && !atomic_compare_exchange_weak(&me->_seekDone, &prev, seq)) { + } + } + }]; + } +} + +int viva_media_seek_landed(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return 1; + } + VivaMediaEngine *me = (VivaMediaEngine *)engine->object; + return atomic_load(&me->_seekDone) >= atomic_load(&me->_seekSeq) ? 1 : 0; +} + +void viva_media_set_rate(viva_media_engine *engine, double rate) { + if (engine == NULL || engine->object == NULL) { + return; + } + @autoreleasepool { + ((VivaMediaEngine *)engine->object)->_player.rate = (float)rate; + } +} + +void viva_media_set_volume(viva_media_engine *engine, double volume) { + if (engine == NULL || engine->object == NULL) { + return; + } + @autoreleasepool { + ((VivaMediaEngine *)engine->object)->_player.volume = (float)volume; + } +} + +void viva_media_set_muted(viva_media_engine *engine, int muted) { + if (engine == NULL || engine->object == NULL) { + return; + } + @autoreleasepool { + ((VivaMediaEngine *)engine->object)->_player.muted = muted != 0; + } +} + +double viva_media_position(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return 0; + } + @autoreleasepool { + double seconds = CMTimeGetSeconds(((VivaMediaEngine *)engine->object)->_player.currentTime); + return isfinite(seconds) && seconds > 0 ? seconds : 0; + } +} + +double viva_media_duration(viva_media_engine *engine) { + if (engine == NULL || engine->object == NULL) { + return 0; + } + @autoreleasepool { + double seconds = CMTimeGetSeconds(((VivaMediaEngine *)engine->object)->_item.duration); + return isfinite(seconds) && seconds > 0 ? seconds : 0; + } +} + +int viva_media_has_new_frame(viva_media_engine *engine, double seconds) { + if (engine == NULL || engine->object == NULL) { + return 0; + } + @autoreleasepool { + CMTime time = CMTimeMakeWithSeconds(seconds, 600); + return [((VivaMediaEngine *)engine->object)->_output hasNewPixelBufferForItemTime:time] ? 1 : 0; + } +} + +void *viva_media_copy_frame(viva_media_engine *engine, double seconds, int force, int *width, int *height, void **surface) { + if (engine == NULL || engine->object == NULL) { + return NULL; + } + @autoreleasepool { + AVPlayerItemVideoOutput *output = ((VivaMediaEngine *)engine->object)->_output; + CMTime time = CMTimeMakeWithSeconds(seconds, 600); + if (force == 0 && ![output hasNewPixelBufferForItemTime:time]) { + return NULL; + } + CVPixelBufferRef buffer = [output copyPixelBufferForItemTime:time itemTimeForDisplay:NULL]; + if (buffer == NULL) { + return NULL; + } + IOSurfaceRef shape = CVPixelBufferGetIOSurface(buffer); + if (shape == NULL) { + CVPixelBufferRelease(buffer); + return NULL; + } + if (width != NULL) { + *width = (int)CVPixelBufferGetWidth(buffer); + } + if (height != NULL) { + *height = (int)CVPixelBufferGetHeight(buffer); + } + if (surface != NULL) { + *surface = (void *)shape; + } + return buffer; + } +} + +void viva_media_release_frame(void *frame) { + if (frame != NULL) { + CVPixelBufferRelease((CVPixelBufferRef)frame); + } +} \ No newline at end of file diff --git a/internal/media/av_darwin_test.go b/internal/media/av_darwin_test.go new file mode 100644 index 000000000..81f4a5b23 --- /dev/null +++ b/internal/media/av_darwin_test.go @@ -0,0 +1,367 @@ +//go:build darwin && cgo && (amd64 || arm64) + +package media + +import ( + "os" + "testing" + "time" + + "github.com/vivaui/viva/internal/platform/darwin/mainpump" +) + +func TestMain(m *testing.M) { + os.Exit(mainpump.Run(m)) +} + +func waitNextFrame(t *testing.T, engine Engine, timeout time.Duration) (Picture, bool) { + t.Helper() + woken := make(chan struct{}, 1) + engine.SetWake(func() { + select { + case woken <- struct{}{}: + default: + } + }) + deadline := time.Now().Add(timeout) + for time.Now().Before(deadline) { + if pic, changed, ok := engine.Frame(); ok && changed { + return pic, true + } + select { + case <-woken: + case <-time.After(10 * time.Millisecond): + } + } + return Picture{}, false +} + +func TestEnginePlaysColorVideo(t *testing.T) { + engine, err := Open(Source{Path: "testdata/colors.mp4"}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer engine.Close() + woken := make(chan struct{}, 1) + engine.SetWake(func() { + select { + case woken <- struct{}{}: + default: + } + }) + engine.Play() + var picture Picture + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + var ok bool + if picture, _, ok = engine.Frame(); ok { + break + } + select { + case <-woken: + case <-time.After(10 * time.Millisecond): + } + } + if picture.Handle == 0 { + t.Fatal("no picture in 10s") + } + if picture.ID == 0 || picture.W != 640 || picture.H != 360 { + t.Fatalf("picture = %+v, want 640x360", picture) + } + if w, h := engine.Size(); w != picture.W || h != picture.H { + t.Errorf("Size = %dx%d, picture %dx%d", w, h, picture.W, picture.H) + } + if d := engine.Duration(); d < 5*time.Second || d > 6*time.Second { + t.Errorf("Duration = %v, want 5s", d) + } + engine.Pause() + if engine.Playing() { + t.Error("a paused engine reports playing") + } + engine.Seek(0) + engine.Play() + if state, err := engine.State(); err != nil || state == Failed { + t.Fatalf("after seek: %v, %v", state, err) + } + if err := engine.Close(); err != nil { + t.Fatal(err) + } + if err := engine.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } + // Methods called after Close must be safe no-ops. + engine.Play() + engine.Pause() + engine.Seek(time.Second) + engine.SetLoop(true) + engine.SetRate(1.5) + engine.SetVolume(0.5) + engine.SetMuted(true) + if engine.Playing() || engine.Duration() != 0 || engine.Position() != 0 { + t.Fatal("closed engine still reported playback activity") + } + if _, _, ok := engine.Frame(); ok { + t.Fatal("closed engine returned a frame") + } + if state, err := engine.State(); state != Ended || err != nil { + t.Fatalf("closed engine State = (%v, %v), want (Ended, nil)", state, err) + } +} + +func TestEnginePausedFirstFrameAndSeek(t *testing.T) { + engine, err := Open(Source{Path: "testdata/colors.mp4"}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer engine.Close() + pic, ok := waitNextFrame(t, engine, 5*time.Second) + if !ok { + state, serr := engine.State() + t.Fatalf("no paused first frame in 5s: state=%v err=%v", state, serr) + } + if pic.W != 640 || pic.H != 360 || pic.Handle == 0 || pic.ID == 0 { + t.Fatalf("paused first frame = %+v, want 640x360", pic) + } + if engine.Playing() { + t.Fatal("paused engine reports playing") + } + if state, serr := engine.State(); state != Ready || serr != nil { + t.Fatalf("state after first frame = (%v, %v), want (Ready, nil)", state, serr) + } + + // Paused seek to middle, exact end, and past end must land and keep the stable texture ID. + for _, target := range []time.Duration{2500 * time.Millisecond, 5 * time.Second, 10 * time.Second} { + engine.Seek(target) + next, ok := waitNextFrame(t, engine, 5*time.Second) + if !ok { + t.Fatalf("paused Seek(%v) produced no frame", target) + } + if next.ID != pic.ID { + t.Fatalf("Seek(%v) changed texture ID %d -> %d", target, pic.ID, next.ID) + } + } +} + +func TestEngineOpenDataPlays(t *testing.T) { + data, err := os.ReadFile("testdata/colors.mp4") + if err != nil { + t.Fatal(err) + } + engine, err := Open(Source{Data: data}) + if err != nil { + t.Fatalf("OpenData: %v", err) + } + defer engine.Close() + pic, ok := waitNextFrame(t, engine, 5*time.Second) + if !ok { + state, serr := engine.State() + t.Fatalf("OpenData: no frame in 5s: state=%v err=%v", state, serr) + } + if pic.W != 640 || pic.H != 360 { + t.Fatalf("OpenData frame = %+v, want 640x360", pic) + } +} + +func TestEngineSeekWhilePlayingReplayLoopAndRate(t *testing.T) { + engine, err := Open(Source{Path: "testdata/colors.mp4"}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer engine.Close() + if _, ok := waitNextFrame(t, engine, 5*time.Second); !ok { + t.Fatal("no initial frame") + } + + // Play to the end (non-looping). + engine.SetLoop(false) + engine.Seek(4600 * time.Millisecond) + if _, ok := waitNextFrame(t, engine, 5*time.Second); !ok { + t.Fatal("seek to 4.6s failed") + } + engine.Play() + deadline := time.Now().Add(4 * time.Second) + reachedEnd := false + for time.Now().Before(deadline) { + engine.Frame() + if state, _ := engine.State(); state == Ended { + reachedEnd = true + break + } + time.Sleep(20 * time.Millisecond) + } + if !reachedEnd { + state, serr := engine.State() + t.Fatalf("did not reach Ended: state=%v err=%v pos=%v", state, serr, engine.Position()) + } + if engine.Playing() { + t.Fatal("ended engine still reports playing") + } + + // Play() after Ended must seek back to 0 and actively advance frames and position. + engine.Play() + changedCount := 0 + for range 12 { + time.Sleep(50 * time.Millisecond) + if _, changed, ok := engine.Frame(); ok && changed { + changedCount++ + } + } + if pos := engine.Position(); pos < 250*time.Millisecond { + t.Fatalf("Play() after Ended did not advance playback: pos=%v", pos) + } + if changedCount == 0 { + t.Fatal("Play() after Ended did not deliver new frames") + } + + // Seek while playing must land and continue advancing frames and position. + engine.Seek(1500 * time.Millisecond) + changedCount = 0 + for range 12 { + time.Sleep(50 * time.Millisecond) + if _, changed, ok := engine.Frame(); ok && changed { + changedCount++ + } + } + if pos := engine.Position(); pos < 1750*time.Millisecond { + t.Fatalf("Seek while playing did not advance: pos=%v", pos) + } + if changedCount == 0 { + t.Fatal("Seek while playing did not deliver new frames") + } + + // SetLoop(true) must wrap past the end and keep playing. + engine.SetLoop(true) + engine.Seek(4600 * time.Millisecond) + wrapped := false + changedAfterWrap := 0 + for range 24 { + time.Sleep(50 * time.Millisecond) + _, changed, ok := engine.Frame() + pos := engine.Position() + if pos < 2*time.Second { + wrapped = true + if ok && changed { + changedAfterWrap++ + } + } + } + if !wrapped || engine.Position() < 200*time.Millisecond || engine.Position() > 2*time.Second { + t.Fatalf("SetLoop(true) did not wrap and continue playing: wrapped=%v pos=%v", wrapped, engine.Position()) + } + if changedAfterWrap == 0 { + t.Fatal("SetLoop(true) did not deliver new frames after wrapping") + } + + // SetRate(2.0) must advance faster than real time. + engine.SetLoop(false) + engine.Seek(0) + time.Sleep(150 * time.Millisecond) + engine.Frame() + engine.SetRate(2.0) + start := engine.Position() + time.Sleep(500 * time.Millisecond) + engine.Frame() + if delta := engine.Position() - start; delta < 750*time.Millisecond { + t.Fatalf("SetRate(2.0) advanced %v in 500ms, want >= 750ms", delta) + } +} + +// TestWatcherParksWithoutAConsumer checks the watcher's reason to poll: a +// paused player has none, and a seek is watched only for a player a view has +// drawn. +func TestWatcherParksWithoutAConsumer(t *testing.T) { + for _, test := range []struct { + name string + playing, seeking, consumed bool + want bool + }{ + {"paused, no view", false, false, false, false}, + {"paused after a view", false, false, true, false}, + {"playing, no view", true, false, false, true}, + {"playing after a view", true, false, true, true}, + {"seek with a view", false, true, true, true}, + {"seek with no view", false, true, false, false}, + {"seek while playing", true, true, false, true}, + } { + if got := watcherActive(test.playing, test.seeking, test.consumed); got != test.want { + t.Errorf("%s: watcherActive(%v, %v, %v) = %v, want %v", + test.name, test.playing, test.seeking, test.consumed, got, test.want) + } + } +} + +// A player no view has drawn has nothing to wait for: it lets the watcher +// park even when its item becomes ready. A seek from it does not start a poll +// loop either, while playback keeps the watcher looking for pictures. +func TestEngineWithoutAViewStaysIdle(t *testing.T) { + engine, err := Open(Source{Path: "testdata/colors.mp4"}) + if err != nil { + t.Fatalf("Open: %v", err) + } + defer engine.Close() + e := engine.(*avEngine) + + // Nothing draws: the watcher looks, learns it has nothing to wait for, + // and parks. + start := e.watchPolls.Load() + time.Sleep(300 * time.Millisecond) + if looks := e.watchPolls.Load() - start; looks > 2 { + t.Fatalf("a player with no view looked %d times in 300ms", looks) + } + + // A seek on a player no view has drawn has no picture to land in. + engine.Seek(500 * time.Millisecond) + start = e.watchPolls.Load() + time.Sleep(400 * time.Millisecond) + if looks := e.watchPolls.Load() - start; looks > 2 { + t.Fatalf("a seek on a player with no view looked %d times in 400ms", looks) + } + + // A view pulls its first picture; a paused player has nothing to wait for + // again. + deadline := time.Now().Add(5 * time.Second) + pulled := false + for !pulled && time.Now().Before(deadline) { + if _, _, pulled = engine.Frame(); !pulled { + time.Sleep(10 * time.Millisecond) + } + } + if !pulled { + t.Fatal("no picture in 5s") + } + time.Sleep(100 * time.Millisecond) + start = e.watchPolls.Load() + time.Sleep(300 * time.Millisecond) + if looks := e.watchPolls.Load() - start; looks > 2 { + t.Fatalf("a paused player looked %d times in 300ms", looks) + } + + // Playback keeps looking: it must see the frames after the seek and the + // end, to loop. + engine.Play() + start = e.watchPolls.Load() + time.Sleep(300 * time.Millisecond) + if looks := e.watchPolls.Load() - start; looks < 5 { + t.Fatalf("a playing player looked %d times in 300ms", looks) + } +} + +func TestEngineInvalidFileFails(t *testing.T) { + engine, err := Open(Source{Path: "testdata/does_not_exist.mp4"}) + if err != nil { + return + } + defer engine.Close() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + if state, serr := engine.State(); state == Failed { + if serr == nil { + t.Fatal("Failed state returned nil error") + } + return + } + time.Sleep(20 * time.Millisecond) + } + state, serr := engine.State() + t.Fatalf("missing file did not fail in 5s: state=%v err=%v", state, serr) +} diff --git a/internal/media/device_windows.go b/internal/media/device_windows.go new file mode 100644 index 000000000..66737be54 --- /dev/null +++ b/internal/media/device_windows.go @@ -0,0 +1,249 @@ +//go:build windows && (amd64 || arm64) + +package media + +import ( + "fmt" + "os" + "sync" + "syscall" + "unsafe" +) + +var ( + kernel32 = syscall.NewLazyDLL("kernel32.dll") + procGetSystemDirectory = kernel32.NewProc("GetSystemDirectoryW") + d3d11 = systemDLL("d3d11.dll") + procD3D11CreateDevice = d3d11.NewProc("D3D11CreateDevice") + dxgi = systemDLL("dxgi.dll") + procCreateDXGIFactory1 = dxgi.NewProc("CreateDXGIFactory1") + iidDXGIFactory1 = syscall.GUID{Data1: 0x770aae78, Data2: 0xf26f, Data3: 0x4dba, Data4: [8]byte{0xa8, 0x29, 0x25, 0x3c, 0x83, 0xd1, 0xb3, 0x87}} + iidDXGIDevice = syscall.GUID{Data1: 0x54ec77fa, Data2: 0x1377, Data3: 0x44e6, Data4: [8]byte{0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}} + rendererAdapterMu sync.RWMutex + rendererAdapterLUIDLow uint32 + rendererAdapterLUIDHigh int32 + rendererAdapterKnown bool +) + +// dxgiAdapterDesc1 matches DXGI_ADAPTER_DESC1 on 64-bit Windows. +type dxgiAdapterDesc1 struct { + Description [128]uint16 + VendorId uint32 + DeviceId uint32 + SubSysId uint32 + Revision uint32 + DedicatedVideoMemory uintptr + DedicatedSystemMemory uintptr + SharedSystemMemory uintptr + AdapterLuidLow uint32 + AdapterLuidHigh int32 + Flags uint32 +} + +// SetRendererAdapterLUID records the DXGI adapter LUID of the window renderer's +// Direct3D 11 device so new video engines decode on the same adapter and can +// share textures across devices on multi-GPU or WARP systems. +func SetRendererAdapterLUID(low uint32, high int32) { + rendererAdapterMu.Lock() + rendererAdapterLUIDLow = low + rendererAdapterLUIDHigh = high + rendererAdapterKnown = true + rendererAdapterMu.Unlock() +} + +func rendererAdapterLUID() (low uint32, high int32, ok bool) { + rendererAdapterMu.RLock() + low, high, ok = rendererAdapterLUIDLow, rendererAdapterLUIDHigh, rendererAdapterKnown + rendererAdapterMu.RUnlock() + return low, high, ok +} + +// sharedRegistry tracks live shared texture IDs back to their owning engine +// and remembers recently retired IDs so the renderer drops closed textures on +// the next frame instead of waiting for its frame-count sweep. +const retiredRingSize = 512 + +var sharedRegistry = struct { + sync.RWMutex + live map[uint64]*mediaEngine + retired map[uint64]struct{} + retiredLog [retiredRingSize]uint64 + retiredPos int +}{ + live: make(map[uint64]*mediaEngine), + retired: make(map[uint64]struct{}), +} + +func registerSharedTexture(id uint64, e *mediaEngine) { + if id == 0 { + return + } + sharedRegistry.Lock() + sharedRegistry.live[id] = e + delete(sharedRegistry.retired, id) + sharedRegistry.Unlock() +} + +func retireSharedTexture(id uint64) { + if id == 0 { + return + } + sharedRegistry.Lock() + delete(sharedRegistry.live, id) + if old := sharedRegistry.retiredLog[sharedRegistry.retiredPos]; old != 0 { + delete(sharedRegistry.retired, old) + } + sharedRegistry.retiredLog[sharedRegistry.retiredPos] = id + sharedRegistry.retiredPos = (sharedRegistry.retiredPos + 1) % retiredRingSize + sharedRegistry.retired[id] = struct{}{} + sharedRegistry.Unlock() +} + +// IsSharedTextureRetired reports whether the media engine that created texture +// id has already freed its slot. +func IsSharedTextureRetired(id uint64) bool { + if id == 0 { + return false + } + sharedRegistry.RLock() + _, ok := sharedRegistry.retired[id] + sharedRegistry.RUnlock() + return ok +} + +// ReportSharedTextureError tells the engine owning texture id that the +// renderer could not open its shared handle, so the player surfaces Failed +// through Err rather than painting black silently. +func ReportSharedTextureError(id uint64, err error) { + if id == 0 || err == nil { + return + } + sharedRegistry.RLock() + e := sharedRegistry.live[id] + sharedRegistry.RUnlock() + if e == nil { + return + } + e.mu.Lock() + if e.closed || e.state == Failed { + e.mu.Unlock() + return + } + e.state = Failed + e.failure = fmt.Errorf("video: renderer could not open shared texture: %w", err) + e.mu.Unlock() + e.wakeWindow() +} + +// systemDLL loads name from the Windows system directory by absolute path, so +// no other directory's DLL with the same name is found first. +func systemDLL(name string) *syscall.LazyDLL { + var path [32768]uint16 + n, _, _ := procGetSystemDirectory.Call(uintptr(unsafe.Pointer(&path[0])), uintptr(len(path))) + if n == 0 || n >= uintptr(len(path)) { + return syscall.NewLazyDLL(name) + } + return syscall.NewLazyDLL(syscall.UTF16ToString(path[:n]) + `\` + name) +} + +// newVideoDevice creates the Direct3D 11 device Media Foundation decodes on: +// matching the renderer's DXGI adapter when known so shared NT handles always +// open on the same GPU (or WARP), with video support where available and +// falling back to a plain device otherwise. The caller releases both. +func newVideoDevice() (device, context uintptr, err error) { + const videoSupport = 0x800 + if low, high, ok := rendererAdapterLUID(); ok { + if adapter := findAdapterByLUID(low, high); adapter != 0 { + defer releaseCom(&adapter) + if device, context, err = createDeviceOnAdapter(adapter, videoSupport); err == nil { + return device, context, nil + } + if device, context, err = createDeviceOnAdapter(adapter, 0); err == nil { + return device, context, nil + } + } + } + if device, context, err = createVideoDevice(videoSupport); err == nil { + return device, context, nil + } + return createVideoDevice(0) +} + +// findAdapterByLUID enumerates DXGI 1.1 adapters (including the software WARP +// adapter) and returns the retained IDXGIAdapter1 whose LUID matches, or 0. +func findAdapterByLUID(low uint32, high int32) uintptr { + if procCreateDXGIFactory1.Find() != nil { + return 0 + } + var factory uintptr + hr, _, _ := procCreateDXGIFactory1.Call(uintptr(unsafe.Pointer(&iidDXGIFactory1)), uintptr(unsafe.Pointer(&factory))) + if hresultFailed(hr) || factory == 0 { + return 0 + } + defer releaseCom(&factory) + const ( + factoryEnumAdapters1 = 12 + adapterGetDesc1 = 10 + ) + for i := uintptr(0); ; i++ { + var adapter uintptr + if hresultFailed(invoke(factory, factoryEnumAdapters1, i, uintptr(unsafe.Pointer(&adapter)))) || adapter == 0 { + return 0 + } + var desc dxgiAdapterDesc1 + if !hresultFailed(invoke(adapter, adapterGetDesc1, uintptr(unsafe.Pointer(&desc)))) && + desc.AdapterLuidLow == low && desc.AdapterLuidHigh == high { + return adapter + } + releaseCom(&adapter) + } +} + +// createDeviceOnAdapter creates a Direct3D 11 device on a specific IDXGIAdapter. +// D3D_DRIVER_TYPE_UNKNOWN (0) is required whenever a non-null adapter is passed. +func createDeviceOnAdapter(adapter, videoSupport uintptr) (device, context uintptr, err error) { + if err := procD3D11CreateDevice.Find(); err != nil { + return 0, 0, err + } + levels := [...]uint32{0xb000, 0xa100, 0xa000} // 11_0, 10_1, 10_0 + const ( + driverUnknown = 0 + bgraSupport = 0x20 + sdkVersion = 7 + ) + var level uint32 + hr, _, _ := procD3D11CreateDevice.Call(adapter, driverUnknown, 0, bgraSupport|videoSupport, + uintptr(unsafe.Pointer(&levels[0])), uintptr(len(levels)), sdkVersion, + uintptr(unsafe.Pointer(&device)), uintptr(unsafe.Pointer(&level)), uintptr(unsafe.Pointer(&context))) + if int32(uint32(hr)) >= 0 { + return device, context, nil + } + return 0, 0, fmt.Errorf("video: cannot create a Direct3D device on adapter: %#x", uint32(hr)) +} + +// createVideoDevice creates the device from the first driver of hardware +// and the software rasterizer that takes flags. +func createVideoDevice(videoSupport uintptr) (device, context uintptr, err error) { + if err := procD3D11CreateDevice.Find(); err != nil { + return 0, 0, err + } + levels := [...]uint32{0xb000, 0xa100, 0xa000} // 11_0, 10_1, 10_0 + const bgraSupport, sdkVersion = 0x20, 7 + const hardware, warp = 1, 5 + drivers := []uintptr{hardware, warp} + if os.Getenv("VIVA_SOFTWARE_RENDERING") == "1" { + drivers = drivers[1:] + } + var hr uintptr + for _, driver := range drivers { + var level uint32 + hr, _, _ = procD3D11CreateDevice.Call(0, driver, 0, bgraSupport|videoSupport, + uintptr(unsafe.Pointer(&levels[0])), uintptr(len(levels)), sdkVersion, + uintptr(unsafe.Pointer(&device)), uintptr(unsafe.Pointer(&level)), uintptr(unsafe.Pointer(&context))) + if int32(uint32(hr)) >= 0 { + return device, context, nil + } + device, context = 0, 0 + } + return 0, 0, fmt.Errorf("video: cannot create a Direct3D device: %#x", uint32(hr)) +} diff --git a/internal/media/device_windows_test.go b/internal/media/device_windows_test.go new file mode 100644 index 000000000..0b1102ca5 --- /dev/null +++ b/internal/media/device_windows_test.go @@ -0,0 +1,54 @@ +//go:build windows && (amd64 || arm64) + +package media + +import ( + "testing" + "unsafe" +) + +func deviceAdapterLUID(t *testing.T, device uintptr) (uint32, int32) { + t.Helper() + var dxgiDevice uintptr + if hresultFailed(invoke(device, comQueryInterface, uintptr(unsafe.Pointer(&iidDXGIDevice)), uintptr(unsafe.Pointer(&dxgiDevice)))) || dxgiDevice == 0 { + t.Fatal("QueryInterface(IDXGIDevice) failed") + } + defer releaseCom(&dxgiDevice) + var adapter uintptr + if hresultFailed(invoke(dxgiDevice, 7, uintptr(unsafe.Pointer(&adapter)))) || adapter == 0 { + t.Fatal("IDXGIDevice.GetAdapter failed") + } + defer releaseCom(&adapter) + var desc dxgiAdapterDesc1 + // IDXGIAdapter::GetDesc (slot 8) populates the identical prefix up to AdapterLuid. + if hresultFailed(invoke(adapter, 8, uintptr(unsafe.Pointer(&desc)))) { + t.Fatal("IDXGIAdapter.GetDesc failed") + } + return desc.AdapterLuidLow, desc.AdapterLuidHigh +} + +func TestNewVideoDevice(t *testing.T) { + device, context, err := newVideoDevice() + if err != nil { + t.Skipf("no Direct3D device: %v", err) + } + if device == 0 || context == 0 { + t.Fatalf("device = %#x, context = %#x", device, context) + } + low, high := deviceAdapterLUID(t, device) + releaseCom(&context) + releaseCom(&device) + + // Registering the renderer's adapter LUID makes newVideoDevice select the same adapter. + SetRendererAdapterLUID(low, high) + device2, context2, err := newVideoDevice() + if err != nil { + t.Fatalf("newVideoDevice with LUID: %v", err) + } + defer releaseCom(&context2) + defer releaseCom(&device2) + low2, high2 := deviceAdapterLUID(t, device2) + if low2 != low || high2 != high { + t.Fatalf("adapter LUID = (%d, %d), want (%d, %d)", low2, high2, low, high) + } +} diff --git a/internal/media/float_windows_amd64.go b/internal/media/float_windows_amd64.go new file mode 100644 index 000000000..99d09a9eb --- /dev/null +++ b/internal/media/float_windows_amd64.go @@ -0,0 +1,30 @@ +//go:build windows + +package media + +import ( + "math" + "syscall" +) + +// A COM method whose argument or result is a double needs the Windows +// floating point calling convention, which syscall.SyscallN does not set up +// on its own. On amd64 it relies on Go's runtime asmstdcall implementation +// (verified on Go 1.22+), which mirrors the first four integer arguments into +// XMM0–XMM3 before the call and returns XMM0 in the second result register r2. +// Thus passing math.Float64bits(v) in the second slot puts v in XMM1, and a +// double return value in XMM0 arrives as the second result of SyscallN. + +func initFloatThunks() error { return nil } + +// callWithDouble calls method i of obj with v as its double argument. +func callWithDouble(obj uintptr, i int, v float64) uintptr { + hr, _, _ := syscall.SyscallN(vfunc(obj, i), obj, uintptr(math.Float64bits(v))) + return hr +} + +// callDouble calls method i of obj, which returns a double. +func callDouble(obj uintptr, i int) float64 { + _, bits, _ := syscall.SyscallN(vfunc(obj, i), obj) + return math.Float64frombits(uint64(bits)) +} diff --git a/internal/media/float_windows_arm64.go b/internal/media/float_windows_arm64.go new file mode 100644 index 000000000..20e523107 --- /dev/null +++ b/internal/media/float_windows_arm64.go @@ -0,0 +1,71 @@ +//go:build windows + +package media + +import ( + "fmt" + "math" + "syscall" + "unsafe" +) + +// A COM method whose argument or result is a double needs the Windows +// floating point calling convention: the argument in D0, the result in D0. +// syscall.SyscallN works in the integer registers only, so on arm64 the call +// goes through one of two thunks of machine code, which move the bits of a +// double between D0 and the registers syscall uses: +// +// withDouble(obj X0, bits X1, fn X2): FMOV D0, X1; BR X2 +// double(obj X0, fn X1): STP X29, X30, [SP, #-16]!; MOV X29, SP; +// BLR X1; FMOV X0, D0; LDP X29, X30, [SP], #16; RET +// +// The thunks are written into a page of memory of their own, made executable +// once, at load. + +var ( + withDoubleThunk, doubleThunk uintptr +) + +func initFloatThunks() error { + setter := []uint32{ + 0x9e670020, // FMOV D0, X1 + 0xd61f0040, // BR X2 + } + getter := []uint32{ + 0xa9bf7bfd, // STP X29, X30, [SP, #-16]! + 0x910003fd, // MOV X29, SP + 0xd63f0020, // BLR X1 + 0x9e660000, // FMOV X0, D0 + 0xa8c17bfd, // LDP X29, X30, [SP], #16 + 0xd65f03c0, // RET + } + code := append(setter, getter...) + kernel := syscall.NewLazyDLL("kernel32.dll") + const commitReserve, pageReadWrite, pageExecuteRead = 0x3000, 0x04, 0x20 + mem, _, err := kernel.NewProc("VirtualAlloc").Call(0, uintptr(4*len(code)), commitReserve, pageReadWrite) + if mem == 0 { + return fmt.Errorf("video: VirtualAlloc: %v", err) + } + copy(unsafe.Slice((*uint32)(ptrAt(mem)), len(code)), code) + var previous uint32 + if ok, _, err := kernel.NewProc("VirtualProtect").Call(mem, uintptr(4*len(code)), pageExecuteRead, uintptr(unsafe.Pointer(&previous))); ok == 0 { + return fmt.Errorf("video: VirtualProtect: %v", err) + } + process, _, _ := kernel.NewProc("GetCurrentProcess").Call() + kernel.NewProc("FlushInstructionCache").Call(process, mem, uintptr(4*len(code))) + withDoubleThunk = mem + doubleThunk = mem + uintptr(4*len(setter)) + return nil +} + +// callWithDouble calls method i of obj with v as its double argument. +func callWithDouble(obj uintptr, i int, v float64) uintptr { + hr, _, _ := syscall.SyscallN(withDoubleThunk, obj, uintptr(math.Float64bits(v)), vfunc(obj, i)) + return hr +} + +// callDouble calls method i of obj, which returns a double. +func callDouble(obj uintptr, i int) float64 { + bits, _, _ := syscall.SyscallN(doubleThunk, obj, vfunc(obj, i)) + return math.Float64frombits(uint64(bits)) +} diff --git a/internal/media/media.go b/internal/media/media.go new file mode 100644 index 000000000..f16cc77bc --- /dev/null +++ b/internal/media/media.go @@ -0,0 +1,81 @@ +// Package media is the contract between a video player and a system media +// engine: an engine decodes a video and hands out its pictures, as GPU +// textures the renderer shares, and knows nothing of gfx or of a window. +package media + +import ( + "errors" + "time" +) + +// ErrUnsupported reports a system without a media framework that plays +// video: a Windows without Media Foundation, or an OS this release has no +// engine for, such as a macOS built without cgo. +var ErrUnsupported = errors.New("video: the system has no media framework that plays video") + +// Source is what an engine opens: a URL, or a video in memory. +type Source struct { + // URL is a file:, http: or https: URL. + URL string + // Path is the local file URL names, which the engine opens as a path. + Path string + // Data is the video in memory; URL is empty then. Engines copy the bytes + // when opening (into a memory stream on Windows, or a temporary file on + // macOS). + Data []byte +} + +// Picture is a frame where the engine left it: a GPU texture shared by the +// platform. The renderer opens it; the engine keeps it alive until the ring +// slot it is in is used again or the engine closes. +type Picture struct { + Handle uintptr // the shared texture: an NT handle, or an IOSurface on macOS + ID uint64 // stable while the texture lives + W, H int +} + +// State is where an engine is in loading and playing its video. +type State uint8 + +const ( + // Loading is the video opening, before its first picture. + Loading State = iota + // Ready is playing, or paused and able to play. + Ready + // Buffering is playing, but waiting for data. + Buffering + // Ended is the video played to its end. + Ended + // Failed is the video stopped by an error, which Err reads. + Failed +) + +// Engine plays one video with the system's media framework. Its methods are +// called on the UI thread, except SetWake's callback, which the engine calls +// from a thread of its own. +type Engine interface { + // SetWake gives the engine what to call, from any goroutine, when its + // state changed and the window should paint again. A nil wake stops + // the calls. + SetWake(wake func()) + // Frame returns the picture the engine has now, whether it is newer + // than the one Frame returned before, and whether there is one. + Frame() (picture Picture, changed bool, ok bool) + // Interval is how often the engine shows a picture, 60 a second. + Interval() time.Duration + State() (State, error) + Size() (w, h int) + Duration() time.Duration + Position() time.Duration + Playing() bool + Play() + Pause() + Seek(time.Duration) + SetLoop(loop bool) + SetRate(rate float64) + SetVolume(volume float64) + SetMuted(muted bool) + // Close stops the engine and frees what it made. It is safe to call + // more than once. + Close() error +} diff --git a/internal/media/media_unsupported.go b/internal/media/media_unsupported.go new file mode 100644 index 000000000..fd627e448 --- /dev/null +++ b/internal/media/media_unsupported.go @@ -0,0 +1,10 @@ +//go:build !((windows && (amd64 || arm64)) || (darwin && cgo && (amd64 || arm64))) + +package media + +// Open opens a video with the system's media framework. This build of the +// package has no engine: Open reports ErrUnsupported, which an application +// may answer by playing a GIF instead. +func Open(s Source) (Engine, error) { + return nil, ErrUnsupported +} diff --git a/internal/media/mf_windows.go b/internal/media/mf_windows.go new file mode 100644 index 000000000..96533284f --- /dev/null +++ b/internal/media/mf_windows.go @@ -0,0 +1,872 @@ +//go:build windows && (amd64 || arm64) + +package media + +// On Windows, Media Foundation plays the video. An IMFMediaEngine decodes it +// and keeps its clock, with sound, on a Direct3D 11 device this package makes; +// the engine converts the picture due into one of three BGRA textures, each +// shared with the window's renderer by an NT handle and ordered by a keyed +// mutex, so the picture reaches the window where it was decoded, on the GPU. +// +// The engine reports what it does through events, from threads of its own. +// A small COM object, made once, carries them to Go and wakes the window. + +import ( + "errors" + "fmt" + "math" + "runtime" + "sync" + "sync/atomic" + "syscall" + "time" + "unsafe" +) + +// frameSlots is the number of textures the engine rotates through, leaving +// the renderer time to read one while the engine fills the next. +const frameSlots = 3 + +var ( + mfOnce sync.Once + mfErr error + + mfplat = systemDLL("mfplat.dll") + combase = systemDLL("ole32.dll") + oleauto = systemDLL("oleaut32.dll") + shlwapi = systemDLL("shlwapi.dll") + + // mfAPI holds the entry points the engine calls, resolved once. + mfAPI struct { + startup *syscall.LazyProc + deviceManager *syscall.LazyProc + attributes *syscall.LazyProc + streamOver *syscall.LazyProc + initCOM *syscall.LazyProc + uninitCOM *syscall.LazyProc + createCOM *syscall.LazyProc + alloc *syscall.LazyProc + freeMemory *syscall.LazyProc + allocString *syscall.LazyProc + freeString *syscall.LazyProc + memoryStream *syscall.LazyProc + } + + // notifyMethods is the vtable of the engine's IMFMediaEngineNotify + // object. Its refcount frees the object when both Go and Media + // Foundation have released it. + notifyMethods [4]uintptr + + // liveEngines finds the engine whose notify object is the this pointer of + // a callback. + liveEngines = struct { + sync.RWMutex + byNotify map[uintptr]*mediaEngine + }{byNotify: make(map[uintptr]*mediaEngine)} + + // sharedIDs numbers the shared textures, for the renderer to tell one + // from another. + sharedIDs atomic.Uint64 +) + +// notifyObject is the COM layout of the engine's IMFMediaEngineNotify object, +// allocated with CoTaskMemAlloc and freed when refs drops to zero. +type notifyObject struct { + vtbl uintptr + refs int32 +} + +var ( + clsidEngineFactory = syscall.GUID{Data1: 0xb44392da, Data2: 0x499b, Data3: 0x446b, Data4: [8]byte{0xa4, 0xcb, 0x00, 0x5f, 0xea, 0xd0, 0xe6, 0xd5}} + iidEngineFactory = syscall.GUID{Data1: 0x4d645ace, Data2: 0x26aa, Data3: 0x4688, Data4: [8]byte{0x9b, 0xe1, 0xdf, 0x35, 0x16, 0x99, 0x0b, 0x93}} + iidNotify = syscall.GUID{Data1: 0xfee7c112, Data2: 0xe776, Data3: 0x42b5, Data4: [8]byte{0x9b, 0xbf, 0x00, 0x48, 0x52, 0x4e, 0x2b, 0xd5}} + iidEngineEx = syscall.GUID{Data1: 0x83015ead, Data2: 0xb1e6, Data3: 0x40d0, Data4: [8]byte{0xa9, 0x8a, 0x37, 0x14, 0x5f, 0xfe, 0x1a, 0xd1}} + iidUnknown = syscall.GUID{Data4: [8]byte{0xc0, 0, 0, 0, 0, 0, 0, 0x46}} + iidMultithread = syscall.GUID{Data1: 0x9b7e4e00, Data2: 0x342c, Data3: 0x4106, Data4: [8]byte{0xa1, 0x9f, 0x4f, 0x27, 0x04, 0xf6, 0x89, 0xf0}} + iidKeyedMutex = syscall.GUID{Data1: 0x9d8e1289, Data2: 0xd7b3, Data3: 0x465f, Data4: [8]byte{0x81, 0x26, 0x25, 0x0e, 0x34, 0x9a, 0xf8, 0x5d}} + iidResource1 = syscall.GUID{Data1: 0x30961379, Data2: 0x4609, Data3: 0x4a41, Data4: [8]byte{0x99, 0x8e, 0x54, 0xfe, 0x56, 0x7e, 0xe0, 0xc1}} + + mfEngineCallback = syscall.GUID{Data1: 0xc60381b8, Data2: 0x83a4, Data3: 0x41f8, Data4: [8]byte{0xa3, 0xd0, 0xde, 0x05, 0x07, 0x68, 0x49, 0xa9}} + mfEngineDXGI = syscall.GUID{Data1: 0x065702da, Data2: 0x1094, Data3: 0x486d, Data4: [8]byte{0x86, 0x17, 0xee, 0x7c, 0xc4, 0xee, 0x46, 0x48}} + mfEngineVideoType = syscall.GUID{Data1: 0x5066893c, Data2: 0x8cf9, Data3: 0x42bc, Data4: [8]byte{0x8b, 0x8a, 0x47, 0x22, 0x12, 0xe5, 0x27, 0x26}} +) + +// Places of the methods the engine calls in the vtables of its interfaces. +const ( + comQueryInterface = 0 + comRelease = 2 + + attrSetUint32 = 21 + attrSetUnknown = 27 + + managerReset = 7 + + factoryCreate = 3 + + engineSetSource = 6 + engineIsSeeking = 15 + engineCurrentTime = 16 + engineSetCurrentTime = 17 + engineDuration = 19 + engineIsPaused = 20 + engineDefaultRate = 22 + enginePlaybackRate = 24 + engineSetLoop = 31 + enginePlay = 32 + enginePause = 33 + engineSetMuted = 35 + engineSetVolume = 37 + engineHasVideo = 38 + engineNativeSize = 40 + engineShutdown = 42 + engineTransferFrame = 43 + engineVideoStreamTick = 44 + engineExSourceFromMem = 45 + engineExFrameStep = 51 + + multithreadSetProtected = 5 + + deviceCreateTexture = 5 + + keyedMutexAcquire = 8 + keyedMutexRelease = 9 + + resourceSharedHandle = 13 +) + +// The events Media Foundation reports (MF_MEDIA_ENGINE_EVENT). +const ( + eventError = 5 + eventLoadedData = 11 + eventWaiting = 12 + eventPlaying = 13 + eventCanPlay = 14 + eventSeeked = 17 + eventEnded = 19 + eventFrameStepDone = 1007 +) + +const ( + eNoInterface = 0x80004002 + waitAbandoned = 0x80 + waitTimeout = 0x102 + // seekRetries caps how often a seek is repeated when Media Foundation + // lands it where the video was rather than where it was asked to go. + seekRetries = 3 +) + +// texture2DDesc is D3D11_TEXTURE2D_DESC. +type texture2DDesc struct { + Width, Height, MipLevels, ArraySize uint32 + Format, SampleCount, SampleQuality uint32 + Usage, BindFlags, CPUAccessFlags uint32 + MiscFlags uint32 +} + +// hresultFailed reports an HRESULT of failure. +func hresultFailed(hr uintptr) bool { return int32(uint32(hr)) < 0 } + +// ptrAt is the pointer at address a, of native memory. +func ptrAt(a uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&a)) } + +// vfunc is the address of method i in obj's vtable. +func vfunc(obj uintptr, i int) uintptr { + vtbl := *(*uintptr)(ptrAt(obj)) + return *(*uintptr)(ptrAt(vtbl + uintptr(i)*unsafe.Sizeof(uintptr(0)))) +} + +// invoke calls method i of the COM object obj, returning its HRESULT. The +// pointers passed as uintptr in args stay alive until it returns +// (go:uintptrescapes). +// +//go:uintptrescapes +func invoke(obj uintptr, i int, args ...uintptr) uintptr { + call := make([]uintptr, 0, len(args)+1) + call = append(call, obj) + call = append(call, args...) + hr, _, _ := syscall.SyscallN(vfunc(obj, i), call...) + return hr +} + +// releaseCom releases the COM object *p and forgets it. +func releaseCom(p *uintptr) { + if *p != 0 { + invoke(*p, comRelease) + *p = 0 + } +} + +func uintptrOf(b bool) uintptr { + if b { + return 1 + } + return 0 +} + +func loadMediaFoundation() error { + mfOnce.Do(func() { + mfAPI.startup = mfplat.NewProc("MFStartup") + mfAPI.deviceManager = mfplat.NewProc("MFCreateDXGIDeviceManager") + mfAPI.attributes = mfplat.NewProc("MFCreateAttributes") + mfAPI.streamOver = mfplat.NewProc("MFCreateMFByteStreamOnStream") + mfAPI.initCOM = combase.NewProc("CoInitializeEx") + mfAPI.uninitCOM = combase.NewProc("CoUninitialize") + mfAPI.createCOM = combase.NewProc("CoCreateInstance") + mfAPI.alloc = combase.NewProc("CoTaskMemAlloc") + mfAPI.freeMemory = combase.NewProc("CoTaskMemFree") + mfAPI.allocString = oleauto.NewProc("SysAllocString") + mfAPI.freeString = oleauto.NewProc("SysFreeString") + mfAPI.memoryStream = shlwapi.NewProc("SHCreateMemStream") + for _, proc := range [...]*syscall.LazyProc{ + mfAPI.startup, mfAPI.deviceManager, mfAPI.attributes, mfAPI.streamOver, + mfAPI.createCOM, mfAPI.allocString, mfAPI.memoryStream, + } { + if err := proc.Find(); err != nil { + // Windows Server without its Media Foundation feature, or an + // N edition without the Media Feature Pack. + mfErr = fmt.Errorf("%w: %v", ErrUnsupported, err) + return + } + } + const mfVersion, mfStartupFull = 0x00020070, 0 + if hr, _, _ := mfAPI.startup.Call(mfVersion, mfStartupFull); hresultFailed(hr) { + mfErr = fmt.Errorf("%w: MFStartup: %#x", ErrUnsupported, uint32(hr)) + return + } + if err := initFloatThunks(); err != nil { + mfErr = err + return + } + notifyMethods = [4]uintptr{ + syscall.NewCallback(notifyQueryInterface), + syscall.NewCallback(notifyAddRef), + syscall.NewCallback(notifyRelease), + syscall.NewCallback(notifyDispatch), + } + }) + return mfErr +} + +func notifyQueryInterface(this, riid, out uintptr) uintptr { + want := *(*syscall.GUID)(ptrAt(riid)) + if want == iidUnknown || want == iidNotify { + *(*uintptr)(ptrAt(out)) = this + notifyAddRef(this) + return 0 // S_OK + } + *(*uintptr)(ptrAt(out)) = 0 + return eNoInterface +} + +func notifyAddRef(this uintptr) uintptr { + obj := (*notifyObject)(ptrAt(this)) + return uintptr(atomic.AddInt32(&obj.refs, 1)) +} + +// notifyRelease drops one reference to the COM notify object, freeing it once +// both Go and Media Foundation have released their references so asynchronous +// callbacks after Shutdown never touch freed memory. +func notifyRelease(this uintptr) uintptr { + obj := (*notifyObject)(ptrAt(this)) + n := atomic.AddInt32(&obj.refs, -1) + if n == 0 { + liveEngines.Lock() + delete(liveEngines.byNotify, this) + liveEngines.Unlock() + mfAPI.freeMemory.Call(this) + } + return uintptr(n) +} + +func notifyDispatch(this, event, param1, param2 uintptr) uintptr { + liveEngines.RLock() + e := liveEngines.byNotify[this] + liveEngines.RUnlock() + if e != nil { + e.dispatch(uint32(event), param1, uint32(param2)) + } + return 0 +} + +// mediaEngine plays one video with Media Foundation. +type mediaEngine struct { + engine uintptr // IMFMediaEngine + extended uintptr // IMFMediaEngineEx, the wider interface over it + notify uintptr // the IMFMediaEngineNotify object, in memory COM's + device uintptr // the Direct3D 11 device the engine decodes on + context uintptr + manager uintptr + protected uintptr // the device's ID3D10Multithread, when it has one + + slots [frameSlots]frameSlot + shown int // the slot Frame last handed out, -1 before the first + width, height int + + // Media Foundation's threads write the fields below under mu, and the + // UI thread reads them there. + mu sync.Mutex + wake func() + state State + failure error + repeat bool + seekTarget time.Duration + seekStart time.Time // when the seek in flight was asked for + landed bool // a seek landed and no picture has come since + stepDone bool // a frame step finished since Frame took one + firstLoaded bool // the engine has the data of the first picture + pollPending bool // a wake for the first picture is scheduled + closed bool + + // How Frame follows the pictures and the seeks, on the UI thread. + pictured bool // a picture came since the last seek + reseek bool // seek again once the step in flight is done + retries int // how often the current Seek sought again +} + +// frameSlot is one texture the engine converts pictures into, the keyed mutex +// that orders its use with the renderer, and the NT handle the renderer opens. +type frameSlot struct { + id uint64 + tex, mutex uintptr + handle uintptr + width, height int +} + +// Open opens a video with Media Foundation. +func Open(s Source) (Engine, error) { + if err := loadMediaFoundation(); err != nil { + return nil, err + } + runtime.LockOSThread() + defer runtime.UnlockOSThread() + // Initialize COM in MTA for CoCreateInstance on this thread. If the caller + // is already on an STA thread (such as the UI thread), RPC_E_CHANGED_MODE + // leaves that apartment intact; only S_OK and S_FALSE are paired with + // CoUninitialize so we never leave a stray apartment on a Go worker thread. + const coinitMultithreaded = 0 + if hr, _, _ := mfAPI.initCOM.Call(0, coinitMultithreaded); hr == 0 || hr == 1 { + defer mfAPI.uninitCOM.Call() + } + + e := &mediaEngine{shown: -1} + if err := e.open(s); err != nil { + e.release() + return nil, err + } + return e, nil +} + +// open makes the device and the engine and gives the engine its source. +func (e *mediaEngine) open(s Source) error { + var err error + if e.device, e.context, err = newVideoDevice(); err != nil { + return fmt.Errorf("%w: %v", ErrUnsupported, err) + } + // The engine decodes on the device from threads of its own. + if !hresultFailed(invoke(e.device, comQueryInterface, uintptr(unsafe.Pointer(&iidMultithread)), uintptr(unsafe.Pointer(&e.protected)))) { + invoke(e.protected, multithreadSetProtected, 1) + } + var token uint32 + if hr, _, _ := mfAPI.deviceManager.Call(uintptr(unsafe.Pointer(&token)), uintptr(unsafe.Pointer(&e.manager))); hresultFailed(hr) { + return fmt.Errorf("video: MFCreateDXGIDeviceManager: %#x", uint32(hr)) + } + if hr := invoke(e.manager, managerReset, e.device, uintptr(token)); hresultFailed(hr) { + return fmt.Errorf("video: IMFDXGIDeviceManager.ResetDevice: %#x", uint32(hr)) + } + if e.notify = newNotify(e); e.notify == 0 { + return errors.New("video: out of memory") + } + + var attrs, factory uintptr + if hr, _, _ := mfAPI.attributes.Call(uintptr(unsafe.Pointer(&attrs)), 3); hresultFailed(hr) { + return fmt.Errorf("video: MFCreateAttributes: %#x", uint32(hr)) + } + defer releaseCom(&attrs) + invoke(attrs, attrSetUnknown, uintptr(unsafe.Pointer(&mfEngineCallback)), e.notify) + invoke(attrs, attrSetUnknown, uintptr(unsafe.Pointer(&mfEngineDXGI)), e.manager) + const formatBGRA = 87 // DXGI_FORMAT_B8G8R8A8_UNORM + invoke(attrs, attrSetUint32, uintptr(unsafe.Pointer(&mfEngineVideoType)), formatBGRA) + const clsctxInprocServer = 1 + if hr, _, _ := mfAPI.createCOM.Call(uintptr(unsafe.Pointer(&clsidEngineFactory)), 0, clsctxInprocServer, + uintptr(unsafe.Pointer(&iidEngineFactory)), uintptr(unsafe.Pointer(&factory))); hresultFailed(hr) { + return fmt.Errorf("%w: no media engine: %#x", ErrUnsupported, uint32(hr)) + } + defer releaseCom(&factory) + if hr := invoke(factory, factoryCreate, 0, attrs, uintptr(unsafe.Pointer(&e.engine))); hresultFailed(hr) { + return fmt.Errorf("video: IMFMediaEngineClassFactory.CreateInstance: %#x", uint32(hr)) + } + invoke(e.engine, comQueryInterface, uintptr(unsafe.Pointer(&iidEngineEx)), uintptr(unsafe.Pointer(&e.extended))) + + if s.Data != nil { + return e.openData(s.Data) + } + // Media Foundation reads the percent-escapes of a file: URL as bytes of + // the system's code page, not UTF-8, so a file whose path is not ASCII + // goes by its path, which SetSource takes as well. + src := s.URL + if s.Path != "" { + src = s.Path + } + url := allocBSTR(src) + hr := invoke(e.engine, engineSetSource, url) + mfAPI.freeString.Call(url) + if hresultFailed(hr) { + return fmt.Errorf("video: cannot open %s: %#x", src, uint32(hr)) + } + return nil +} + +// newNotify makes the IMFMediaEngineNotify object of e, in memory COM +// allocates, with an initial reference count of 1 owned by e, and registers e +// for the callbacks it takes. +func newNotify(e *mediaEngine) uintptr { + mem, _, _ := mfAPI.alloc.Call(unsafe.Sizeof(notifyObject{})) + if mem == 0 { + return 0 + } + obj := (*notifyObject)(ptrAt(mem)) + obj.vtbl = uintptr(unsafe.Pointer(¬ifyMethods)) + obj.refs = 1 + liveEngines.Lock() + liveEngines.byNotify[mem] = e + liveEngines.Unlock() + return mem +} + +// openData has the engine read the video from bytes in memory, through a +// stream over those bytes, so the video needs no file. +func (e *mediaEngine) openData(data []byte) error { + if e.extended == 0 { + return fmt.Errorf("%w: no IMFMediaEngineEx", ErrUnsupported) + } + stream, _, _ := mfAPI.memoryStream.Call(uintptr(unsafe.Pointer(&data[0])), uintptr(len(data))) + if stream == 0 { + return errors.New("video: out of memory") + } + defer releaseCom(&stream) + var byteStream uintptr + if hr, _, _ := mfAPI.streamOver.Call(stream, uintptr(unsafe.Pointer(&byteStream))); hresultFailed(hr) { + return fmt.Errorf("video: MFCreateMFByteStreamOnStream: %#x", uint32(hr)) + } + defer releaseCom(&byteStream) + // The URL names only the container, for the engine to choose a source. + name := "data.mp4" + switch { + case len(data) >= 12 && string(data[4:8]) == "ftyp" && string(data[8:12]) == "qt ": + name = "data.mov" + case len(data) >= 4 && string(data[:4]) == "\x1a\x45\xdf\xa3": + name = "data.webm" + } + url := allocBSTR(name) + defer mfAPI.freeString.Call(url) + if hr := invoke(e.extended, engineExSourceFromMem, byteStream, url); hresultFailed(hr) { + return fmt.Errorf("video: cannot open the video: %#x", uint32(hr)) + } + return nil +} + +// allocBSTR copies s into a BSTR, which the caller frees with SysFreeString. +func allocBSTR(s string) uintptr { + text, _ := syscall.UTF16PtrFromString(s) + b, _, _ := mfAPI.allocString.Call(uintptr(unsafe.Pointer(text))) + return b +} + +// dispatch takes an event the engine reported, on a thread of Media +// Foundation's. +func (e *mediaEngine) dispatch(event uint32, param1 uintptr, param2 uint32) { + e.mu.Lock() + switch event { + case eventError: + e.state = Failed + e.failure = fmt.Errorf("video: Media Foundation could not play the video (error %d, %#x)", param1, param2) + case eventEnded: + if !e.repeat { + e.state = Ended + } + case eventWaiting: + if e.state == Ready { + e.state = Buffering + } + case eventPlaying, eventCanPlay: + if e.state == Buffering { + e.state = Ready + } + case eventSeeked: + e.seekStart = time.Time{} + e.landed = true + case eventFrameStepDone: + e.stepDone = true + case eventLoadedData: + e.firstLoaded = true + default: + e.mu.Unlock() + return + } + e.mu.Unlock() + e.wakeWindow() +} + +// wakeWindow asks the window to paint a frame. +func (e *mediaEngine) wakeWindow() { + e.mu.Lock() + wake := e.wake + e.mu.Unlock() + if wake != nil { + wake() + } +} + +func (e *mediaEngine) SetWake(wake func()) { + e.mu.Lock() + e.wake = wake + e.mu.Unlock() +} + +func (e *mediaEngine) Frame() (Picture, bool, bool) { + if e.engine == 0 { + return Picture{}, false, false + } + var pts int64 + fresh := invoke(e.engine, engineVideoStreamTick, uintptr(unsafe.Pointer(&pts))) == 0 // S_OK: a new picture + e.mu.Lock() + landed, target, stepDone := e.landed, e.seekTarget, e.stepDone + e.mu.Unlock() + if landed && (fresh || invoke(e.engine, engineIsSeeking) == 0) { + e.mu.Lock() + e.landed = false + e.mu.Unlock() + if !fresh && !e.pictured && e.extended != 0 && invoke(e.engine, engineIsPaused) != 0 { + // A seek of a paused video can land without a picture, which then + // never comes (Media Foundation on Windows on Arm, about one seek + // in three). A step forward shows the picture there and keeps the + // position. A seek just after a pause, as the video starts, may + // also land where the video was (about one in ten), and seeking + // again at once lands there too: once the step is done Frame + // seeks again, a few times, and shows no picture from where the + // video was. This recovery requires IMFMediaEngineEx; when + // QueryInterface for it did not succeed, e.extended is 0 and the + // workaround is skipped. + if at := callDouble(e.engine, engineCurrentTime); e.retries < seekRetries && math.Abs(at-target.Seconds()) > 0.001 { + e.reseek = true + e.retries++ + } + e.mu.Lock() + e.stepDone, stepDone = false, false + e.mu.Unlock() + invoke(e.extended, engineExFrameStep, 1) + } + } + changed := false + if e.reseek { + if stepDone { + e.reseek = false + e.seek(target) + } + } else if fresh { + e.pictured = true + var w, h uint32 + invoke(e.engine, engineNativeSize, uintptr(unsafe.Pointer(&w)), uintptr(unsafe.Pointer(&h))) + if w > 0 && h > 0 { + next := (e.shown + 1) % frameSlots + if e.transfer(next, int(w), int(h)) { + e.shown, changed = next, true + e.width, e.height = int(w), int(h) + e.mu.Lock() + if e.state == Loading { + e.state = Ready + } + e.mu.Unlock() + } + } + } + if e.shown < 0 { + e.pollFirst() + return Picture{}, false, false + } + slot := &e.slots[e.shown] + return Picture{Handle: slot.handle, ID: slot.id, W: slot.width, H: slot.height}, changed, true +} + +// pollFirst wakes the window again soon while the first picture is loaded +// but not there yet. No event says that a picture came, and the last one may +// come before it does: where decoding is slow (Windows 11 on Arm in a virtual +// machine without a GPU, even for H.264), Playing comes, the frame that wake +// asks for finds no picture (OnVideoStreamTick answers S_FALSE), and no event +// that wakes comes again until the end, so a window that paints only when +// woken shows nothing. Until the first picture, Frame asks for another look +// at the engine's interval, as Media Foundation's own samples look every +// vsync. +func (e *mediaEngine) pollFirst() { + e.mu.Lock() + due := !e.closed && !e.pollPending && e.firstLoaded && e.state == Loading && e.wake != nil + e.mu.Unlock() + // A video of sound alone has no picture to wait for. + if !due || e.engine == 0 || invoke(e.engine, engineHasVideo) == 0 { + return + } + e.mu.Lock() + if e.closed || e.pollPending { + e.mu.Unlock() + return + } + e.pollPending = true + e.mu.Unlock() + time.AfterFunc(e.Interval(), func() { + e.mu.Lock() + closed := e.closed + e.pollPending = false + e.mu.Unlock() + if !closed { + e.wakeWindow() + } + }) +} + +// transfer converts the picture due into slot i, making the slot again when +// its size changed, and writing it under the slot's keyed mutex. +func (e *mediaEngine) transfer(i, w, h int) bool { + slot := &e.slots[i] + if slot.tex == 0 || slot.width != w || slot.height != h { + e.freeSlot(slot) + if !e.makeSlot(slot, w, h) { + return false + } + } + const wait = 100 // ms: the renderer reads the texture meanwhile + // On WAIT_ABANDONED (0x80) we still own the mutex; overwriting the entire + // texture and releasing restores valid contents. + if hr := invoke(slot.mutex, keyedMutexAcquire, 0, wait); hresultFailed(hr) || hr == waitTimeout { + return false + } + bounds := [4]int32{0, 0, int32(w), int32(h)} + border := uint32(0xff000000) // opaque black, MFARGB + hr := invoke(e.engine, engineTransferFrame, slot.tex, 0, uintptr(unsafe.Pointer(&bounds)), uintptr(unsafe.Pointer(&border))) + invoke(slot.mutex, keyedMutexRelease, 0) + return !hresultFailed(hr) +} + +// makeSlot gives slot a w×h BGRA texture that the engine converts into and +// the renderer opens by an NT handle, ordered by a keyed mutex. +func (e *mediaEngine) makeSlot(slot *frameSlot, w, h int) bool { + const ( + formatBGRA = 87 + usageDefault = 0 + bindShader = 0x8 + bindRender = 0x20 + sharedKeyed = 0x100 + sharedNTHandle = 0x800 + readWrite = 0x80000001 // GENERIC_READ | GENERIC_WRITE + ) + desc := texture2DDesc{ + Width: uint32(w), Height: uint32(h), MipLevels: 1, ArraySize: 1, + Format: formatBGRA, SampleCount: 1, Usage: usageDefault, + BindFlags: bindShader | bindRender, MiscFlags: sharedKeyed | sharedNTHandle, + } + if hresultFailed(invoke(e.device, deviceCreateTexture, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&slot.tex)))) { + slot.tex = 0 + return false + } + var resource uintptr + if hresultFailed(invoke(slot.tex, comQueryInterface, uintptr(unsafe.Pointer(&iidKeyedMutex)), uintptr(unsafe.Pointer(&slot.mutex)))) || + hresultFailed(invoke(slot.tex, comQueryInterface, uintptr(unsafe.Pointer(&iidResource1)), uintptr(unsafe.Pointer(&resource)))) { + e.freeSlot(slot) + return false + } + hr := invoke(resource, resourceSharedHandle, 0, readWrite, 0, uintptr(unsafe.Pointer(&slot.handle))) + releaseCom(&resource) + if hresultFailed(hr) { + e.freeSlot(slot) + return false + } + slot.width, slot.height = w, h + slot.id = sharedIDs.Add(1) + registerSharedTexture(slot.id, e) + return true +} + +func (e *mediaEngine) freeSlot(slot *frameSlot) { + if slot.id != 0 { + retireSharedTexture(slot.id) + slot.id = 0 + } + releaseCom(&slot.mutex) + releaseCom(&slot.tex) + if slot.handle != 0 { + syscall.CloseHandle(syscall.Handle(slot.handle)) + slot.handle = 0 + } +} + +func (e *mediaEngine) Interval() time.Duration { return time.Second / 60 } + +func (e *mediaEngine) State() (State, error) { + e.mu.Lock() + defer e.mu.Unlock() + if e.closed { + return Ended, nil + } + return e.state, e.failure +} + +func (e *mediaEngine) Size() (int, int) { + if e.engine == 0 { + return 0, 0 + } + return e.width, e.height +} + +func (e *mediaEngine) Duration() time.Duration { + if e.engine == 0 { + return 0 + } + seconds := callDouble(e.engine, engineDuration) + if math.IsNaN(seconds) || math.IsInf(seconds, 0) || seconds <= 0 { + return 0 + } + return time.Duration(seconds * float64(time.Second)) +} + +func (e *mediaEngine) Position() time.Duration { + if e.engine == 0 { + return 0 + } + e.mu.Lock() + if !e.seekStart.IsZero() { + target := e.seekTarget + e.mu.Unlock() + return target + } + e.mu.Unlock() + seconds := callDouble(e.engine, engineCurrentTime) + if math.IsNaN(seconds) || seconds < 0 { + return 0 + } + return time.Duration(seconds * float64(time.Second)) +} + +func (e *mediaEngine) Play() { + if e.engine == 0 { + return + } + e.mu.Lock() + if e.state == Ended { + e.state = Ready + } + e.mu.Unlock() + invoke(e.engine, enginePlay) +} + +func (e *mediaEngine) Pause() { + if e.engine == 0 { + return + } + invoke(e.engine, enginePause) +} + +// Playing reports whether the engine is not paused. A video at its end plays +// no more, which the player knows by its state. +func (e *mediaEngine) Playing() bool { + if e.engine == 0 { + return false + } + return invoke(e.engine, engineIsPaused) == 0 +} + +func (e *mediaEngine) Seek(d time.Duration) { + if e.engine == 0 { + return + } + e.reseek, e.retries = false, 0 + e.seek(d) +} + +func (e *mediaEngine) seek(d time.Duration) { + if e.engine == 0 { + return + } + e.mu.Lock() + if e.state == Ended { + e.state = Ready + } + e.seekTarget, e.seekStart, e.landed = d, time.Now(), false + e.mu.Unlock() + e.pictured = false + callWithDouble(e.engine, engineSetCurrentTime, d.Seconds()) +} + +func (e *mediaEngine) SetLoop(loop bool) { + if e.engine == 0 { + return + } + e.mu.Lock() + e.repeat = loop + e.mu.Unlock() + invoke(e.engine, engineSetLoop, uintptrOf(loop)) +} + +func (e *mediaEngine) SetRate(rate float64) { + if e.engine == 0 { + return + } + callWithDouble(e.engine, engineDefaultRate, rate) + callWithDouble(e.engine, enginePlaybackRate, rate) +} + +func (e *mediaEngine) SetVolume(volume float64) { + if e.engine == 0 { + return + } + callWithDouble(e.engine, engineSetVolume, volume) +} + +func (e *mediaEngine) SetMuted(muted bool) { + if e.engine == 0 { + return + } + invoke(e.engine, engineSetMuted, uintptrOf(muted)) +} + +// Close shuts the engine down and frees what it made. +func (e *mediaEngine) Close() error { + e.mu.Lock() + if e.closed { + e.mu.Unlock() + return nil + } + e.closed = true + e.wake = nil + e.mu.Unlock() + // Detach callbacks before Shutdown so asynchronous events during or after + // teardown never dispatch to the closing engine. + if e.notify != 0 { + liveEngines.Lock() + delete(liveEngines.byNotify, e.notify) + liveEngines.Unlock() + } + if e.engine != 0 { + invoke(e.engine, engineShutdown) + } + e.release() + return nil +} + +func (e *mediaEngine) release() { + releaseCom(&e.extended) + releaseCom(&e.engine) + if e.notify != 0 { + liveEngines.Lock() + delete(liveEngines.byNotify, e.notify) + liveEngines.Unlock() + // Drop Go's reference; the COM object frees itself once Media + // Foundation has also released any remaining references. + releaseCom(&e.notify) + } + for i := range e.slots { + e.freeSlot(&e.slots[i]) + } + releaseCom(&e.manager) + releaseCom(&e.protected) + releaseCom(&e.context) + releaseCom(&e.device) +} diff --git a/internal/media/mf_windows_test.go b/internal/media/mf_windows_test.go new file mode 100644 index 000000000..2ee20ea24 --- /dev/null +++ b/internal/media/mf_windows_test.go @@ -0,0 +1,142 @@ +//go:build windows && (amd64 || arm64) + +package media + +import ( + "errors" + "testing" + "time" + "unsafe" +) + +func TestEnginePlaysColorVideo(t *testing.T) { + engine, err := Open(Source{Path: "testdata/colors.mp4"}) + if err != nil { + if errors.Is(err, ErrUnsupported) { + t.Skipf("no media framework: %v", err) + } + t.Fatalf("Open: %v", err) + } + defer engine.Close() + woken := make(chan struct{}, 1) + engine.SetWake(func() { + select { + case woken <- struct{}{}: + default: + } + }) + engine.Play() + var picture Picture + deadline := time.Now().Add(10 * time.Second) + for time.Now().Before(deadline) { + var ok bool + if picture, _, ok = engine.Frame(); ok { + break + } + select { + case <-woken: + case <-time.After(10 * time.Millisecond): + } + } + if picture.Handle == 0 { + t.Fatal("no picture in 10s") + } + if picture.ID == 0 || picture.W != 640 || picture.H != 360 { + t.Fatalf("picture = %+v, want 640x360", picture) + } + if w, h := engine.Size(); w != picture.W || h != picture.H { + t.Errorf("Size = %dx%d, picture %dx%d", w, h, picture.W, picture.H) + } + if d := engine.Duration(); d < 5*time.Second || d > 6*time.Second { + t.Errorf("Duration = %v, want 5s", d) + } + engine.Pause() + if engine.Playing() { + t.Error("a paused engine reports playing") + } + engine.Seek(0) + engine.Play() + if state, err := engine.State(); err != nil || state == Failed { + t.Fatalf("after seek: %v, %v", state, err) + } + if err := engine.Close(); err != nil { + t.Fatal(err) + } + if err := engine.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } + // Methods called after Close must be safe no-ops rather than dereferencing a zero COM pointer. + engine.Play() + engine.Pause() + engine.Seek(time.Second) + engine.SetLoop(true) + engine.SetRate(1.5) + engine.SetVolume(0.5) + engine.SetMuted(true) + if engine.Playing() || engine.Duration() != 0 || engine.Position() != 0 { + t.Fatal("closed engine still reported playback activity") + } + if _, _, ok := engine.Frame(); ok { + t.Fatal("closed engine returned a frame") + } + if state, err := engine.State(); state != Ended || err != nil { + t.Fatalf("closed engine State = (%v, %v), want (Ended, nil)", state, err) + } +} + +// TestNotifyRefCountAndDetach verifies that the COM notify object tracks +// references atomically, ignores events once detached, and stays valid until +// the last COM reference is released. +func TestNotifyRefCountAndDetach(t *testing.T) { + if err := loadMediaFoundation(); err != nil { + t.Skipf("no media framework: %v", err) + } + e := &mediaEngine{shown: -1} + notify := newNotify(e) + if notify == 0 { + t.Fatal("newNotify returned 0") + } + // QueryInterface for IMFMediaEngineNotify must succeed and AddRef (refs: 1 -> 2). + var out uintptr + if hr := invoke(notify, comQueryInterface, uintptr(unsafe.Pointer(&iidNotify)), uintptr(unsafe.Pointer(&out))); hresultFailed(hr) || out != notify { + t.Fatalf("QueryInterface = %#x, out = %#x", hr, out) + } + // Simulate engine teardown detaching the engine and releasing Go's ref (refs: 2 -> 1). + liveEngines.Lock() + delete(liveEngines.byNotify, notify) + liveEngines.Unlock() + if rem := invoke(notify, comRelease); rem != 1 { + t.Fatalf("remaining refs after Go release = %d, want 1", rem) + } + // A late Media Foundation callback after detach must not touch e or crash. + invoke(notify, 3, eventError, 1, 2) + if state, err := e.State(); state != Loading || err != nil { + t.Fatalf("detached engine state changed to (%v, %v)", state, err) + } + // Final release from MF frees the object (refs: 1 -> 0). + if rem := invoke(notify, comRelease); rem != 0 { + t.Fatalf("remaining refs after final release = %d, want 0", rem) + } +} + +// TestSharedTextureErrorReporting verifies that renderer open failures surface +// on the owning engine and retired texture IDs are tracked. +func TestSharedTextureErrorReporting(t *testing.T) { + e := &mediaEngine{shown: -1} + woken := false + e.SetWake(func() { woken = true }) + id := sharedIDs.Add(1) + registerSharedTexture(id, e) + ReportSharedTextureError(id, errors.New("adapter mismatch")) + state, err := e.State() + if state != Failed || err == nil { + t.Fatalf("State = (%v, %v), want (Failed, error)", state, err) + } + if !woken { + t.Fatal("ReportSharedTextureError did not wake the window") + } + retireSharedTexture(id) + if !IsSharedTextureRetired(id) { + t.Fatal("retired texture ID was not marked retired") + } +} diff --git a/internal/media/shared_windows_other.go b/internal/media/shared_windows_other.go new file mode 100644 index 000000000..877d6df05 --- /dev/null +++ b/internal/media/shared_windows_other.go @@ -0,0 +1,7 @@ +//go:build windows && !amd64 && !arm64 + +package media + +func SetRendererAdapterLUID(low uint32, high int32) {} +func IsSharedTextureRetired(id uint64) bool { return false } +func ReportSharedTextureError(id uint64, err error) {} diff --git a/internal/media/testdata/colors.mp4 b/internal/media/testdata/colors.mp4 new file mode 100644 index 000000000..359037b89 Binary files /dev/null and b/internal/media/testdata/colors.mp4 differ diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 07806937f..216ab8742 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -509,6 +509,17 @@ type TextLabel struct { // BitmapUpload is true only when Bitmap content must cross a native // boundary. A false bitmap label references the matching retained texture. BitmapUpload bool + // TextureHandle, while TextureID is nonzero, is a GPU texture of a + // platform engine the renderer draws in place of a bitmap: an NT shared + // handle on Windows, an IOSurface on macOS. TextureWidth and + // TextureHeight are its size in pixels, and TextureVersion counts how + // often its contents changed. A texture label carries no Bitmap and no + // font metrics. + TextureHandle uintptr + TextureID uint64 + TextureWidth int + TextureHeight int + TextureVersion uint32 // Quad, while HasQuad, is the shape the label paints instead of the // axis-aligned X, Y, Width, Height rectangle: four corners (top-left, // top-right, bottom-left, bottom-right) in logical pixels, and the straight diff --git a/internal/platform/darwin/composite_test.go b/internal/platform/darwin/composite_test.go index 971c15f93..61253b4e0 100644 --- a/internal/platform/darwin/composite_test.go +++ b/internal/platform/darwin/composite_test.go @@ -15,11 +15,11 @@ func TestCompositeABI(t *testing.T) { if rectangleSize != 80 || rectangleLayerOffset != 36 { t.Fatalf("viva_rectangle ABI = size %d layer offset %d, want 80 and 36", rectangleSize, rectangleLayerOffset) } - if textSize != 272 || textLayerOffset != 56 { - t.Fatalf("viva_text_label ABI = size %d layer offset %d, want 272 and 56", textSize, textLayerOffset) + if textSize != 304 || textLayerOffset != 56 { + t.Fatalf("viva_text_label ABI = size %d layer offset %d, want 304 and 56", textSize, textLayerOffset) } - if labelSize, runsOffset, runSize := labelABI(); labelSize != 272 || runsOffset != 64 || runSize != 36 { - t.Fatalf("label ABI = size %d runs offset %d run size %d, want 272, 64 and 36", labelSize, runsOffset, runSize) + if labelSize, runsOffset, runSize := labelABI(); labelSize != 304 || runsOffset != 64 || runSize != 36 { + t.Fatalf("label ABI = size %d runs offset %d run size %d, want 304, 64 and 36", labelSize, runsOffset, runSize) } if commandSize != 36 { t.Fatalf("viva_composite_command size = %d, want 36", commandSize) diff --git a/internal/platform/darwin/core.h b/internal/platform/darwin/core.h index 8210b010a..4420edbea 100644 --- a/internal/platform/darwin/core.h +++ b/internal/platform/darwin/core.h @@ -14,6 +14,7 @@ #endif #include #import +#import #import #import @@ -90,6 +91,18 @@ typedef struct { uint64_t _bitmapID; uint32_t _bitmapVersion; float _imageRadius; + // A shared-texture label draws a picture a media engine decoded into an + // IOSurface: _sharedID names the engine's ring slot, _sharedHandle the + // surface to wrap, _sharedSurface retains it for this layer's lifetime, + // and _builtHandle is the surface _texture was made from. + BOOL _shared; + uint64_t _sharedID; + uint64_t _sharedHandle; + IOSurfaceRef _sharedSurface; + uint32_t _sharedVersion; + uint32_t _sharedWidth; + uint32_t _sharedHeight; + uint64_t _builtHandle; id _texture; NSMutableArray> *_additionalTextures; // A text label wider than a texture holds is rasterized in part: its textures hold the @@ -113,6 +126,7 @@ typedef struct { - (void)updateFrame:(CGRect)frame; - (void)updateClipFromConfig:(viva_text_label)config; - (void)updateQuadFromConfig:(viva_text_label)config; +- (void)updateSharedFromConfig:(viva_text_label)config; - (const float *)quad; - (const float *)tint; - (float)imageRadius; diff --git a/internal/platform/darwin/core_render.m b/internal/platform/darwin/core_render.m index 9729adda8..121d4fb49 100644 --- a/internal/platform/darwin/core_render.m +++ b/internal/platform/darwin/core_render.m @@ -321,10 +321,11 @@ float viva_quantized_origin(float value) { uint64_t viva_label_content_hash(viva_text_label config) { uint64_t hash = 14695981039346656037ULL; hash = viva_hash_bytes(hash, config.utf8, config.utf8_length); - // Bitmap textures retain their source dimensions. Resizing their draw quad - // must find the same texture when Go omits an unchanged pixel payload. - BOOL bitmap = (config.flags & VIVA_LABEL_BITMAP) != 0; - float values[] = {bitmap ? 0 : config.width, bitmap ? 0 : config.height, config.font_size, config.font_weight, + // Bitmap and shared-texture layers retain their source dimensions. Resizing + // their draw quad must find the same texture when Go omits an unchanged + // pixel payload. + BOOL image = (config.flags & (VIVA_LABEL_BITMAP | VIVA_LABEL_TEXTURE)) != 0; + float values[] = {image ? 0 : config.width, image ? 0 : config.height, config.font_size, config.font_weight, config.red, config.green, config.blue, config.alpha, config.cell_width, viva_quantized_origin(config.origin_x), viva_quantized_origin(config.origin_y), config.baseline}; hash = viva_hash_bytes(hash, values, sizeof(values)); @@ -346,6 +347,15 @@ uint64_t viva_label_content_hash(viva_text_label config) { if (config.bitmap != NULL && config.bitmap_id == 0) { hash = viva_hash_bytes(hash, config.bitmap, config.bitmap_length); } + // The slot's surface may change every frame as the engine's ring turns; + // the slot id and size identify the picture the label shows, and the + // layer wraps whatever surface comes in the same slot. + uint64_t textureIdentity[] = { + config.texture_id, + config.texture_width, + config.texture_height, + }; + hash = viva_hash_bytes(hash, textureIdentity, sizeof(textureIdentity)); return hash; } @@ -536,11 +546,33 @@ - (instancetype)initWithConfig:(viva_text_label)config { _bitmapID = config.bitmap_id; _bitmapVersion = config.bitmap_version; } + if ((config.flags & VIVA_LABEL_TEXTURE) != 0) { + // A texture label without a surface has nothing to draw: fail the + // update rather than keep a layer that renders blank. + if (config.texture_handle == 0 || config.texture_width == 0 || config.texture_height == 0) { + [self release]; + return nil; + } + _shared = YES; + _sharedID = config.texture_id; + _sharedHandle = config.texture_handle; + _sharedSurface = (IOSurfaceRef)(uintptr_t)config.texture_handle; + if (_sharedSurface != NULL) { + CFRetain(_sharedSurface); + } + _sharedVersion = config.texture_version; + _sharedWidth = config.texture_width; + _sharedHeight = config.texture_height; + } } return self; } - (void)dealloc { + if (_sharedSurface != NULL) { + CFRelease(_sharedSurface); + _sharedSurface = NULL; + } [_texture release]; [_additionalTextures release]; [_value release]; @@ -558,7 +590,7 @@ - (BOOL)matchesConfig:(viva_text_label)config { if (![self contentMatchesSizeAgnostic:config]) { return NO; } - if (_bitmap != nil) { + if (_bitmap != nil || _shared) { return YES; } return _frame.size.width == config.width && _frame.size.height == config.height; @@ -587,6 +619,14 @@ - (BOOL)contentMatchesSizeAgnostic:(viva_text_label)config { (_runCount > 0 && memcmp(_runs, config.runs, _runCount * sizeof(viva_text_run)) != 0)) { return NO; } + BOOL shared = (config.flags & VIVA_LABEL_TEXTURE) != 0; + if (_shared != shared) { + return NO; + } + if (shared && (_sharedID != config.texture_id || + _sharedWidth != config.texture_width || _sharedHeight != config.texture_height)) { + return NO; + } BOOL bitmap = (config.flags & VIVA_LABEL_BITMAP) != 0; if ((_bitmap != nil) != bitmap) { return NO; @@ -658,6 +698,28 @@ - (void)updateQuadFromConfig:(viva_text_label)config { } } +// updateSharedFromConfig takes the latest surface of a shared-texture label: +// the engine's ring slot holds a new pixel buffer, which rebuildWithDevice +// wraps as a texture when the frame draws. Retain the IOSurface so device +// rebuilds or pipelined rendering stay safe if the player closes concurrently. +- (void)updateSharedFromConfig:(viva_text_label)config { + if (!_shared) { + return; + } + if (config.texture_handle != _sharedHandle) { + IOSurfaceRef next = (IOSurfaceRef)(uintptr_t)config.texture_handle; + if (next != NULL) { + CFRetain(next); + } + if (_sharedSurface != NULL) { + CFRelease(_sharedSurface); + } + _sharedSurface = next; + _sharedHandle = config.texture_handle; + } + _sharedVersion = config.texture_version; +} + - (const float *)quad { return _quad; } @@ -684,6 +746,7 @@ - (void)updateFrame:(CGRect)frame { - (BOOL)forceTextureRebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport { _lastScale = 0; + _builtHandle = 0; return [self rebuildWithDevice:device scale:scale viewport:viewport]; } @@ -695,6 +758,9 @@ - (void)markContentRebuild { // can be seen in viewport is no longer all in its texture: it moved, or its clip or the // viewport did. Any other label is left as it is. - (BOOL)refreshWindowWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport { + if (_shared) { + return [self rebuildWithDevice:device scale:scale viewport:viewport]; + } CGFloat widthScale = [self rasterWidthScale:scale]; if (_texture == nil || _lastScale != scale || viva_bitmap_extent_stale((size_t)ceil(_frame.size.width * _windowPixelScale), (size_t)ceil(_frame.size.width * widthScale))) { @@ -731,6 +797,38 @@ - (CGFloat)rasterWidthScale:(CGFloat)scale { } - (BOOL)rebuildWithDevice:(id)device scale:(CGFloat)scale viewport:(CGSize)viewport { + if (_shared) { + // The surface follows the engine's ring: a slot may show a new pixel + // buffer each frame, which becomes this layer's texture. The contents + // of a surface already wrapped change in place and need no rebuild. + if (_texture != nil && _texture.device == device && _builtHandle == _sharedHandle && + _textureWidth == _sharedWidth && _textureHeight == _sharedHeight) { + return YES; + } + IOSurfaceRef surface = _sharedSurface; + if (surface == NULL) { + return NO; + } + MTLTextureDescriptor *descriptor = [MTLTextureDescriptor + texture2DDescriptorWithPixelFormat:MTLPixelFormatBGRA8Unorm + width:_sharedWidth + height:_sharedHeight + mipmapped:NO]; + descriptor.storageMode = MTLStorageModeShared; + descriptor.usage = MTLTextureUsageShaderRead; + id texture = [device newTextureWithDescriptor:descriptor iosurface:surface plane:0]; + if (texture == nil) { + return NO; + } + [_texture release]; + _texture = texture; + _textureWidth = _sharedWidth; + _textureHeight = _sharedHeight; + _builtHandle = _sharedHandle; + _windowed = NO; + _lastScale = scale; + return YES; + } size_t wantWidth = 0, wantHeight = 0; if (_bitmap != nil) { viva_bitmap_texture_extent(_frame, scale, _bitmapWidth, _bitmapHeight, &wantWidth, &wantHeight); @@ -1106,7 +1204,7 @@ - (CGRect)frame { } - (CGRect)quadAtIndex:(NSUInteger)index { - if (_bitmap != nil) { + if (_bitmap != nil || _shared) { return _frame; } size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); @@ -1118,7 +1216,7 @@ - (CGRect)quadAtIndex:(NSUInteger)index { } - (CGRect)textureFrameAtIndex:(NSUInteger)index { - if (_bitmap != nil) return _frame; + if (_bitmap != nil || _shared) return _frame; size_t full = (size_t)MAX(1.0, ceil(_frame.size.width * _windowPixelScale)); size_t tileLeft = _windowLeft + index * VIVA_LABEL_TILE_WIDTH; size_t tileRight = tileLeft + MIN(_windowRight - tileLeft, VIVA_LABEL_TILE_WIDTH); @@ -1180,9 +1278,10 @@ int viva_update_label_layers( labels[index].width, labels[index].height)]; [existing updateClipFromConfig:labels[index]]; [existing updateQuadFromConfig:labels[index]]; + [existing updateSharedFromConfig:labels[index]]; // An image drawn at a new size may need a texture of another resolution, and a // line held in part another part of it. - BOOL rebuilt = (labels[index].flags & VIVA_LABEL_BITMAP) != 0 + BOOL rebuilt = (labels[index].flags & (VIVA_LABEL_BITMAP | VIVA_LABEL_TEXTURE)) != 0 ? [existing rebuildWithDevice:device scale:scale viewport:viewport] : [existing refreshWindowWithDevice:device scale:scale viewport:viewport]; if (!rebuilt) { @@ -1441,7 +1540,7 @@ int viva_make_scene_resources( if (config.shader_library != NULL && config.shader_library_length > 0) { viva_remember_shader_library(config.shader_library, config.shader_library_length); _Static_assert(sizeof(viva_rectangle) == 80, "rectangle ABI must be 80 bytes"); - _Static_assert(sizeof(viva_text_label) == 272, "text label ABI must be 272 bytes"); + _Static_assert(sizeof(viva_text_label) == 304, "text label ABI must be 304 bytes"); _Static_assert(sizeof(viva_text_run) == 36, "text run ABI must be 36 bytes"); _Static_assert(sizeof(viva_composite_command) == 36, "composite command ABI must be 36 bytes"); dispatch_data_t libraryData = dispatch_data_create( diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 36863dc09..1372bab9b 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -149,6 +149,9 @@ enum { // The label may only paint inside clip_x/clip_y/clip_width/clip_height. VIVA_LABEL_CLIPPED = 8, VIVA_LABEL_ITALIC = 16, + // The label draws a GPU texture a media engine decoded into, addressed by + // texture_handle, rather than pixels or text. + VIVA_LABEL_TEXTURE = 32, }; typedef struct { @@ -213,6 +216,16 @@ typedef struct { // label (platform.TextLabel.ShapesBefore): the composite plan interleaves // text and shapes at that index. uint32_t shapes_before; + // A shared-texture label (VIVA_LABEL_TEXTURE) draws the texture a media + // engine decoded into: texture_handle is its IOSurface, texture_id names + // the engine's ring slot, and texture_version counts the contents' + // changes. texture_width and texture_height are its size in pixels; the + // label's own width and height are the size it is drawn at. + uint64_t texture_handle; + uint64_t texture_id; + uint32_t texture_version; + uint32_t texture_width; + uint32_t texture_height; } viva_text_label; // viva_clip is the region, in logical pixels, that one rectangle or triangle diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 6f86c0107..b36467a85 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -694,7 +694,8 @@ func makeNativeTextLabels(labels []TextLabel) (unsafe.Pointer, []unsafe.Pointer, validCount := 0 for index, label := range labels { bitmap := len(label.Bitmap) > 0 - if label.Width <= 0 || label.Height <= 0 || !bitmap && label.FontSize <= 0 { + texture := label.TextureID != 0 + if label.Width <= 0 || label.Height <= 0 || !bitmap && !texture && label.FontSize <= 0 { continue } content, runBytes := nativeLabelText(label.Value, label.Runs) @@ -760,6 +761,12 @@ func makeNativeTextLabels(labels []TextLabel) (unsafe.Pointer, []unsafe.Pointer, } flags |= C.VIVA_LABEL_BITMAP } + if texture { + if label.TextureHandle == 0 || label.TextureWidth <= 0 || label.TextureHeight <= 0 { + return fail(fmt.Errorf("darwin: texture label %d has invalid dimensions", index)) + } + flags |= C.VIVA_LABEL_TEXTURE + } native[validCount] = C.viva_text_label{ utf8: (*C.uchar)(value), utf8_length: C.size_t(len(content)), @@ -798,6 +805,11 @@ func makeNativeTextLabels(labels []TextLabel) (unsafe.Pointer, []unsafe.Pointer, origin_y: C.float(label.OriginY), font_generation: C.uint32_t(label.FontGeneration), shapes_before: C.uint32_t(label.ShapesBefore), + texture_handle: C.uint64_t(label.TextureHandle), + texture_id: C.uint64_t(label.TextureID), + texture_version: C.uint32_t(label.TextureVersion), + texture_width: C.uint32_t(max(label.TextureWidth, 0)), + texture_height: C.uint32_t(max(label.TextureHeight, 0)), } if label.HasQuad { // The corners and their colours decide where the label's picture diff --git a/internal/platform/darwin/shared_darwin_test.go b/internal/platform/darwin/shared_darwin_test.go new file mode 100644 index 000000000..507c4d122 --- /dev/null +++ b/internal/platform/darwin/shared_darwin_test.go @@ -0,0 +1,115 @@ +//go:build darwin && vivahead && !ios + +package darwin + +import ( + "path/filepath" + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/media" + "github.com/vivaui/viva/internal/platform" +) + +func TestOffscreenDrawsSharedVideoTexture(t *testing.T) { + offscreen, err := NewOffscreen(160, 90, 1, Color{Alpha: 1}) + if err != nil { + t.Skipf("no Metal device: %v", err) + } + defer offscreen.Close() + + abs, err := filepath.Abs("../../media/testdata/colors.mp4") + if err != nil { + t.Fatal(err) + } + engine, err := media.Open(media.Source{Path: abs}) + if err != nil { + t.Fatalf("media.Open: %v", err) + } + defer engine.Close() + + waitFrame := func(wantChanged bool) media.Picture { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + pic, changed, ok := engine.Frame() + if ok && (!wantChanged || changed) { + return pic + } + time.Sleep(20 * time.Millisecond) + } + state, serr := engine.State() + t.Fatalf("no video frame in 5s (state=%v err=%v)", state, serr) + return media.Picture{} + } + + pic1 := waitFrame(true) + label := platform.TextLabel{ + X: 0, Y: 0, Width: 160, Height: 90, + TextureID: pic1.ID, TextureHandle: pic1.Handle, + TextureWidth: pic1.W, TextureHeight: pic1.H, TextureVersion: 1, + } + if err := offscreen.Set(nil, []platform.TextLabel{label}, nil); err != nil { + t.Fatalf("offscreen.Set frame 1: %v", err) + } + pixels, width, _, err := offscreen.Render() + if err != nil { + t.Fatalf("offscreen.Render frame 1: %v", err) + } + if b, g, r, a := pixelAt(pixels, width, 80, 45); r < 180 || a < 240 { + t.Fatalf("frame 1 (t=0) pixel = BGRA(%d,%d,%d,%d), want red-ish opaque", b, g, r, a) + } + + // Clipping (Cover mode) scissors the shared texture outside its clip rect. + clipped := label + clipped.Clipped = true + clipped.Clip = gfx.Rect{X: 0, Y: 0, Width: 40, Height: 40} + if err := offscreen.Set(nil, []platform.TextLabel{clipped}, nil); err != nil { + t.Fatalf("offscreen.Set clipped: %v", err) + } + pixelsC, widthC, _, err := offscreen.Render() + if err != nil { + t.Fatalf("offscreen.Render clipped: %v", err) + } + if b, g, r, a := pixelAt(pixelsC, widthC, 20, 20); r < 180 || a < 240 { + t.Fatalf("inside clip = BGRA(%d,%d,%d,%d), want red-ish opaque", b, g, r, a) + } + if b, g, r, a := pixelAt(pixelsC, widthC, 100, 60); r > 10 || g > 10 || b > 10 { + t.Fatalf("outside clip = BGRA(%d,%d,%d,%d), want clear color", b, g, r, a) + } + + // Seeking to 2.5s updates the IOSurface in place on the reused VivaTextLayer. + engine.Seek(2500 * time.Millisecond) + pic2 := waitFrame(true) + if pic2.ID != pic1.ID { + t.Fatalf("texture ID changed across frames: %d -> %d", pic1.ID, pic2.ID) + } + label2 := platform.TextLabel{ + X: 0, Y: 0, Width: 160, Height: 90, + TextureID: pic2.ID, TextureHandle: pic2.Handle, + TextureWidth: pic2.W, TextureHeight: pic2.H, TextureVersion: 2, + } + if err := offscreen.Set(nil, []platform.TextLabel{label2}, nil); err != nil { + t.Fatalf("offscreen.Set frame 2: %v", err) + } + pixels2, width2, _, err := offscreen.Render() + if err != nil { + t.Fatalf("offscreen.Render frame 2: %v", err) + } + if b, g, r, a := pixelAt(pixels2, width2, 80, 45); b < 180 || r > 100 || a < 240 { + t.Fatalf("frame 2 (t=2.5s) pixel = BGRA(%d,%d,%d,%d), want blue-ish opaque", b, g, r, a) + } + + // Closing the media engine must leave the renderer's retained IOSurface valid. + if err := engine.Close(); err != nil { + t.Fatal(err) + } + pixels3, width3, _, err := offscreen.Render() + if err != nil { + t.Fatalf("offscreen.Render after engine.Close: %v", err) + } + if b, g, r, a := pixelAt(pixels3, width3, 80, 45); b < 180 || r > 100 || a < 240 { + t.Fatalf("after engine.Close pixel = BGRA(%d,%d,%d,%d), want blue-ish opaque", b, g, r, a) + } +} diff --git a/internal/platform/label_validate.go b/internal/platform/label_validate.go index fc5c44f33..ddf0e8ce6 100644 --- a/internal/platform/label_validate.go +++ b/internal/platform/label_validate.go @@ -15,9 +15,17 @@ func ValidateTextLabel(index int, label TextLabel) error { return fmt.Errorf("platform: text label %d has a non-finite metric", index) } } - if label.Width < 0 || label.Height < 0 || len(label.Bitmap) == 0 && !ValidFontSize(label.FontSize) { + image := len(label.Bitmap) > 0 || label.TextureID != 0 + if label.Width < 0 || label.Height < 0 || !image && !ValidFontSize(label.FontSize) { return fmt.Errorf("platform: text label %d has invalid bounds or font size", index) } + if label.TextureID != 0 { + if label.Width <= 0 || label.Height <= 0 || label.TextureHandle == 0 || + label.TextureWidth <= 0 || label.TextureHeight <= 0 { + return fmt.Errorf("platform: texture label %d has invalid dimensions", index) + } + return nil + } if len(label.Runs) > 0 && label.CellWidth <= 0 { return fmt.Errorf("platform: text label %d has invalid cell width", index) } diff --git a/internal/platform/label_validate_test.go b/internal/platform/label_validate_test.go new file mode 100644 index 000000000..11a1ad3ca --- /dev/null +++ b/internal/platform/label_validate_test.go @@ -0,0 +1,37 @@ +package platform + +import "testing" + +func TestTextureLabelsAreValidated(t *testing.T) { + valid := TextLabel{ + X: 0, Y: 0, Width: 100, Height: 50, + TextureHandle: 0x1234, TextureID: 7, TextureWidth: 640, TextureHeight: 360, TextureVersion: 3, + } + if err := ValidateTextLabel(0, valid); err != nil { + t.Fatalf("a valid texture label: %v", err) + } + tests := []struct { + name string + change func(*TextLabel) + }{ + {"no handle", func(l *TextLabel) { l.TextureHandle = 0 }}, + {"no width", func(l *TextLabel) { l.Width = 0 }}, + {"no height", func(l *TextLabel) { l.Height = -1 }}, + {"no texture width", func(l *TextLabel) { l.TextureWidth = 0 }}, + {"no texture height", func(l *TextLabel) { l.TextureHeight = -1 }}, + } + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + label := valid + test.change(&label) + if err := ValidateTextLabel(0, label); err == nil { + t.Fatal("an invalid texture label passed validation") + } + }) + } + // A bitmap label is still validated for its payload. + broken := TextLabel{Width: 10, Height: 10, Bitmap: []byte{1, 2, 3}, BitmapWidth: 4, BitmapHeight: 4, BitmapStride: 16} + if err := ValidateTextLabel(0, broken); err == nil { + t.Fatal("a short bitmap payload passed validation") + } +} diff --git a/internal/platform/native_textures_darwin.go b/internal/platform/native_textures_darwin.go new file mode 100644 index 000000000..e4025b99a --- /dev/null +++ b/internal/platform/native_textures_darwin.go @@ -0,0 +1,8 @@ +//go:build darwin + +package platform + +// NativeTextures reports whether the platform's renderer draws GPU textures +// shared by a media engine. The macOS renderer wraps the engine's IOSurfaces +// as Metal textures, as the Windows renderer opens its NT handles. +const NativeTextures = true diff --git a/internal/platform/native_textures_other.go b/internal/platform/native_textures_other.go new file mode 100644 index 000000000..1d1249c9f --- /dev/null +++ b/internal/platform/native_textures_other.go @@ -0,0 +1,8 @@ +//go:build !windows && !darwin + +package platform + +// NativeTextures reports whether the platform's renderer draws GPU textures +// shared by a media engine. Windows and macOS do in this release; the other +// backends drop a texture image, whose pixels never cross into Go. +const NativeTextures = false diff --git a/internal/platform/native_textures_windows.go b/internal/platform/native_textures_windows.go new file mode 100644 index 000000000..c95cf99f8 --- /dev/null +++ b/internal/platform/native_textures_windows.go @@ -0,0 +1,8 @@ +//go:build windows + +package platform + +// NativeTextures reports whether the platform's renderer draws GPU textures +// shared by a media engine. Windows and macOS do in this release; the other +// backends drop a texture image, whose pixels never cross into Go. +const NativeTextures = true diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index f2cfc6989..4000775fc 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -133,6 +133,7 @@ type renderer struct { // than the display driver, when the driver could not be used or was skipped. software bool window, device, context, swap, target uintptr + device1 uintptr // ID3D11Device1, for opening shared textures rectangleVertex, rectangleFragment, textVertex, textFragment uintptr buffer, view, constants, blend, textBlend, raster, sampler uintptr direct *directRasterizer @@ -163,6 +164,11 @@ type renderer struct { // noLabelBatch makes a frame rasterize each changed label on its own, as // before the batch path existed. Tests compare the two pixel by pixel. noLabelBatch bool + // shared are the media engine textures opened on this device, by texture + // ID, and acquired are the ones this frame holds, released at its end. + shared map[uint64]*sharedTexture + acquired []*sharedTexture + frameNumber uint64 } var textureIID = guid{0x6f15aaf2, 0xd208, 0x4e89, [8]byte{0x9a, 0xb4, 0x48, 0x95, 0x35, 0xd3, 0x4f, 0x9c}} @@ -349,7 +355,17 @@ func (renderer *renderer) createResources() error { return err } sampler := samplerDesc{Filter: 0x15, AddressU: 3, AddressV: 3, AddressW: 3, MaxLOD: math.MaxFloat32} - return hresult(comCall2(renderer.device, 23, uintptr(unsafe.Pointer(&sampler)), uintptr(unsafe.Pointer(&renderer.sampler)))) + if err := hresult(comCall2(renderer.device, 23, uintptr(unsafe.Pointer(&sampler)), uintptr(unsafe.Pointer(&renderer.sampler)))); err != nil { + return err + } + // The 11.1 interface opens textures a media engine shares by handle; a + // device without it draws every frame except video. + var device1 uintptr + if hresult(comCall2(renderer.device, 0, uintptr(unsafe.Pointer(&iidDevice1)), uintptr(unsafe.Pointer(&device1)))) == nil { + renderer.device1 = device1 + } + renderer.publishAdapterLUID() + return nil } // storeRectangles copies the changed instances and their layer and clip, then @@ -620,6 +636,11 @@ func swapChainResize(bufferWidth, bufferHeight, width, height int, hasTarget, he // compositing batch onto it. The window's present and the offscreen render // share it, so a screenshot is made of the pixels the window would show. func (renderer *renderer) draw(width, height int, scale float32) error { + renderer.frameNumber++ + defer func() { + renderer.releaseShared() + renderer.sweepShared(false) + }() // A page that appeared has many labels to draw; draw their pixels in one // Direct2D session before any of them is composited. if err := renderer.prepareLabels(scale, width); err != nil { @@ -686,6 +707,10 @@ func (renderer *renderer) draw(width, height int, scale float32) error { for labelOffset := batch.First; labelOffset < batch.First+batch.Count; labelOffset++ { index := renderer.labelOrder[labelOffset] label := &renderer.labels[index] + if label.label.TextureID != 0 { + renderer.drawSharedTexture(label, scale, width, height, frame, ¤t) + continue + } if label.label.Width <= 0 || label.label.Height <= 0 || label.label.Value == "" && len(label.label.Bitmap) == 0 { // Nothing to draw: a texture kept from the text it had is not needed. label.dropTexture() @@ -797,6 +822,9 @@ func (renderer *renderer) close() { // keeps in memory, the instances, the labels and their batches, is left, so a // device made again can draw the same scene. func (renderer *renderer) releaseDevice() { + renderer.releaseShared() + renderer.sweepShared(true) + release(&renderer.device1) if renderer.context != 0 { comCall0(renderer.context, 110) comCall0(renderer.context, 111) diff --git a/internal/platform/windows/shared_windows.go b/internal/platform/windows/shared_windows.go new file mode 100644 index 000000000..c7d0f77e7 --- /dev/null +++ b/internal/platform/windows/shared_windows.go @@ -0,0 +1,236 @@ +package windows + +import ( + "errors" + "time" + "unsafe" + + "github.com/vivaui/viva/internal/media" + "github.com/vivaui/viva/internal/platform" +) + +// A shared texture is one a media engine decoded a picture into, in BGRA, +// on a device of its own, which this renderer opens on its device by an NT +// handle and reads under the texture's keyed mutex. Opening is a per-texture +// cost, so entries are kept by texture ID and swept promptly once retired by +// the engine or after an idle window. + +const ( + deviceOpenSharedResource1 = 48 // ID3D11Device1 + keyedAcquireSync = 8 // IDXGIKeyedMutex + keyedReleaseSync = 9 // IDXGIKeyedMutex + sharedWaitAbandoned = 0x80 // WAIT_ABANDONED: caller owns mutex, contents may be invalid + sharedWaitTimeout = 0x102 // WaitForSingleObject's timeout HRESULT + dxgiErrorDeviceRemoved = 0x887a0005 // DXGI_ERROR_DEVICE_REMOVED + dxgiErrorDeviceReset = 0x887a0007 // DXGI_ERROR_DEVICE_RESET + sharedAcquireTimeout = 100 // ms a frame waits for the engine to finish writing + sharedSweepFrames = 240 // frames an unused texture stays open + sharedSweepAge = 5 * time.Second +) + +var ( + iidDevice1 = guid{0xa04bfb29, 0x08ef, 0x43d6, [8]byte{0xa4, 0x9c, 0xa9, 0xbd, 0xbd, 0xcb, 0xe6, 0x86}} + iidKeyedMutex = guid{0x9d8e1289, 0xd7b3, 0x465f, [8]byte{0x81, 0x26, 0x25, 0x0e, 0x34, 0x9a, 0xf8, 0x5d}} + iidDXGIResource1 = guid{0x30961379, 0x4609, 0x4a41, [8]byte{0x99, 0x8e, 0x54, 0xfe, 0x56, 0x7e, 0xe0, 0xc1}} + iidDXGIDevice = guid{0x54ec77fa, 0x1377, 0x44e6, [8]byte{0x8c, 0x32, 0x88, 0xfd, 0x5f, 0x44, 0xc8, 0x4c}} +) + +// dxgiAdapterDesc matches DXGI_ADAPTER_DESC on 64-bit Windows. +type dxgiAdapterDesc struct { + Description [128]uint16 + VendorId uint32 + DeviceId uint32 + SubSysId uint32 + Revision uint32 + DedicatedVideoMemory uintptr + DedicatedSystemMemory uintptr + SharedSystemMemory uintptr + AdapterLuidLow uint32 + AdapterLuidHigh int32 +} + +// publishAdapterLUID records this renderer's DXGI adapter LUID in internal/media +// so newly opened video engines create their decode device on the same adapter. +func (renderer *renderer) publishAdapterLUID() { + if renderer.device == 0 { + return + } + var dxgiDevice uintptr + if hresult(comCall2(renderer.device, 0, uintptr(unsafe.Pointer(&iidDXGIDevice)), uintptr(unsafe.Pointer(&dxgiDevice)))) != nil || dxgiDevice == 0 { + return + } + defer release(&dxgiDevice) + var adapter uintptr + if hresult(comCall1(dxgiDevice, 7, uintptr(unsafe.Pointer(&adapter)))) != nil || adapter == 0 { + return + } + defer release(&adapter) + var desc dxgiAdapterDesc + if hresult(comCall1(adapter, 8, uintptr(unsafe.Pointer(&desc)))) == nil { + media.SetRendererAdapterLUID(desc.AdapterLuidLow, desc.AdapterLuidHigh) + } +} + +// sharedTexture is a texture a media engine decoded into, opened on the +// renderer's device and read under its keyed mutex. +type sharedTexture struct { + id uint64 + handle uintptr + width int + height int + view uintptr // ID3D11ShaderResourceView + mutex uintptr // IDXGIKeyedMutex + frame uint64 // the last frame that acquired it + lastUsed time.Time +} + +func (texture *sharedTexture) close() { + release(&texture.view) + release(&texture.mutex) +} + +// sharedView returns the view of a label's shared texture, opening it the +// first time and acquiring its keyed mutex for this frame, or nil when the +// texture cannot be opened or the engine is still writing it. The frame's +// mutexes are released by releaseShared once its draws are issued. +func (renderer *renderer) sharedView(label platform.TextLabel) *sharedTexture { + if label.TextureHandle == 0 || label.TextureID == 0 { + return nil + } + if renderer.device1 == 0 { + media.ReportSharedTextureError(label.TextureID, errors.New("ID3D11Device1 is unavailable")) + return nil + } + entry := renderer.shared[label.TextureID] + if entry != nil && (entry.handle != label.TextureHandle || entry.width != label.TextureWidth || entry.height != label.TextureHeight) { + entry.close() + delete(renderer.shared, label.TextureID) + entry = nil + } + if entry == nil { + opened, status, err := renderer.openShared(label) + if err != nil { + // A device-removed/reset error means the renderer is about to + // recreate its own device; report every other failure so the + // player surfaces Err instead of painting black silently. + code := uint32(status) + if code != dxgiErrorDeviceRemoved && code != dxgiErrorDeviceReset { + media.ReportSharedTextureError(label.TextureID, err) + } + return nil + } + if renderer.shared == nil { + renderer.shared = make(map[uint64]*sharedTexture) + } + renderer.shared[label.TextureID] = opened + entry = opened + } + return renderer.acquireShared(entry) +} + +// acquireShared acquires entry's keyed mutex for the current frame. +func (renderer *renderer) acquireShared(entry *sharedTexture) *sharedTexture { + if entry == nil { + return nil + } + if entry.frame == renderer.frameNumber { + return entry + } + status := comCall2(entry.mutex, keyedAcquireSync, 0, sharedAcquireTimeout) + if status == sharedWaitAbandoned { + // Ownership was granted, so release immediately, but skip drawing + // potentially inconsistent pixels. + comCall1(entry.mutex, keyedReleaseSync, 0) + return nil + } + if err := hresult(status); err != nil || status == sharedWaitTimeout { + return nil + } + entry.frame = renderer.frameNumber + entry.lastUsed = time.Now() + renderer.acquired = append(renderer.acquired, entry) + return entry +} + +// openShared opens a label's texture on the renderer's device and makes the +// view and keyed mutex it is read through. +func (renderer *renderer) openShared(label platform.TextLabel) (*sharedTexture, uintptr, error) { + var texture uintptr + status := comCall3(renderer.device1, deviceOpenSharedResource1, label.TextureHandle, uintptr(unsafe.Pointer(&textureIID)), uintptr(unsafe.Pointer(&texture))) + if err := hresult(status); err != nil { + return nil, status, err + } + defer release(&texture) + entry := &sharedTexture{id: label.TextureID, handle: label.TextureHandle, width: label.TextureWidth, height: label.TextureHeight} + status = comCall2(texture, 0, uintptr(unsafe.Pointer(&iidKeyedMutex)), uintptr(unsafe.Pointer(&entry.mutex))) + if err := hresult(status); err != nil { + return nil, status, err + } + status = comCall3(renderer.device, 7, texture, 0, uintptr(unsafe.Pointer(&entry.view))) + if err := hresult(status); err != nil { + release(&entry.mutex) + return nil, status, err + } + return entry, 0, nil +} + +// drawSharedTexture draws a shared-texture label with the text pipeline's +// quad shader, narrowed to its scissor. If the latest slot's keyed mutex times +// out, it falls back to the last valid slot drawn by this label to avoid a +// blank-frame flicker. +func (renderer *renderer) drawSharedTexture(label *labelTexture, scale float32, width, height int, frame *frameConstants, current *scissorRect) { + l := label.label + if label.picture != nil || label.view != 0 || label.texture != 0 { + // A slot that showed text or a bitmap before keeps nothing of it. + label.dropTexture() + } + entry := renderer.sharedView(l) + if entry == nil && label.lastSharedID != 0 && label.lastSharedID != l.TextureID && !media.IsSharedTextureRetired(label.lastSharedID) { + entry = renderer.acquireShared(renderer.shared[label.lastSharedID]) + } + if entry == nil { + return + } + label.lastSharedID = entry.id + scissor, visible := labelScissor(l, scale, width, height) + if !visible { + return + } + x, y := platform.DevicePosition(l.X, 0, scale), platform.DevicePosition(l.Y, 0, scale) + w, h := platform.DeviceExtent(l.X, l.Width, scale), platform.DeviceExtent(l.Y, l.Height, scale) + frame.Bounds = [4]float32{float32(x) / scale, float32(y) / scale, float32(w) / scale, float32(h) / scale} + frame.TextShape = [4]float32{l.Width, l.Height, l.ImageRadius, l.ImageFade} + frame.TextMode = 0 + comCall6(renderer.context, 48, renderer.constants, 0, 0, uintptr(unsafe.Pointer(frame)), 0, 0) + if scissor != *current { + renderer.setScissor(scissor) + *current = scissor + } + comCall3(renderer.context, 8, 1, 1, uintptr(unsafe.Pointer(&entry.view))) + comCall2(renderer.context, 13, 6, 0) +} + +// releaseShared releases the keyed mutexes the frame read, its draws issued: +// the GPU then reads the texture after the engine's writes, and the engine +// may write it again after the frame's reads. +func (renderer *renderer) releaseShared() { + for _, entry := range renderer.acquired { + comCall1(entry.mutex, keyedReleaseSync, 0) + } + renderer.acquired = renderer.acquired[:0] +} + +// sweepShared closes shared textures that the engine has retired, or that no +// frame has read within the frame or time window, or all of them when the +// device is going. +func (renderer *renderer) sweepShared(all bool) { + now := time.Now() + for id, entry := range renderer.shared { + retired := media.IsSharedTextureRetired(id) + aged := !entry.lastUsed.IsZero() && now.Sub(entry.lastUsed) > sharedSweepAge + if all || retired || renderer.frameNumber-entry.frame > sharedSweepFrames || aged { + entry.close() + delete(renderer.shared, id) + } + } +} diff --git a/internal/platform/windows/shared_windows_test.go b/internal/platform/windows/shared_windows_test.go new file mode 100644 index 000000000..bf9a6ab75 --- /dev/null +++ b/internal/platform/windows/shared_windows_test.go @@ -0,0 +1,159 @@ +//go:build windows + +package windows + +import ( + "syscall" + "testing" + "time" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +func closeSharedHandle(handle uintptr) { + if handle != 0 { + syscall.CloseHandle(syscall.Handle(handle)) + } +} + +// createSharedBGRA makes a width by height BGRA texture of pixels on device, +// shared by an NT handle with a keyed mutex, as a media engine's frame is. +func createSharedBGRA(device uintptr, width, height int, pixels []byte) (uintptr, error) { + var device1 uintptr + if err := hresult(comCall2(device, 0, uintptr(unsafe.Pointer(&iidDevice1)), uintptr(unsafe.Pointer(&device1)))); err != nil { + return 0, err + } + defer release(&device1) + description := textureDesc{ + Width: uint32(width), Height: uint32(height), Mips: 1, Array: 1, Format: 87, Samples: 1, + Usage: 0, Bind: 0x8 | 0x20, Misc: 0x100 | 0x800, + } + data := resourceData{Data: unsafe.Pointer(&pixels[0]), Pitch: uint32(width * 4)} + var texture uintptr + if err := hresult(comCall3(device1, 5, uintptr(unsafe.Pointer(&description)), uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&texture)))); err != nil { + return 0, err + } + defer release(&texture) + var resource uintptr + if err := hresult(comCall2(texture, 0, uintptr(unsafe.Pointer(&iidDXGIResource1)), uintptr(unsafe.Pointer(&resource)))); err != nil { + return 0, err + } + defer release(&resource) + var handle uintptr + if err := hresult(comCall4(resource, 13, 0, 0x80000001, 0, uintptr(unsafe.Pointer(&handle)))); err != nil { + return 0, err + } + return handle, nil +} + +func redPixels(size int) []byte { + pixels := make([]byte, size*size*4) + for i := 0; i < len(pixels); i += 4 { + pixels[i], pixels[i+1], pixels[i+2], pixels[i+3] = 0, 0, 255, 255 // BGRA + } + return pixels +} + +func TestOffscreenDrawsASharedTexture(t *testing.T) { + offscreen, err := NewOffscreen(64, 64, 1, platform.Color{}) + if err != nil { + t.Skipf("offscreen renderer unavailable: %v", err) + } + defer offscreen.Close() + const size = 64 + handle, err := createSharedBGRA(offscreen.renderer.device, size, size, redPixels(size)) + if err != nil { + t.Skipf("shared textures unavailable: %v", err) + } + defer closeSharedHandle(handle) + label := platform.TextLabel{ + Width: size, Height: size, + TextureID: 1, TextureHandle: handle, + TextureWidth: size, TextureHeight: size, TextureVersion: 1, + } + if err := offscreen.Set(nil, []platform.TextLabel{label}); err != nil { + t.Fatal(err) + } + drawn, err := offscreen.Image() + if err != nil { + t.Fatal(err) + } + if red, _, _, _ := drawn.At(32, 32).RGBA(); red>>8 < 0xf0 { + t.Fatalf("pixel = %v, want the shared texture's red", drawn.At(32, 32)) + } +} + +func TestOffscreenClipsASharedTexture(t *testing.T) { + offscreen, err := NewOffscreen(64, 64, 1, platform.Color{}) + if err != nil { + t.Skipf("offscreen renderer unavailable: %v", err) + } + defer offscreen.Close() + const size = 64 + handle, err := createSharedBGRA(offscreen.renderer.device, size, size, redPixels(size)) + if err != nil { + t.Skipf("shared textures unavailable: %v", err) + } + defer closeSharedHandle(handle) + label := platform.TextLabel{ + Width: size, Height: size, + TextureID: 1, TextureHandle: handle, + TextureWidth: size, TextureHeight: size, TextureVersion: 1, + Clip: gfx.Rect{Width: 10, Height: 10}, Clipped: true, + } + if err := offscreen.Set(nil, []platform.TextLabel{label}); err != nil { + t.Fatal(err) + } + drawn, err := offscreen.Image() + if err != nil { + t.Fatal(err) + } + if red, _, _, _ := drawn.At(4, 4).RGBA(); red>>8 < 0xf0 { + t.Fatalf("inside the clip: %v, want red", drawn.At(4, 4)) + } + if red, _, _, _ := drawn.At(32, 32).RGBA(); red>>8 > 0x10 { + t.Fatalf("outside the clip: %v, want the clear color", drawn.At(32, 32)) + } +} + +func TestOffscreenSweepsAgedSharedTexture(t *testing.T) { + offscreen, err := NewOffscreen(64, 64, 1, platform.Color{}) + if err != nil { + t.Skipf("offscreen renderer unavailable: %v", err) + } + defer offscreen.Close() + const size = 64 + handle, err := createSharedBGRA(offscreen.renderer.device, size, size, redPixels(size)) + if err != nil { + t.Skipf("shared textures unavailable: %v", err) + } + defer closeSharedHandle(handle) + label := platform.TextLabel{ + Width: size, Height: size, + TextureID: 77, TextureHandle: handle, + TextureWidth: size, TextureHeight: size, TextureVersion: 1, + } + if err := offscreen.Set(nil, []platform.TextLabel{label}); err != nil { + t.Fatal(err) + } + if _, err := offscreen.Image(); err != nil { + t.Fatal(err) + } + entry := offscreen.renderer.shared[77] + if entry == nil { + t.Fatal("shared texture entry was not cached") + } + // Back-date lastUsed past sharedSweepAge and paint an empty scene: sweepShared must drop it even after 1 frame. + entry.lastUsed = time.Now().Add(-sharedSweepAge - time.Second) + if err := offscreen.Set(nil, nil); err != nil { + t.Fatal(err) + } + if _, err := offscreen.Image(); err != nil { + t.Fatal(err) + } + if _, ok := offscreen.renderer.shared[77]; ok { + t.Fatal("aged shared texture was not swept") + } +} diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index 6181a2ac3..462224ff5 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -59,6 +59,9 @@ type labelTexture struct { // spans are the columns of an lcd grid label's texture that are text of one color; // empty for a label that is all in label.Color. spans []colorSpan + // lastSharedID remembers the last shared media texture this label drew so + // a transient keyed-mutex timeout keeps showing it instead of flickering. + lastSharedID uint64 } type bitmapInfoHeader struct { Size uint32 @@ -321,6 +324,9 @@ func (label *labelTexture) update(next platform.TextLabel) { if labelContentChanged(label.label, next) { label.stale = true } + if next.TextureID == 0 { + label.lastSharedID = 0 + } // The runs belong to the caller's frame; keep a copy for the next comparison. label.runs = append(label.runs[:0], next.Runs...) label.label = next @@ -328,6 +334,11 @@ func (label *labelTexture) update(next platform.TextLabel) { } func labelContentChanged(previous, next platform.TextLabel) bool { + if previous.TextureID != next.TextureID || previous.TextureHandle != next.TextureHandle || + previous.TextureWidth != next.TextureWidth || previous.TextureHeight != next.TextureHeight || + previous.TextureVersion != next.TextureVersion { + return true + } isBitmap := len(previous.Bitmap) > 0 || len(next.Bitmap) > 0 return previous.Value != next.Value || (!isBitmap && previous.Height != next.Height) || previous.FontSize != next.FontSize || previous.Weight != next.Weight || previous.Italic != next.Italic || previous.Color != next.Color || previous.FontGeneration != next.FontGeneration || previous.Mono != next.Mono || previous.MonoFace != next.MonoFace || previous.CellWidth != next.CellWidth || !sameRuns(previous.Runs, next.Runs) || diff --git a/tools/appaudit/appaudit_test.go b/tools/appaudit/appaudit_test.go new file mode 100644 index 000000000..38a07e80d --- /dev/null +++ b/tools/appaudit/appaudit_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "bufio" + "go/token" + "os" + "path/filepath" + "strings" + "testing" +) + +// Every line the sample marks with a want comment is reported with that check, +// and nothing else is: allowed lines, conditional frames, background work and +// a directive with no reason behave as the comment on each says. +func TestTheSampleIsReportedWhereItSaysAndNowhereElse(t *testing.T) { + path := filepath.Join("testdata", "sample", "sample.go") + want := map[int]string{} + file, err := os.Open(path) + if err != nil { + t.Fatal(err) + } + scanner := bufio.NewScanner(file) + for line := 1; scanner.Scan(); line++ { + if _, check, ok := strings.Cut(scanner.Text(), "// want "); ok { + want[line] = strings.TrimSpace(check) + } + } + file.Close() + // A directive with no reason allows nothing. + want[25] = "ticker" + + findings, err := auditFile(token.NewFileSet(), path) + if err != nil { + t.Fatal(err) + } + got := map[int]string{} + for _, f := range findings { + got[f.position.Line] = f.check + } + for line, check := range want { + if got[line] != check { + t.Errorf("line %d: reported %q, want %q", line, got[line], check) + } + } + for line, check := range got { + if want[line] == "" { + t.Errorf("line %d: reported %q, want nothing", line, check) + } + } +} + +func TestTestFilesAndSkippedFoldersAreNotRead(t *testing.T) { + files, err := sourceFiles([]string{"./..."}) + if err != nil { + t.Fatal(err) + } + for _, file := range files { + if strings.HasSuffix(file, "_test.go") || strings.Contains(filepath.ToSlash(file), "testdata/") { + t.Errorf("read %s", file) + } + } +} diff --git a/tools/appaudit/main.go b/tools/appaudit/main.go new file mode 100644 index 000000000..2c098bc60 --- /dev/null +++ b/tools/appaudit/main.go @@ -0,0 +1,346 @@ +// Command appaudit points at the patterns that keep a Viva application busy +// when it has nothing to do, or stall its window thread. It reads Go source +// without building it, so a finding is a place to look, not a verdict: +// +// - ticker: time.NewTicker or time.Tick. A ticker wakes the process on a +// schedule whether or not anything changed. Wait for the event that says +// something did (a file or network notification, a channel, Post), or ask +// for one timer when work becomes due. +// - paint-io: a file-system call in a function that is handed a canvas, a +// page (ui.C) or a draw context. Paint and declaration run on the window +// thread every frame; a slow or locked disk stalls the window. +// - frame-loop: canvas.RequestFrameIn with a duration of a frame or less, +// outside any condition. It asks for frames forever. +// +// A line that does this on purpose says why with a directive on it or on the +// line above, and is not reported: +// +// ticker := time.NewTicker(interval) //appaudit:allow keepalive the protocol requires +// +// Test files, vendor, testdata and third_party are skipped. Run it with the +// packages to read, ./... for a tree: +// +// go run github.com/vivaui/viva/tools/appaudit ./... +// +// It exits 1 when it reports anything and 2 when it cannot read the source. +package main + +import ( + "flag" + "fmt" + "go/ast" + "go/parser" + "go/token" + "io/fs" + "os" + "path/filepath" + "sort" + "strconv" + "strings" +) + +const directive = "//appaudit:allow" + +type finding struct { + position token.Position + check string + message string +} + +func (f finding) String() string { + return fmt.Sprintf("%s:%d: %s: %s", f.position.Filename, f.position.Line, f.check, f.message) +} + +func main() { + flag.Usage = func() { + fmt.Fprintln(os.Stderr, "usage: appaudit [packages] (./... reads a tree)") + } + flag.Parse() + patterns := flag.Args() + if len(patterns) == 0 { + patterns = []string{"./..."} + } + files, err := sourceFiles(patterns) + if err != nil { + fmt.Fprintln(os.Stderr, "appaudit:", err) + os.Exit(2) + } + var findings []finding + fset := token.NewFileSet() + for _, path := range files { + found, err := auditFile(fset, path) + if err != nil { + fmt.Fprintln(os.Stderr, "appaudit:", err) + os.Exit(2) + } + findings = append(findings, found...) + } + for _, f := range findings { + fmt.Println(f) + } + if len(findings) > 0 { + fmt.Fprintf(os.Stderr, "appaudit: %d finding(s); fix them, or say why on the line with %s \n", len(findings), directive) + os.Exit(1) + } +} + +// sourceFiles lists the non-test Go files the patterns name, in order. +func sourceFiles(patterns []string) ([]string, error) { + var files []string + for _, pattern := range patterns { + root, recursive := strings.CutSuffix(pattern, "/...") + if root == "." || root == "" { + root = "." + } + info, err := os.Stat(root) + if err != nil { + return nil, err + } + if !info.IsDir() { + files = append(files, root) + continue + } + err = filepath.WalkDir(root, func(path string, entry fs.DirEntry, err error) error { + if err != nil { + return err + } + if entry.IsDir() { + if path != root && (!recursive || skippedDir(entry.Name())) { + return filepath.SkipDir + } + return nil + } + if strings.HasSuffix(path, ".go") && !strings.HasSuffix(path, "_test.go") { + files = append(files, path) + } + return nil + }) + if err != nil { + return nil, err + } + } + sort.Strings(files) + return files, nil +} + +func skippedDir(name string) bool { + return name == "vendor" || name == "testdata" || name == "third_party" || strings.HasPrefix(name, ".") || strings.HasPrefix(name, "_") +} + +// auditFile reports what one file does. +func auditFile(fset *token.FileSet, path string) ([]finding, error) { + file, err := parser.ParseFile(fset, path, nil, parser.ParseComments) + if err != nil { + return nil, err + } + allowed := allowedLines(fset, file) + var findings []finding + report := func(node ast.Node, check, message string) { + position := fset.Position(node.Pos()) + if allowed[position.Line] { + return + } + findings = append(findings, finding{position: position, check: check, message: message}) + } + timePkg, osPkg := importName(file, "time"), importName(file, "os") + + // stack is the path from the file to the node being visited, which says + // what function a call is in and whether a condition guards it. + var stack []ast.Node + ast.Inspect(file, func(node ast.Node) bool { + if node == nil { + stack = stack[:len(stack)-1] + return true + } + stack = append(stack, node) + call, ok := node.(*ast.CallExpr) + if !ok { + return true + } + if pkg, name, ok := qualified(call.Fun); ok { + switch { + case pkg == timePkg && (name == "NewTicker" || name == "Tick"): + report(call, "ticker", "time."+name+" wakes the process on a schedule; wait for an event, or ask for one timer when work is due") + case pkg == osPkg && fileCalls[name] && paintsFrame(stack): + report(call, "paint-io", "os."+name+" in a function that paints or declares the page runs on the window thread every frame") + } + } + if selector, ok := call.Fun.(*ast.SelectorExpr); ok && selector.Sel.Name == "RequestFrameIn" && len(call.Args) == 1 { + if wait, ok := duration(call.Args[0], timePkg); ok && wait <= frame && !conditional(stack) { + report(call, "frame-loop", "RequestFrameIn of a frame or less, outside any condition, asks for frames forever") + } + } + return true + }) + return findings, nil +} + +var fileCalls = map[string]bool{ + "Open": true, "OpenFile": true, "Create": true, "ReadFile": true, "WriteFile": true, "ReadDir": true, + "Stat": true, "Lstat": true, "Rename": true, "Remove": true, "RemoveAll": true, "Mkdir": true, "MkdirAll": true, +} + +// allowedLines are the lines a directive covers: its own, and the next one when +// it stands alone. +func allowedLines(fset *token.FileSet, file *ast.File) map[int]bool { + allowed := map[int]bool{} + for _, group := range file.Comments { + for _, comment := range group.List { + reason, ok := strings.CutPrefix(comment.Text, directive) + if !ok || strings.TrimSpace(reason) == "" { + continue + } + line := fset.Position(comment.Pos()).Line + allowed[line] = true + allowed[line+1] = true + } + } + return allowed +} + +// importName is the name a file refers to an import path by, "" when it does +// not import it. +func importName(file *ast.File, path string) string { + for _, spec := range file.Imports { + if value, _ := strconv.Unquote(spec.Path.Value); value != path { + continue + } + if spec.Name != nil { + return spec.Name.Name + } + return path[strings.LastIndexByte(path, '/')+1:] + } + return "" +} + +func qualified(expr ast.Expr) (pkg, name string, ok bool) { + selector, ok := expr.(*ast.SelectorExpr) + if !ok { + return "", "", false + } + ident, ok := selector.X.(*ast.Ident) + if !ok { + return "", "", false + } + return ident.Name, selector.Sel.Name, true +} + +// paintsFrame reports whether the innermost function on the stack is handed a +// canvas, a page or a draw context. +func paintsFrame(stack []ast.Node) bool { + for index := len(stack) - 1; index >= 0; index-- { + var params *ast.FieldList + switch fn := stack[index].(type) { + case *ast.FuncDecl: + params = fn.Type.Params + case *ast.FuncLit: + params = fn.Type.Params + default: + continue + } + for _, field := range params.List { + if frameType(field.Type) { + return true + } + } + return false + } + return false +} + +func frameType(expr ast.Expr) bool { + if star, ok := expr.(*ast.StarExpr); ok { + expr = star.X + } + pkg, name, ok := qualified(expr) + if !ok { + return false + } + return pkg == "gfx" && name == "Canvas" || pkg == "ui" && (name == "C" || name == "DrawContext") +} + +// conditional reports whether the node is inside an if, switch, select or a +// loop of the innermost function, or comes after an if of that function that +// returns: the guard Go writes as an early return. +func conditional(stack []ast.Node) bool { + for index := len(stack) - 2; index >= 0; index-- { + switch fn := stack[index].(type) { + case *ast.IfStmt, *ast.SwitchStmt, *ast.TypeSwitchStmt, *ast.SelectStmt, *ast.CaseClause, *ast.CommClause, *ast.ForStmt, *ast.RangeStmt: + return true + case *ast.FuncDecl: + return guardedEarlier(fn.Body, stack[index+1:]) + case *ast.FuncLit: + return guardedEarlier(fn.Body, stack[index+1:]) + } + } + return false +} + +// guardedEarlier reports whether a statement of body before the one leading to +// the node is an if whose branch returns. +func guardedEarlier(body *ast.BlockStmt, path []ast.Node) bool { + if body == nil || len(path) < 2 { + return false + } + current := path[1] // path[0] is the body itself + for _, statement := range body.List { + if ast.Node(statement) == current { + return false + } + guard, ok := statement.(*ast.IfStmt) + if !ok || len(guard.Body.List) == 0 { + continue + } + if _, returns := guard.Body.List[len(guard.Body.List)-1].(*ast.ReturnStmt); returns { + return true + } + } + return false +} + +// frame is the longest wait that still counts as asking for the next frame. +const frame = 33 + +// duration evaluates a constant wait written with the time package, in +// milliseconds: 16*time.Millisecond, time.Second/60, a bare time.Millisecond. +func duration(expr ast.Expr, timePkg string) (float64, bool) { + switch e := expr.(type) { + case *ast.ParenExpr: + return duration(e.X, timePkg) + case *ast.SelectorExpr: + if pkg, name, ok := qualified(e); ok && pkg == timePkg { + unit, known := units[name] + return unit, known + } + case *ast.BinaryExpr: + left, leftUnit := duration(e.X, timePkg) + right, rightUnit := duration(e.Y, timePkg) + leftNumber, leftOK := number(e.X) + rightNumber, rightOK := number(e.Y) + switch { + case e.Op == token.MUL && leftUnit && rightOK: + return left * rightNumber, true + case e.Op == token.MUL && leftOK && rightUnit: + return leftNumber * right, true + case e.Op == token.QUO && leftUnit && rightOK && rightNumber != 0: + return left / rightNumber, true + } + } + return 0, false +} + +func number(expr ast.Expr) (float64, bool) { + if paren, ok := expr.(*ast.ParenExpr); ok { + return number(paren.X) + } + literal, ok := expr.(*ast.BasicLit) + if !ok || (literal.Kind != token.INT && literal.Kind != token.FLOAT) { + return 0, false + } + value, err := strconv.ParseFloat(literal.Value, 64) + return value, err == nil +} + +var units = map[string]float64{ + "Nanosecond": 1e-6, "Microsecond": 1e-3, "Millisecond": 1, "Second": 1000, "Minute": 60000, "Hour": 3600000, +} diff --git a/tools/appaudit/testdata/sample/sample.go b/tools/appaudit/testdata/sample/sample.go new file mode 100644 index 000000000..8675845af --- /dev/null +++ b/tools/appaudit/testdata/sample/sample.go @@ -0,0 +1,53 @@ +package sample + +import ( + "os" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" +) + +func poll() { + ticker := time.NewTicker(time.Second) // want ticker + defer ticker.Stop() + _ = time.Tick(time.Second) // want ticker +} + +func allowed() { + //appaudit:allow the protocol needs a keepalive while connected + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + _ = time.NewTicker(time.Minute) //appaudit:allow measured once a minute while a transfer runs +} + +func bare() { + _ = time.NewTicker(time.Second) //appaudit:allow +} + +func paint(canvas *gfx.Canvas, size gfx.Size) { + _, _ = os.Stat("/tmp") // want paint-io + canvas.RequestFrameIn(16 * time.Millisecond) // want frame-loop + if size.Width > 0 { + canvas.RequestFrameIn(time.Millisecond) + } + canvas.RequestFrameIn(time.Second) +} + +func declare(c ui.C) { + _, _ = os.ReadFile("x") // want paint-io + go func() { + _, _ = os.ReadFile("x") + }() +} + +func worker() { + _, _ = os.ReadFile("x") +} + +func edge(canvas *gfx.Canvas, direction int) { + if direction == 0 { + return + } + canvas.RequestFrameIn(16 * time.Millisecond) +} diff --git a/ui/field_paste_test.go b/ui/field_paste_test.go new file mode 100644 index 000000000..5212bcf0f --- /dev/null +++ b/ui/field_paste_test.go @@ -0,0 +1,149 @@ +package ui_test + +import ( + "bytes" + "image" + "image/png" + "path/filepath" + "testing" + + "github.com/vivaui/viva/text" + "github.com/vivaui/viva/ui" +) + +func pastedPNG(t *testing.T) []byte { + t.Helper() + var out bytes.Buffer + if err := png.Encode(&out, image.NewNRGBA(image.Rect(0, 0, 2, 2))); err != nil { + t.Fatal(err) + } + return out.Bytes() +} + +func (d *pageDriver) paste() { + d.t.Helper() + if handled, err := d.driver.Shortcut('v'); err != nil || !handled { + d.t.Fatalf("paste: handled=%v err=%v", handled, err) + } +} + +// OnPaste sees every paste into a TextArea before the field does: a paste it +// takes leaves the field as it was and paints the page again, text it leaves +// pastes as usual, and a clipboard of no text is offered as nothing. A cut is +// not a paste. +func TestTextAreaOnPasteTakesOrLeavesThePaste(t *testing.T) { + var notes ui.Field + editor := text.NewEditor("") + notes.Bind(editor) + var offered []string + attached := "" + take := true + d := openPage(t, func(c ui.C) { + ui.Column(c).Pad(16).Gap(8).Children(func() { + ui.TextArea(c, ¬es, "Notes", "").Height(120).OnPaste(func(value string) bool { + offered = append(offered, value) + if take { + attached = value + } + return take + }) + if attached != "" { + ui.Button(c, "Attached "+attached) + } + }) + }) + d.click("Notes") + + d.driver.SetClipboardFiles([]string{filepath.Join(t.TempDir(), "report.txt")}) + d.paste() + if notes.Text() != "" || len(offered) != 1 || offered[0] != "report.txt" { + t.Fatalf("a paste the handler took: text %q, offered %q", notes.Text(), offered) + } + if !d.has("Attached report.txt") { + t.Fatal("the page did not paint again after the handler took the paste") + } + + if err := d.driver.SetClipboardImage(pastedPNG(t)); err != nil { + t.Fatal(err) + } + d.paste() + if notes.Text() != "" || len(offered) != 2 || offered[1] != "" { + t.Fatalf("a paste of a picture: text %q, offered %q", notes.Text(), offered) + } + + take = false + d.driver.SetClipboard("one\ntwo") + d.paste() + if notes.Text() != "one\ntwo" || len(offered) != 3 || offered[2] != "one\ntwo" { + t.Fatalf("a paste the handler left: text %q, offered %q", notes.Text(), offered) + } + if !editor.CanUndo() { + t.Fatal("the paste the handler left is not an edit the field can undo") + } + + editor.SetSelection(text.Range{Start: 0, End: 3}) + d.repaint() + if handled, err := d.driver.Shortcut('x'); err != nil || !handled { + t.Fatalf("cut: handled=%v err=%v", handled, err) + } + if notes.Text() != "\ntwo" || len(offered) != 3 { + t.Fatalf("a cut: text %q, offered %q", notes.Text(), offered) + } +} + +// A single-line field's handler sees the text the paste would insert, its lines +// folded into one, as the system hands a single-line field its paste. +func TestTextFieldOnPasteSeesTheTextTheFieldWouldTake(t *testing.T) { + var name ui.Field + offered := "" + d := openPage(t, func(c ui.C) { + ui.TextField(c, &name, "Name", "").OnPaste(func(value string) bool { + offered = value + return false + }) + }) + d.click("Name") + d.driver.SetClipboard("a\nb") + d.paste() + if offered != "a b" || name.Text() != "a b" { + t.Fatalf("offered %q, field %q", offered, name.Text()) + } +} + +// The edit menu's Paste is offered to the handler too. +func TestEditMenuPasteIsOfferedToOnPaste(t *testing.T) { + var notes ui.Field + var offered []string + d := openCanvasMenus(t, func(c ui.C) { + ui.TextArea(c, ¬es, "Notes", "").Height(120).OnPaste(func(value string) bool { + offered = append(offered, value) + return true + }) + }) + d.driver.SetClipboardFiles([]string{filepath.Join(t.TempDir(), "plan.md")}) + d.secondaryClick("Notes") + d.click("Paste") + if notes.Text() != "" || len(offered) != 1 || offered[0] != "plan.md" { + t.Fatalf("the edit menu's Paste: text %q, offered %q", notes.Text(), offered) + } +} + +// OnPaste is for a TextField or a TextArea, with a handler. +func TestOnPasteNeedsATextFieldAndAHandler(t *testing.T) { + for name, view := range map[string]func(ui.C){ + "container": func(c ui.C) { ui.Column(c).OnPaste(func(string) bool { return false }) }, + "no handler": func(c ui.C) { + var field ui.Field + ui.TextField(c, &field, "Name", "").OnPaste(nil) + }, + } { + t.Run(name, func(t *testing.T) { + defer func() { + if recover() == nil { + t.Fatal("OnPaste did not panic") + } + }() + openPage(t, view) + }) + } +} diff --git a/ui/video/apng.go b/ui/video/apng.go new file mode 100644 index 000000000..cc2536df1 --- /dev/null +++ b/ui/video/apng.go @@ -0,0 +1,481 @@ +package video + +import ( + "bytes" + "encoding/binary" + "errors" + "hash/crc32" + "image" + "image/png" + "io" + "time" +) + +// pngSignature begins every PNG file. +var pngSignature = []byte("\x89PNG\r\n\x1a\n") + +const ( + apngDisposeBackground = 1 + apngDisposePrevious = 2 + apngBlendOver = 1 +) + +// apngDecoder plays an animated PNG. It reads the whole file at once but +// keeps each frame's pixels compressed, as they came; a frame is decoded and +// composed over the picture as it comes due. +type apngDecoder struct { + header []byte // the IHDR chunk's data, of the whole picture + palette [][]byte // complete PLTE and tRNS chunks, which a frame needs + frames []apngFrame + next int + + width, height, stride int + picture []byte // the composed frame, premultiplied BGRA + before []byte // the picture before the current frame drew + hasBefore bool // before holds that picture +} + +// apngFrame is one frame of an animated PNG: its compressed pixels, the +// rectangle it draws, how long it shows, and how it clears (dispose) and +// draws (blend) before the next. +type apngFrame struct { + pixels []byte + rect image.Rectangle + delay time.Duration + dispose, blend byte +} + +// NewAPNGDecoder returns a decoder of an animated PNG's frames, for +// NewDecoder, as browsers show them: a frame of 10 ms or less shows for +// 100 ms. A PNG that is not animated is a video of one frame. Each frame +// is kept compressed, and decoded as it plays. The player's SetLoop, not +// the PNG's count of plays, says whether it plays again. A PNG whose +// composed picture and largest frame would need more than maxDecoderBytes +// is an error, and its picture is made when the first frame is asked for, +// not when the PNG opens. +func NewAPNGDecoder(data []byte) (Decoder, error) { + if !bytes.HasPrefix(data, pngSignature) { + return nil, errors.New("video: not a PNG") + } + d := &apngDecoder{} + if err := d.read(data); err != nil { + return nil, err + } + d.stride = 4 * d.width + return d, nil +} + +// read walks the PNG's chunks: its header and palette, then the frames the +// frame controls and image data make. +func (d *apngDecoder) read(data []byte) error { + var ( + off = len(pngSignature) + first = true + animated bool + defaultImage []byte // IDAT pixels of a PNG with no frame control before them + current *apngFrame // the frame the image data belongs to + sawHeader bool + sawImage bool + framePixels uint64 // the pixels of the largest frame, decoded one at a time + ) + for off < len(data) { + kind, body, raw, next, err := pngChunk(data, off) + if err != nil { + return err + } + off = next + isFirst := first + first = false + switch kind { + case "IHDR": + // The header is the first chunk and appears once; a second one + // would leave the frames it already read outside the picture. + if !isFirst || sawHeader { + return errors.New("video: a PNG with a second header") + } + if len(body) != 13 { + return errors.New("video: a PNG of a bad header") + } + d.header = append([]byte(nil), body...) + d.width = int(binary.BigEndian.Uint32(body)) + d.height = int(binary.BigEndian.Uint32(body[4:])) + if d.width <= 0 || d.height <= 0 || uint64(d.width)*uint64(d.height) > maxDecoderPixels { + return errors.New("video: a PNG of an invalid size") + } + sawHeader = true + case "PLTE", "tRNS": + d.palette = append(d.palette, append([]byte(nil), raw...)) + case "acTL": + animated = true + case "fcTL": + if !sawHeader { + return errors.New("video: an APNG of a bad frame control") + } + if current != nil && len(current.pixels) == 0 { + return errors.New("video: an APNG frame of no data") + } + f, err := readFrameControl(body, d.width, d.height) + if err != nil { + return err + } + if len(d.frames) == 0 && f.dispose == apngDisposePrevious { + f.dispose = apngDisposeBackground // there is nothing before it + } + if pixels := uint64(f.rect.Dx()) * uint64(f.rect.Dy()); pixels > framePixels { + framePixels = pixels + } + d.frames = append(d.frames, f) + current = &d.frames[len(d.frames)-1] + case "IDAT": + sawImage = true + switch { + case current != nil: + current.pixels = append(current.pixels, body...) + case !animated: + defaultImage = append(defaultImage, body...) + } + case "fdAT": + if current != nil && len(body) >= 4 { + current.pixels = append(current.pixels, body[4:]...) + } + case "IEND": + off = len(data) + } + } + if !sawHeader || !sawImage { + return errors.New("video: a PNG of no image") + } + if current != nil && len(current.pixels) == 0 { + return errors.New("video: an APNG frame of no data") + } + if len(d.frames) == 0 { + if len(defaultImage) == 0 { + return errors.New("video: a PNG of no image") + } + framePixels = uint64(d.width) * uint64(d.height) + d.frames = []apngFrame{{ + pixels: defaultImage, + rect: image.Rect(0, 0, d.width, d.height), + delay: 100 * time.Millisecond, + }} + } + // A frame is decoded one at a time, so the peak is the composed picture, + // the copy a disposal may restore, and the largest frame. + if pictureBytes(d.width, d.height)+4*framePixels > maxDecoderBytes { + return errors.New("video: a PNG whose picture and frames need too much memory") + } + return nil +} + +// pngChunk reads the chunk at off: its kind, its body, the bytes it spans, +// and where the next chunk starts. +func pngChunk(data []byte, off int) (kind string, body, raw []byte, next int, err error) { + if off+12 > len(data) { + return "", nil, nil, 0, errors.New("video: a truncated PNG") + } + n := uint64(binary.BigEndian.Uint32(data[off:])) + if n > uint64(len(data)-off-12) { + return "", nil, nil, 0, errors.New("video: a truncated PNG") + } + kind = string(data[off+4 : off+8]) + body = data[off+8 : off+8+int(n)] + raw = data[off : off+12+int(n)] + return kind, body, raw, off + 12 + int(n), nil +} + +// readFrameControl reads an fcTL chunk: the rectangle the frame draws, how +// long it shows, and how it clears and blends. +func readFrameControl(body []byte, width, height int) (apngFrame, error) { + if len(body) != 26 { + return apngFrame{}, errors.New("video: an APNG of a bad frame control") + } + w := binary.BigEndian.Uint32(body[4:]) + h := binary.BigEndian.Uint32(body[8:]) + x := binary.BigEndian.Uint32(body[12:]) + y := binary.BigEndian.Uint32(body[16:]) + if w == 0 || h == 0 || uint64(x)+uint64(w) > uint64(width) || uint64(y)+uint64(h) > uint64(height) { + return apngFrame{}, errors.New("video: an APNG frame out of its picture") + } + num, den := binary.BigEndian.Uint16(body[20:]), binary.BigEndian.Uint16(body[22:]) + if den == 0 { + den = 100 // the numerator counts hundredths of a second + } + delay := time.Duration(num) * time.Second / time.Duration(den) + if delay <= 10*time.Millisecond { + delay = 100 * time.Millisecond + } + return apngFrame{ + rect: image.Rect(int(x), int(y), int(x)+int(w), int(y)+int(h)), + delay: delay, + dispose: body[24], + blend: body[25], + }, nil +} + +func (d *apngDecoder) Next() (Frame, error) { + if d.next >= len(d.frames) { + return Frame{}, io.EOF + } + if err := d.advance(); err != nil { + return Frame{}, err + } + return Frame{ + Pix: d.picture, + Width: d.width, + Height: d.height, + Stride: d.stride, + Duration: d.frames[d.next-1].delay, + }, nil +} + +// advance decodes the next frame and draws it over the picture, after undoing +// the frame before as its disposal says. +func (d *apngDecoder) advance() error { + i := d.next + f := &d.frames[i] + img, err := png.Decode(bytes.NewReader(d.framePNG(f))) + if err != nil { + return err + } + d.ensurePicture() + if i > 0 { + d.undo(i - 1) + } + d.hasBefore = f.dispose == apngDisposePrevious + if d.hasBefore { + d.ensureBefore() + copy(d.before, d.picture) + } + d.draw(img, f.rect, f.blend == apngBlendOver) + d.next++ + return nil +} + +// ensurePicture makes the composed picture, when the first frame needs it. +func (d *apngDecoder) ensurePicture() { + if d.picture == nil { + d.picture = make([]byte, d.stride*d.height) + } +} + +// ensureBefore makes the copy a disposal-previous frame restores, when a +// frame whose dispose asks for it is drawn. +func (d *apngDecoder) ensureBefore() { + d.ensurePicture() + if d.before == nil { + d.before = make([]byte, len(d.picture)) + } +} + +// framePNG is the PNG a frame's pixels decode from: the picture's header at +// the frame's size, the picture's palette, and the frame's data. +func (d *apngDecoder) framePNG(f *apngFrame) []byte { + var b bytes.Buffer + b.Write(pngSignature) + hdr := append([]byte(nil), d.header...) + binary.BigEndian.PutUint32(hdr, uint32(f.rect.Dx())) + binary.BigEndian.PutUint32(hdr[4:], uint32(f.rect.Dy())) + writeChunk(&b, "IHDR", hdr) + for _, chunk := range d.palette { + b.Write(chunk) + } + writeChunk(&b, "IDAT", f.pixels) + writeChunk(&b, "IEND", nil) + return b.Bytes() +} + +// draw puts a decoded frame over the picture in its rectangle, replacing what +// is under it or blending with it. Fast paths handle the common concrete +// PNG image types directly without per-pixel interface boxing. A rectangle +// outside the picture is cut to it: the parser refuses a frame outside the +// header's picture, and this keeps a picture and a frame that disagree from +// slicing past the composed pixels. +func (d *apngDecoder) draw(img image.Image, r image.Rectangle, over bool) { + d.ensurePicture() + r = r.Intersect(image.Rect(0, 0, d.width, d.height)) + b := img.Bounds() + w := min(r.Dx(), b.Dx()) + h := min(r.Dy(), b.Dy()) + if w <= 0 || h <= 0 { + return + } + switch src := img.(type) { + case *image.NRGBA: + for y := 0; y < h; y++ { + in := src.Pix[src.PixOffset(b.Min.X, b.Min.Y+y):] + out := d.picture[(r.Min.Y+y)*d.stride+r.Min.X*4:] + for x := 0; x < w; x++ { + si := x * 4 + sr, sg, sb, sa := in[si], in[si+1], in[si+2], in[si+3] + if sa == 0 { + if !over { + out[si], out[si+1], out[si+2], out[si+3] = 0, 0, 0, 0 + } + continue + } + if sa == 255 { + out[si], out[si+1], out[si+2], out[si+3] = sb, sg, sr, 255 + continue + } + a := uint32(sa) + pixel := [4]byte{ + byte((uint32(sb)*a + 127) / 255), + byte((uint32(sg)*a + 127) / 255), + byte((uint32(sr)*a + 127) / 255), + sa, + } + if over { + putOver(out[si:], pixel) + } else { + copy(out[si:si+4], pixel[:]) + } + } + } + case *image.RGBA: + for y := 0; y < h; y++ { + in := src.Pix[src.PixOffset(b.Min.X, b.Min.Y+y):] + out := d.picture[(r.Min.Y+y)*d.stride+r.Min.X*4:] + for x := 0; x < w; x++ { + si := x * 4 + pixel := [4]byte{in[si+2], in[si+1], in[si], in[si+3]} + if over { + if pixel[3] == 0 { + continue + } + if pixel[3] == 255 { + copy(out[si:si+4], pixel[:]) + } else { + putOver(out[si:], pixel) + } + } else { + copy(out[si:si+4], pixel[:]) + } + } + } + case *image.Paletted: + var colors [256][4]byte + for i, c := range src.Palette { + if i == len(colors) { + break + } + cr, cg, cb, ca := c.RGBA() + colors[i] = [4]byte{byte(cb >> 8), byte(cg >> 8), byte(cr >> 8), byte(ca >> 8)} + } + for y := 0; y < h; y++ { + in := src.Pix[src.PixOffset(b.Min.X, b.Min.Y+y):] + out := d.picture[(r.Min.Y+y)*d.stride+r.Min.X*4:] + for x := 0; x < w; x++ { + pixel := colors[in[x]] + si := x * 4 + if over { + if pixel[3] == 0 { + continue + } + if pixel[3] == 255 { + copy(out[si:si+4], pixel[:]) + } else { + putOver(out[si:], pixel) + } + } else { + copy(out[si:si+4], pixel[:]) + } + } + } + default: + for y := 0; y < h; y++ { + out := d.picture[(r.Min.Y+y)*d.stride+r.Min.X*4:] + for x := 0; x < w; x++ { + cr, cg, cb, ca := img.At(b.Min.X+x, b.Min.Y+y).RGBA() + pixel := [4]byte{byte(cb >> 8), byte(cg >> 8), byte(cr >> 8), byte(ca >> 8)} + if over { + putOver(out[x*4:], pixel) + } else { + copy(out[x*4:x*4+4], pixel[:]) + } + } + } + } +} + +// putOver puts a premultiplied pixel over the one at the start of dst. +func putOver(dst []byte, src [4]byte) { + rest := uint32(255 - src[3]) + for i := 0; i < 4; i++ { + dst[i] = byte(uint32(src[i]) + (uint32(dst[i])*rest+127)/255) + } +} + +// undo takes frame i back as its disposal says: it clears the frame's +// rectangle to transparent, restores what was under it, or leaves it. +func (d *apngDecoder) undo(i int) { + switch d.frames[i].dispose { + case apngDisposeBackground: + d.clear(d.frames[i].rect) + case apngDisposePrevious: + if d.hasBefore { + copy(d.picture, d.before) + } + } +} + +// clear makes a rectangle of the picture transparent. +func (d *apngDecoder) clear(r image.Rectangle) { + r = r.Intersect(image.Rect(0, 0, d.width, d.height)) + for y := r.Min.Y; y < r.Max.Y; y++ { + clear(d.picture[y*d.stride+r.Min.X*4 : y*d.stride+r.Max.X*4]) + } +} + +func (d *apngDecoder) Rewind() error { + d.reset() + return nil +} + +// reset takes the picture back to its state before the first frame. +func (d *apngDecoder) reset() { + d.next = 0 + d.hasBefore = false + clear(d.picture) + clear(d.before) +} + +// Seek starts the animation at to, composing the frames before the one that +// shows then. It returns when that frame starts. +func (d *apngDecoder) Seek(to time.Duration) (time.Duration, error) { + if to < 0 { + to = 0 + } + d.reset() + var start time.Duration + for d.next+1 < len(d.frames) && start+d.frames[d.next].delay <= to { + start += d.frames[d.next].delay + if err := d.advance(); err != nil { + return 0, err + } + } + return start, nil +} + +// Duration is the length of the animation, for the player's Duration. +func (d *apngDecoder) Duration() time.Duration { + var total time.Duration + for _, f := range d.frames { + total += f.delay + } + return total +} + +// writeChunk writes a PNG chunk: its length, kind, body and CRC. +func writeChunk(b *bytes.Buffer, kind string, data []byte) { + crc := crc32.NewIEEE() + crc.Write([]byte(kind)) + crc.Write(data) + var head [8]byte + binary.BigEndian.PutUint32(head[:4], uint32(len(data))) + copy(head[4:], kind) + b.Write(head[:]) + b.Write(data) + var sum [4]byte + binary.BigEndian.PutUint32(sum[:], crc.Sum32()) + b.Write(sum[:]) +} diff --git a/ui/video/apng_test.go b/ui/video/apng_test.go new file mode 100644 index 000000000..a12fe1323 --- /dev/null +++ b/ui/video/apng_test.go @@ -0,0 +1,389 @@ +package video + +import ( + "bytes" + "compress/zlib" + "encoding/binary" + "image" + "image/color" + "image/png" + "testing" + "time" +) + +// apngFrameSpec is a frame of a test APNG: a solid w×h rectangle at x, y. +type apngFrameSpec struct { + c color.NRGBA + x, y, w, h int + dispose, blend byte + delayNum, delDen uint16 +} + +// testAPNG builds an animated PNG of w×h of the frames given, the first the +// default image unless hidden, which adds a default image that is no frame. +func testAPNG(t *testing.T, w, h int, hidden bool, frames ...apngFrameSpec) []byte { + t.Helper() + encode := func(c color.NRGBA, fw, fh int) (ihdr, idat []byte) { + img := image.NewNRGBA(image.Rect(0, 0, fw, fh)) + for i := 0; i < len(img.Pix); i += 4 { + img.Pix[i], img.Pix[i+1], img.Pix[i+2], img.Pix[i+3] = c.R, c.G, c.B, c.A + } + var b bytes.Buffer + if err := (&png.Encoder{CompressionLevel: png.NoCompression}).Encode(&b, translucent{img}); err != nil { + t.Fatal(err) + } + data := b.Bytes()[8:] + for len(data) >= 12 { + n := binary.BigEndian.Uint32(data) + kind, chunk := string(data[4:8]), data[8:8+n] + switch kind { + case "IHDR": + ihdr = chunk + case "IDAT": + idat = append(idat, chunk...) + } + data = data[12+n:] + } + return ihdr, idat + } + var b bytes.Buffer + b.Write(pngSignature) + ihdr, _ := encode(color.NRGBA{}, w, h) + ihdr = append([]byte(nil), ihdr...) + writeChunk(&b, "IHDR", ihdr) + actl := make([]byte, 8) + binary.BigEndian.PutUint32(actl, uint32(len(frames))) + writeChunk(&b, "acTL", actl) + seq := uint32(0) + if hidden { + _, idat := encode(color.NRGBA{255, 255, 255, 255}, w, h) + writeChunk(&b, "IDAT", idat) + } + for i, f := range frames { + fc := make([]byte, 26) + binary.BigEndian.PutUint32(fc, seq) + seq++ + binary.BigEndian.PutUint32(fc[4:], uint32(f.w)) + binary.BigEndian.PutUint32(fc[8:], uint32(f.h)) + binary.BigEndian.PutUint32(fc[12:], uint32(f.x)) + binary.BigEndian.PutUint32(fc[16:], uint32(f.y)) + binary.BigEndian.PutUint16(fc[20:], f.delayNum) + binary.BigEndian.PutUint16(fc[22:], f.delDen) + fc[24], fc[25] = f.dispose, f.blend + writeChunk(&b, "fcTL", fc) + _, idat := encode(f.c, f.w, f.h) + if i == 0 && !hidden { + writeChunk(&b, "IDAT", idat) + continue + } + fd := make([]byte, 4, 4+len(idat)) + binary.BigEndian.PutUint32(fd, seq) + seq++ + writeChunk(&b, "fdAT", append(fd, idat...)) + } + writeChunk(&b, "IEND", nil) + return b.Bytes() +} + +// translucent has the PNG encoder keep alpha, as every frame of an APNG is +// of the same color type. +type translucent struct{ *image.NRGBA } + +func (translucent) Opaque() bool { return false } + +// TestAPNGDecoderFrames checks that an animated PNG's frames draw over what +// the ones before left as their disposal and blending say, for as long as +// their delays say, that a default image before the first frame control is +// not a frame, and that a PNG not animated is a frame. +func TestAPNGDecoderFrames(t *testing.T) { + red, green := color.NRGBA{255, 0, 0, 255}, color.NRGBA{0, 255, 0, 255} + half := color.NRGBA{0, 0, 255, 128} + data := testAPNG(t, 4, 4, false, + apngFrameSpec{c: red, w: 4, h: 4, delayNum: 1, delDen: 5}, + // Over the red, then cleared. + apngFrameSpec{c: green, x: 1, y: 1, w: 2, h: 2, delayNum: 30, dispose: apngDisposeBackground}, + // Blended over what the clearing left. + apngFrameSpec{c: half, x: 0, y: 0, w: 2, h: 2, blend: apngBlendOver, dispose: apngDisposePrevious}, + // Over what the frame before had under it, replacing it. + apngFrameSpec{c: half, x: 3, y: 3, w: 1, h: 1, delayNum: 0}, + ) + d, err := NewAPNGDecoder(data) + if err != nil { + t.Fatal(err) + } + videored := color.RGBA{255, 0, 0, 255} + greenRGBA := color.RGBA{0, 255, 0, 255} + type check struct { + x, y int + want color.RGBA + } + blue := color.RGBA{0, 0, 128, 128} + steps := []struct { + delay time.Duration + checks []check + }{ + {200 * time.Millisecond, []check{{0, 0, videored}, {3, 3, videored}}}, + {300 * time.Millisecond, []check{{1, 1, greenRGBA}, {0, 0, videored}}}, + {100 * time.Millisecond, []check{{0, 0, blend(videored, blue)}, {1, 1, blue}, {2, 2, videored}}}, + {100 * time.Millisecond, []check{{0, 0, videored}, {1, 1, color.RGBA{}}, {3, 3, blue}}}, + } + for range 2 { + for i, s := range steps { + f, err := d.Next() + if err != nil { + t.Fatalf("frame %d: %v", i, err) + } + if f.Duration != s.delay { + t.Errorf("frame %d shows for %v, want %v", i, f.Duration, s.delay) + } + for _, c := range s.checks { + if got := framePixel(f, c.x, c.y); !nearRGBA(got, c.want) { + t.Errorf("frame %d at %d,%d: %v, want %v", i, c.x, c.y, got, c.want) + } + } + } + if _, err := d.Next(); err == nil { + t.Fatal("a frame after the last") + } + if err := d.Rewind(); err != nil { + t.Fatal(err) + } + } + if got := d.(durationReader).Duration(); got != 700*time.Millisecond { + t.Errorf("duration %v, want 700ms", got) + } + + // A default image before the first frame control is no frame. + d, err = NewAPNGDecoder(testAPNG(t, 2, 2, true, apngFrameSpec{c: green, w: 2, h: 2})) + if err != nil { + t.Fatal(err) + } + if f, err := d.Next(); err != nil || framePixel(f, 0, 0) != greenRGBA { + t.Fatalf("first frame after a default image: %v", err) + } + if _, err := d.Next(); err == nil { + t.Fatal("the default image was a frame") + } + + // A PNG not animated. + var b bytes.Buffer + png.Encode(&b, image.NewRGBA(image.Rect(0, 0, 3, 2))) + d, err = NewAPNGDecoder(b.Bytes()) + if err != nil { + t.Fatal(err) + } + if f, err := d.Next(); err != nil || f.Width != 3 || f.Height != 2 { + t.Fatalf("a PNG not animated: %v", err) + } + if _, err := NewAPNGDecoder([]byte("GIF89a")); err == nil { + t.Error("a GIF decoded as a PNG") + } +} + +// TestAPNGSeek checks that a seek starts at the frame showing then, the +// frames before it composed, and reports when it starts. +func TestAPNGSeek(t *testing.T) { + red, green, blue := color.NRGBA{255, 0, 0, 255}, color.NRGBA{0, 255, 0, 255}, color.NRGBA{0, 0, 255, 255} + d, err := NewAPNGDecoder(testAPNG(t, 2, 2, false, + apngFrameSpec{c: red, w: 2, h: 2, delayNum: 10, delDen: 100}, + apngFrameSpec{c: green, w: 2, h: 2, delayNum: 10, delDen: 100}, + apngFrameSpec{c: blue, w: 2, h: 2, delayNum: 10, delDen: 100}, + )) + if err != nil { + t.Fatal(err) + } + seeker, ok := d.(Seeker) + if !ok { + t.Fatal("the APNG decoder does not seek") + } + for _, test := range []struct { + to time.Duration + start time.Duration + want color.RGBA + }{ + {0, 0, color.RGBA{255, 0, 0, 255}}, + {250 * time.Millisecond, 200 * time.Millisecond, color.RGBA{0, 0, 255, 255}}, + {time.Hour, 200 * time.Millisecond, color.RGBA{0, 0, 255, 255}}, + } { + start, err := seeker.Seek(test.to) + if err != nil { + t.Fatalf("Seek(%v): %v", test.to, err) + } + if start != test.start { + t.Fatalf("Seek(%v) starts at %v, want %v", test.to, start, test.start) + } + f, err := d.Next() + if err != nil { + t.Fatalf("Seek(%v): %v", test.to, err) + } + if got := framePixel(f, 0, 0); got != test.want { + t.Fatalf("Seek(%v) shows %v, want %v", test.to, got, test.want) + } + } +} + +// TestAPNGDecoderDimensions checks that a PNG whose picture is empty or too +// large for its pixel buffer returns an error instead of panicking. +func TestAPNGDecoderDimensions(t *testing.T) { + var plain bytes.Buffer + if err := png.Encode(&plain, image.NewRGBA(image.Rect(0, 0, 1, 1))); err != nil { + t.Fatal(err) + } + for _, src := range []struct { + name string + data []byte + }{ + {"plain", plain.Bytes()}, + {"animated", testAPNG(t, 1, 1, false, apngFrameSpec{w: 1, h: 1})}, + } { + for _, size := range []struct { + name string + w, h uint32 + }{ + {"zero width", 0, 1}, + {"zero height", 1, 0}, + {"exceeds pixel cap", 10000, 10000}, + {"needs more than the decoder budget", 8192, 8192}, + {"pixel buffer overflow", 0x7fffffff, 0x7fffffff}, + {"largest dimensions", 0xffffffff, 0xffffffff}, + } { + t.Run(src.name+"/"+size.name, func(t *testing.T) { + // Replace only IHDR, including its checksum; keep the frames. + hdr := append([]byte(nil), src.data[16:29]...) + binary.BigEndian.PutUint32(hdr, size.w) + binary.BigEndian.PutUint32(hdr[4:], size.h) + var b bytes.Buffer + b.Write(pngSignature) + writeChunk(&b, "IHDR", hdr) + b.Write(src.data[33:]) + if _, err := NewAPNGDecoder(b.Bytes()); err == nil { + t.Fatal("a PNG of an invalid size decoded") + } + }) + } + } +} + +// TestAPNGSecondHeaderIsRejected checks that a PNG whose header follows the +// frames, shrinking the picture they were read against, is an error rather +// than a frame that slices past the composed pixels. The frame's rectangle +// would be outside the 1×1 picture the second header names. +func TestAPNGSecondHeaderIsRejected(t *testing.T) { + var compressed bytes.Buffer + w := zlib.NewWriter(&compressed) + if _, err := w.Write([]byte{0, 255, 0, 0, 255}); err != nil { + t.Fatal(err) + } + if err := w.Close(); err != nil { + t.Fatal(err) + } + header := func(width, height uint32) []byte { + body := make([]byte, 13) + binary.BigEndian.PutUint32(body, width) + binary.BigEndian.PutUint32(body[4:], height) + body[8], body[9] = 8, 6 // 8-bit RGBA + var chunk bytes.Buffer + writeChunk(&chunk, "IHDR", body) + return chunk.Bytes() + } + var b bytes.Buffer + b.Write(pngSignature) + b.Write(header(100, 100)) + fc := make([]byte, 26) + binary.BigEndian.PutUint32(fc[4:], 1) // width + binary.BigEndian.PutUint32(fc[8:], 1) // height + binary.BigEndian.PutUint32(fc[12:], 99) // x + binary.BigEndian.PutUint32(fc[16:], 99) // y + binary.BigEndian.PutUint16(fc[20:], 1) // delay 1/10 + binary.BigEndian.PutUint16(fc[22:], 10) + writeChunk(&b, "fcTL", fc) + writeChunk(&b, "IDAT", compressed.Bytes()) + b.Write(header(1, 1)) + writeChunk(&b, "IEND", nil) + + if _, err := NewAPNGDecoder(b.Bytes()); err == nil { + t.Fatal("a PNG with a second header decoded; its frame lies outside the picture") + } +} + +// TestAPNGDrawClampsAFrameToItsPicture checks the backstop behind the parser: +// a frame rectangle that disagrees with the picture is cut to it, not sliced +// past the composed pixels. +func TestAPNGDrawClampsAFrameToItsPicture(t *testing.T) { + d := &apngDecoder{width: 2, height: 2, stride: 8} + d.draw(image.NewNRGBA(image.Rect(0, 0, 2, 2)), image.Rect(5, 5, 7, 7), true) + d.draw(image.NewNRGBA(image.Rect(0, 0, 2, 2)), image.Rect(-3, -3, -1, -1), true) + if len(d.picture) != 16 { + t.Fatalf("picture = %d bytes, want 16", len(d.picture)) + } +} + +// blend is src, premultiplied, over dst. +func blend(dst, src color.RGBA) color.RGBA { + k := 255 - uint32(src.A) + f := func(d, s uint8) uint8 { return uint8(uint32(s) + (uint32(d)*k+127)/255) } + return color.RGBA{f(dst.R, src.R), f(dst.G, src.G), f(dst.B, src.B), f(dst.A, src.A)} +} + +func nearRGBA(a, b color.RGBA) bool { + d := func(x, y uint8) bool { return x-y <= 1 || y-x <= 1 } + return d(a.R, b.R) && d(a.G, b.G) && d(a.B, b.B) && d(a.A, b.A) +} + +// TestAPNGDrawFastPaths verifies that the concrete NRGBA, RGBA and Paletted +// fast paths match the generic color.RGBA compositing behavior. +func TestAPNGDrawFastPaths(t *testing.T) { + base := color.RGBA{200, 40, 20, 255} + half := color.NRGBA{20, 100, 220, 128} + halfPremul := color.RGBA{ + R: byte((uint32(half.R)*uint32(half.A) + 127) / 255), + G: byte((uint32(half.G)*uint32(half.A) + 127) / 255), + B: byte((uint32(half.B)*uint32(half.A) + 127) / 255), + A: half.A, + } + wantOver := blend(base, halfPremul) + + makeDec := func() *apngDecoder { + d := &apngDecoder{width: 2, height: 2, stride: 8} + d.picture = make([]byte, 16) + for i := 0; i < len(d.picture); i += 4 { + d.picture[i], d.picture[i+1], d.picture[i+2], d.picture[i+3] = base.B, base.G, base.R, base.A + } + return d + } + + nrgba := image.NewNRGBA(image.Rect(0, 0, 2, 2)) + nrgba.SetNRGBA(0, 0, half) + rgba := image.NewRGBA(image.Rect(0, 0, 2, 2)) + rgba.SetRGBA(0, 0, halfPremul) + pal := image.NewPaletted(image.Rect(0, 0, 2, 2), color.Palette{color.NRGBA{}, half}) + pal.SetColorIndex(0, 0, 1) + + for _, tc := range []struct { + name string + img image.Image + }{ + {"NRGBA", nrgba}, + {"RGBA", rgba}, + {"Paletted", pal}, + } { + d := makeDec() + d.draw(tc.img, image.Rect(0, 0, 2, 2), true) + f := Frame{Pix: d.picture, Width: 2, Height: 2, Stride: 8} + if got := framePixel(f, 0, 0); !nearRGBA(got, wantOver) { + t.Errorf("%s over at (0,0) = %v, want %v", tc.name, got, wantOver) + } + if got := framePixel(f, 1, 1); got != base { + t.Errorf("%s over transparent at (1,1) = %v, want %v", tc.name, got, base) + } + d = makeDec() + d.draw(tc.img, image.Rect(0, 0, 2, 2), false) + f = Frame{Pix: d.picture, Width: 2, Height: 2, Stride: 8} + if got := framePixel(f, 0, 0); !nearRGBA(got, halfPremul) { + t.Errorf("%s replace at (0,0) = %v, want %v", tc.name, got, halfPremul) + } + if got := framePixel(f, 1, 1); got != (color.RGBA{}) { + t.Errorf("%s replace transparent at (1,1) = %v, want zero", tc.name, got) + } + } +} diff --git a/ui/video/decode.go b/ui/video/decode.go new file mode 100644 index 000000000..22062d928 --- /dev/null +++ b/ui/video/decode.go @@ -0,0 +1,73 @@ +package video + +import ( + "time" +) + +// defaultFrameDuration is how long a decoder frame with no duration of its +// own shows, as browsers show a GIF frame that names none. +const defaultFrameDuration = 100 * time.Millisecond + +// maxDecoderPixels caps the pixel count of a Go-decoded animation (8K×8K) so +// a malformed header cannot exhaust memory before decoding pixels. +const maxDecoderPixels = 8192 * 8192 + +// maxDecoderBytes caps the decoded memory of one animation: the pictures it +// composes and the frames it keeps. A GIF keeps every frame it decoded, and +// both decoders compose a picture the size their header declares, so a small +// file can name more memory than it holds; an animation past this budget is +// an error rather than a way to exhaust the machine. +const maxDecoderBytes = 256 << 20 + +// pictureBytes is the memory an animation of width by height needs for the +// pictures it composes: the one it shows, and the copy taken before a frame +// whose disposal restores it. Both decoders allocate these when they first +// need them, not when the animation opens. +func pictureBytes(width, height int) uint64 { + if width <= 0 || height <= 0 { + return 0 + } + return 8 * uint64(width) * uint64(height) +} + +// Frame is one picture of a decoder. +type Frame struct { + // Pix is the picture's pixels, premultiplied BGRA, Stride bytes a row, + // top row first. The player copies it; the decoder may reuse the + // buffer for its next frame. + Pix []byte + Width, Height int + Stride int + // Duration is how long the frame shows, before the next one. Zero is + // defaultFrameDuration. + Duration time.Duration +} + +// Decoder is a video decoded in Go, such as an animated GIF or PNG: the +// player draws its frames itself, on every system, without a media +// framework. Its methods are called from one goroutine at a time, never +// from the UI thread. +type Decoder interface { + // Next returns the frame after the one before, or io.EOF after the + // last. + Next() (Frame, error) + // Rewind makes the next Next return the first frame again. + Rewind() error +} + +// Seeker is a Decoder that can start at a time, so the player can seek +// without decoding every frame. A decoder that is not a Seeker plays from +// its start, and the player ignores Seek. +type Seeker interface { + Decoder + // Seek makes the next Next return the frame showing at to, and returns + // when that frame starts: a frame starts on a multiple of the frames' + // durations, which may be before to. + Seek(to time.Duration) (time.Duration, error) +} + +// durationReader is what a decoder whose animation has a known length +// implements, for the player's Duration before it reached the end. +type durationReader interface { + Duration() time.Duration +} diff --git a/ui/video/decoder.go b/ui/video/decoder.go new file mode 100644 index 000000000..73baec7f2 --- /dev/null +++ b/ui/video/decoder.go @@ -0,0 +1,436 @@ +package video + +import ( + "io" + "time" +) + +// decoderAhead is how many frames the decoder decodes before the one shown: +// enough that the next frame is there when its time comes, without decoding +// the whole animation a frame at a time. +const decoderAhead = 2 + +// decoded is one frame a decoder made, or the error that stopped it. +type decoded struct { + frame Frame + at time.Duration // when the frame starts + landed bool // the first frame after a seek or a rewind + err error + gen uint64 // the run that made it +} + +// decodeRequest makes the decoder start over at a time, or at its start. +type decodeRequest struct { + gen uint64 + rewind bool + to time.Duration +} + +// decoderPlayback plays a Decoder's frames: a goroutine decodes ahead, and +// the UI thread shows the frame due as the canvas clock passes it. The +// goroutine only ever fills the channels; every field below is read and +// written on the UI thread. +type decoderPlayback struct { + src Decoder + seeker Seeker + + cmd chan decodeRequest + out chan decoded + pool chan []byte + stop chan struct{} + done chan struct{} + wake func() + + total time.Duration // the animation's length, when known + end time.Duration // where its last frame ends + endKnown bool + + gen uint64 // the run the player shows + waiting bool // a seek's frame has not landed yet + queue []decoded // frames decoded but not shown yet + cur Frame + have bool + pos time.Duration // where the shown frame starts + + rate float64 + playing bool + loop bool + resync bool // base the play clock at the next advance + playAt time.Duration + playPos time.Duration + lastNow time.Duration + + state State + err error +} + +func newDecoderPlayback(src Decoder, wake func()) *decoderPlayback { + d := &decoderPlayback{src: src, wake: wake, rate: 1, state: Loading} + if seeker, ok := src.(Seeker); ok { + d.seeker = seeker + } + if reader, ok := src.(durationReader); ok { + if total := reader.Duration(); total > 0 { + d.total, d.end, d.endKnown = total, total, true + } + } + d.cmd = make(chan decodeRequest, 1) + d.out = make(chan decoded, decoderAhead) + d.pool = make(chan []byte, decoderAhead+2) + d.stop = make(chan struct{}) + d.done = make(chan struct{}) + go d.decode() + d.request(decodeRequest{rewind: true}) + return d +} + +// decode is the decoder's goroutine: it takes a request, starts the decoder +// there, and decodes ahead until the animation ends or a newer request comes. +func (d *decoderPlayback) decode() { + defer close(d.done) + var ( + next decodeRequest + haveNext bool + ) + for { + var req decodeRequest + if haveNext { + req, haveNext = next, false + } else { + select { + case <-d.stop: + return + case req = <-d.cmd: + } + } + at, err := d.start(req) + if err != nil { + d.deliver(decoded{at: at, err: err, gen: req.gen}) + continue + } + landed := true + run: + for { + frame, err := d.src.Next() + if err != nil { + d.deliver(decoded{at: at, err: err, gen: req.gen}) + break run + } + duration := frame.Duration + if duration <= 0 { + duration = defaultFrameDuration + } + // Copy the frame's pixels before the next Next call can reuse + // the decoder's buffer while this frame is still queued. + copied := d.cloneFrame(frame) + select { + case <-d.stop: + d.recycle(copied.Pix) + return + case d.out <- decoded{frame: copied, at: at, landed: landed, gen: req.gen}: + d.woken() + case req = <-d.cmd: + // A newer run starts: what this one decoded is stale. + d.recycle(copied.Pix) + next, haveNext = req, true + break run + } + at += duration + landed = false + } + } +} + +// cloneFrame copies frame's pixel bytes into a buffer owned by the queue, +// reusing a pooled slice when one fits. +func (d *decoderPlayback) cloneFrame(frame Frame) Frame { + if frame.Width <= 0 || frame.Height <= 0 || frame.Stride < frame.Width*4 { + frame.Pix = nil + return frame + } + n := frame.Stride * frame.Height + if len(frame.Pix) < n { + frame.Pix = nil + return frame + } + var buf []byte + select { + case buf = <-d.pool: + default: + } + if cap(buf) < n { + buf = make([]byte, n) + } else { + buf = buf[:n] + } + copy(buf, frame.Pix[:n]) + frame.Pix = buf + return frame +} + +// recycle returns a pixel buffer to the pool for reuse by the decoder +// goroutine. +func (d *decoderPlayback) recycle(pix []byte) { + if pix == nil { + return + } + select { + case d.pool <- pix: + default: + } +} + +// start makes the decoder return its first frame at the request's time. +func (d *decoderPlayback) start(req decodeRequest) (time.Duration, error) { + if req.rewind || d.seeker == nil { + return 0, d.src.Rewind() + } + return d.seeker.Seek(req.to) +} + +// deliver hands the UI thread a message, unless the player closed first. +func (d *decoderPlayback) deliver(msg decoded) { + select { + case <-d.stop: + case d.out <- msg: + d.woken() + } +} + +// woken asks for a paint: a frame, or an error, is there. +func (d *decoderPlayback) woken() { + if d.wake != nil { + d.wake() + } +} + +// request makes the decoder start at a request, replacing one it has not +// taken yet. It never blocks the UI thread. +func (d *decoderPlayback) request(req decodeRequest) { + for { + select { + case <-d.cmd: + default: + select { + case d.cmd <- req: + default: + } + return + } + } +} + +// pump takes what the decoder made since the last look. +func (d *decoderPlayback) pump() { + for { + select { + case msg := <-d.out: + if msg.gen != d.gen { + d.recycle(msg.frame.Pix) + continue + } + if msg.err != nil { + d.recycle(msg.frame.Pix) + d.fail(msg.err, msg.at) + continue + } + d.queue = append(d.queue, msg) + default: + return + } + } +} + +// fail records the end of the animation, or the error that stopped it. +func (d *decoderPlayback) fail(err error, at time.Duration) { + if err != io.EOF { + d.err = err + d.state = Failed + d.playing = false + d.waiting = false + return + } + d.end = at + if at > 0 { + d.total, d.endKnown = at, true + } + if !d.have && len(d.queue) == 0 && !d.endKnown { + // An animation of no frames. + d.state = Ended + d.playing = false + } +} + +// advance shows the frame the clock is in, and ends or loops the animation. +// It reports whether the shown picture changed. now is the canvas time. +func (d *decoderPlayback) advance(now time.Duration) bool { + d.pump() + d.lastNow = now + if d.playing && d.resync { + d.playAt, d.playPos = now, d.pos + d.resync = false + } + changed := d.show(d.current(now)) + if d.playing && d.resync { + // A landed frame put the video where a seek or a loop start asked; the + // clock starts there, not where it was before the frame arrived. + d.playAt, d.playPos = now, d.pos + d.resync = false + } + if d.playing && d.endKnown && d.current(now) >= d.end { + d.finish() + } + return changed +} + +// current is the time the video is at, now: the shown frame's start while it +// pauses, and the playing clock's time as it plays. +func (d *decoderPlayback) current(now time.Duration) time.Duration { + if !d.playing { + return d.pos + } + current := d.playPos + if elapsed := now - d.playAt; elapsed > 0 && d.rate > 0 { + current += time.Duration(float64(elapsed) * d.rate) + } + return current +} + +// show shows every frame due by current. A landed frame shows whatever the +// clock says: it is where the seek put the video. +func (d *decoderPlayback) show(current time.Duration) bool { + changed := false + for len(d.queue) > 0 { + msg := d.queue[0] + if !msg.landed && msg.at > current { + break + } + d.queue = d.queue[1:] + if d.have { + d.recycle(d.cur.Pix) + } + d.cur = msg.frame + d.have = true + d.pos = msg.at + changed = true + if d.state == Loading { + d.state = Ready + } + if msg.landed { + d.waiting = false + if d.playing { + d.resync = true + } + } + } + return changed +} + +// finish ends the animation, or starts it over when it loops. +func (d *decoderPlayback) finish() { + if d.loop { + d.gen++ + d.clearQueue() + d.waiting = true + d.pos = 0 + d.resync = true + d.request(decodeRequest{rewind: true, gen: d.gen}) + return + } + d.playing = false + d.state = Ended + d.pos = d.end +} + +func (d *decoderPlayback) clearQueue() { + for i := range d.queue { + d.recycle(d.queue[i].frame.Pix) + d.queue[i] = decoded{} + } + d.queue = d.queue[:0] +} + +// pace says when the view should paint again, and whether it should: while +// the decoder owes a frame, and when the next frame is due. +func (d *decoderPlayback) pace(now time.Duration) (time.Duration, bool) { + if d.waiting || d.state == Loading || d.state == Buffering { + return pollInterval, true + } + if !d.playing || d.state == Ended || d.state == Failed { + return 0, false + } + if len(d.queue) == 0 { + return pollInterval, true + } + delay := d.queue[0].at - d.current(now) + if d.rate > 0 { + delay = time.Duration(float64(delay) / d.rate) + } + if delay < pollInterval { + delay = pollInterval + } + return delay, true +} + +func (d *decoderPlayback) play() { + if d.state == Ended { + // Play starts an ended animation over from its start. + d.gen++ + d.waiting = true + d.pos = 0 + d.state = Ready + d.request(decodeRequest{rewind: true, gen: d.gen}) + } + d.playing = true + d.resync = true +} + +func (d *decoderPlayback) pause() { d.playing = false } + +func (d *decoderPlayback) setRate(rate float64) { + d.rate = rate + d.resync = true +} + +// seek starts the animation at to. A decoder that cannot seek keeps playing. +func (d *decoderPlayback) seek(to time.Duration) { + if d.seeker == nil { + return + } + d.gen++ + d.clearQueue() + d.waiting = true + d.pos = to + d.resync = d.playing + d.request(decodeRequest{to: to, gen: d.gen}) +} + +func (d *decoderPlayback) position() time.Duration { + if !d.playing || d.resync { + return d.pos + } + current := d.current(d.lastNow) + if d.endKnown && current > d.end { + current = d.end + } + return current +} + +func (d *decoderPlayback) duration() time.Duration { + if !d.endKnown { + return 0 + } + return d.total +} + +func (d *decoderPlayback) size() (w, h int) { + if !d.have { + return 0, 0 + } + return d.cur.Width, d.cur.Height +} + +func (d *decoderPlayback) close() { + close(d.stop) + <-d.done +} diff --git a/ui/video/fit.go b/ui/video/fit.go new file mode 100644 index 000000000..58e12707d --- /dev/null +++ b/ui/video/fit.go @@ -0,0 +1,35 @@ +package video + +import "github.com/vivaui/viva/gfx" + +// Fit is how a view sizes a video's picture in its box. +type Fit uint8 + +const ( + // Contain shows the whole picture inside the box, centered, with its + // proportions kept. It is the default. + Contain Fit = iota + // Cover fills the box with the picture, centered, with its proportions + // kept: the parts outside the box are cut. + Cover + // Fill stretches the picture to the box, whatever its proportions. + Fill +) + +// fitRect is where a picture of width by height pixels is drawn in box for +// the fit. A fit that keeps the proportions gives the picture more room than +// the box where the fit is Cover; the view then clips it to the box. +func fitRect(fit Fit, box gfx.Rect, width, height int) gfx.Rect { + if width <= 0 || height <= 0 || box.Width <= 0 || box.Height <= 0 { + return gfx.Rect{} + } + if fit == Fill { + return box + } + scale := box.Width / float32(width) + if stretch := box.Height / float32(height); (fit == Cover) == (stretch > scale) { + scale = stretch + } + w, h := float32(width)*scale, float32(height)*scale + return gfx.Rect{X: box.X + (box.Width-w)/2, Y: box.Y + (box.Height-h)/2, Width: w, Height: h} +} diff --git a/ui/video/fit_test.go b/ui/video/fit_test.go new file mode 100644 index 000000000..7fcce7b67 --- /dev/null +++ b/ui/video/fit_test.go @@ -0,0 +1,46 @@ +package video + +import ( + "testing" + + "github.com/vivaui/viva/gfx" +) + +func TestFitRect(t *testing.T) { + box := gfx.Rect{X: 10, Y: 20, Width: 100, Height: 100} + // A 2:1 picture in a square box. + if got := fitRect(Contain, box, 200, 100); got != (gfx.Rect{X: 10, Y: 45, Width: 100, Height: 50}) { + t.Fatalf("Contain = %+v", got) + } + if got := fitRect(Cover, box, 200, 100); got != (gfx.Rect{X: -40, Y: 20, Width: 200, Height: 100}) { + t.Fatalf("Cover = %+v", got) + } + if got := fitRect(Fill, box, 200, 100); got != box { + t.Fatalf("Fill = %+v", got) + } + // A 1:2 picture narrower than the box. + tall := gfx.Rect{X: 0, Y: 0, Width: 200, Height: 50} + if got := fitRect(Contain, tall, 100, 200); got != (gfx.Rect{X: 87.5, Width: 25, Height: 50}) { + t.Fatalf("Contain tall = %+v", got) + } + if got := fitRect(Cover, tall, 100, 200); got != (gfx.Rect{Y: -175, Width: 200, Height: 400}) { + t.Fatalf("Cover tall = %+v", got) + } +} + +func TestFitRectOfNothingIsEmpty(t *testing.T) { + for _, test := range []struct { + box gfx.Rect + width int + height int + }{ + {gfx.Rect{Width: 10, Height: 10}, 0, 10}, + {gfx.Rect{Width: 10, Height: 10}, 10, 0}, + {gfx.Rect{}, 10, 10}, + {gfx.Rect{Width: -1, Height: 10}, 10, 10}, + } { + if got := fitRect(Contain, test.box, test.width, test.height); got != (gfx.Rect{}) { + t.Fatalf("fitRect(%+v, %d, %d) = %+v, want empty", test.box, test.width, test.height, got) + } + } +} diff --git a/ui/video/gif.go b/ui/video/gif.go new file mode 100644 index 000000000..99530d095 --- /dev/null +++ b/ui/video/gif.go @@ -0,0 +1,415 @@ +package video + +import ( + "bytes" + "encoding/binary" + "errors" + "image" + "image/gif" + "io" + "time" +) + +// gifDecoder shows an animated GIF. Every frame is drawn over the one before +// it, or over whatever that frame's disposal left, into a single picture +// that holds the bytes of the frame as it stands. +type gifDecoder struct { + g *gif.GIF + delays []time.Duration + next int + + width, height, stride int + picture []byte // the composed frame, premultiplied BGRA + before []byte // the picture before the current frame drew + hasBefore bool // before holds that picture + colors [256][4]byte +} + +// NewGIFDecoder returns a decoder of an animated GIF's frames, for +// NewDecoder, as browsers show them: a frame of 10 ms or less shows for +// 100 ms. The GIF decodes into memory at once, its frames' pixels a byte +// each, and each frame is composed as it plays. A GIF that ends early, with +// no trailer or cut off in a frame, plays the frames it has whole, and a +// pixel past its frame's colors is black. The player's SetLoop, not the +// GIF's loop count, says whether it plays again. A GIF whose frames and +// pictures would need more than maxDecoderBytes is an error, and its picture +// is made when the first frame is asked for, not when the GIF opens. +func NewGIFDecoder(data []byte) (Decoder, error) { + framePixels, pictureW, pictureH, err := checkGIFDimensions(data) + if err != nil { + return nil, err + } + // The picture is the logical screen, or the frames' bounds when the GIF + // names none. Check the budget before image/gif decodes and keeps every + // frame, so a small file cannot allocate its frames before being refused. + if pictureBytes(int(pictureW), int(pictureH))+framePixels > maxDecoderBytes { + return nil, errors.New("video: a GIF whose frames and pictures need too much memory") + } + g, err := decodeGIF(data) + if err != nil { + return nil, err + } + w, h := g.Config.Width, g.Config.Height + if w <= 0 || h <= 0 { + // No logical screen: the frames' bounds are the picture's. + for _, f := range g.Image { + if m := f.Bounds().Max.X; m > w { + w = m + } + if m := f.Bounds().Max.Y; m > h { + h = m + } + } + } + if w <= 0 || h <= 0 || uint64(w)*uint64(h) > maxDecoderPixels { + return nil, errors.New("video: a GIF of an invalid size") + } + if pictureBytes(w, h)+framePixels > maxDecoderBytes { + return nil, errors.New("video: a GIF whose frames and pictures need too much memory") + } + d := &gifDecoder{g: g, width: w, height: h, stride: 4 * w} + d.delays = make([]time.Duration, len(g.Image)) + for i := range d.delays { + d.delays[i] = gifFrameDelay(g, i) + } + return d, nil +} + +// checkGIFDimensions rejects GIFs whose logical screen or frame descriptors +// exceed maxDecoderPixels before image/gif allocates frame buffers, and +// reports how many pixels the frames it names take once decoded, and the +// bounds of the picture they compose. +func checkGIFDimensions(data []byte) (framePixels, width, height uint64, err error) { + const headerAndScreen = 13 + if len(data) < headerAndScreen || (!bytes.HasPrefix(data, []byte("GIF87a")) && !bytes.HasPrefix(data, []byte("GIF89a"))) { + return 0, 0, 0, nil + } + width = uint64(binary.LittleEndian.Uint16(data[6:8])) + height = uint64(binary.LittleEndian.Uint16(data[8:10])) + if width*height > maxDecoderPixels { + return 0, 0, 0, errors.New("video: a GIF of an invalid size") + } + off := headerAndScreen + if data[10]&0x80 != 0 { + off += 3 << (data[10]&7 + 1) + } + var maxRight, maxBottom uint64 + for off < len(data) { + switch data[off] { + case 0x21: + if off+2 > len(data) { + return framePixels, width, height, nil + } + end, ok := skipSubBlocks(data, off+2) + if !ok { + return framePixels, width, height, nil + } + off = end + case 0x2c: + if off+10 > len(data) { + return framePixels, width, height, nil + } + left := uint64(binary.LittleEndian.Uint16(data[off+1 : off+3])) + top := uint64(binary.LittleEndian.Uint16(data[off+3 : off+5])) + fw := uint64(binary.LittleEndian.Uint16(data[off+5 : off+7])) + fh := uint64(binary.LittleEndian.Uint16(data[off+7 : off+9])) + if fw*fh > maxDecoderPixels { + return 0, 0, 0, errors.New("video: a GIF of an invalid size") + } + framePixels += fw * fh + if right := left + fw; right > maxRight { + maxRight = right + } + if bottom := top + fh; bottom > maxBottom { + maxBottom = bottom + } + flags := data[off+9] + off += 10 + if flags&0x80 != 0 { + off += 3 << (flags&7 + 1) + } + if off >= len(data) { + return framePixels, width, height, nil + } + end, ok := skipSubBlocks(data, off+1) + if !ok { + return framePixels, width, height, nil + } + off = end + default: + return framePixels, width, height, nil + } + } + // A GIF of no logical screen is as big as the frames it holds. + if width == 0 { + width = maxRight + } + if height == 0 { + height = maxBottom + } + return framePixels, width, height, nil +} + +// decodeGIF decodes a GIF, from the part of the file that is whole when the +// file as it is does not decode. +func decodeGIF(data []byte) (*gif.GIF, error) { + g, err := gif.DecodeAll(bytes.NewReader(data)) + if err == nil { + return g, nil + } + whole := salvageGIF(data) + if whole == nil { + return nil, err + } + return gif.DecodeAll(bytes.NewReader(whole)) +} + +// salvageGIF rebuilds a GIF from the part of it that is whole, for a file +// that ends early or whose pixels point past its colors. Every color table +// is widened to its full 256 entries, black where the file named no color, +// so the pixels a short table cannot name read black rather than failing the +// decode, as Chrome draws them. What comes back is the last complete frame +// and the trailer; nil says that no frame is complete. +func salvageGIF(data []byte) []byte { + const headerAndScreen = 13 + if len(data) < headerAndScreen { + return nil + } + out := append([]byte(nil), data[:headerAndScreen]...) + off := headerAndScreen + if out[10]&0x80 != 0 { // a global color table follows + var ok bool + if off, ok = widenColorTable(&out, data, off, 10); !ok { + return nil + } + } + lastFrame := -1 + for off < len(data) { + switch data[off] { + case 0x21: // an extension: its label, then data sub-blocks + if off+2 > len(data) { + off = len(data) + continue + } + end, ok := skipSubBlocks(data, off+2) + if !ok { + off = len(data) + continue + } + out = append(out, data[off:end]...) + off = end + case 0x2c: // a frame: descriptor, color table, code size, sub-blocks + if off+10 > len(data) { + off = len(data) + continue + } + out = append(out, data[off:off+10]...) + next, flags := off+10, len(out)-1 + if out[flags]&0x80 != 0 { // a local color table follows + var ok bool + if next, ok = widenColorTable(&out, data, next, flags); !ok { + off = len(data) + continue + } + } + if next >= len(data) { + off = len(data) + continue + } + end, ok := skipSubBlocks(data, next+1) // past the minimum code size + if !ok { + off = len(data) + continue + } + out = append(out, data[next:end]...) + off = end + lastFrame = len(out) + default: // the trailer, or bytes that are no GIF: stop here + off = len(data) + } + } + if lastFrame < 0 { + return nil + } + return append(out[:lastFrame:lastFrame], 0x3b) +} + +// widenColorTable copies the color table at off, whose size bits are in the +// byte at flags, padding it to 256 colors of black. It returns where the +// table ended in data. +func widenColorTable(out *[]byte, data []byte, off, flags int) (int, bool) { + bytes := 3 << ((*out)[flags]&7 + 1) + if off+bytes > len(data) { + return 0, false + } + (*out)[flags] |= 7 + *out = append(*out, data[off:off+bytes]...) + *out = append(*out, make([]byte, 3*256-bytes)...) + return off + bytes, true +} + +// skipSubBlocks returns the offset just past the empty sub-block that ends +// the chain beginning at off, or false when the data ends inside it. +func skipSubBlocks(data []byte, off int) (int, bool) { + for off < len(data) { + n := int(data[off]) + off++ + if n == 0 { + return off, true + } + off += n + } + return 0, false +} + +func (d *gifDecoder) Next() (Frame, error) { + if d.next >= len(d.g.Image) { + return Frame{}, io.EOF + } + d.advance() + return Frame{ + Pix: d.picture, + Width: d.width, + Height: d.height, + Stride: d.stride, + Duration: d.delays[d.next-1], + }, nil +} + +// advance undoes the frame before the next as its disposal says, then draws +// the next over the picture. +func (d *gifDecoder) advance() { + i := d.next + d.ensurePicture() + if i > 0 { + d.undo(i - 1) + } + d.hasBefore = d.disposal(i) == gif.DisposalPrevious + if d.hasBefore { + d.ensureBefore() + copy(d.before, d.picture) + } + d.paint(d.g.Image[i]) + d.next++ +} + +// ensurePicture makes the composed picture, when the first frame needs it. +func (d *gifDecoder) ensurePicture() { + if d.picture == nil { + d.picture = make([]byte, d.stride*d.height) + } +} + +// ensureBefore makes the copy a DisposalPrevious frame restores, when a frame +// whose disposal asks for it is drawn. +func (d *gifDecoder) ensureBefore() { + d.ensurePicture() + if d.before == nil { + d.before = make([]byte, len(d.picture)) + } +} + +// disposal is how frame i goes before the next draws. +func (d *gifDecoder) disposal(i int) byte { + if i < len(d.g.Disposal) { + return d.g.Disposal[i] + } + return 0 +} + +// undo takes frame i back as its disposal says: it clears the frame's +// rectangle (DisposalBackground, to transparent rather than the background +// color, as browsers clear it), restores what was under it +// (DisposalPrevious), or leaves it. +func (d *gifDecoder) undo(i int) { + switch d.disposal(i) { + case gif.DisposalBackground: + d.clear(d.g.Image[i].Bounds()) + case gif.DisposalPrevious: + if d.hasBefore { + copy(d.picture, d.before) + } + } +} + +// clear makes a rectangle of the picture transparent. +func (d *gifDecoder) clear(r image.Rectangle) { + r = r.Intersect(image.Rect(0, 0, d.width, d.height)) + for y := r.Min.Y; y < r.Max.Y; y++ { + clear(d.picture[y*d.stride+r.Min.X*4 : y*d.stride+r.Max.X*4]) + } +} + +// paint draws a frame over the picture at its place. Its colors are written +// out premultiplied in BGRA, and a transparent pixel leaves what is under it. +func (d *gifDecoder) paint(f *image.Paletted) { + for i := range d.colors { + d.colors[i] = [4]byte{} + } + for i, c := range f.Palette { + if i == len(d.colors) { + break + } + r, g, b, a := c.RGBA() // premultiplied + d.colors[i] = [4]byte{byte(b >> 8), byte(g >> 8), byte(r >> 8), byte(a >> 8)} + } + r := f.Bounds().Intersect(image.Rect(0, 0, d.width, d.height)) + for y := r.Min.Y; y < r.Max.Y; y++ { + row := f.Pix[f.PixOffset(r.Min.X, y):f.PixOffset(r.Max.X, y)] + out := d.picture[y*d.stride+r.Min.X*4:] + for x, i := range row { + c := d.colors[i] + if c[3] == 0 { + continue + } + copy(out[x*4:x*4+4], c[:]) + } + } +} + +func (d *gifDecoder) Rewind() error { + d.reset() + return nil +} + +// reset takes the picture back to its state before the first frame. +func (d *gifDecoder) reset() { + d.next = 0 + d.hasBefore = false + clear(d.picture) + clear(d.before) +} + +// Seek starts the animation at to, composing the frames before the one that +// shows then. It returns when that frame starts. +func (d *gifDecoder) Seek(to time.Duration) (time.Duration, error) { + if to < 0 { + to = 0 + } + d.reset() + var start time.Duration + for d.next+1 < len(d.delays) && start+d.delays[d.next] <= to { + start += d.delays[d.next] + d.advance() + } + return start, nil +} + +// Duration is the length of the animation, for the player's Duration. +func (d *gifDecoder) Duration() time.Duration { + var total time.Duration + for _, delay := range d.delays { + total += delay + } + return total +} + +// gifFrameDelay is how long frame i shows. A GIF counts delays in hundredths +// of a second; a frame of a hundredth or less shows for a tenth instead, as +// browsers show it, so that no GIF flashes through its frames. +func gifFrameDelay(g *gif.GIF, i int) time.Duration { + if i < len(g.Delay) && g.Delay[i] > 1 { + return time.Duration(g.Delay[i]) * 10 * time.Millisecond + } + return 100 * time.Millisecond +} diff --git a/ui/video/gif_test.go b/ui/video/gif_test.go new file mode 100644 index 000000000..c3d27b6f2 --- /dev/null +++ b/ui/video/gif_test.go @@ -0,0 +1,320 @@ +package video + +import ( + "bytes" + "compress/lzw" + "image" + "image/color" + "image/gif" + "io" + "runtime" + "testing" + "time" +) + +var ( + gifRed = color.RGBA{255, 0, 0, 255} + gifGreen = color.RGBA{0, 255, 0, 255} + gifBlue = color.RGBA{0, 0, 255, 255} + gifWhite = color.RGBA{255, 255, 255, 255} +) + +// solidGIF returns a GIF of 4×4 frames of solid colors, each showing for +// delay hundredths of a second. +func solidGIF(t *testing.T, delay int, colors ...color.RGBA) []byte { + t.Helper() + g := &gif.GIF{Config: image.Config{Width: 4, Height: 4}} + for _, c := range colors { + f := image.NewPaletted(image.Rect(0, 0, 4, 4), color.Palette{c}) + g.Image = append(g.Image, f) + g.Delay = append(g.Delay, delay) + g.Disposal = append(g.Disposal, gif.DisposalNone) + } + var b bytes.Buffer + if err := gif.EncodeAll(&b, g); err != nil { + t.Fatal(err) + } + return b.Bytes() +} + +// framePixel reads a frame's pixel, its BGRA bytes back as a color. +func framePixel(f Frame, x, y int) color.RGBA { + i := y*f.Stride + x*4 + return color.RGBA{R: f.Pix[i+2], G: f.Pix[i+1], B: f.Pix[i], A: f.Pix[i+3]} +} + +// TestGIFDecoderFrames checks that a GIF's frames draw over what the ones +// before left as their disposal says, with their transparent pixels showing +// what is under them, for as long as their delays say, and that the decoder +// starts over after Rewind. +func TestGIFDecoderFrames(t *testing.T) { + transparent := color.RGBA{} + full := image.NewPaletted(image.Rect(0, 0, 4, 4), color.Palette{gifRed}) + // Green over the top left, but for a transparent pixel at 1,1. + corner := image.NewPaletted(image.Rect(0, 0, 2, 2), color.Palette{gifGreen, transparent}) + corner.SetColorIndex(1, 1, 1) + low := image.NewPaletted(image.Rect(2, 2, 4, 4), color.Palette{gifBlue}) + dot := image.NewPaletted(image.Rect(3, 0, 4, 1), color.Palette{gifWhite}) + g := &gif.GIF{ + Config: image.Config{Width: 4, Height: 4}, + Image: []*image.Paletted{full, corner, low, dot}, + Delay: []int{0, 5, 20, 1}, + Disposal: []byte{gif.DisposalNone, gif.DisposalBackground, gif.DisposalPrevious, gif.DisposalNone}, + } + var b bytes.Buffer + if err := gif.EncodeAll(&b, g); err != nil { + t.Fatal(err) + } + d, err := NewGIFDecoder(b.Bytes()) + if err != nil { + t.Fatal(err) + } + type px struct { + x, y int + c color.RGBA + } + frames := []struct { + d time.Duration + want []px + }{ + {100 * time.Millisecond, []px{{0, 0, gifRed}, {3, 3, gifRed}}}, + {50 * time.Millisecond, []px{{0, 0, gifGreen}, {1, 1, gifRed}, {3, 3, gifRed}}}, + // The green corner went, leaving nothing; blue covers the bottom + // right. + {200 * time.Millisecond, []px{{0, 0, transparent}, {1, 1, transparent}, {3, 3, gifBlue}, {3, 0, gifRed}}}, + // The blue went back to what was under it. + {100 * time.Millisecond, []px{{3, 0, gifWhite}, {3, 3, gifRed}, {0, 0, transparent}}}, + } + check := func(round int) { + for i, want := range frames { + f, err := d.Next() + if err != nil { + t.Fatalf("round %d, frame %d: %v", round, i, err) + } + if f.Duration != want.d { + t.Errorf("round %d, frame %d shows for %v, want %v", round, i, f.Duration, want.d) + } + for _, p := range want.want { + if got := framePixel(f, p.x, p.y); got != p.c { + t.Errorf("round %d, frame %d at %d,%d: %v, want %v", round, i, p.x, p.y, got, p.c) + } + } + } + if _, err := d.Next(); err != io.EOF { + t.Errorf("round %d: after the last frame, %v", round, err) + } + } + check(1) + if err := d.Rewind(); err != nil { + t.Fatal(err) + } + check(2) + + if _, err := NewGIFDecoder([]byte("GIF89a, not quite")); err == nil { + t.Error("data that is no GIF decoded") + } +} + +// TestGIFSeek checks that a seek starts at the frame showing then, composed +// over the frames before it, and that the decoder knows the animation's +// length. +func TestGIFSeek(t *testing.T) { + d, err := NewGIFDecoder(solidGIF(t, 10, gifRed, gifGreen, gifBlue)) + if err != nil { + t.Fatal(err) + } + seeker, ok := d.(Seeker) + if !ok { + t.Fatal("the GIF decoder does not seek") + } + reader, ok := d.(durationReader) + if !ok { + t.Fatal("the GIF decoder does not know its duration") + } + if got := reader.Duration(); got != 300*time.Millisecond { + t.Fatalf("Duration = %v, want 300ms", got) + } + + for _, test := range []struct { + to time.Duration + start time.Duration + want color.RGBA + }{ + {0, 0, gifRed}, + {150 * time.Millisecond, 100 * time.Millisecond, gifGreen}, + {250 * time.Millisecond, 200 * time.Millisecond, gifBlue}, + {time.Hour, 200 * time.Millisecond, gifBlue}, + {-time.Second, 0, gifRed}, + } { + start, err := seeker.Seek(test.to) + if err != nil { + t.Fatalf("Seek(%v): %v", test.to, err) + } + if start != test.start { + t.Fatalf("Seek(%v) starts at %v, want %v", test.to, start, test.start) + } + f, err := d.Next() + if err != nil { + t.Fatalf("Seek(%v): %v", test.to, err) + } + if got := framePixel(f, 1, 1); got != test.want { + t.Fatalf("Seek(%v) shows %v, want %v", test.to, got, test.want) + } + } +} + +// TestGIFDecoderEndsEarly checks that a GIF that ends early, with no trailer +// or cut off in a frame, plays the frames it has whole, as browsers do, and +// that one with no whole frame is an error. +func TestGIFDecoderEndsEarly(t *testing.T) { + data := solidGIF(t, 10, gifRed, gifGreen, gifBlue) + for _, tc := range []struct { + name string + data []byte + want []color.RGBA + }{ + {"no trailer", data[:len(data)-1], []color.RGBA{gifRed, gifGreen, gifBlue}}, + // Without the last frame's block terminator and a byte of its + // pixels. + {"cut off in the last frame", data[:len(data)-3], []color.RGBA{gifRed, gifGreen}}, + } { + d, err := NewGIFDecoder(tc.data) + if err != nil { + t.Errorf("%s: %v", tc.name, err) + continue + } + for i, want := range tc.want { + f, err := d.Next() + if err != nil { + t.Fatalf("%s, frame %d: %v", tc.name, i, err) + } + if got := framePixel(f, 1, 1); got != want { + t.Errorf("%s, frame %d: %v, want %v", tc.name, i, got, want) + } + } + if _, err := d.Next(); err != io.EOF { + t.Errorf("%s: after %d frames, %v", tc.name, len(tc.want), err) + } + } + if _, err := NewGIFDecoder(data[:40]); err == nil { + t.Error("a GIF cut off in its first frame decoded") + } +} + +// TestGIFDecoderPixelsPastColors checks that a GIF whose pixels point past +// its color table plays, those pixels black, as Chrome draws them, where +// image/gif decodes none of it. +func TestGIFDecoderPixelsPastColors(t *testing.T) { + // A 2×2 frame of pixels 0 to 3, its color table red and green. + var px bytes.Buffer + w := lzw.NewWriter(&px, lzw.LSB, 2) + w.Write([]byte{0, 1, 2, 3}) + w.Close() + frame := func(table []byte) []byte { + b := []byte{0x2c, 0, 0, 0, 0, 2, 0, 2, 0, 0} + if table != nil { + b[9] = 0x80 + b = append(b, table...) + } + b = append(b, 2, byte(px.Len())) + b = append(b, px.Bytes()...) + return append(b, 0) + } + colors := []byte{255, 0, 0, 0, 255, 0} + screen := []byte("GIF89a\x02\x00\x02\x00\x00\x00\x00") + global := append(append([]byte{}, screen...), colors...) + global[10] = 0x80 + black := color.RGBA{0, 0, 0, 255} + for _, tc := range []struct { + name string + data []byte + }{ + {"global color table", append(append(global, frame(nil)...), 0x3b)}, + {"local color table", append(append(append([]byte{}, screen...), frame(colors)...), 0x3b)}, + } { + d, err := NewGIFDecoder(tc.data) + if err != nil { + t.Errorf("%s: %v", tc.name, err) + continue + } + f, err := d.Next() + if err != nil { + t.Fatalf("%s: %v", tc.name, err) + } + for i, want := range []color.RGBA{gifRed, gifGreen, black, black} { + if got := framePixel(f, i%2, i/2); got != want { + t.Errorf("%s: pixel %d is %v, want %v", tc.name, i, got, want) + } + } + } +} + +// TestGIFDecoderDimensions rejects GIFs whose logical screen or frame exceeds +// the pixel cap before allocating frame buffers. +func TestGIFDecoderDimensions(t *testing.T) { + // 65535×65535 logical screen header. + hugeScreen := []byte("GIF89a\xff\xff\xff\xff\x00\x00\x00\x3b") + if _, err := NewGIFDecoder(hugeScreen); err == nil { + t.Fatal("oversized GIF screen decoded") + } + // Small logical screen with a 65535×65535 frame descriptor. + hugeFrame := []byte{ + 'G', 'I', 'F', '8', '9', 'a', + 1, 0, 1, 0, 0, 0, 0, + 0x2c, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, + 2, 0, 0x3b, + } + if _, err := NewGIFDecoder(hugeFrame); err == nil { + t.Fatal("oversized GIF frame decoded") + } +} + +// TestGIFDecoderRejectsAnAnimationOverBudget checks that a header naming more +// picture memory than the decoder budget is an error, however small the file +// and its frames are. +func TestGIFDecoderRejectsAnAnimationOverBudget(t *testing.T) { + g := &gif.GIF{Config: image.Config{Width: 8192, Height: 8192}} + f := image.NewPaletted(image.Rect(0, 0, 1, 1), color.Palette{color.Black}) + g.Image = []*image.Paletted{f} + g.Delay = []int{10} + g.Disposal = []byte{gif.DisposalNone} + var b bytes.Buffer + if err := gif.EncodeAll(&b, g); err != nil { + t.Fatal(err) + } + if b.Len() > 1<<10 { + t.Fatalf("the test GIF is %d bytes, want a tiny file", b.Len()) + } + if _, err := NewGIFDecoder(b.Bytes()); err == nil { + t.Fatal("a GIF whose declared picture needs 512 MB decoded") + } +} + +// TestGIFDecoderDoesNotAllocateTheDeclaredCanvas checks that opening a GIF +// whose screen is larger than its payload does not make the composed picture +// up front: a 43-byte 4096×4096 GIF must not allocate the 128 MB those +// pictures take until a frame is asked for. +func TestGIFDecoderDoesNotAllocateTheDeclaredCanvas(t *testing.T) { + g := &gif.GIF{Config: image.Config{Width: 4096, Height: 4096}} + f := image.NewPaletted(image.Rect(0, 0, 1, 1), color.Palette{color.Black}) + g.Image = []*image.Paletted{f} + g.Delay = []int{10} + g.Disposal = []byte{gif.DisposalNone} + var b bytes.Buffer + if err := gif.EncodeAll(&b, g); err != nil { + t.Fatal(err) + } + var before, after runtime.MemStats + runtime.ReadMemStats(&before) + d, err := NewGIFDecoder(b.Bytes()) + runtime.ReadMemStats(&after) + if err != nil { + t.Fatalf("NewGIFDecoder: %v", err) + } + if d == nil { + t.Fatal("NewGIFDecoder returned no decoder") + } + if alloc := after.TotalAlloc - before.TotalAlloc; alloc > 16<<20 { + t.Fatalf("NewGIFDecoder allocated %d bytes for a %d-byte GIF with a 4096×4096 screen", alloc, b.Len()) + } +} diff --git a/ui/video/player.go b/ui/video/player.go new file mode 100644 index 000000000..9a9b010a7 --- /dev/null +++ b/ui/video/player.go @@ -0,0 +1,443 @@ +package video + +import ( + "sync/atomic" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/media" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/window" +) + +// State is where a player is in loading and playing its video. +type State uint8 + +const ( + // Loading is the video opening, before its first picture. + Loading State = iota + // Ready is playing, or paused and able to play. + Ready + // Buffering is playing, but waiting for data. + Buffering + // Ended is the video played to its end. + Ended + // Failed is the video stopped by an error, which Err reports. + Failed +) + +// invalidator wakes the page's window when a picture arrives from a thread +// that is not the UI thread. +type invalidator struct { + page *ui.Page + wake window.Invalidator +} + +// bitmapIDs names the bitmaps of every player, so two players' pictures do +// not share a name in the renderer's caches. +var bitmapIDs atomic.Uint64 + +// Player plays one video, and shows it through View. Its methods are called +// on the UI thread; a player is not copied after it has been shown. +type Player struct { + engine media.Engine + dec *decoderPlayback + + inv atomic.Pointer[invalidator] + wake func() + + handlers ui.Handlers + drawFn func(*ui.DrawContext) + prepared bool + + fit Fit + rate float64 + closed bool + + // texture is the engine's picture, with the version of its contents. + texture gfx.NativeTexture + textureVersion uint32 + // bitmap is the picture of a decoder, copied from its frames. + bitmap gfx.Bitmap + bitmapVersion uint32 +} + +func newPlayer() *Player { + p := &Player{rate: 1} + p.wake = p.invalidate + return p +} + +func newEnginePlayer(engine media.Engine) *Player { + p := newPlayer() + p.engine = engine + return p +} + +// NewDecoder returns a player of a decoder's frames, such as a GIF's. It +// plays on every system, decoded in Go. The player uses the decoder until +// Close. +func NewDecoder(d Decoder) *Player { + if d == nil { + panic("video: NewDecoder needs a decoder") + } + p := newPlayer() + p.dec = newDecoderPlayback(d, p.wake) + return p +} + +// Play starts the video, or starts it again after its end. +func (p *Player) Play() { + if p.closed { + return + } + if p.dec != nil { + p.dec.play() + } else if p.engine != nil { + p.engine.Play() + } + p.invalidate() +} + +// Pause stops the video where it is. +func (p *Player) Pause() { + if p.closed { + return + } + if p.dec != nil { + p.dec.pause() + } else if p.engine != nil { + p.engine.Pause() + } + p.invalidate() +} + +// Playing reports whether the video is playing: not paused, and not ended. +func (p *Player) Playing() bool { + if p.closed { + return false + } + if p.dec != nil { + return p.dec.playing + } + if p.engine != nil { + if state := playerState(p.engine); state == Ended || state == Failed { + return false + } + return p.engine.Playing() + } + return false +} + +// Seek starts the video at d, the nearest frame before it. A decoder that +// cannot seek plays from its start, and Seek does nothing. The position +// reads d until the frame there shows, as with most players. +func (p *Player) Seek(d time.Duration) { + if p.closed { + return + } + if d < 0 { + d = 0 + } + if p.dec != nil { + p.dec.seek(d) + } else if p.engine != nil { + p.engine.Seek(d) + } + p.invalidate() +} + +// Position is where the video is: the start of the picture shown, while it +// pauses, and the time the next frame is due as it plays. +func (p *Player) Position() time.Duration { + if p.closed { + return 0 + } + if p.dec != nil { + return p.dec.position() + } + if p.engine != nil { + return p.engine.Position() + } + return 0 +} + +// Duration is the video's length, or 0 while it is not known: before an +// engine's first picture, or a decoder with no frame times of its own. +func (p *Player) Duration() time.Duration { + if p.closed { + return 0 + } + if p.dec != nil { + return p.dec.duration() + } + if p.engine != nil { + return p.engine.Duration() + } + return 0 +} + +// Size is the picture's size in pixels, or 0, 0 before the first one. +func (p *Player) Size() (w, h int) { + if p.closed { + return 0, 0 + } + if p.dec != nil { + return p.dec.size() + } + if p.engine != nil { + return p.engine.Size() + } + return 0, 0 +} + +// State is where the player is in loading and playing the video. +func (p *Player) State() State { + if p.closed { + return Ended + } + if p.dec != nil { + return p.dec.state + } + if p.engine != nil { + return playerState(p.engine) + } + return Loading +} + +// Err is the error the video stopped with, or nil. +func (p *Player) Err() error { + if p.closed { + return nil + } + if p.dec != nil { + return p.dec.err + } + if p.engine != nil { + _, err := p.engine.State() + return err + } + return nil +} + +// SetLoop makes the video play again from its start after its end. It plays +// again on its own, without Play. +func (p *Player) SetLoop(loop bool) { + if p.closed { + return + } + if p.dec != nil { + p.dec.loop = loop + } else if p.engine != nil { + p.engine.SetLoop(loop) + } + p.invalidate() +} + +// SetMuted turns the video's sound off or on. A decoder's frames have no +// sound, and SetMuted does nothing. +func (p *Player) SetMuted(muted bool) { + if p.closed { + return + } + if p.engine != nil { + p.engine.SetMuted(muted) + p.invalidate() + } +} + +// SetVolume sets the video's volume, from 0 to 1. A decoder's frames have no +// sound, and SetVolume does nothing. +func (p *Player) SetVolume(volume float64) { + if p.closed { + return + } + if p.engine != nil { + p.engine.SetVolume(volume) + p.invalidate() + } +} + +// SetRate sets how fast the video plays, 1 being its own speed. A rate of +// zero or less keeps a decoder's animation still; an engine's video decides +// what rates it plays at. +func (p *Player) SetRate(rate float64) { + if p.closed { + return + } + p.rate = rate + if p.dec != nil { + p.dec.setRate(rate) + } else if p.engine != nil { + p.engine.SetRate(rate) + } + p.invalidate() +} + +// Fit chooses how the picture fills the view's box, and returns the player. +func (p *Player) Fit(fit Fit) *Player { + p.fit = fit + p.invalidate() + return p +} + +// Close stops the video and frees what it made: its decoder, its engine and +// the GPU textures the engine shares. It is safe to call more than once. A +// view of a closed player paints nothing. +func (p *Player) Close() error { + if p.closed { + return nil + } + p.closed = true + p.invalidate() + if p.dec != nil { + p.dec.close() + return nil + } + if p.engine != nil { + return p.engine.Close() + } + return nil +} + +// prepare makes the player ready to be shown in c: it learns how to wake the +// page's window, and gives an engine the same way. +func (p *Player) prepare(c ui.C) { + page := c.GetPage() + if inv := p.inv.Load(); inv == nil || inv.page != page { + p.inv.Store(&invalidator{page: page, wake: page.GetInvalidator()}) + } + if !p.prepared { + p.prepared = true + p.handlers.Role = gfx.RoleGroup + p.drawFn = p.draw + } + if p.engine != nil { + // The engine wakes the window from its own threads when its state + // changes; it is told again each paint, in case the page changed. + p.engine.SetWake(p.wake) + } +} + +// invalidate asks for one more paint, from any goroutine: a picture arrived, +// or the player's state changed. +func (p *Player) invalidate() { + inv := p.inv.Load() + if inv == nil || inv.wake == nil { + return + } + inv.wake.Invalidate() +} + +func (p *Player) draw(d *ui.DrawContext) { + if p.closed { + return + } + if p.dec != nil { + p.drawDecoder(d) + return + } + p.drawEngine(d) +} + +// drawEngine draws the engine's picture, opening its texture on the GPU. +func (p *Player) drawEngine(d *ui.DrawContext) { + picture, changed, ok := p.engine.Frame() + if ok && (changed || p.texture.ID != picture.ID || p.texture.Handle != picture.Handle || + p.texture.Width != picture.W || p.texture.Height != picture.H) { + p.textureVersion++ + p.texture = gfx.NativeTexture{ID: picture.ID, Handle: picture.Handle, Width: picture.W, Height: picture.H, Version: p.textureVersion} + } + state := playerState(p.engine) + if p.texture.ID != 0 { + bounds := fitRect(p.fit, d.Rect, p.texture.Width, p.texture.Height) + if p.fit == Cover { + d.Canvas.Clip(d.Rect) + } + d.Canvas.DrawTexture(&p.texture, bounds, 1-d.Opacity) + if p.fit == Cover { + d.Canvas.Unclip() + } + } + if !d.Canvas.HasClock() { + return + } + if state == Ended || state == Failed { + return + } + if p.engine.Playing() { + d.Canvas.RequestFrameIn(frameInterval(p.engine.Interval(), p.rate)) + return + } + if p.texture.ID == 0 { + // The first picture may come with no event to wake the window: look + // again soon, as Media Foundation's samples look every vsync. + d.Canvas.RequestFrameIn(pollInterval) + } +} + +// drawDecoder draws the decoder's frames, one bitmap per picture. +func (p *Player) drawDecoder(d *ui.DrawContext) { + now := d.Canvas.Now() + if p.dec.advance(now) && p.dec.have { + p.copyFrame(p.dec.cur) + } + if p.dec.have && p.bitmap.Width > 0 && p.bitmap.Height > 0 { + bounds := fitRect(p.fit, d.Rect, p.bitmap.Width, p.bitmap.Height) + if p.fit == Cover { + d.Canvas.Clip(d.Rect) + } + source := gfx.Rect{Width: float32(p.bitmap.Width), Height: float32(p.bitmap.Height)} + d.Canvas.DrawBitmapShaded(p.bitmap, source, bounds, 0, 1-d.Opacity) + if p.fit == Cover { + d.Canvas.Unclip() + } + } + if !d.Canvas.HasClock() { + return + } + if delay, ok := p.dec.pace(now); ok { + d.Canvas.RequestFrameIn(delay) + } +} + +// copyFrame copies a decoder frame into the player's bitmap, naming it a new +// picture: the decoder may reuse its buffer for the frame after. +func (p *Player) copyFrame(f Frame) { + if f.Width <= 0 || f.Height <= 0 || f.Stride < f.Width*4 || len(f.Pix) < f.Stride*f.Height { + return + } + if p.bitmap.ID == 0 { + p.bitmap.ID = bitmapIDs.Add(1) + } + p.bitmap.Pix = append(p.bitmap.Pix[:0], f.Pix[:f.Stride*f.Height]...) + p.bitmap.Width, p.bitmap.Height, p.bitmap.Stride = f.Width, f.Height, f.Stride + p.bitmapVersion++ + p.bitmap.Version = p.bitmapVersion +} + +// playerState is the engine's state as the player reports it. +func playerState(engine media.Engine) State { + state, _ := engine.State() + return State(state) +} + +// pollInterval is how soon a view looks again for a picture that comes with +// no event to wake the window. +const pollInterval = 16 * time.Millisecond + +// frameInterval is how long a view waits before looking for another picture +// of an engine: the engine's interval, sooner while the rate is faster than +// its own. +func frameInterval(interval time.Duration, rate float64) time.Duration { + if interval <= 0 { + interval = time.Second / 60 + } + if rate > 1 { + interval = time.Duration(float64(interval) / rate) + } + if interval < time.Millisecond { + interval = time.Millisecond + } + return interval +} diff --git a/ui/video/player_test.go b/ui/video/player_test.go new file mode 100644 index 000000000..3d5be51db --- /dev/null +++ b/ui/video/player_test.go @@ -0,0 +1,473 @@ +package video + +import ( + "io" + "sync/atomic" + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/media" + "github.com/vivaui/viva/ui" +) + +// fakeWake counts the repaints a player asked for, from any goroutine. +type fakeWake struct{ calls atomic.Int64 } + +func (w *fakeWake) Invalidate() { w.calls.Add(1) } + +// harness is a page that shows one player, with a clock the test moves. +type harness struct { + player *Player + page *ui.Page + canvas *gfx.Canvas + wake *fakeWake + now time.Duration +} + +func newHarness(t *testing.T, p *Player) *harness { + t.Helper() + h := &harness{player: p, canvas: new(gfx.Canvas), wake: new(fakeWake)} + h.canvas.SetClock(func() time.Duration { return h.now }) + theme := gfx.LightTheme() + h.page = ui.NewPage(ui.PageConfig{View: h.viewPage, Theme: &theme, Invalidator: h.wake}) + return h +} + +func (h *harness) viewPage(c ui.C) { + View(c, "Video", h.player).FillWidth().Height(240) +} + +func (h *harness) draw() { + h.canvas.Reset() + h.canvas.BeginFrame() + h.page.Draw(h.canvas, gfx.Rect{Width: 400, Height: 300}, h.viewPage) + h.canvas.EndFrame() +} + +// settle draws until the player shows a picture: the decoder runs on its own +// goroutine, so its first frame arrives a moment after the player opens. +func (h *harness) settle(t *testing.T) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + h.draw() + if h.player.dec.have { + return + } + if time.Now().After(deadline) { + t.Fatal("the decoder made no frame") + } + time.Sleep(time.Millisecond) + } +} + +// fakeDecoder plays a list of frames, and seeks by their durations. +type fakeDecoder struct { + frames []Frame + next int + rewind int + seeks int +} + +func (d *fakeDecoder) Next() (Frame, error) { + if d.next >= len(d.frames) { + return Frame{}, io.EOF + } + frame := d.frames[d.next] + d.next++ + return frame, nil +} + +func (d *fakeDecoder) Rewind() error { + d.next = 0 + d.rewind++ + return nil +} + +func (d *fakeDecoder) Seek(to time.Duration) (time.Duration, error) { + d.seeks++ + var at time.Duration + index := 0 + for index+1 < len(d.frames) && at+frameDuration(d.frames[index]) <= to { + at += frameDuration(d.frames[index]) + index++ + } + d.next = index + return at, nil +} + +func frameDuration(frame Frame) time.Duration { + if frame.Duration <= 0 { + return defaultFrameDuration + } + return frame.Duration +} + +var ( + red = Frame{Pix: []byte{0, 0, 255, 255}, Width: 1, Height: 1, Stride: 4, Duration: 100 * time.Millisecond} + green = Frame{Pix: []byte{0, 255, 0, 255}, Width: 1, Height: 1, Stride: 4, Duration: 100 * time.Millisecond} + blue = Frame{Pix: []byte{255, 0, 0, 255}, Width: 1, Height: 1, Stride: 4, Duration: 100 * time.Millisecond} +) + +func newFakePlayer(frames ...Frame) (*Player, *fakeDecoder) { + d := &fakeDecoder{frames: frames} + return NewDecoder(d), d +} + +func paintedPixel(t *testing.T, h *harness) []byte { + t.Helper() + images := h.canvas.Images() + if len(images) != 1 { + t.Fatalf("painted %d images, want 1", len(images)) + } + if len(images[0].Bitmap.Pix) < 4 { + t.Fatal("the painted bitmap has no pixels") + } + return images[0].Bitmap.Pix[:4] +} + +func wantPixel(t *testing.T, h *harness, want []byte, what string) { + t.Helper() + got := paintedPixel(t, h) + if got[0] != want[0] || got[1] != want[1] || got[2] != want[2] || got[3] != want[3] { + t.Fatalf("%s painted %v, want %v", what, got, want) + } +} + +// drawUntil draws at the harness's time until done says the state arrived. +func (h *harness) drawUntil(t *testing.T, done func() bool, what string) { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + h.draw() + if done() { + return + } + if time.Now().After(deadline) { + t.Fatal(what) + } + time.Sleep(time.Millisecond) + } +} + +// Frames show as the canvas clock passes their times, not all at once: the +// view paints the frame the video is in. +func TestDecoderShowsFramesOnTime(t *testing.T) { + p, _ := newFakePlayer(red, green, blue) + defer p.Close() + h := newHarness(t, p) + p.Play() + h.settle(t) + wantPixel(t, h, red.Pix, "the first frame") + if p.State() != Ready || !p.Playing() { + t.Fatalf("state %v, playing %v; want a playing video", p.State(), p.Playing()) + } + + h.now = 50 * time.Millisecond + h.draw() + wantPixel(t, h, red.Pix, "mid-frame") + + h.now = 100 * time.Millisecond + h.draw() + wantPixel(t, h, green.Pix, "the second frame") + + h.now = 200 * time.Millisecond + h.draw() + wantPixel(t, h, blue.Pix, "the third frame") +} + +// The view asks for the next paint when the next frame is due. +func TestDecoderPacesItsFrames(t *testing.T) { + p, _ := newFakePlayer(red, green, blue) + defer p.Close() + h := newHarness(t, p) + p.Play() + h.settle(t) + h.draw() + if delay, ok := h.canvas.NextFrame(); !ok || delay != 100*time.Millisecond { + t.Fatalf("the next frame is in %v, %v; want 100ms", delay, ok) + } + + p.SetRate(2) + h.draw() + if delay, ok := h.canvas.NextFrame(); !ok || delay != 50*time.Millisecond { + t.Fatalf("at twice the rate the next frame is in %v, %v; want 50ms", delay, ok) + } +} + +// Every setting that changes what the view shows wakes the page, as Play and +// Seek do: a player changed from code does not wait for the next unrelated +// event to be drawn again. +func TestPlayerSettingsWakeThePage(t *testing.T) { + e := newEngine(media.Picture{Handle: 0x42, ID: 9, W: 640, H: 360}) + p := newEnginePlayer(e) + defer p.Close() + h := newHarness(t, p) + h.draw() + for _, change := range []struct { + name string + run func() + }{ + {"Pause", p.Pause}, + {"SetLoop", func() { p.SetLoop(true) }}, + {"SetRate", func() { p.SetRate(2) }}, + {"SetMuted", func() { p.SetMuted(true) }}, + {"SetVolume", func() { p.SetVolume(0.5) }}, + } { + before := h.wake.calls.Load() + change.run() + if got := h.wake.calls.Load() - before; got != 1 { + t.Errorf("%s made %d repaints, want 1", change.name, got) + } + } +} + +// Pausing keeps the picture and the clock where they were; the clock starts +// again from there. +func TestDecoderPausesAndResumes(t *testing.T) { + p, _ := newFakePlayer(red, green, blue) + defer p.Close() + h := newHarness(t, p) + p.Play() + h.settle(t) + + h.now = 150 * time.Millisecond + h.draw() + wantPixel(t, h, green.Pix, "the second frame") + + p.Pause() + h.now = 500 * time.Millisecond + h.draw() + wantPixel(t, h, green.Pix, "a paused frame") + if p.Position() != 100*time.Millisecond { + t.Fatalf("paused at %v, want the shown frame's start, 100ms", p.Position()) + } + if p.Playing() { + t.Fatal("a paused video reports playing") + } + + p.Play() + h.now = 600 * time.Millisecond + h.draw() + wantPixel(t, h, green.Pix, "the frame just after resuming") + if p.Position() != 100*time.Millisecond { + t.Fatalf("position just after resuming = %v, want 100ms", p.Position()) + } + h.now = 700 * time.Millisecond + h.draw() + wantPixel(t, h, blue.Pix, "the frame 100ms after resuming") + if p.Position() != 200*time.Millisecond { + t.Fatalf("100ms after resuming at 100ms, position = %v, want 200ms", p.Position()) + } +} + +// A seek shows the nearest frame at or before the time, paused or playing. +func TestDecoderSeeks(t *testing.T) { + p, d := newFakePlayer(red, green, blue) + defer p.Close() + h := newHarness(t, p) + p.Play() + h.settle(t) + + p.Seek(250 * time.Millisecond) + h.now = 250 * time.Millisecond + h.drawUntil(t, func() bool { return !p.dec.waiting }, "the seek's frame never landed") + if d.seeks != 1 { + t.Fatalf("the decoder was asked to seek %d times, want 1", d.seeks) + } + wantPixel(t, h, blue.Pix, "the frame at 250ms") + if p.Position() != 200*time.Millisecond { + t.Fatalf("position after seeking to 250ms = %v, want 200ms", p.Position()) + } +} + +// A looping video starts again by itself when it ends. +func TestDecoderLoops(t *testing.T) { + p, d := newFakePlayer(red, green) + defer p.Close() + p.SetLoop(true) + h := newHarness(t, p) + p.Play() + h.settle(t) + + h.now = 100 * time.Millisecond + h.draw() + wantPixel(t, h, green.Pix, "the second frame") + + h.now = 200 * time.Millisecond + h.draw() + if p.State() != Ready || !p.Playing() { + t.Fatalf("at the end of a looping video: state %v, playing %v", p.State(), p.Playing()) + } + h.drawUntil(t, func() bool { + got := paintedPixel(t, h) + return got[0] == red.Pix[0] && got[1] == red.Pix[1] && got[2] == red.Pix[2] + }, "the looping video did not start again") + if p.Position() > 100*time.Millisecond { + t.Fatalf("position after the loop started again = %v, want near 0", p.Position()) + } + if d.rewind < 2 { + t.Fatalf("the decoder was rewound %d times, want a rewind for the loop", d.rewind) + } +} + +// A video that does not loop ends at its end and stays there. +func TestDecoderEnds(t *testing.T) { + p, _ := newFakePlayer(red, green) + defer p.Close() + h := newHarness(t, p) + p.Play() + h.settle(t) + + h.now = 200 * time.Millisecond + h.drawUntil(t, func() bool { return p.State() == Ended }, "the video never ended") + wantPixel(t, h, green.Pix, "the last frame") + if p.Playing() { + t.Fatal("an ended video reports playing") + } + if p.Duration() != 200*time.Millisecond || p.Position() != 200*time.Millisecond { + t.Fatalf("duration %v, position %v; want 200ms", p.Duration(), p.Position()) + } + if _, ok := h.canvas.NextFrame(); ok { + t.Fatal("an ended video asked for another paint") + } + + // Play starts it again from its start. + p.Play() + h.drawUntil(t, func() bool { + got := paintedPixel(t, h) + return got[1] == red.Pix[1] && got[2] == red.Pix[2] + }, "Play after the end did not start the video again") + if p.Position() > 100*time.Millisecond { + t.Fatalf("position after playing again = %v, want near 0", p.Position()) + } +} + +// A faster rate covers more of the video in the same canvas time. +func TestDecoderRateScalesTheClock(t *testing.T) { + p, _ := newFakePlayer(red, green, blue) + defer p.Close() + h := newHarness(t, p) + p.SetRate(2) + p.Play() + h.settle(t) + + h.now = 100 * time.Millisecond + h.draw() + wantPixel(t, h, blue.Pix, "200ms of video after 100ms at twice the rate") + if p.Position() != 200*time.Millisecond { + t.Fatalf("position = %v, want 200ms", p.Position()) + } +} + +// Close stops the decoder and the view paints nothing; it may be called +// twice, and a closed player ignores the other methods. +func TestDecoderClose(t *testing.T) { + p, _ := newFakePlayer(red, green) + h := newHarness(t, p) + p.Play() + h.settle(t) + if err := p.Close(); err != nil { + t.Fatalf("Close = %v", err) + } + if err := p.Close(); err != nil { + t.Fatalf("Close again = %v", err) + } + p.Play() + p.Pause() + p.Seek(time.Second) + if p.Playing() || p.Position() != 0 || p.Duration() != 0 || p.State() != Ended { + t.Fatalf("a closed player still reports: playing %v, position %v, duration %v, state %v", + p.Playing(), p.Position(), p.Duration(), p.State()) + } + h.draw() + if images := h.canvas.Images(); len(images) != 0 { + t.Fatalf("a closed player painted %d images", len(images)) + } + if _, ok := h.canvas.NextFrame(); ok { + t.Fatal("a closed player asked for another paint") + } +} + +// A decoder frame's pixels are copied: the decoder may reuse its buffer. +func TestDecoderCopiesFrames(t *testing.T) { + p, d := newFakePlayer(red) + defer p.Close() + h := newHarness(t, p) + p.Play() + h.settle(t) + h.drawUntil(t, func() bool { return p.dec.endKnown }, "the decoder never reached its end") + + frame := d.frames[0] + frame.Pix = []byte{1, 2, 3, 4} + d.frames[0] = frame + h.draw() + wantPixel(t, h, red.Pix, "the player's copy of the frame") +} + +// reusingDecoder writes every frame into the same backing buffer, as the GIF +// and APNG decoders do. +type reusingDecoder struct { + buf []byte + colors [][4]byte + next int +} + +func (d *reusingDecoder) Next() (Frame, error) { + if d.next >= len(d.colors) { + return Frame{}, io.EOF + } + c := d.colors[d.next] + d.next++ + for i := 0; i < len(d.buf); i += 4 { + d.buf[i], d.buf[i+1], d.buf[i+2], d.buf[i+3] = c[0], c[1], c[2], c[3] + } + return Frame{ + Pix: d.buf, + Width: 4, + Height: 4, + Stride: 16, + Duration: 100 * time.Millisecond, + }, nil +} + +func (d *reusingDecoder) Rewind() error { + d.next = 0 + return nil +} + +// A decoder that reuses one pixel buffer across frames must not race with +// the UI thread or overwrite frames still waiting in the queue. +func TestDecoderReusesSharedBufferSafely(t *testing.T) { + colors := [][4]byte{ + {0, 0, 255, 255}, + {0, 255, 0, 255}, + {255, 0, 0, 255}, + {255, 255, 0, 255}, + {0, 255, 255, 255}, + } + dec := &reusingDecoder{buf: make([]byte, 4*4*4), colors: colors} + p := NewDecoder(dec) + defer p.Close() + h := newHarness(t, p) + p.Play() + h.settle(t) + // Give the decoder goroutine time to decode ahead and overwrite dec.buf. + time.Sleep(10 * time.Millisecond) + + for i, want := range colors { + h.now = time.Duration(i) * 100 * time.Millisecond + h.draw() + wantPixel(t, h, want[:], "frame from reusing decoder") + } +} + +func TestNewDecoderNeedsADecoder(t *testing.T) { + defer func() { + if recover() == nil { + t.Fatal("NewDecoder(nil) did not panic") + } + }() + NewDecoder(nil) +} diff --git a/ui/video/video.go b/ui/video/video.go new file mode 100644 index 000000000..0741c1cd9 --- /dev/null +++ b/ui/video/video.go @@ -0,0 +1,85 @@ +// Package video plays videos, as pictures: a system media framework decodes +// them where the system has one, and Go decodes animated GIFs and PNGs on +// every system. The application gives the player its own controls; View shows +// the picture, fit into the box the page gives it. +// +// //go:embed trailer.mp4 +// var trailer []byte +// +// m.video, err = video.OpenData(trailer) +// ... +// m.video.Fit(video.Cover) +// m.video.SetLoop(true) +// m.video.Play() +// video.View(c, "Trailer", m.video).Fill().Height(240) +// +// A player opens paused, and loads in the background: its Size is 0×0 and its +// State Loading until its first picture, and Play starts it. The system's +// decoders play what the system plays: H.264 in MP4 and MOV on Windows, where +// Media Foundation has them, and on macOS, where AVFoundation has them. +// Elsewhere Open reports ErrUnsupported, and the application may show a GIF in +// its place. A player made with NewDecoder plays on every system. +// +// A player's methods are called on the UI thread. Keep one in the model, call +// Close when done, and declare its View in the page's own paint, not inside a +// Memo. +package video + +import ( + "errors" + "net/url" + "path/filepath" + + "github.com/vivaui/viva/internal/media" +) + +// ErrUnsupported reports a system without a media framework that plays +// video: an OS this release has no engine for, or a Windows without Media +// Foundation. An application may show a GIF in its place, with NewDecoder. +var ErrUnsupported = media.ErrUnsupported + +// Open opens a video file, playing once Play is called. +func Open(path string) (*Player, error) { + abs, err := filepath.Abs(path) + if err != nil { + return nil, err + } + return open(media.Source{URL: fileURL(abs), Path: abs}) +} + +// OpenURL opens a video at a URL: a file:, http: or https: URL. It plays once +// Play is called. +func OpenURL(url string) (*Player, error) { + return open(media.Source{URL: url}) +} + +// OpenData opens a video in memory, as one embedded in the application, +// without the application writing it to a file. Windows copies the bytes into +// a memory stream (SHCreateMemStream); macOS's AVFoundation reads a file, so +// the engine writes the bytes to a temporary file, which it removes when the +// player closes. The caller may reuse or modify data after OpenData returns. +func OpenData(data []byte) (*Player, error) { + if len(data) == 0 { + return nil, errors.New("video: no data") + } + return open(media.Source{Data: data}) +} + +func open(s media.Source) (*Player, error) { + engine, err := media.Open(s) + if err != nil { + return nil, err + } + return newEnginePlayer(engine), nil +} + +// fileURL is the file: URL of an absolute path, its characters escaped as a +// URL needs them. +func fileURL(abs string) string { + p := filepath.ToSlash(abs) + if len(p) == 0 || p[0] != '/' { + p = "/" + p // C:/… on Windows + } + u := url.URL{Scheme: "file", Path: p} + return u.String() +} diff --git a/ui/video/video_test.go b/ui/video/video_test.go new file mode 100644 index 000000000..0c3da52b0 --- /dev/null +++ b/ui/video/video_test.go @@ -0,0 +1,41 @@ +package video + +import ( + "path/filepath" + "runtime" + "strings" + "testing" +) + +func TestFileURL(t *testing.T) { + if runtime.GOOS == "windows" { + if got, want := fileURL(`C:\Users\jq\a b.mp4`), "file:///C:/Users/jq/a%20b.mp4"; got != want { + t.Fatalf("fileURL = %q, want %q", got, want) + } + if got, want := fileURL(`\\server\share\film.mp4`), "file:////server/share/film.mp4"; got != want { + t.Fatalf("fileURL of a UNC path = %q, want %q", got, want) + } + } + if got, want := fileURL("/tmp/a b/c.mp4"), "file:///tmp/a%20b/c.mp4"; got != want { + t.Fatalf("fileURL = %q, want %q", got, want) + } + if got, want := fileURL("/tmp/100#.mp4"), "file:///tmp/100%23.mp4"; got != want { + t.Fatalf("fileURL = %q, want %q", got, want) + } + abs, err := filepath.Abs("trailer.mp4") + if err != nil { + t.Fatal(err) + } + if got := fileURL(abs); !strings.HasPrefix(got, "file:///") || !strings.HasSuffix(got, "/trailer.mp4") { + t.Fatalf("fileURL(%q) = %q", abs, got) + } +} + +func TestOpenDataRejectsEmptyData(t *testing.T) { + if _, err := OpenData(nil); err == nil { + t.Fatal("OpenData(nil) opened a video") + } + if _, err := OpenData([]byte{}); err == nil { + t.Fatal("OpenData of no bytes opened a video") + } +} diff --git a/ui/video/view.go b/ui/video/view.go new file mode 100644 index 000000000..b3448d264 --- /dev/null +++ b/ui/video/view.go @@ -0,0 +1,21 @@ +package video + +import ( + "github.com/vivaui/viva/ui" +) + +// View shows the player's picture, fit into the box the page gives it. The +// picture keeps its aspect: contain fits it inside, cover fills the box and +// clips the overflow, fill stretches it. The view paints nothing until the +// first picture arrives, and keeps the box it is given. +// +// A player has one view: declare it in the page's own paint, not inside a +// Memo, so the view is there when a picture wakes the page. Declare it with +// the other controls, and keep the player in the model. +func View(c ui.C, label string, p *Player) ui.Box { + if p == nil { + panic("video: View needs a player") + } + p.prepare(c) + return ui.Control(c, label, &p.handlers).Draw(p.drawFn) +} diff --git a/ui/video/view_test.go b/ui/video/view_test.go new file mode 100644 index 000000000..71e205982 --- /dev/null +++ b/ui/video/view_test.go @@ -0,0 +1,222 @@ +package video + +import ( + "math" + "testing" + "time" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/media" +) + +// fakeEngine is a media engine whose picture, state and clock the test sets. +type fakeEngine struct { + picture media.Picture + ok bool + changed bool + state media.State + err error + w, h int + duration time.Duration + position time.Duration + playing bool + interval time.Duration + wake func() + closes int + loop bool + rate float64 + volume float64 + muted bool + seeked time.Duration +} + +func (e *fakeEngine) SetWake(wake func()) { e.wake = wake } +func (e *fakeEngine) Frame() (media.Picture, bool, bool) { return e.picture, e.changed, e.ok } +func (e *fakeEngine) Interval() time.Duration { return e.interval } +func (e *fakeEngine) State() (media.State, error) { return e.state, e.err } +func (e *fakeEngine) Size() (w, h int) { return e.w, e.h } +func (e *fakeEngine) Duration() time.Duration { return e.duration } +func (e *fakeEngine) Position() time.Duration { return e.position } +func (e *fakeEngine) Playing() bool { return e.playing } +func (e *fakeEngine) Play() { e.playing, e.state = true, media.Ready } +func (e *fakeEngine) Pause() { e.playing = false } +func (e *fakeEngine) Seek(to time.Duration) { e.seeked, e.position = to, to } +func (e *fakeEngine) SetLoop(loop bool) { e.loop = loop } +func (e *fakeEngine) SetRate(rate float64) { e.rate = rate } +func (e *fakeEngine) SetVolume(volume float64) { e.volume = volume } +func (e *fakeEngine) SetMuted(muted bool) { e.muted = muted } +func (e *fakeEngine) Close() error { e.closes++; return nil } + +func closeTo(got, want float32) bool { return math.Abs(float64(got-want)) < .001 } + +func newEngine(picture media.Picture) *fakeEngine { + return &fakeEngine{ + picture: picture, + ok: true, + state: media.Ready, + playing: true, + interval: 33 * time.Millisecond, + } +} + +// The view draws the engine's picture where it fits, and passes the texture +// and its version to the canvas without a copy. +func TestViewDrawsThePicture(t *testing.T) { + e := newEngine(media.Picture{Handle: 0x42, ID: 9, W: 640, H: 360}) + p := newEnginePlayer(e) + defer p.Close() + h := newHarness(t, p) + h.draw() + + images := h.canvas.Images() + if len(images) != 1 { + t.Fatalf("painted %d images, want 1", len(images)) + } + painted := images[0] + if painted.Texture == nil { + t.Fatal("the image has no texture") + } + if *painted.Texture != (gfx.NativeTexture{ID: 9, Handle: 0x42, Width: 640, Height: 360, Version: 1}) { + t.Fatalf("texture = %+v", *painted.Texture) + } + if !closeTo(painted.Bounds.X, 0) || !closeTo(painted.Bounds.Y, 7.5) || + !closeTo(painted.Bounds.Width, 400) || !closeTo(painted.Bounds.Height, 225) { + t.Fatalf("bounds = %+v, want a 400x225 picture centered at y=7.5", painted.Bounds) + } + if painted.Fade != 0 { + t.Fatalf("fade = %g, want 0", painted.Fade) + } + if delay, ok := h.canvas.NextFrame(); !ok || delay != e.interval { + t.Fatalf("the next picture is due in %v, %v; want %v", delay, ok, e.interval) + } + + // The same picture keeps its version; a new one bumps it. + h.draw() + if *h.canvas.Images()[0].Texture != *painted.Texture { + t.Fatal("redrawing the same picture changed its texture") + } + e.picture = media.Picture{Handle: 0x43, ID: 10, W: 640, H: 360} + h.draw() + if got := h.canvas.Images()[0].Texture; got.ID != 10 || got.Version != 2 { + t.Fatalf("after the picture changed texture = %+v, want ID 10 version 2", got) + } +} + +// Cover fills the view's box and clips the picture to it. +func TestViewClipsCover(t *testing.T) { + e := newEngine(media.Picture{Handle: 0x42, ID: 9, W: 640, H: 360}) + p := newEnginePlayer(e) + defer p.Close() + p.Fit(Cover) + h := newHarness(t, p) + h.draw() + + images := h.canvas.Images() + if len(images) != 1 { + t.Fatalf("painted %d images, want 1", len(images)) + } + painted := images[0] + if !closeTo(painted.Bounds.X, -13.333) || !closeTo(painted.Bounds.Y, 0) || + !closeTo(painted.Bounds.Width, 426.667) || !closeTo(painted.Bounds.Height, 240) { + t.Fatalf("bounds = %+v, want a cover 426.667x240 at x=-13.333", painted.Bounds) + } + if !painted.HasClip || painted.ClipOf != (gfx.Rect{Width: 400, Height: 240}) { + t.Fatalf("clip = %+v, %v; want the view's box", painted.ClipOf, painted.HasClip) + } +} + +// Before the first picture the view paints nothing and looks again soon. +func TestViewPollsForTheFirstPicture(t *testing.T) { + e := &fakeEngine{state: media.Loading, w: 640, h: 360} + p := newEnginePlayer(e) + defer p.Close() + h := newHarness(t, p) + h.draw() + if images := h.canvas.Images(); len(images) != 0 { + t.Fatalf("painted %d images before the first picture", len(images)) + } + if delay, ok := h.canvas.NextFrame(); !ok || delay != pollInterval { + t.Fatalf("the next look is in %v, %v; want %v", delay, ok, pollInterval) + } +} + +// The engine wakes the page through the player when its state changes. +func TestViewSetsTheEngineWake(t *testing.T) { + e := newEngine(media.Picture{Handle: 0x42, ID: 9, W: 640, H: 360}) + p := newEnginePlayer(e) + defer p.Close() + h := newHarness(t, p) + h.draw() + if e.wake == nil { + t.Fatal("the view did not give the engine a way to wake it") + } + before := h.wake.calls.Load() + e.wake() + if got := h.wake.calls.Load() - before; got != 1 { + t.Fatalf("the engine's wake made %d repaints, want 1", got) + } +} + +// A closed player paints nothing and closes its engine once. +func TestViewClosedPaintsNothing(t *testing.T) { + e := newEngine(media.Picture{Handle: 0x42, ID: 9, W: 640, H: 360}) + p := newEnginePlayer(e) + h := newHarness(t, p) + h.draw() + if err := p.Close(); err != nil { + t.Fatalf("Close = %v", err) + } + if err := p.Close(); err != nil { + t.Fatalf("Close again = %v", err) + } + if e.closes != 1 { + t.Fatalf("the engine was closed %d times, want 1", e.closes) + } + h.draw() + if images := h.canvas.Images(); len(images) != 0 { + t.Fatalf("a closed player painted %d images", len(images)) + } + if _, ok := h.canvas.NextFrame(); ok { + t.Fatal("a closed player asked for another paint") + } +} + +// The player passes its settings to the engine, and reads its state back. +func TestPlayerDrivesTheEngine(t *testing.T) { + e := newEngine(media.Picture{Handle: 0x42, ID: 9, W: 640, H: 360}) + e.duration = 5 * time.Second + p := newEnginePlayer(e) + defer p.Close() + p.Play() + p.Seek(2 * time.Second) + p.SetLoop(true) + p.SetRate(1.5) + p.SetVolume(0.25) + p.SetMuted(true) + if !e.playing || e.seeked != 2*time.Second || !e.loop || e.rate != 1.5 || e.volume != 0.25 || !e.muted { + t.Fatalf("the engine got playing %v, seek %v, loop %v, rate %v, volume %v, muted %v", + e.playing, e.seeked, e.loop, e.rate, e.volume, e.muted) + } + if p.Duration() != 5*time.Second || p.Position() != 2*time.Second || !p.Playing() || p.State() != Ready { + t.Fatalf("the player reports duration %v, position %v, playing %v, state %v", + p.Duration(), p.Position(), p.Playing(), p.State()) + } + p.Pause() + if e.playing || p.Playing() { + t.Fatal("Pause did not pause the engine") + } + e.state = media.Failed + e.err = media.ErrUnsupported + if p.State() != Failed || p.Err() != media.ErrUnsupported || p.Playing() { + t.Fatalf("a failed engine: state %v, err %v, playing %v", p.State(), p.Err(), p.Playing()) + } +} + +func TestViewNeedsAPlayer(t *testing.T) { + defer func() { + if recover() == nil { + t.Fatal("View(nil player) did not panic") + } + }() + View(nil, "Video", nil) +} diff --git a/website/content/guides/en/components.md b/website/content/guides/en/components.md index d382a412a..e424bcc29 100644 --- a/website/content/guides/en/components.md +++ b/website/content/guides/en/components.md @@ -25,7 +25,7 @@ A theme is a value, `gfx.LightTheme()` or `gfx.DarkTheme()`. Switching appearanc A page control for a heavy or stateful component lives in its own package under `ui/`. Import it only when the page uses it; the package is the pay-for-use boundary. -- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid` +- Editors and visuals: `ui/codeeditor`, `ui/textview`, `ui/chart`, `ui/markdown`, `ui/image`, `ui/video`, `ui/calendar`, `ui/carousel`, `ui/columnresize`, `ui/reordergrid` - Navigation and overlays: `ui/command`, `ui/menubar`, `ui/navigationmenu`, `ui/sidebar`, `ui/hovercard` - Data and inputs: `ui/avatar`, `ui/avatareditor`, `ui/attachment`, `ui/metriccard`, `ui/marker`, `ui/skeleton`, `ui/aspectratio`, `ui/questionnaire`, `ui/messagescroller`, `ui/message`, `ui/inputgroup`, `ui/inputotp`, `ui/multiselect`, `ui/hierarchypicker`, `ui/buttongroup`, `ui/togglegroup`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer`, `ui/alert`, `ui/tag`, `ui/breadcrumb`, `ui/card`, `ui/empty`, `ui/result`, `ui/pagination`, `ui/editabletabs`, `ui/popconfirm`, `ui/divider`, `ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator`, `ui/steps`, `ui/descriptions`, `ui/timeline`, `ui/rate`, `ui/inputnumber`, `ui/datepicker`, `ui/timepicker`, `ui/transfer` @@ -76,6 +76,188 @@ The chart owns no input. Keep a `components.ChartState` next to your data, and f Two limits are deliberate. A chart draws every point it is given, so a very long series should go through `components.ChartDownsample` once when the data changes, not on every paint. And stacked series must not be negative: a negative value stacks as zero. +## Video + +`ui/video` plays video as pictures, without a built-in control bar: the application keeps a `*video.Player` in its model, opens a file, URL or embedded bytes with `video.Open`, `video.OpenURL` or `video.OpenData`, declares `video.View(c, label, player)` where the picture goes, and provides its own transport controls. On Windows (Media Foundation) and macOS (AVFoundation), decoded frames reach the renderer directly on the GPU as shared textures; elsewhere the open functions report `video.ErrUnsupported`, while `video.NewGIFDecoder` and `video.NewAPNGDecoder` decode animated images in Go on every platform. + + +```go +// Video plays video in a Viva window, as a launcher's store page does: a +// short color-wave GIF loops behind the window's content, and a five-second +// color clip plays over it, with controls to pause it, seek and close it. +// +// go run ./examples/guides/video +// +// The GIF decodes in Go, on every system: package video.NewGIFDecoder's +// frames decode on a goroutine a few ahead, and each reaches the screen as it +// comes due, so the window draws one frame for each of the clip's and none +// between. +// +// The color clip is a 640×360 MP4 embedded in the application, made for this +// example: five seconds of full-frame color changes at 30 frames a second. It +// plays with the system's media framework, Media Foundation on Windows and +// AVFoundation on macOS, and its pictures reach the window's renderer where +// the decoder left them, on the GPU. Elsewhere OpenData reports +// ErrUnsupported: the example says so and keeps the GIF playing. +package main + +import ( + _ "embed" + "fmt" + "log" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/video" +) + +var ( + //go:embed waves.gif + wavesGIF []byte + //go:embed colors.mp4 + clipMP4 []byte +) + +// model is the state the window shows. +type model struct { + waves *video.Player + // clip is the color clip's player once opened, and clipErr what stopped it + // from opening, as a system without a media framework. + clip *video.Player + clipErr error + seek ui.SliderState +} + +func newModel() (*model, error) { + d, err := video.NewGIFDecoder(wavesGIF) + if err != nil { + return nil, err + } + waves := video.NewDecoder(d) + waves.Fit(video.Cover) + waves.SetLoop(true) + waves.Play() + return &model{waves: waves}, nil +} + +// openClip opens the color clip, which plays once its view shows it. The +// background holds still while the clip plays. +func (m *model) openClip() { + m.clip, m.clipErr = video.OpenData(clipMP4) + if m.clip != nil { + m.clip.Fit(video.Contain) + m.waves.Pause() + } +} + +// closeClip stops the clip and goes back to the background. +func (m *model) closeClip() { + m.clip.Close() + m.clip = nil + m.seek.Value = 0 + m.waves.Play() +} + +// page builds the interface from the state, on the main thread, whenever the +// window needs a frame. +func (m *model) page(c ui.C) { + white := ui.RGB(255, 255, 255) + ui.Stack(c).Fill().Children(func() { + video.View(c, "Waves", m.waves).Fill() + // Over the clip, which takes the window. + ui.Column(c).Absolute().Inset(0).Center().Gap(16).Children(func() { + if m.clip != nil { + m.clipView(c) + return + } + ui.Text(c, "Wavelength").FontSize(44).Bold().Color(white) + ui.Row(c).Gap(8).Children(func() { + label := "Pause" + if !m.waves.Playing() { + label = "Play" + } + if ui.Button(c, label).Width(96).Clicked() { + if m.waves.Playing() { + m.waves.Pause() + } else { + m.waves.Play() + } + } + if ui.Button(c, "Watch the clip").Clicked() { + m.openClip() + } + }) + if m.clipErr != nil { + ui.Text(c, m.clipErr.Error()).Color(white) + } + }) + }) +} + +// clipView shows the color clip and its controls. +func (m *model) clipView(c ui.C) { + p := m.clip + white := ui.RGB(255, 255, 255) + ui.Column(c).Width(480).Gap(8).Pad(12).Background(ui.RGBA(0, 0, 0, 0.78)).Radius(12).Children(func() { + ui.Stack(c).Width(456).Height(256).Children(func() { + video.View(c, "Clip", p).Fill() + if p.Err() != nil { + ui.Text(c, p.Err().Error()).Color(white) + } + }) + ui.Row(c).Gap(8).Items(ui.Center).Children(func() { + label := "Pause" + if !p.Playing() { + label = "Play" + } + if ui.Button(c, label).Width(72).Clicked() { + if p.Playing() { + p.Pause() + } else { + p.Play() + } + } + duration := float32(p.Duration().Seconds()) + if duration <= 0 { + duration = 0.001 + } + if !m.seek.Dragging() { + m.seek.Value = float32(p.Position().Seconds()) + } + if ui.Slider(c, &m.seek).Range(0, duration).Grow(1).Label("Position").Changed() { + p.Seek(time.Duration(float64(m.seek.Value) * float64(time.Second))) + } + ui.Text(c, clock(p.Position())+" / "+clock(p.Duration())).Color(white) + if ui.Button(c, "Close").Clicked() { + m.closeClip() + } + }) + }) +} + +// clock is a time as minutes and seconds. +func clock(d time.Duration) string { + sec := int(d.Round(time.Second) / time.Second) + return fmt.Sprintf("%d:%02d", sec/60, sec%60) +} + +func main() { + m, err := newModel() + if err != nil { + log.Fatal(err) + } + err = ui.Run(app.Config{Title: "Video", Width: 640, Height: 400}, ui.PageConfig{View: m.page}) + m.waves.Close() + if m.clip != nil { + m.clip.Close() + } + if err != nil { + log.Fatal(err) + } +} +``` + ## Owning a copy If you want to change a component, copy it. `viva list` names the recipes the installer can copy, and `viva add` writes them into your project as ordinary Go files. A copy is a painting recipe: it draws into a `gfx.Canvas` in the rectangle you give it (`BeginButton(canvas, theme, id, bounds)`), so you use it from a `Draw` callback of a page's element or from a whole-window `Paint`, and its look is the code you edit. To change how every `ui.Button` looks without copying anything, give the page `PageConfig.Styles`; to build a control of your own look on the behavior `ui` ships, use `ui.ButtonBase` and the other Bases. diff --git a/website/content/guides/zh/components.md b/website/content/guides/zh/components.md index 89580825c..a3a4fe0d5 100644 --- a/website/content/guides/zh/components.md +++ b/website/content/guides/zh/components.md @@ -25,7 +25,7 @@ components.BeginButton(canvas, theme, hitSave, bounds).Outline("Save") 重功能或有状态的页面控件放在 `ui/<能力名>` 的独立包里。用到才 import;包本身就是按需付费的边界。 -- 编辑器与可视化:`ui/codeeditor`、`ui/textview`、`ui/chart`、`ui/markdown`、`ui/image`、`ui/calendar`、`ui/carousel`、`ui/columnresize`、`ui/reordergrid` +- 编辑器与可视化:`ui/codeeditor`、`ui/textview`、`ui/chart`、`ui/markdown`、`ui/image`、`ui/video`、`ui/calendar`、`ui/carousel`、`ui/columnresize`、`ui/reordergrid` - 导航与浮层:`ui/command`、`ui/menubar`、`ui/navigationmenu`、`ui/sidebar`、`ui/hovercard` - 数据与输入:`ui/avatar`、`ui/avatareditor`、`ui/attachment`、`ui/metriccard`、`ui/marker`、`ui/skeleton`、`ui/aspectratio`、`ui/questionnaire`、`ui/messagescroller`、`ui/message`、`ui/inputgroup`、`ui/inputotp`、`ui/multiselect`、`ui/hierarchypicker`、`ui/buttongroup`、`ui/togglegroup`、`ui/steps`、`ui/descriptions`、`ui/timeline`、`ui/rate`、`ui/inputnumber`、`ui/datepicker`、`ui/timepicker`、`ui/transfer`、`ui/alert`、`ui/tag`、`ui/breadcrumb`、`ui/card`、`ui/empty`、`ui/result`、`ui/pagination`、`ui/editabletabs`、`ui/popconfirm`、`ui/divider`、`ui/typography`, `ui/validate`, `ui/upload`, `ui/anchor`, `ui/comment`, `ui/imagepreview`, `ui/mentions`, `ui/tour`, `ui/overflowlist`, `ui/statistic`, `ui/inputtag`, `ui/autocomplete`, `ui/indicator` @@ -76,6 +76,188 @@ plot := components.PaintAreaChart(canvas, theme, bounds, chartID, chart, &state) 有两条限制是有意为之。图表会画出给它的每一个点,所以很长的序列应当在数据变化时用 `components.ChartDownsample` 降采样一次,而不是每次绘制都做。堆叠的序列不能为负:负值按零堆叠。 +## 视频 + +`ui/video` 把视频当作画面来播放,不内置播放条:应用在 model 中保存 `*video.Player`,用 `video.Open`、`video.OpenURL` 或 `video.OpenData` 打开文件、URL 或内嵌字节,在需要显示画面的位置声明 `video.View(c, label, player)`,并自行提供播放控制。在 Windows(Media Foundation)和 macOS(AVFoundation)上,解码后的帧直接作为 GPU 共享纹理送达渲染器;其他平台上的打开函数返回 `video.ErrUnsupported`,而 `video.NewGIFDecoder` 与 `video.NewAPNGDecoder` 在所有平台上用纯 Go 解码动图。 + + +```go +// Video plays video in a Viva window, as a launcher's store page does: a +// short color-wave GIF loops behind the window's content, and a five-second +// color clip plays over it, with controls to pause it, seek and close it. +// +// go run ./examples/guides/video +// +// The GIF decodes in Go, on every system: package video.NewGIFDecoder's +// frames decode on a goroutine a few ahead, and each reaches the screen as it +// comes due, so the window draws one frame for each of the clip's and none +// between. +// +// The color clip is a 640×360 MP4 embedded in the application, made for this +// example: five seconds of full-frame color changes at 30 frames a second. It +// plays with the system's media framework, Media Foundation on Windows and +// AVFoundation on macOS, and its pictures reach the window's renderer where +// the decoder left them, on the GPU. Elsewhere OpenData reports +// ErrUnsupported: the example says so and keeps the GIF playing. +package main + +import ( + _ "embed" + "fmt" + "log" + "time" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" + "github.com/vivaui/viva/ui/video" +) + +var ( + //go:embed waves.gif + wavesGIF []byte + //go:embed colors.mp4 + clipMP4 []byte +) + +// model is the state the window shows. +type model struct { + waves *video.Player + // clip is the color clip's player once opened, and clipErr what stopped it + // from opening, as a system without a media framework. + clip *video.Player + clipErr error + seek ui.SliderState +} + +func newModel() (*model, error) { + d, err := video.NewGIFDecoder(wavesGIF) + if err != nil { + return nil, err + } + waves := video.NewDecoder(d) + waves.Fit(video.Cover) + waves.SetLoop(true) + waves.Play() + return &model{waves: waves}, nil +} + +// openClip opens the color clip, which plays once its view shows it. The +// background holds still while the clip plays. +func (m *model) openClip() { + m.clip, m.clipErr = video.OpenData(clipMP4) + if m.clip != nil { + m.clip.Fit(video.Contain) + m.waves.Pause() + } +} + +// closeClip stops the clip and goes back to the background. +func (m *model) closeClip() { + m.clip.Close() + m.clip = nil + m.seek.Value = 0 + m.waves.Play() +} + +// page builds the interface from the state, on the main thread, whenever the +// window needs a frame. +func (m *model) page(c ui.C) { + white := ui.RGB(255, 255, 255) + ui.Stack(c).Fill().Children(func() { + video.View(c, "Waves", m.waves).Fill() + // Over the clip, which takes the window. + ui.Column(c).Absolute().Inset(0).Center().Gap(16).Children(func() { + if m.clip != nil { + m.clipView(c) + return + } + ui.Text(c, "Wavelength").FontSize(44).Bold().Color(white) + ui.Row(c).Gap(8).Children(func() { + label := "Pause" + if !m.waves.Playing() { + label = "Play" + } + if ui.Button(c, label).Width(96).Clicked() { + if m.waves.Playing() { + m.waves.Pause() + } else { + m.waves.Play() + } + } + if ui.Button(c, "Watch the clip").Clicked() { + m.openClip() + } + }) + if m.clipErr != nil { + ui.Text(c, m.clipErr.Error()).Color(white) + } + }) + }) +} + +// clipView shows the color clip and its controls. +func (m *model) clipView(c ui.C) { + p := m.clip + white := ui.RGB(255, 255, 255) + ui.Column(c).Width(480).Gap(8).Pad(12).Background(ui.RGBA(0, 0, 0, 0.78)).Radius(12).Children(func() { + ui.Stack(c).Width(456).Height(256).Children(func() { + video.View(c, "Clip", p).Fill() + if p.Err() != nil { + ui.Text(c, p.Err().Error()).Color(white) + } + }) + ui.Row(c).Gap(8).Items(ui.Center).Children(func() { + label := "Pause" + if !p.Playing() { + label = "Play" + } + if ui.Button(c, label).Width(72).Clicked() { + if p.Playing() { + p.Pause() + } else { + p.Play() + } + } + duration := float32(p.Duration().Seconds()) + if duration <= 0 { + duration = 0.001 + } + if !m.seek.Dragging() { + m.seek.Value = float32(p.Position().Seconds()) + } + if ui.Slider(c, &m.seek).Range(0, duration).Grow(1).Label("Position").Changed() { + p.Seek(time.Duration(float64(m.seek.Value) * float64(time.Second))) + } + ui.Text(c, clock(p.Position())+" / "+clock(p.Duration())).Color(white) + if ui.Button(c, "Close").Clicked() { + m.closeClip() + } + }) + }) +} + +// clock is a time as minutes and seconds. +func clock(d time.Duration) string { + sec := int(d.Round(time.Second) / time.Second) + return fmt.Sprintf("%d:%02d", sec/60, sec%60) +} + +func main() { + m, err := newModel() + if err != nil { + log.Fatal(err) + } + err = ui.Run(app.Config{Title: "Video", Width: 640, Height: 400}, ui.PageConfig{View: m.page}) + m.waves.Close() + if m.clip != nil { + m.clip.Close() + } + if err != nil { + log.Fatal(err) + } +} +``` + ## 拥有一份副本 想修改组件时,就复制它。`viva list` 列出安装器能复制的配方,`viva add` 把它们作为普通 Go 文件写进你的项目。复制出来的是绘制配方:它在你给定的矩形里往 `gfx.Canvas` 上画(`BeginButton(canvas, theme, id, bounds)`),所以要在页面元素的 `Draw` 回调里或整窗的 `Paint` 里使用,外观就是你要改的那段代码。想改变所有 `ui.Button` 的外观又不想复制任何东西,给页面设置 `PageConfig.Styles`;想基于 `ui` 自带的行为做自己外观的控件,用 `ui.ButtonBase` 等 Base。 diff --git a/window/text_input.go b/window/text_input.go index 096a6cb14..5732dc2b4 100644 --- a/window/text_input.go +++ b/window/text_input.go @@ -238,6 +238,18 @@ type TextInput struct { // while native editing continues. It combines with the declaration on the // focused Canvas hit. HideNativeOverlays bool + // Paste, when set, is offered every paste into the field before the field + // takes it, whether the keyboard, a menu or the system asked for it: text + // is what the paste would insert (a single-line field's with its lines + // folded into one), or empty when the clipboard holds no text (a + // TextPasteNoText). Returning true takes the paste: neither Editor + // nor OnEvent sees it, the field stays as it was and the window paints + // again, so a chat box can attach the files or the picture on the + // clipboard (ClipboardFiles, ClipboardImagePNG) rather than paste their + // names. Returning false lets the paste go on as usual. A cut, which + // arrives as a paste of nothing over the selection, is not offered. It + // runs on the window's thread, between paints. + Paste func(text string) bool } // Apply routes one native text event into editor. The event kinds and commands are