From b036c884fa0720f708c6cf3c22cc3ce6712fa728 Mon Sep 17 00:00:00 2001 From: t8y2 <1156263951@qq.com> Date: Sat, 28 Nov 2026 23:49:05 +0800 Subject: [PATCH 1/5] feat(tools): audit applications for idle wakes and window-thread I/O appaudit reads Go source and points at what keeps an application busy with nothing to do or stalls its window thread: a time.NewTicker or time.Tick, a file-system call in a function handed a canvas, a page or a draw context, and a RequestFrameIn of a frame or less with no condition (an if, a loop or an early return) around it. A line that does it on purpose says why with //appaudit:allow . It is a heuristic: a finding is a place to look. Viva runs it over itself in CI; its one ticker, the development reload host's source scan, says why. Motty runs it in its companion commit, where it would have caught the two polling loops that commit's predecessors replaced with notifications. --- .github/workflows/ci.yml | 5 + internal/devreload/watcher.go | 2 +- tools/appaudit/appaudit_test.go | 62 ++++ tools/appaudit/main.go | 346 +++++++++++++++++++++++ tools/appaudit/testdata/sample/sample.go | 53 ++++ 5 files changed, 467 insertions(+), 1 deletion(-) create mode 100644 tools/appaudit/appaudit_test.go create mode 100644 tools/appaudit/main.go create mode 100644 tools/appaudit/testdata/sample/sample.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f84b3e5af..96797e145 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 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/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) +} From 086247ad37014f043872016af193a4884d6b7380 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sun, 29 Nov 2026 14:02:03 +0800 Subject: [PATCH 2/5] feat(ui): let text fields inspect a paste before taking it --- app/painter.go | 9 ++ base/edit_menu.go | 22 +++-- base/field.go | 63 +++++++++++++ base/names.go | 1 + base/page.go | 1 + cmd/viva/initfiles/AGENTS.md.txt | 4 + ui/field_paste_test.go | 149 +++++++++++++++++++++++++++++++ window/text_input.go | 12 +++ 8 files changed, 254 insertions(+), 7 deletions(-) create mode 100644 ui/field_paste_test.go diff --git a/app/painter.go b/app/painter.go index 623d4a6d0..35bf72a6d 100644 --- a/app/painter.go +++ b/app/painter.go @@ -1628,6 +1628,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/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 25d7a70dc..a757ae166 100644 --- a/base/page.go +++ b/base/page.go @@ -1205,6 +1205,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 4076ce2d5..a870fd4e5 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -262,6 +262,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/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/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 From fcf7cba5ed52727a0f87a45a4b064dfc636c8633 Mon Sep 17 00:00:00 2001 From: muchen <145200703+Mucheen@users.noreply.github.com> Date: Sun, 29 Nov 2026 14:02:23 +0800 Subject: [PATCH 3/5] perf(markdown): index MarkdownView paint and hit testing --- cmd/viva/components_gen.go | 4 +- cmd/viva/templates/markdown.go.txt | 349 ++++++++++--------- cmd/viva/templates/markdown_index.go.txt | 423 +++++++++++++++++++++++ components/doc_test.go | 1 + components/markdown.go | 349 ++++++++++--------- components/markdown_index.go | 423 +++++++++++++++++++++++ components/markdown_index_test.go | 376 ++++++++++++++++++++ tools/docs/catalog.go | 2 +- 8 files changed, 1603 insertions(+), 324 deletions(-) create mode 100644 cmd/viva/templates/markdown_index.go.txt create mode 100644 components/markdown_index.go create mode 100644 components/markdown_index_test.go diff --git a/cmd/viva/components_gen.go b/cmd/viva/components_gen.go index 95d3c8a00..275b12ced 100644 --- a/cmd/viva/components_gen.go +++ b/cmd/viva/components_gen.go @@ -63,6 +63,7 @@ var componentFiles = map[string]string{ "label": "label.go.txt", "markdown": "markdown.go.txt", "markdown-anchor": "markdown_anchor.go.txt", + "markdown-index": "markdown_index.go.txt", "marker": "marker.go.txt", "menu-typeahead": "menu_typeahead.go.txt", "menubar": "menubar.go.txt", @@ -145,8 +146,9 @@ var componentRequires = map[string][]string{ "input-group": {"button", "input", "spinner", "textarea"}, "input-otp": {"input"}, "item": {"button"}, - "markdown": {"markdown-anchor"}, + "markdown": {"markdown-anchor", "markdown-index"}, "markdown-anchor": {"markdown"}, + "markdown-index": {"markdown"}, "marker": {"spinner"}, "menubar": {"dialog", "direction", "dropdown-menu", "hover-card", "popover"}, "metric-card": {"card"}, diff --git a/cmd/viva/templates/markdown.go.txt b/cmd/viva/templates/markdown.go.txt index e58982cae..4d10d75b6 100644 --- a/cmd/viva/templates/markdown.go.txt +++ b/cmd/viva/templates/markdown.go.txt @@ -143,29 +143,35 @@ var _ gfx.TextPlacement = (*MarkdownView)(nil) // Layout measures text and is the expensive half: do it when the text or the // width changed, and call Paint every frame. type MarkdownView struct { - pieces []mdPiece - runs []mdCodeRun - hl []MarkdownCodeRun - scratch []gfx.TextRun - selScratch []gfx.TextSpan - boxes []mdBox - links []mdLink - codes []MarkdownCode - images []mdImage - anchors []MarkdownAnchor - atoms []mdAtom - numbers []byte - tabs []byte // code lines with their tabs spread into blanks - tabBound []int32 // where each byte of a spread code line came from - plain []byte // the rendered text, for selection and copying - spanBase []int32 // where each span of the current inline block starts in plain - measure *gfx.Canvas - paintX float32 // where the last Paint put the document - paintY float32 - painted bool - bars [markdownMaxQuote + 1]int32 - face gfx.MonoFace - height float32 + pieces []mdPiece + runs []mdCodeRun + hl []MarkdownCodeRun + scratch []gfx.TextRun + selScratch []gfx.TextSpan + boxes []mdBox + links []mdLink + codes []MarkdownCode + images []mdImage + anchors []MarkdownAnchor + atoms []mdAtom + numbers []byte + tabs []byte // code lines with their tabs spread into blanks + tabBound []int32 // where each byte of a spread code line came from + plain []byte // the rendered text, for selection and copying + spanBase []int32 // where each span of the current inline block starts in plain + blockSpans []mdBlockSpan + rowSpans []mdRowSpan + cellSpans []mdCellSpan + tableRows []mdTableRowSpan + quoteBarIdx [markdownMaxQuote][]int32 + plainPieces []int32 + measure *gfx.Canvas + paintX float32 // where the last Paint put the document + paintY float32 + painted bool + bars [markdownMaxQuote + 1]int32 + face gfx.MonoFace + height float32 } // Height is the height of the laid-out document. @@ -190,53 +196,7 @@ func (v *MarkdownView) OffsetAt(point gfx.Point) (offset int, ok bool) { if !v.painted || v.measure == nil || len(v.pieces) == 0 { return 0, false } - x, y := point.X-v.paintX, point.Y-v.paintY - best, bestScore := -1, float32(0) - var previous *mdPiece - for index := range v.pieces { - piece := &v.pieces[index] - if piece.plainLo < 0 { - continue - } - if previous != nil && previous.y == piece.y && previous.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { - start := previous.x + v.caretAdvance(previous, int(previous.plainHi-previous.plainLo)) - end := piece.x + v.caretAdvance(piece, 0) - if end > start && x >= start && x <= end { - gap := int(piece.plainLo - previous.plainHi) - position := int(float32(gap)*(x-start)/(end-start) + 0.5) - return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(previous.plainHi)+min(max(position, 0), gap)), true - } - } - previous = piece - dx, dy := float32(0), float32(0) - if x < piece.x { - dx = piece.x - x - } else if x > piece.x+piece.w { - dx = x - piece.x - piece.w - } - if y < piece.y { - dy = piece.y - y - } else if y > piece.y+piece.h { - dy = y - piece.y - piece.h - } - score := dy*1_000_000 + dx - if best < 0 || score < bestScore { - best, bestScore = index, score - } - } - if best < 0 { - return 0, false - } - piece := &v.pieces[best] - localX := min(max(x-piece.x, 0), piece.w) - var local int - if piece.mono { - local = v.codeOffsetAt(piece, localX) - } else { - local = v.measure.TextOffsetAtStyle(piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, localX) - } - local = min(max(local, 0), int(piece.plainHi-piece.plainLo)) - return int(piece.plainLo) + local, true + return v.offsetAtIndexed(point.X-v.paintX, point.Y-v.paintY) } // CaretAt returns the window rectangle for a rendered byte offset after Paint. @@ -245,50 +205,7 @@ func (v *MarkdownView) CaretAt(offset int) (gfx.Rect, bool) { if !v.painted || v.measure == nil || len(v.pieces) == 0 { return gfx.Rect{}, false } - value := unsafe.String(unsafe.SliceData(v.plain), len(v.plain)) - offset = gfx.GraphemeStart(value, offset) - var chosen, before, after *mdPiece - for index := range v.pieces { - piece := &v.pieces[index] - if piece.plainLo < 0 { - continue - } - switch { - case offset >= int(piece.plainLo) && offset <= int(piece.plainHi): - if chosen == nil || piece.plainLo == int32(offset) && chosen.plainLo < int32(offset) { - chosen = piece - } - case int(piece.plainHi) < offset: - if before == nil || piece.plainHi > before.plainHi { - before = piece - } - case int(piece.plainLo) > offset: - if after == nil || piece.plainLo < after.plainLo { - after = piece - } - } - } - if chosen == nil { - if before != nil && after != nil && before.y == after.y { - start := before.x + v.caretAdvance(before, int(before.plainHi-before.plainLo)) - end := after.x + v.caretAdvance(after, 0) - fraction := float32(offset-int(before.plainHi)) / float32(after.plainLo-before.plainHi) - return gfx.Rect{X: v.paintX + start + (end-start)*fraction, Y: v.paintY + before.y, Width: 1, Height: before.h}, true - } - if before == nil && after == nil { - return gfx.Rect{}, false - } - if before == nil || after != nil && int(after.plainLo)-offset <= offset-int(before.plainHi) { - chosen = after - offset = int(after.plainLo) - } else { - chosen = before - offset = int(before.plainHi) - } - } - local := min(max(offset-int(chosen.plainLo), 0), int(chosen.plainHi-chosen.plainLo)) - advance := v.caretAdvance(chosen, local) - return gfx.Rect{X: v.paintX + chosen.x + advance, Y: v.paintY + chosen.y, Width: 1, Height: chosen.h}, true + return v.caretAtIndexed(offset) } func (v *MarkdownView) caretAdvance(piece *mdPiece, local int) float32 { @@ -520,6 +437,10 @@ func (v *MarkdownView) Layout(canvas *gfx.Canvas, style MarkdownStyle, doc *mark } v.images = v.images[:0] v.pieces, v.boxes, v.links, v.codes, v.anchors, v.numbers, v.runs, v.tabs, v.tabBound, v.plain, v.spanBase = v.pieces[:0], v.boxes[:0], v.links[:0], v.codes[:0], v.anchors[:0], v.numbers[:0], v.runs[:0], v.tabs[:0], v.tabBound[:0], v.plain[:0], v.spanBase[:0] + v.blockSpans, v.rowSpans, v.cellSpans, v.tableRows, v.plainPieces = v.blockSpans[:0], v.rowSpans[:0], v.cellSpans[:0], v.tableRows[:0], v.plainPieces[:0] + for qi := range v.quoteBarIdx { + v.quoteBarIdx[qi] = v.quoteBarIdx[qi][:0] + } v.bars = [markdownMaxQuote + 1]int32{} v.face = style.MonoFace v.measure = canvas @@ -544,35 +465,58 @@ func (v *MarkdownView) Layout(canvas *gfx.Canvas, style MarkdownStyle, doc *mark t.color = mdColMuted } l.blockBreak() + blkSpan := mdBlockSpan{kind: b.Kind, y: top, blockBox: -1, markerPiece: -1} switch b.Kind { case markdown.Paragraph: indent := float32(0) if b.Level > 0 { indent = float32(b.Level-1)*markdownListStep + markdownMarkerW } + blkSpan.rowLo = int32(len(v.rowSpans)) l.appendSpans(doc.Spans(b)) y = l.inline(doc.Spans(b), x0+indent, w-indent, y, t, markdown.AlignLeft) + blkSpan.rowHi = int32(len(v.rowSpans)) case markdown.Heading: + blkSpan.rowLo = int32(len(v.rowSpans)) l.appendSpans(doc.Spans(b)) y = l.inline(doc.Spans(b), x0, w, y, l.heading(b.Level, t), markdown.AlignLeft) + blkSpan.rowHi = int32(len(v.rowSpans)) case markdown.Item: indent := float32(b.Level)*markdownListStep + markdownMarkerW + blkSpan.markerPiece = int32(len(v.pieces)) l.marker(b, x0+float32(b.Level)*markdownListStep, y, t) + blkSpan.rowLo = int32(len(v.rowSpans)) l.appendSpans(doc.Spans(b)) y = l.inline(doc.Spans(b), x0+indent, w-indent, y, t, markdown.AlignLeft) + blkSpan.rowHi = int32(len(v.rowSpans)) y = max(y, top+t.line) case markdown.Code: + blkSpan.rowLo = int32(len(v.rowSpans)) y = l.code(b, x0, w, y) + blkSpan.rowHi = int32(len(v.rowSpans)) + if len(v.boxes) > 0 && v.boxes[len(v.boxes)-1].kind == mdBoxCode { + blkSpan.blockBox = int32(len(v.boxes) - 1) + } case markdown.Rule: + blkSpan.blockBox = int32(len(v.boxes)) v.boxes = append(v.boxes, mdBox{kind: mdBoxLine, x: x0, y: y + 6, w: w, h: 1}) y += 13 case markdown.Table: + blkSpan.tableRowLo = int32(len(v.tableRows)) y = l.table(b, x0, w, y, t) + blkSpan.tableRowHi = int32(len(v.tableRows)) } + blkSpan.bottom = y + v.blockSpans = append(v.blockSpans, blkSpan) l.quoteBars(b.Quote, top, y) v.anchors = append(v.anchors, MarkdownAnchor{Start: b.Start, End: b.End, Top: top, Bottom: y}) prev = b } + for i := range v.pieces { + if v.pieces[i].plainLo >= 0 { + v.plainPieces = append(v.plainPieces, int32(i)) + } + } v.height = y return y } @@ -649,8 +593,10 @@ func (l *mdLayout) quoteBars(quote int, top, bottom float32) { box.h = bottom - box.y continue } + boxIdx := int32(len(v.boxes)) v.boxes = append(v.boxes, mdBox{kind: mdBoxBar, x: float32(level-1)*markdownQuoteStep + 2, y: top, w: 3, h: bottom - top}) - v.bars[level] = int32(len(v.boxes)) + v.quoteBarIdx[level-1] = append(v.quoteBarIdx[level-1], boxIdx) + v.bars[level] = boxIdx + 1 } } @@ -704,6 +650,7 @@ func (l *mdLayout) code(b *markdown.Block, x, width, y float32) float32 { end, done := monoBreak(line[start:], cols) end += start end = codeBreak(line, bound, start, end) + pieceLo := int32(len(v.pieces)) if end > start { chunk := line[start:end] plainLo := int32(len(v.plain)) @@ -723,6 +670,10 @@ func (l *mdLayout) code(b *markdown.Block, x, width, y float32) float32 { v.pieces = append(v.pieces, piece) column += monoCells(chunk) } + v.rowSpans = append(v.rowSpans, mdRowSpan{ + y: y, bottom: y + height, + pieceLo: pieceLo, pieceHi: int32(len(v.pieces)), + }) l.lines++ y += height start = end @@ -986,6 +937,7 @@ func (l *mdLayout) table(b *markdown.Block, x, width, y float32, t mdFont) float } rowTop := y rowBottom := y + 2*markdownCellPadY + t.line + cellLo := int32(len(v.cellSpans)) cx := x for c := 0; c < columns; c++ { cell := cells[r*columns+c] @@ -996,16 +948,24 @@ func (l *mdLayout) table(b *markdown.Block, x, width, y float32, t mdFont) float if c > 0 { v.plain = append(v.plain, ' ') } + cRowLo := int32(len(v.rowSpans)) l.appendSpans(doc.CellSpans(cell)) end := l.inline(doc.CellSpans(cell), cx+markdownCellPadX, widths[c]-2*markdownCellPadX, rowTop+markdownCellPadY, style, cell.Align) + v.cellSpans = append(v.cellSpans, mdCellSpan{rowLo: cRowLo, rowHi: int32(len(v.rowSpans))}) rowBottom = max(rowBottom, end+markdownCellPadY) cx += widths[c] } y = rowBottom + boxLo := int32(len(v.boxes)) if r == 0 { v.boxes = append(v.boxes, mdBox{kind: mdBoxHead, x: x, y: rowTop, w: tableW, h: rowBottom - rowTop}) } v.boxes = append(v.boxes, mdBox{kind: mdBoxLine, x: x, y: y - 1, w: tableW, h: 1}) + v.tableRows = append(v.tableRows, mdTableRowSpan{ + y: rowTop, bottom: rowBottom, + cellLo: cellLo, cellHi: int32(len(v.cellSpans)), + boxLo: boxLo, boxHi: int32(len(v.boxes)), + }) } return y } @@ -1597,16 +1557,27 @@ func (m *mdLine) endLine() { } // A line with an image is as tall as the tallest image, with the text along its // top and a little air below the pixels so that stacked images do not touch. + lineTop := m.y m.y += max(m.t.line, m.tall+4) + v.rowSpans = append(v.rowSpans, mdRowSpan{ + y: lineTop, bottom: m.y, + pieceLo: int32(m.pieceP), pieceHi: int32(len(v.pieces)), + boxLo: int32(m.pieceB), boxHi: int32(len(v.boxes)), + linkLo: int32(m.pieceL), linkHi: int32(len(v.links)), + imageLo: int32(m.pieceI), imageHi: int32(len(v.images)), + }) m.l.lines++ m.reset() } -// Paint draws the laid-out document. +// Paint draws the laid-out document, querying the spatial index so only +// visible blocks, quote bars, table rows, and cell visual rows are visited. func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { v.paintX, v.paintY, v.painted = p.X, p.Y, true look := p.Look clipped := p.Clip.Height > 0 + clipTop := p.Clip.Y - p.Y + clipBottom := p.Clip.Y + p.Clip.Height - p.Y visible := func(y, h float32) bool { return !clipped || (y+h >= p.Clip.Y && y <= p.Clip.Y+p.Clip.Height) } @@ -1616,10 +1587,12 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { }) defer canvas.Unclip() } - for _, box := range v.boxes { + firstBlk, lastBlk := v.visibleBlockRange(clipped, clipTop, clipBottom) + + paintBox := func(box mdBox) { rect := gfx.Rect{X: p.X + box.x, Y: p.Y + box.y, Width: box.w, Height: box.h} if !visible(rect.Y, rect.Height) { - continue + return } switch box.kind { case mdBoxCode: @@ -1634,54 +1607,92 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { canvas.Rounded(rect, 4, look.InlineCodeFill) } } - for _, image := range v.images { - rect := gfx.Rect{X: p.X + image.x, Y: p.Y + image.y, Width: image.w, Height: image.h} - if visible(rect.Y, rect.Height) { - canvas.DrawBitmap(image.bitmap, rect) + + // Pass 1: quote bars, block/table backgrounds, and inline-code pills. + for level := 0; level < markdownMaxQuote; level++ { + for _, bi := range v.visibleQuoteBars(level, clipped, clipTop, clipBottom) { + paintBox(v.boxes[bi]) } } - start, end := p.Selection.Range(v.plain) - if start < end && look.Selection.Alpha > 0 { - for index := range v.pieces { - piece := &v.pieces[index] - if piece.plainLo < 0 { - continue + for bi := firstBlk; bi < lastBlk; bi++ { + blk := &v.blockSpans[bi] + if blk.blockBox >= 0 { + paintBox(v.boxes[blk.blockBox]) + } + if blk.kind == markdown.Table { + tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] + rLo, rHi := visibleTableRowRange(tRows, clipped, clipTop, clipBottom) + for ri := rLo; ri < rHi; ri++ { + tr := &tRows[ri] + for k := tr.boxLo; k < tr.boxHi; k++ { + paintBox(v.boxes[k]) + } } - lo, hi := max(int(piece.plainLo), start), min(int(piece.plainHi), end) - if lo >= hi || !visible(p.Y+piece.y, piece.h) { - continue + } + } + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for k := row.boxLo; k < row.boxHi; k++ { + paintBox(v.boxes[k]) + } + }) + + // Pass 2: images. + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for k := row.imageLo; k < row.imageHi; k++ { + image := &v.images[k] + rect := gfx.Rect{X: p.X + image.x, Y: p.Y + image.y, Width: image.w, Height: image.h} + if visible(rect.Y, rect.Height) { + canvas.DrawBitmap(image.bitmap, rect) } - if piece.mono { - from, to := lo-int(piece.plainLo), hi-int(piece.plainLo) - if piece.spread { - from, to = v.codeDisplayRange(piece, from, to) + } + }) + + // Pass 3: selection highlights. + start, end := p.Selection.Range(v.plain) + if start < end && look.Selection.Alpha > 0 { + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for index := row.pieceLo; index < row.pieceHi; index++ { + piece := &v.pieces[index] + if piece.plainLo < 0 { + continue + } + lo, hi := max(int(piece.plainLo), start), min(int(piece.plainHi), end) + if lo >= hi || !visible(p.Y+piece.y, piece.h) { + continue } - if to > from { - cell := piece.cell - if cell <= 0 { - cell = 1 + if piece.mono { + from, to := lo-int(piece.plainLo), hi-int(piece.plainLo) + if piece.spread { + from, to = v.codeDisplayRange(piece, from, to) } - x := p.X + piece.x + piece.padX + float32(monoCells(piece.text[:from]))*cell - width := float32(monoCells(piece.text[from:to])) * cell - canvas.Fill(gfx.Rect{X: x, Y: p.Y + piece.y, Width: width, Height: piece.h}, look.Selection) + if to > from { + cell := piece.cell + if cell <= 0 { + cell = 1 + } + x := p.X + piece.x + piece.padX + float32(monoCells(piece.text[:from]))*cell + width := float32(monoCells(piece.text[from:to])) * cell + canvas.Fill(gfx.Rect{X: x, Y: p.Y + piece.y, Width: width, Height: piece.h}, look.Selection) + } + continue + } + v.selScratch = canvas.TextSelectionStyle(v.selScratch[:0], piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, + lo-int(piece.plainLo), hi-int(piece.plainLo)) + for _, span := range v.selScratch { + canvas.Fill(gfx.Rect{X: p.X + piece.x + span.X, Y: p.Y + piece.y, Width: span.Width, Height: piece.h}, look.Selection) } - continue - } - v.selScratch = canvas.TextSelectionStyle(v.selScratch[:0], piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, - lo-int(piece.plainLo), hi-int(piece.plainLo)) - for _, span := range v.selScratch { - canvas.Fill(gfx.Rect{X: p.X + piece.x + span.X, Y: p.Y + piece.y, Width: span.Width, Height: piece.h}, look.Selection) } - } + }) } - for index := range v.pieces { - piece := &v.pieces[index] + + // Pass 4: text pieces (and list markers). + paintPiece := func(piece *mdPiece) { rect := gfx.Rect{ X: p.X + piece.x + piece.padX, Y: p.Y + piece.y, Width: piece.w - 2*piece.padX, Height: piece.h, } if !visible(rect.Y, rect.Height) { - continue + return } color := look.Text switch piece.color { @@ -1713,16 +1724,32 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { canvas.Fill(gfx.Rect{X: rect.X, Y: rect.Y + rect.Height/2, Width: rect.Width, Height: 1}, color) } } - for index := range v.links { - link := &v.links[index] - rect := gfx.Rect{X: p.X + link.x, Y: p.Y + link.y, Width: link.w, Height: link.h} - if !visible(rect.Y, rect.Height) || p.Links.IsZero() { - continue + for bi := firstBlk; bi < lastBlk; bi++ { + if mp := v.blockSpans[bi].markerPiece; mp >= 0 { + paintPiece(&v.pieces[mp]) } - id := p.Links.At(p.Base + index) - canvas.HitWithOptions(id, rect, link.text, gfx.HitOptions{Role: gfx.RoleLink}) - if canvas.Hovered() == id { - canvas.Fill(gfx.Rect{X: rect.X, Y: rect.Y + link.underline, Width: rect.Width, Height: 1}, look.Link) + } + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for index := row.pieceLo; index < row.pieceHi; index++ { + paintPiece(&v.pieces[index]) } + }) + + // Pass 5: clickable link hits & hover underlines. + if !p.Links.IsZero() { + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for index := int(row.linkLo); index < int(row.linkHi); index++ { + link := &v.links[index] + rect := gfx.Rect{X: p.X + link.x, Y: p.Y + link.y, Width: link.w, Height: link.h} + if !visible(rect.Y, rect.Height) { + continue + } + id := p.Links.At(p.Base + index) + canvas.HitWithOptions(id, rect, link.text, gfx.HitOptions{Role: gfx.RoleLink}) + if canvas.Hovered() == id { + canvas.Fill(gfx.Rect{X: rect.X, Y: rect.Y + link.underline, Width: rect.Width, Height: 1}, look.Link) + } + } + }) } } diff --git a/cmd/viva/templates/markdown_index.go.txt b/cmd/viva/templates/markdown_index.go.txt new file mode 100644 index 000000000..92ee0dca1 --- /dev/null +++ b/cmd/viva/templates/markdown_index.go.txt @@ -0,0 +1,423 @@ +package {{PACKAGE}} + +import ( + "sort" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/markdown" +) + +// Four-level hierarchical spatial index and independent text-offset index for +// MarkdownView. Original pieces, boxes, images, links and plain text stay in +// reading order so selection and copy semantics never change; Paint, OffsetAt +// and CaretAt query these flat reusable indices in O(log N + visible) time +// without steady-state allocations. + +// mdRowSpan indexes one laid-out visual line of a block or table cell. Ranges +// refer to contiguous slices of MarkdownView's backing arrays in exact emission +// order. +type mdRowSpan struct { + y, bottom float32 + pieceLo, pieceHi int32 + boxLo, boxHi int32 + linkLo, linkHi int32 + imageLo, imageHi int32 +} + +// mdCellSpan indexes the monotonic visual rows of one table cell. +type mdCellSpan struct { + rowLo, rowHi int32 +} + +// mdTableRowSpan indexes one row of a Table block: its cells (at most 24) and +// row-level boxes (header fill and horizontal divider). +type mdTableRowSpan struct { + y, bottom float32 + cellLo, cellHi int32 + boxLo, boxHi int32 +} + +// mdBlockSpan indexes one top-level block of the laid-out document. Blocks are +// strictly disjoint and monotonically ordered by y. +type mdBlockSpan struct { + kind markdown.Kind + y, bottom float32 + rowLo, rowHi int32 + tableRowLo, tableRowHi int32 + blockBox int32 // mdBoxCode or mdBoxLine, or -1 + markerPiece int32 // Item bullet/number piece, or -1 +} + +func (v *MarkdownView) visibleBlockRange(clipped bool, clipTop, clipBottom float32) (int, int) { + n := len(v.blockSpans) + if !clipped || n == 0 { + return 0, n + } + lo := sort.Search(n, func(i int) bool { return v.blockSpans[i].bottom >= clipTop }) + hi := sort.Search(n, func(i int) bool { return v.blockSpans[i].y > clipBottom }) + if hi < lo { + hi = lo + } + return lo, hi +} + +func visibleRowRange(rows []mdRowSpan, clipped bool, clipTop, clipBottom float32) (int, int) { + n := len(rows) + if !clipped || n == 0 { + return 0, n + } + lo := sort.Search(n, func(i int) bool { return rows[i].bottom >= clipTop }) + hi := sort.Search(n, func(i int) bool { return rows[i].y > clipBottom }) + if hi < lo { + hi = lo + } + return lo, hi +} + +func visibleTableRowRange(rows []mdTableRowSpan, clipped bool, clipTop, clipBottom float32) (int, int) { + n := len(rows) + if !clipped || n == 0 { + return 0, n + } + lo := sort.Search(n, func(i int) bool { return rows[i].bottom >= clipTop }) + hi := sort.Search(n, func(i int) bool { return rows[i].y > clipBottom }) + if hi < lo { + hi = lo + } + return lo, hi +} + +func (v *MarkdownView) visibleQuoteBars(level int, clipped bool, clipTop, clipBottom float32) []int32 { + bars := v.quoteBarIdx[level] + n := len(bars) + if !clipped || n == 0 { + return bars + } + lo := sort.Search(n, func(i int) bool { + b := v.boxes[bars[i]] + return b.y+b.h >= clipTop + }) + hi := sort.Search(n, func(i int) bool { + return v.boxes[bars[i]].y > clipBottom + }) + if hi < lo { + hi = lo + } + return bars[lo:hi] +} + +// visitVisibleRows invokes fn for every laid-out visual row intersecting +// [clipTop, clipBottom] inside blocks [firstBlk, lastBlk). For Table blocks it +// descends Table -> TableRow -> Cell -> CellVisualRow so a single very tall +// cell row only visits its visible lines. +func (v *MarkdownView) visitVisibleRows(firstBlk, lastBlk int, clipped bool, clipTop, clipBottom float32, fn func(row *mdRowSpan)) { + for bi := firstBlk; bi < lastBlk; bi++ { + blk := &v.blockSpans[bi] + if blk.kind == markdown.Table { + tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] + rLo, rHi := visibleTableRowRange(tRows, clipped, clipTop, clipBottom) + for ri := rLo; ri < rHi; ri++ { + tr := &tRows[ri] + for ci := tr.cellLo; ci < tr.cellHi; ci++ { + cell := &v.cellSpans[ci] + cRows := v.rowSpans[cell.rowLo:cell.rowHi] + lo, hi := visibleRowRange(cRows, clipped, clipTop, clipBottom) + for k := lo; k < hi; k++ { + fn(&cRows[k]) + } + } + } + continue + } + rows := v.rowSpans[blk.rowLo:blk.rowHi] + lo, hi := visibleRowRange(rows, clipped, clipTop, clipBottom) + for k := lo; k < hi; k++ { + fn(&rows[k]) + } + } +} + +// offsetAtIndexed locates the rendered byte offset nearest (x, y) in local +// coordinates using the hierarchical spatial index. Because every block, table +// row, and visual row strictly encloses its pieces vertically, widening outward +// by increasing vertical distance and pruning once minDy*1_000_000 > bestScore +// produces the exact same result as a full linear scan over v.pieces. +func (v *MarkdownView) offsetAtIndexed(x, y float32) (int, bool) { + if len(v.blockSpans) == 0 { + return 0, false + } + best, bestScore := -1, float32(0) + + prevPlainPiece := func(pi int32) *mdPiece { + for j := pi - 1; j >= 0; j-- { + if v.pieces[j].plainLo >= 0 { + return &v.pieces[j] + } + } + return nil + } + + checkRow := func(row *mdRowSpan) (int, bool) { + var previous *mdPiece + for pi := row.pieceLo; pi < row.pieceHi; pi++ { + piece := &v.pieces[pi] + if piece.plainLo < 0 { + continue + } + prev := previous + if prev == nil && y >= piece.y && y <= piece.y+piece.h { + prev = prevPlainPiece(pi) + } + if prev != nil && prev.y == piece.y && prev.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { + start := prev.x + v.caretAdvance(prev, int(prev.plainHi-prev.plainLo)) + end := piece.x + v.caretAdvance(piece, 0) + if end > start && x >= start && x <= end { + gap := int(piece.plainLo - prev.plainHi) + position := int(float32(gap)*(x-start)/(end-start) + 0.5) + return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(prev.plainHi)+min(max(position, 0), gap)), true + } + } + previous = piece + dx, dy := float32(0), float32(0) + if x < piece.x { + dx = piece.x - x + } else if x > piece.x+piece.w { + dx = x - piece.x - piece.w + } + if y < piece.y { + dy = piece.y - y + } else if y > piece.y+piece.h { + dy = y - piece.y - piece.h + } + score := dy*1_000_000 + dx + if best < 0 || score < bestScore || (score == bestScore && int(pi) < best) { + best, bestScore = int(pi), score + } + } + return 0, false + } + + spanDist := func(top, bottom float32) float32 { + if y < top { + return top - y + } + if y > bottom { + return y - bottom + } + return 0 + } + + spanCouldBeat := func(top, bottom float32) bool { + return best < 0 || spanDist(top, bottom)*1_000_000 <= bestScore + } + + // checkRowsNearY searches rows sorted by y around the pointer, widening + // within the slice before returning so empty rows (such as blank lines + // inside a code block) resolve against other rows of the same cell/block. + checkRowsNearY := func(rows []mdRowSpan) (int, bool) { + rn := len(rows) + if rn == 0 { + return 0, false + } + ri := sort.Search(rn, func(i int) bool { return rows[i].bottom >= y }) + up := ri - 1 + down := ri + if down < rn && y >= rows[down].y && y <= rows[down].bottom { + if off, hit := checkRow(&rows[down]); hit { + return off, true + } + down++ + } + for up >= 0 || down < rn { + upOK := up >= 0 && spanCouldBeat(rows[up].y, rows[up].bottom) + downOK := down < rn && spanCouldBeat(rows[down].y, rows[down].bottom) + if !upOK && !downOK { + break + } + if upOK && (!downOK || spanDist(rows[up].y, rows[up].bottom) <= spanDist(rows[down].y, rows[down].bottom)) { + if off, hit := checkRow(&rows[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkRow(&rows[down]); hit { + return off, true + } + down++ + } + } + return 0, false + } + + checkTableRow := func(tr *mdTableRowSpan) (int, bool) { + for ci := tr.cellLo; ci < tr.cellHi; ci++ { + cell := &v.cellSpans[ci] + if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { + return off, true + } + } + return 0, false + } + + checkBlock := func(blk *mdBlockSpan) (int, bool) { + if blk.kind == markdown.Table { + tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] + trn := len(tRows) + if trn == 0 { + return 0, false + } + tri := sort.Search(trn, func(i int) bool { return tRows[i].bottom >= y }) + up := tri - 1 + down := tri + if down < trn && y >= tRows[down].y && y <= tRows[down].bottom { + if off, hit := checkTableRow(&tRows[down]); hit { + return off, true + } + down++ + } + for up >= 0 || down < trn { + upOK := up >= 0 && spanCouldBeat(tRows[up].y, tRows[up].bottom) + downOK := down < trn && spanCouldBeat(tRows[down].y, tRows[down].bottom) + if !upOK && !downOK { + break + } + if upOK && (!downOK || spanDist(tRows[up].y, tRows[up].bottom) <= spanDist(tRows[down].y, tRows[down].bottom)) { + if off, hit := checkTableRow(&tRows[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkTableRow(&tRows[down]); hit { + return off, true + } + down++ + } + } + return 0, false + } + if off, hit := checkRowsNearY(v.rowSpans[blk.rowLo:blk.rowHi]); hit { + return off, true + } + return 0, false + } + + // Search the block covering y first, then widen outward by increasing + // vertical distance while any neighbour block could still beat bestScore. + n := len(v.blockSpans) + bi := sort.Search(n, func(i int) bool { return v.blockSpans[i].bottom >= y }) + up := bi - 1 + down := bi + if down < n && y >= v.blockSpans[down].y && y <= v.blockSpans[down].bottom { + if off, hit := checkBlock(&v.blockSpans[down]); hit { + return off, true + } + down++ + } + for up >= 0 || down < n { + upOK := up >= 0 && spanCouldBeat(v.blockSpans[up].y, v.blockSpans[up].bottom) + downOK := down < n && spanCouldBeat(v.blockSpans[down].y, v.blockSpans[down].bottom) + if !upOK && !downOK { + break + } + if upOK && (!downOK || spanDist(v.blockSpans[up].y, v.blockSpans[up].bottom) <= spanDist(v.blockSpans[down].y, v.blockSpans[down].bottom)) { + if off, hit := checkBlock(&v.blockSpans[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkBlock(&v.blockSpans[down]); hit { + return off, true + } + down++ + } + } + + if best < 0 { + return 0, false + } + piece := &v.pieces[best] + localX := min(max(x-piece.x, 0), piece.w) + var local int + if piece.mono { + local = v.codeOffsetAt(piece, localX) + } else { + local = v.measure.TextOffsetAtStyle(piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, localX) + } + local = min(max(local, 0), int(piece.plainHi-piece.plainLo)) + return int(piece.plainLo) + local, true +} + +// caretAtIndexed resolves a rendered byte offset using the monotonic +// plainPieces index in O(log P) time, preserving exact boundary affinity and +// same-line gap interpolation semantics. +func (v *MarkdownView) caretAtIndexed(offset int) (gfx.Rect, bool) { + n := len(v.plainPieces) + if n == 0 { + return gfx.Rect{}, false + } + value := unsafe.String(unsafe.SliceData(v.plain), len(v.plain)) + offset = gfx.GraphemeStart(value, offset) + + // Find the first text-bearing piece whose plainHi >= offset. + i := sort.Search(n, func(k int) bool { + return int(v.pieces[v.plainPieces[k]].plainHi) >= offset + }) + + var chosen, before, after *mdPiece + for i < n && v.pieces[v.plainPieces[i]].plainLo < 0 { + i++ + } + if i < n { + cand := &v.pieces[v.plainPieces[i]] + if offset >= int(cand.plainLo) && offset <= int(cand.plainHi) { + chosen = cand + // When offset sits on the exact seam between two adjacent pieces + // (prev.plainHi == offset == next.plainLo), prefer the piece that + // starts at offset, matching the linear scan's affinity rule. + if i+1 < n { + next := &v.pieces[v.plainPieces[i+1]] + if next.plainLo >= 0 && int(next.plainLo) == offset && int(chosen.plainLo) < offset { + chosen = next + } + } + } else { + after = cand + for j := i - 1; j >= 0; j-- { + if v.pieces[v.plainPieces[j]].plainLo >= 0 { + before = &v.pieces[v.plainPieces[j]] + break + } + } + } + } else { + for j := n - 1; j >= 0; j-- { + if v.pieces[v.plainPieces[j]].plainLo >= 0 { + before = &v.pieces[v.plainPieces[j]] + break + } + } + } + + if chosen == nil { + if before != nil && after != nil && before.y == after.y { + start := before.x + v.caretAdvance(before, int(before.plainHi-before.plainLo)) + end := after.x + v.caretAdvance(after, 0) + fraction := float32(offset-int(before.plainHi)) / float32(after.plainLo-before.plainHi) + return gfx.Rect{X: v.paintX + start + (end-start)*fraction, Y: v.paintY + before.y, Width: 1, Height: before.h}, true + } + if before == nil && after == nil { + return gfx.Rect{}, false + } + if before == nil || after != nil && int(after.plainLo)-offset <= offset-int(before.plainHi) { + chosen = after + offset = int(after.plainLo) + } else { + chosen = before + offset = int(before.plainHi) + } + } + local := min(max(offset-int(chosen.plainLo), 0), int(chosen.plainHi-chosen.plainLo)) + advance := v.caretAdvance(chosen, local) + return gfx.Rect{X: v.paintX + chosen.x + advance, Y: v.paintY + chosen.y, Width: 1, Height: chosen.h}, true +} diff --git a/components/doc_test.go b/components/doc_test.go index c16552bc9..aaf06f12e 100644 --- a/components/doc_test.go +++ b/components/doc_test.go @@ -36,6 +36,7 @@ var docPrimaryEntries = map[string][]string{ "kbd.go": {"Kbd"}, "markdown.go": {"MarkdownView"}, "markdown_anchor.go": {"MarkdownView"}, + "markdown_index.go": {"MarkdownView"}, "marker.go": {"Marker"}, "menu_typeahead.go": {"MenuTypeahead"}, "message.go": {"Message"}, diff --git a/components/markdown.go b/components/markdown.go index 2f24d1783..6bee1a52e 100644 --- a/components/markdown.go +++ b/components/markdown.go @@ -143,29 +143,35 @@ var _ gfx.TextPlacement = (*MarkdownView)(nil) // Layout measures text and is the expensive half: do it when the text or the // width changed, and call Paint every frame. type MarkdownView struct { - pieces []mdPiece - runs []mdCodeRun - hl []MarkdownCodeRun - scratch []gfx.TextRun - selScratch []gfx.TextSpan - boxes []mdBox - links []mdLink - codes []MarkdownCode - images []mdImage - anchors []MarkdownAnchor - atoms []mdAtom - numbers []byte - tabs []byte // code lines with their tabs spread into blanks - tabBound []int32 // where each byte of a spread code line came from - plain []byte // the rendered text, for selection and copying - spanBase []int32 // where each span of the current inline block starts in plain - measure *gfx.Canvas - paintX float32 // where the last Paint put the document - paintY float32 - painted bool - bars [markdownMaxQuote + 1]int32 - face gfx.MonoFace - height float32 + pieces []mdPiece + runs []mdCodeRun + hl []MarkdownCodeRun + scratch []gfx.TextRun + selScratch []gfx.TextSpan + boxes []mdBox + links []mdLink + codes []MarkdownCode + images []mdImage + anchors []MarkdownAnchor + atoms []mdAtom + numbers []byte + tabs []byte // code lines with their tabs spread into blanks + tabBound []int32 // where each byte of a spread code line came from + plain []byte // the rendered text, for selection and copying + spanBase []int32 // where each span of the current inline block starts in plain + blockSpans []mdBlockSpan + rowSpans []mdRowSpan + cellSpans []mdCellSpan + tableRows []mdTableRowSpan + quoteBarIdx [markdownMaxQuote][]int32 + plainPieces []int32 + measure *gfx.Canvas + paintX float32 // where the last Paint put the document + paintY float32 + painted bool + bars [markdownMaxQuote + 1]int32 + face gfx.MonoFace + height float32 } // Height is the height of the laid-out document. @@ -190,53 +196,7 @@ func (v *MarkdownView) OffsetAt(point gfx.Point) (offset int, ok bool) { if !v.painted || v.measure == nil || len(v.pieces) == 0 { return 0, false } - x, y := point.X-v.paintX, point.Y-v.paintY - best, bestScore := -1, float32(0) - var previous *mdPiece - for index := range v.pieces { - piece := &v.pieces[index] - if piece.plainLo < 0 { - continue - } - if previous != nil && previous.y == piece.y && previous.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { - start := previous.x + v.caretAdvance(previous, int(previous.plainHi-previous.plainLo)) - end := piece.x + v.caretAdvance(piece, 0) - if end > start && x >= start && x <= end { - gap := int(piece.plainLo - previous.plainHi) - position := int(float32(gap)*(x-start)/(end-start) + 0.5) - return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(previous.plainHi)+min(max(position, 0), gap)), true - } - } - previous = piece - dx, dy := float32(0), float32(0) - if x < piece.x { - dx = piece.x - x - } else if x > piece.x+piece.w { - dx = x - piece.x - piece.w - } - if y < piece.y { - dy = piece.y - y - } else if y > piece.y+piece.h { - dy = y - piece.y - piece.h - } - score := dy*1_000_000 + dx - if best < 0 || score < bestScore { - best, bestScore = index, score - } - } - if best < 0 { - return 0, false - } - piece := &v.pieces[best] - localX := min(max(x-piece.x, 0), piece.w) - var local int - if piece.mono { - local = v.codeOffsetAt(piece, localX) - } else { - local = v.measure.TextOffsetAtStyle(piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, localX) - } - local = min(max(local, 0), int(piece.plainHi-piece.plainLo)) - return int(piece.plainLo) + local, true + return v.offsetAtIndexed(point.X-v.paintX, point.Y-v.paintY) } // CaretAt returns the window rectangle for a rendered byte offset after Paint. @@ -245,50 +205,7 @@ func (v *MarkdownView) CaretAt(offset int) (gfx.Rect, bool) { if !v.painted || v.measure == nil || len(v.pieces) == 0 { return gfx.Rect{}, false } - value := unsafe.String(unsafe.SliceData(v.plain), len(v.plain)) - offset = gfx.GraphemeStart(value, offset) - var chosen, before, after *mdPiece - for index := range v.pieces { - piece := &v.pieces[index] - if piece.plainLo < 0 { - continue - } - switch { - case offset >= int(piece.plainLo) && offset <= int(piece.plainHi): - if chosen == nil || piece.plainLo == int32(offset) && chosen.plainLo < int32(offset) { - chosen = piece - } - case int(piece.plainHi) < offset: - if before == nil || piece.plainHi > before.plainHi { - before = piece - } - case int(piece.plainLo) > offset: - if after == nil || piece.plainLo < after.plainLo { - after = piece - } - } - } - if chosen == nil { - if before != nil && after != nil && before.y == after.y { - start := before.x + v.caretAdvance(before, int(before.plainHi-before.plainLo)) - end := after.x + v.caretAdvance(after, 0) - fraction := float32(offset-int(before.plainHi)) / float32(after.plainLo-before.plainHi) - return gfx.Rect{X: v.paintX + start + (end-start)*fraction, Y: v.paintY + before.y, Width: 1, Height: before.h}, true - } - if before == nil && after == nil { - return gfx.Rect{}, false - } - if before == nil || after != nil && int(after.plainLo)-offset <= offset-int(before.plainHi) { - chosen = after - offset = int(after.plainLo) - } else { - chosen = before - offset = int(before.plainHi) - } - } - local := min(max(offset-int(chosen.plainLo), 0), int(chosen.plainHi-chosen.plainLo)) - advance := v.caretAdvance(chosen, local) - return gfx.Rect{X: v.paintX + chosen.x + advance, Y: v.paintY + chosen.y, Width: 1, Height: chosen.h}, true + return v.caretAtIndexed(offset) } func (v *MarkdownView) caretAdvance(piece *mdPiece, local int) float32 { @@ -520,6 +437,10 @@ func (v *MarkdownView) Layout(canvas *gfx.Canvas, style MarkdownStyle, doc *mark } v.images = v.images[:0] v.pieces, v.boxes, v.links, v.codes, v.anchors, v.numbers, v.runs, v.tabs, v.tabBound, v.plain, v.spanBase = v.pieces[:0], v.boxes[:0], v.links[:0], v.codes[:0], v.anchors[:0], v.numbers[:0], v.runs[:0], v.tabs[:0], v.tabBound[:0], v.plain[:0], v.spanBase[:0] + v.blockSpans, v.rowSpans, v.cellSpans, v.tableRows, v.plainPieces = v.blockSpans[:0], v.rowSpans[:0], v.cellSpans[:0], v.tableRows[:0], v.plainPieces[:0] + for qi := range v.quoteBarIdx { + v.quoteBarIdx[qi] = v.quoteBarIdx[qi][:0] + } v.bars = [markdownMaxQuote + 1]int32{} v.face = style.MonoFace v.measure = canvas @@ -544,35 +465,58 @@ func (v *MarkdownView) Layout(canvas *gfx.Canvas, style MarkdownStyle, doc *mark t.color = mdColMuted } l.blockBreak() + blkSpan := mdBlockSpan{kind: b.Kind, y: top, blockBox: -1, markerPiece: -1} switch b.Kind { case markdown.Paragraph: indent := float32(0) if b.Level > 0 { indent = float32(b.Level-1)*markdownListStep + markdownMarkerW } + blkSpan.rowLo = int32(len(v.rowSpans)) l.appendSpans(doc.Spans(b)) y = l.inline(doc.Spans(b), x0+indent, w-indent, y, t, markdown.AlignLeft) + blkSpan.rowHi = int32(len(v.rowSpans)) case markdown.Heading: + blkSpan.rowLo = int32(len(v.rowSpans)) l.appendSpans(doc.Spans(b)) y = l.inline(doc.Spans(b), x0, w, y, l.heading(b.Level, t), markdown.AlignLeft) + blkSpan.rowHi = int32(len(v.rowSpans)) case markdown.Item: indent := float32(b.Level)*markdownListStep + markdownMarkerW + blkSpan.markerPiece = int32(len(v.pieces)) l.marker(b, x0+float32(b.Level)*markdownListStep, y, t) + blkSpan.rowLo = int32(len(v.rowSpans)) l.appendSpans(doc.Spans(b)) y = l.inline(doc.Spans(b), x0+indent, w-indent, y, t, markdown.AlignLeft) + blkSpan.rowHi = int32(len(v.rowSpans)) y = max(y, top+t.line) case markdown.Code: + blkSpan.rowLo = int32(len(v.rowSpans)) y = l.code(b, x0, w, y) + blkSpan.rowHi = int32(len(v.rowSpans)) + if len(v.boxes) > 0 && v.boxes[len(v.boxes)-1].kind == mdBoxCode { + blkSpan.blockBox = int32(len(v.boxes) - 1) + } case markdown.Rule: + blkSpan.blockBox = int32(len(v.boxes)) v.boxes = append(v.boxes, mdBox{kind: mdBoxLine, x: x0, y: y + 6, w: w, h: 1}) y += 13 case markdown.Table: + blkSpan.tableRowLo = int32(len(v.tableRows)) y = l.table(b, x0, w, y, t) + blkSpan.tableRowHi = int32(len(v.tableRows)) } + blkSpan.bottom = y + v.blockSpans = append(v.blockSpans, blkSpan) l.quoteBars(b.Quote, top, y) v.anchors = append(v.anchors, MarkdownAnchor{Start: b.Start, End: b.End, Top: top, Bottom: y}) prev = b } + for i := range v.pieces { + if v.pieces[i].plainLo >= 0 { + v.plainPieces = append(v.plainPieces, int32(i)) + } + } v.height = y return y } @@ -649,8 +593,10 @@ func (l *mdLayout) quoteBars(quote int, top, bottom float32) { box.h = bottom - box.y continue } + boxIdx := int32(len(v.boxes)) v.boxes = append(v.boxes, mdBox{kind: mdBoxBar, x: float32(level-1)*markdownQuoteStep + 2, y: top, w: 3, h: bottom - top}) - v.bars[level] = int32(len(v.boxes)) + v.quoteBarIdx[level-1] = append(v.quoteBarIdx[level-1], boxIdx) + v.bars[level] = boxIdx + 1 } } @@ -704,6 +650,7 @@ func (l *mdLayout) code(b *markdown.Block, x, width, y float32) float32 { end, done := monoBreak(line[start:], cols) end += start end = codeBreak(line, bound, start, end) + pieceLo := int32(len(v.pieces)) if end > start { chunk := line[start:end] plainLo := int32(len(v.plain)) @@ -723,6 +670,10 @@ func (l *mdLayout) code(b *markdown.Block, x, width, y float32) float32 { v.pieces = append(v.pieces, piece) column += monoCells(chunk) } + v.rowSpans = append(v.rowSpans, mdRowSpan{ + y: y, bottom: y + height, + pieceLo: pieceLo, pieceHi: int32(len(v.pieces)), + }) l.lines++ y += height start = end @@ -986,6 +937,7 @@ func (l *mdLayout) table(b *markdown.Block, x, width, y float32, t mdFont) float } rowTop := y rowBottom := y + 2*markdownCellPadY + t.line + cellLo := int32(len(v.cellSpans)) cx := x for c := 0; c < columns; c++ { cell := cells[r*columns+c] @@ -996,16 +948,24 @@ func (l *mdLayout) table(b *markdown.Block, x, width, y float32, t mdFont) float if c > 0 { v.plain = append(v.plain, ' ') } + cRowLo := int32(len(v.rowSpans)) l.appendSpans(doc.CellSpans(cell)) end := l.inline(doc.CellSpans(cell), cx+markdownCellPadX, widths[c]-2*markdownCellPadX, rowTop+markdownCellPadY, style, cell.Align) + v.cellSpans = append(v.cellSpans, mdCellSpan{rowLo: cRowLo, rowHi: int32(len(v.rowSpans))}) rowBottom = max(rowBottom, end+markdownCellPadY) cx += widths[c] } y = rowBottom + boxLo := int32(len(v.boxes)) if r == 0 { v.boxes = append(v.boxes, mdBox{kind: mdBoxHead, x: x, y: rowTop, w: tableW, h: rowBottom - rowTop}) } v.boxes = append(v.boxes, mdBox{kind: mdBoxLine, x: x, y: y - 1, w: tableW, h: 1}) + v.tableRows = append(v.tableRows, mdTableRowSpan{ + y: rowTop, bottom: rowBottom, + cellLo: cellLo, cellHi: int32(len(v.cellSpans)), + boxLo: boxLo, boxHi: int32(len(v.boxes)), + }) } return y } @@ -1597,16 +1557,27 @@ func (m *mdLine) endLine() { } // A line with an image is as tall as the tallest image, with the text along its // top and a little air below the pixels so that stacked images do not touch. + lineTop := m.y m.y += max(m.t.line, m.tall+4) + v.rowSpans = append(v.rowSpans, mdRowSpan{ + y: lineTop, bottom: m.y, + pieceLo: int32(m.pieceP), pieceHi: int32(len(v.pieces)), + boxLo: int32(m.pieceB), boxHi: int32(len(v.boxes)), + linkLo: int32(m.pieceL), linkHi: int32(len(v.links)), + imageLo: int32(m.pieceI), imageHi: int32(len(v.images)), + }) m.l.lines++ m.reset() } -// Paint draws the laid-out document. +// Paint draws the laid-out document, querying the spatial index so only +// visible blocks, quote bars, table rows, and cell visual rows are visited. func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { v.paintX, v.paintY, v.painted = p.X, p.Y, true look := p.Look clipped := p.Clip.Height > 0 + clipTop := p.Clip.Y - p.Y + clipBottom := p.Clip.Y + p.Clip.Height - p.Y visible := func(y, h float32) bool { return !clipped || (y+h >= p.Clip.Y && y <= p.Clip.Y+p.Clip.Height) } @@ -1616,10 +1587,12 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { }) defer canvas.Unclip() } - for _, box := range v.boxes { + firstBlk, lastBlk := v.visibleBlockRange(clipped, clipTop, clipBottom) + + paintBox := func(box mdBox) { rect := gfx.Rect{X: p.X + box.x, Y: p.Y + box.y, Width: box.w, Height: box.h} if !visible(rect.Y, rect.Height) { - continue + return } switch box.kind { case mdBoxCode: @@ -1634,54 +1607,92 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { canvas.Rounded(rect, 4, look.InlineCodeFill) } } - for _, image := range v.images { - rect := gfx.Rect{X: p.X + image.x, Y: p.Y + image.y, Width: image.w, Height: image.h} - if visible(rect.Y, rect.Height) { - canvas.DrawBitmap(image.bitmap, rect) + + // Pass 1: quote bars, block/table backgrounds, and inline-code pills. + for level := 0; level < markdownMaxQuote; level++ { + for _, bi := range v.visibleQuoteBars(level, clipped, clipTop, clipBottom) { + paintBox(v.boxes[bi]) } } - start, end := p.Selection.Range(v.plain) - if start < end && look.Selection.Alpha > 0 { - for index := range v.pieces { - piece := &v.pieces[index] - if piece.plainLo < 0 { - continue + for bi := firstBlk; bi < lastBlk; bi++ { + blk := &v.blockSpans[bi] + if blk.blockBox >= 0 { + paintBox(v.boxes[blk.blockBox]) + } + if blk.kind == markdown.Table { + tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] + rLo, rHi := visibleTableRowRange(tRows, clipped, clipTop, clipBottom) + for ri := rLo; ri < rHi; ri++ { + tr := &tRows[ri] + for k := tr.boxLo; k < tr.boxHi; k++ { + paintBox(v.boxes[k]) + } } - lo, hi := max(int(piece.plainLo), start), min(int(piece.plainHi), end) - if lo >= hi || !visible(p.Y+piece.y, piece.h) { - continue + } + } + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for k := row.boxLo; k < row.boxHi; k++ { + paintBox(v.boxes[k]) + } + }) + + // Pass 2: images. + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for k := row.imageLo; k < row.imageHi; k++ { + image := &v.images[k] + rect := gfx.Rect{X: p.X + image.x, Y: p.Y + image.y, Width: image.w, Height: image.h} + if visible(rect.Y, rect.Height) { + canvas.DrawBitmap(image.bitmap, rect) } - if piece.mono { - from, to := lo-int(piece.plainLo), hi-int(piece.plainLo) - if piece.spread { - from, to = v.codeDisplayRange(piece, from, to) + } + }) + + // Pass 3: selection highlights. + start, end := p.Selection.Range(v.plain) + if start < end && look.Selection.Alpha > 0 { + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for index := row.pieceLo; index < row.pieceHi; index++ { + piece := &v.pieces[index] + if piece.plainLo < 0 { + continue + } + lo, hi := max(int(piece.plainLo), start), min(int(piece.plainHi), end) + if lo >= hi || !visible(p.Y+piece.y, piece.h) { + continue } - if to > from { - cell := piece.cell - if cell <= 0 { - cell = 1 + if piece.mono { + from, to := lo-int(piece.plainLo), hi-int(piece.plainLo) + if piece.spread { + from, to = v.codeDisplayRange(piece, from, to) } - x := p.X + piece.x + piece.padX + float32(monoCells(piece.text[:from]))*cell - width := float32(monoCells(piece.text[from:to])) * cell - canvas.Fill(gfx.Rect{X: x, Y: p.Y + piece.y, Width: width, Height: piece.h}, look.Selection) + if to > from { + cell := piece.cell + if cell <= 0 { + cell = 1 + } + x := p.X + piece.x + piece.padX + float32(monoCells(piece.text[:from]))*cell + width := float32(monoCells(piece.text[from:to])) * cell + canvas.Fill(gfx.Rect{X: x, Y: p.Y + piece.y, Width: width, Height: piece.h}, look.Selection) + } + continue + } + v.selScratch = canvas.TextSelectionStyle(v.selScratch[:0], piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, + lo-int(piece.plainLo), hi-int(piece.plainLo)) + for _, span := range v.selScratch { + canvas.Fill(gfx.Rect{X: p.X + piece.x + span.X, Y: p.Y + piece.y, Width: span.Width, Height: piece.h}, look.Selection) } - continue - } - v.selScratch = canvas.TextSelectionStyle(v.selScratch[:0], piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, - lo-int(piece.plainLo), hi-int(piece.plainLo)) - for _, span := range v.selScratch { - canvas.Fill(gfx.Rect{X: p.X + piece.x + span.X, Y: p.Y + piece.y, Width: span.Width, Height: piece.h}, look.Selection) } - } + }) } - for index := range v.pieces { - piece := &v.pieces[index] + + // Pass 4: text pieces (and list markers). + paintPiece := func(piece *mdPiece) { rect := gfx.Rect{ X: p.X + piece.x + piece.padX, Y: p.Y + piece.y, Width: piece.w - 2*piece.padX, Height: piece.h, } if !visible(rect.Y, rect.Height) { - continue + return } color := look.Text switch piece.color { @@ -1713,16 +1724,32 @@ func (v *MarkdownView) Paint(canvas *gfx.Canvas, p MarkdownPaint) { canvas.Fill(gfx.Rect{X: rect.X, Y: rect.Y + rect.Height/2, Width: rect.Width, Height: 1}, color) } } - for index := range v.links { - link := &v.links[index] - rect := gfx.Rect{X: p.X + link.x, Y: p.Y + link.y, Width: link.w, Height: link.h} - if !visible(rect.Y, rect.Height) || p.Links.IsZero() { - continue + for bi := firstBlk; bi < lastBlk; bi++ { + if mp := v.blockSpans[bi].markerPiece; mp >= 0 { + paintPiece(&v.pieces[mp]) } - id := p.Links.At(p.Base + index) - canvas.HitWithOptions(id, rect, link.text, gfx.HitOptions{Role: gfx.RoleLink}) - if canvas.Hovered() == id { - canvas.Fill(gfx.Rect{X: rect.X, Y: rect.Y + link.underline, Width: rect.Width, Height: 1}, look.Link) + } + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for index := row.pieceLo; index < row.pieceHi; index++ { + paintPiece(&v.pieces[index]) } + }) + + // Pass 5: clickable link hits & hover underlines. + if !p.Links.IsZero() { + v.visitVisibleRows(firstBlk, lastBlk, clipped, clipTop, clipBottom, func(row *mdRowSpan) { + for index := int(row.linkLo); index < int(row.linkHi); index++ { + link := &v.links[index] + rect := gfx.Rect{X: p.X + link.x, Y: p.Y + link.y, Width: link.w, Height: link.h} + if !visible(rect.Y, rect.Height) { + continue + } + id := p.Links.At(p.Base + index) + canvas.HitWithOptions(id, rect, link.text, gfx.HitOptions{Role: gfx.RoleLink}) + if canvas.Hovered() == id { + canvas.Fill(gfx.Rect{X: rect.X, Y: rect.Y + link.underline, Width: rect.Width, Height: 1}, look.Link) + } + } + }) } } diff --git a/components/markdown_index.go b/components/markdown_index.go new file mode 100644 index 000000000..77bd100bf --- /dev/null +++ b/components/markdown_index.go @@ -0,0 +1,423 @@ +package components + +import ( + "sort" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/markdown" +) + +// Four-level hierarchical spatial index and independent text-offset index for +// MarkdownView. Original pieces, boxes, images, links and plain text stay in +// reading order so selection and copy semantics never change; Paint, OffsetAt +// and CaretAt query these flat reusable indices in O(log N + visible) time +// without steady-state allocations. + +// mdRowSpan indexes one laid-out visual line of a block or table cell. Ranges +// refer to contiguous slices of MarkdownView's backing arrays in exact emission +// order. +type mdRowSpan struct { + y, bottom float32 + pieceLo, pieceHi int32 + boxLo, boxHi int32 + linkLo, linkHi int32 + imageLo, imageHi int32 +} + +// mdCellSpan indexes the monotonic visual rows of one table cell. +type mdCellSpan struct { + rowLo, rowHi int32 +} + +// mdTableRowSpan indexes one row of a Table block: its cells (at most 24) and +// row-level boxes (header fill and horizontal divider). +type mdTableRowSpan struct { + y, bottom float32 + cellLo, cellHi int32 + boxLo, boxHi int32 +} + +// mdBlockSpan indexes one top-level block of the laid-out document. Blocks are +// strictly disjoint and monotonically ordered by y. +type mdBlockSpan struct { + kind markdown.Kind + y, bottom float32 + rowLo, rowHi int32 + tableRowLo, tableRowHi int32 + blockBox int32 // mdBoxCode or mdBoxLine, or -1 + markerPiece int32 // Item bullet/number piece, or -1 +} + +func (v *MarkdownView) visibleBlockRange(clipped bool, clipTop, clipBottom float32) (int, int) { + n := len(v.blockSpans) + if !clipped || n == 0 { + return 0, n + } + lo := sort.Search(n, func(i int) bool { return v.blockSpans[i].bottom >= clipTop }) + hi := sort.Search(n, func(i int) bool { return v.blockSpans[i].y > clipBottom }) + if hi < lo { + hi = lo + } + return lo, hi +} + +func visibleRowRange(rows []mdRowSpan, clipped bool, clipTop, clipBottom float32) (int, int) { + n := len(rows) + if !clipped || n == 0 { + return 0, n + } + lo := sort.Search(n, func(i int) bool { return rows[i].bottom >= clipTop }) + hi := sort.Search(n, func(i int) bool { return rows[i].y > clipBottom }) + if hi < lo { + hi = lo + } + return lo, hi +} + +func visibleTableRowRange(rows []mdTableRowSpan, clipped bool, clipTop, clipBottom float32) (int, int) { + n := len(rows) + if !clipped || n == 0 { + return 0, n + } + lo := sort.Search(n, func(i int) bool { return rows[i].bottom >= clipTop }) + hi := sort.Search(n, func(i int) bool { return rows[i].y > clipBottom }) + if hi < lo { + hi = lo + } + return lo, hi +} + +func (v *MarkdownView) visibleQuoteBars(level int, clipped bool, clipTop, clipBottom float32) []int32 { + bars := v.quoteBarIdx[level] + n := len(bars) + if !clipped || n == 0 { + return bars + } + lo := sort.Search(n, func(i int) bool { + b := v.boxes[bars[i]] + return b.y+b.h >= clipTop + }) + hi := sort.Search(n, func(i int) bool { + return v.boxes[bars[i]].y > clipBottom + }) + if hi < lo { + hi = lo + } + return bars[lo:hi] +} + +// visitVisibleRows invokes fn for every laid-out visual row intersecting +// [clipTop, clipBottom] inside blocks [firstBlk, lastBlk). For Table blocks it +// descends Table -> TableRow -> Cell -> CellVisualRow so a single very tall +// cell row only visits its visible lines. +func (v *MarkdownView) visitVisibleRows(firstBlk, lastBlk int, clipped bool, clipTop, clipBottom float32, fn func(row *mdRowSpan)) { + for bi := firstBlk; bi < lastBlk; bi++ { + blk := &v.blockSpans[bi] + if blk.kind == markdown.Table { + tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] + rLo, rHi := visibleTableRowRange(tRows, clipped, clipTop, clipBottom) + for ri := rLo; ri < rHi; ri++ { + tr := &tRows[ri] + for ci := tr.cellLo; ci < tr.cellHi; ci++ { + cell := &v.cellSpans[ci] + cRows := v.rowSpans[cell.rowLo:cell.rowHi] + lo, hi := visibleRowRange(cRows, clipped, clipTop, clipBottom) + for k := lo; k < hi; k++ { + fn(&cRows[k]) + } + } + } + continue + } + rows := v.rowSpans[blk.rowLo:blk.rowHi] + lo, hi := visibleRowRange(rows, clipped, clipTop, clipBottom) + for k := lo; k < hi; k++ { + fn(&rows[k]) + } + } +} + +// offsetAtIndexed locates the rendered byte offset nearest (x, y) in local +// coordinates using the hierarchical spatial index. Because every block, table +// row, and visual row strictly encloses its pieces vertically, widening outward +// by increasing vertical distance and pruning once minDy*1_000_000 > bestScore +// produces the exact same result as a full linear scan over v.pieces. +func (v *MarkdownView) offsetAtIndexed(x, y float32) (int, bool) { + if len(v.blockSpans) == 0 { + return 0, false + } + best, bestScore := -1, float32(0) + + prevPlainPiece := func(pi int32) *mdPiece { + for j := pi - 1; j >= 0; j-- { + if v.pieces[j].plainLo >= 0 { + return &v.pieces[j] + } + } + return nil + } + + checkRow := func(row *mdRowSpan) (int, bool) { + var previous *mdPiece + for pi := row.pieceLo; pi < row.pieceHi; pi++ { + piece := &v.pieces[pi] + if piece.plainLo < 0 { + continue + } + prev := previous + if prev == nil && y >= piece.y && y <= piece.y+piece.h { + prev = prevPlainPiece(pi) + } + if prev != nil && prev.y == piece.y && prev.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { + start := prev.x + v.caretAdvance(prev, int(prev.plainHi-prev.plainLo)) + end := piece.x + v.caretAdvance(piece, 0) + if end > start && x >= start && x <= end { + gap := int(piece.plainLo - prev.plainHi) + position := int(float32(gap)*(x-start)/(end-start) + 0.5) + return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(prev.plainHi)+min(max(position, 0), gap)), true + } + } + previous = piece + dx, dy := float32(0), float32(0) + if x < piece.x { + dx = piece.x - x + } else if x > piece.x+piece.w { + dx = x - piece.x - piece.w + } + if y < piece.y { + dy = piece.y - y + } else if y > piece.y+piece.h { + dy = y - piece.y - piece.h + } + score := dy*1_000_000 + dx + if best < 0 || score < bestScore || (score == bestScore && int(pi) < best) { + best, bestScore = int(pi), score + } + } + return 0, false + } + + spanDist := func(top, bottom float32) float32 { + if y < top { + return top - y + } + if y > bottom { + return y - bottom + } + return 0 + } + + spanCouldBeat := func(top, bottom float32) bool { + return best < 0 || spanDist(top, bottom)*1_000_000 <= bestScore + } + + // checkRowsNearY searches rows sorted by y around the pointer, widening + // within the slice before returning so empty rows (such as blank lines + // inside a code block) resolve against other rows of the same cell/block. + checkRowsNearY := func(rows []mdRowSpan) (int, bool) { + rn := len(rows) + if rn == 0 { + return 0, false + } + ri := sort.Search(rn, func(i int) bool { return rows[i].bottom >= y }) + up := ri - 1 + down := ri + if down < rn && y >= rows[down].y && y <= rows[down].bottom { + if off, hit := checkRow(&rows[down]); hit { + return off, true + } + down++ + } + for up >= 0 || down < rn { + upOK := up >= 0 && spanCouldBeat(rows[up].y, rows[up].bottom) + downOK := down < rn && spanCouldBeat(rows[down].y, rows[down].bottom) + if !upOK && !downOK { + break + } + if upOK && (!downOK || spanDist(rows[up].y, rows[up].bottom) <= spanDist(rows[down].y, rows[down].bottom)) { + if off, hit := checkRow(&rows[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkRow(&rows[down]); hit { + return off, true + } + down++ + } + } + return 0, false + } + + checkTableRow := func(tr *mdTableRowSpan) (int, bool) { + for ci := tr.cellLo; ci < tr.cellHi; ci++ { + cell := &v.cellSpans[ci] + if off, hit := checkRowsNearY(v.rowSpans[cell.rowLo:cell.rowHi]); hit { + return off, true + } + } + return 0, false + } + + checkBlock := func(blk *mdBlockSpan) (int, bool) { + if blk.kind == markdown.Table { + tRows := v.tableRows[blk.tableRowLo:blk.tableRowHi] + trn := len(tRows) + if trn == 0 { + return 0, false + } + tri := sort.Search(trn, func(i int) bool { return tRows[i].bottom >= y }) + up := tri - 1 + down := tri + if down < trn && y >= tRows[down].y && y <= tRows[down].bottom { + if off, hit := checkTableRow(&tRows[down]); hit { + return off, true + } + down++ + } + for up >= 0 || down < trn { + upOK := up >= 0 && spanCouldBeat(tRows[up].y, tRows[up].bottom) + downOK := down < trn && spanCouldBeat(tRows[down].y, tRows[down].bottom) + if !upOK && !downOK { + break + } + if upOK && (!downOK || spanDist(tRows[up].y, tRows[up].bottom) <= spanDist(tRows[down].y, tRows[down].bottom)) { + if off, hit := checkTableRow(&tRows[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkTableRow(&tRows[down]); hit { + return off, true + } + down++ + } + } + return 0, false + } + if off, hit := checkRowsNearY(v.rowSpans[blk.rowLo:blk.rowHi]); hit { + return off, true + } + return 0, false + } + + // Search the block covering y first, then widen outward by increasing + // vertical distance while any neighbour block could still beat bestScore. + n := len(v.blockSpans) + bi := sort.Search(n, func(i int) bool { return v.blockSpans[i].bottom >= y }) + up := bi - 1 + down := bi + if down < n && y >= v.blockSpans[down].y && y <= v.blockSpans[down].bottom { + if off, hit := checkBlock(&v.blockSpans[down]); hit { + return off, true + } + down++ + } + for up >= 0 || down < n { + upOK := up >= 0 && spanCouldBeat(v.blockSpans[up].y, v.blockSpans[up].bottom) + downOK := down < n && spanCouldBeat(v.blockSpans[down].y, v.blockSpans[down].bottom) + if !upOK && !downOK { + break + } + if upOK && (!downOK || spanDist(v.blockSpans[up].y, v.blockSpans[up].bottom) <= spanDist(v.blockSpans[down].y, v.blockSpans[down].bottom)) { + if off, hit := checkBlock(&v.blockSpans[up]); hit { + return off, true + } + up-- + } else { + if off, hit := checkBlock(&v.blockSpans[down]); hit { + return off, true + } + down++ + } + } + + if best < 0 { + return 0, false + } + piece := &v.pieces[best] + localX := min(max(x-piece.x, 0), piece.w) + var local int + if piece.mono { + local = v.codeOffsetAt(piece, localX) + } else { + local = v.measure.TextOffsetAtStyle(piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, localX) + } + local = min(max(local, 0), int(piece.plainHi-piece.plainLo)) + return int(piece.plainLo) + local, true +} + +// caretAtIndexed resolves a rendered byte offset using the monotonic +// plainPieces index in O(log P) time, preserving exact boundary affinity and +// same-line gap interpolation semantics. +func (v *MarkdownView) caretAtIndexed(offset int) (gfx.Rect, bool) { + n := len(v.plainPieces) + if n == 0 { + return gfx.Rect{}, false + } + value := unsafe.String(unsafe.SliceData(v.plain), len(v.plain)) + offset = gfx.GraphemeStart(value, offset) + + // Find the first text-bearing piece whose plainHi >= offset. + i := sort.Search(n, func(k int) bool { + return int(v.pieces[v.plainPieces[k]].plainHi) >= offset + }) + + var chosen, before, after *mdPiece + for i < n && v.pieces[v.plainPieces[i]].plainLo < 0 { + i++ + } + if i < n { + cand := &v.pieces[v.plainPieces[i]] + if offset >= int(cand.plainLo) && offset <= int(cand.plainHi) { + chosen = cand + // When offset sits on the exact seam between two adjacent pieces + // (prev.plainHi == offset == next.plainLo), prefer the piece that + // starts at offset, matching the linear scan's affinity rule. + if i+1 < n { + next := &v.pieces[v.plainPieces[i+1]] + if next.plainLo >= 0 && int(next.plainLo) == offset && int(chosen.plainLo) < offset { + chosen = next + } + } + } else { + after = cand + for j := i - 1; j >= 0; j-- { + if v.pieces[v.plainPieces[j]].plainLo >= 0 { + before = &v.pieces[v.plainPieces[j]] + break + } + } + } + } else { + for j := n - 1; j >= 0; j-- { + if v.pieces[v.plainPieces[j]].plainLo >= 0 { + before = &v.pieces[v.plainPieces[j]] + break + } + } + } + + if chosen == nil { + if before != nil && after != nil && before.y == after.y { + start := before.x + v.caretAdvance(before, int(before.plainHi-before.plainLo)) + end := after.x + v.caretAdvance(after, 0) + fraction := float32(offset-int(before.plainHi)) / float32(after.plainLo-before.plainHi) + return gfx.Rect{X: v.paintX + start + (end-start)*fraction, Y: v.paintY + before.y, Width: 1, Height: before.h}, true + } + if before == nil && after == nil { + return gfx.Rect{}, false + } + if before == nil || after != nil && int(after.plainLo)-offset <= offset-int(before.plainHi) { + chosen = after + offset = int(after.plainLo) + } else { + chosen = before + offset = int(before.plainHi) + } + } + local := min(max(offset-int(chosen.plainLo), 0), int(chosen.plainHi-chosen.plainLo)) + advance := v.caretAdvance(chosen, local) + return gfx.Rect{X: v.paintX + chosen.x + advance, Y: v.paintY + chosen.y, Width: 1, Height: chosen.h}, true +} diff --git a/components/markdown_index_test.go b/components/markdown_index_test.go new file mode 100644 index 000000000..1f8d838c7 --- /dev/null +++ b/components/markdown_index_test.go @@ -0,0 +1,376 @@ +package components + +import ( + "fmt" + "strings" + "testing" + "unsafe" + + "github.com/vivaui/viva/base" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/markdown" +) + +// linearOffsetAtReference mirrors the pre-index linear scan over v.pieces so +// tests can verify exact equivalence across dense grids of pointer positions. +func linearOffsetAtReference(v *MarkdownView, point gfx.Point) (int, bool) { + if !v.painted || v.measure == nil || len(v.pieces) == 0 { + return 0, false + } + x, y := point.X-v.paintX, point.Y-v.paintY + best, bestScore := -1, float32(0) + var previous *mdPiece + for index := range v.pieces { + piece := &v.pieces[index] + if piece.plainLo < 0 { + continue + } + if previous != nil && previous.y == piece.y && previous.plainHi < piece.plainLo && y >= piece.y && y <= piece.y+piece.h { + start := previous.x + v.caretAdvance(previous, int(previous.plainHi-previous.plainLo)) + end := piece.x + v.caretAdvance(piece, 0) + if end > start && x >= start && x <= end { + gap := int(piece.plainLo - previous.plainHi) + position := int(float32(gap)*(x-start)/(end-start) + 0.5) + return gfx.GraphemeStart(unsafe.String(unsafe.SliceData(v.plain), len(v.plain)), int(previous.plainHi)+min(max(position, 0), gap)), true + } + } + previous = piece + dx, dy := float32(0), float32(0) + if x < piece.x { + dx = piece.x - x + } else if x > piece.x+piece.w { + dx = x - piece.x - piece.w + } + if y < piece.y { + dy = piece.y - y + } else if y > piece.y+piece.h { + dy = y - piece.y - piece.h + } + score := dy*1_000_000 + dx + if best < 0 || score < bestScore { + best, bestScore = index, score + } + } + if best < 0 { + return 0, false + } + piece := &v.pieces[best] + localX := min(max(x-piece.x, 0), piece.w) + var local int + if piece.mono { + local = v.codeOffsetAt(piece, localX) + } else { + local = v.measure.TextOffsetAtStyle(piece.text, gfx.TextStyle{Size: piece.size, Weight: piece.weight, Italic: piece.italic}, localX) + } + local = min(max(local, 0), int(piece.plainHi-piece.plainLo)) + return int(piece.plainLo) + local, true +} + +// linearCaretAtReference mirrors the pre-index linear scan over v.pieces so +// tests can verify exact equivalence for every byte offset. +func linearCaretAtReference(v *MarkdownView, offset int) (gfx.Rect, bool) { + if !v.painted || v.measure == nil || len(v.pieces) == 0 { + return gfx.Rect{}, false + } + value := unsafe.String(unsafe.SliceData(v.plain), len(v.plain)) + offset = gfx.GraphemeStart(value, offset) + var chosen, before, after *mdPiece + for index := range v.pieces { + piece := &v.pieces[index] + if piece.plainLo < 0 { + continue + } + switch { + case offset >= int(piece.plainLo) && offset <= int(piece.plainHi): + if chosen == nil || piece.plainLo == int32(offset) && chosen.plainLo < int32(offset) { + chosen = piece + } + case int(piece.plainHi) < offset: + if before == nil || piece.plainHi > before.plainHi { + before = piece + } + case int(piece.plainLo) > offset: + if after == nil || piece.plainLo < after.plainLo { + after = piece + } + } + } + if chosen == nil { + if before != nil && after != nil && before.y == after.y { + start := before.x + v.caretAdvance(before, int(before.plainHi-before.plainLo)) + end := after.x + v.caretAdvance(after, 0) + fraction := float32(offset-int(before.plainHi)) / float32(after.plainLo-before.plainHi) + return gfx.Rect{X: v.paintX + start + (end-start)*fraction, Y: v.paintY + before.y, Width: 1, Height: before.h}, true + } + if before == nil && after == nil { + return gfx.Rect{}, false + } + if before == nil || after != nil && int(after.plainLo)-offset <= offset-int(before.plainHi) { + chosen = after + offset = int(after.plainLo) + } else { + chosen = before + offset = int(before.plainHi) + } + } + local := min(max(offset-int(chosen.plainLo), 0), int(chosen.plainHi-chosen.plainLo)) + advance := v.caretAdvance(chosen, local) + return gfx.Rect{X: v.paintX + chosen.x + advance, Y: v.paintY + chosen.y, Width: 1, Height: chosen.h}, true +} + +func TestMarkdownIndexMatchesLinearReferenceOnGrid(t *testing.T) { + fullSrc := strings.Join([]string{ + "# Overview", + "", + "before text with [link](https://example.com) and `code` 中文", + "", + "```go", + "firstLine := 1", + "", + "", + "", + "lastLine := 2", + "```", + "", + "after text", + "", + "---", + "", + "```", + "", + "", + "", + "onlyTrailing()", + "```", + "", + "> outer quote line one", + ">> nested quote line two", + "", + "| Col A | Col B | Col C |", + "| --- | :---: | ---: |", + "| alpha | | gamma wrapped across multiple words in a narrow column |", + "| | | |", + "| delta | epsilon | zeta |", + "", + "1. First item", + "2. Second item with **bold** and *italic*", + "", + "- Unordered bullet", + }, "\n") + + edgeSrc := strings.Join([]string{ + "lead paragraph", + "", + "---", + "", + "---", + "", + "```", + "", + "", + "", + "```", + "", + "| A | B |", + "| - | - |", + "| | |", + "", + "tail paragraph", + }, "\n") + + cases := []struct { + name string + src string + width float32 + }{ + {name: "parsed-full-features", src: fullSrc, width: 320}, + {name: "parsed-empty-blocks-and-rules", src: edgeSrc, width: 260}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + var doc markdown.Document + doc.Parse(tc.src) + + canvas := markdownCanvas() + var view MarkdownView + h := view.Layout(canvas, MarkdownStyle{Size: 13, LineHeight: 20}, &doc, tc.width) + if h <= 0 { + t.Fatalf("expected positive height, got %v", h) + } + const originX, originY float32 = 16, 24 + canvas.Reset() + view.Paint(canvas, MarkdownPaint{ + Look: MarkdownLookFor(gfx.Theme{}), + X: originX, + Y: originY, + }) + + // Verify OffsetAt on a dense grid covering margins, gaps, blank code + // lines, rules, table cell gaps, and boundaries. + for y := float32(-10); y <= h+20; y += 5 { + for x := float32(-10); x <= tc.width+20; x += 17 { + pt := gfx.Point{X: originX + x, Y: originY + y} + gotOff, gotOK := view.OffsetAt(pt) + wantOff, wantOK := linearOffsetAtReference(&view, pt) + if gotOff != wantOff || gotOK != wantOK { + t.Fatalf("OffsetAt(%v) = (%d, %v), want linear (%d, %v)", pt, gotOff, gotOK, wantOff, wantOK) + } + } + } + + // Verify CaretAt for every byte offset in [0, TextLen]. + n := view.TextLen() + for off := 0; off <= n; off++ { + gotRect, gotOK := view.CaretAt(off) + wantRect, wantOK := linearCaretAtReference(&view, off) + if gotRect != wantRect || gotOK != wantOK { + t.Fatalf("CaretAt(%d) = (%+v, %v), want linear (%+v, %v)", off, gotRect, gotOK, wantRect, wantOK) + } + } + }) + } +} + +func TestMarkdownEmptyCodeLinesStayInCodeBlock(t *testing.T) { + // Direct regression for blank lines inside a code block: clicking an empty + // line between code lines must resolve to the code block, not before/after text. + src := "before text\n\n```\nline1\n\n\n\nline5\n```\n\nafter text\n" + var doc markdown.Document + doc.Parse(src) + + canvas := markdownCanvas() + var view MarkdownView + h := view.Layout(canvas, MarkdownStyle{Size: 13, LineHeight: 20}, &doc, 400) + canvas.Reset() + view.Paint(canvas, MarkdownPaint{Look: MarkdownLookFor(gfx.Theme{})}) + + plain := view.SelectedText(base.TextRange{Anchor: 0, Focus: view.TextLen()}) + codeLo := strings.Index(plain, "line1") + codeHi := strings.Index(plain, "line5") + len("line5") + if codeLo < 0 || codeHi <= codeLo { + t.Fatalf("expected code block text in plain %q", plain) + } + r1, ok1 := view.CaretAt(codeLo) + r5, ok5 := view.CaretAt(codeHi) + if !ok1 || !ok5 || r5.Y <= r1.Y+r1.Height { + t.Fatalf("expected empty lines between line1 (%+v) and line5 (%+v), height=%v", r1, r5, h) + } + for y := r1.Y + r1.Height + 2; y < r5.Y; y += 6 { + off, ok := view.OffsetAt(gfx.Point{X: 40, Y: y}) + if !ok || off < codeLo || off > codeHi { + t.Fatalf("empty code line at y=%v resolved to offset %d (plain=%q), want inside [%d,%d]", y, off, plain, codeLo, codeHi) + } + } +} + +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 BenchmarkMarkdownViewClippedPaintSteady(b *testing.B) { + var sb strings.Builder + for i := 0; i < 400; i++ { + 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) + look := MarkdownLookFor(gfx.Theme{}) + paint := MarkdownPaint{ + Look: look, + X: 0, + Y: -4000, + Clip: gfx.Rect{X: 0, Y: 0, Width: 500, Height: 300}, + } + // Warm canvas command buffer and view scratch slices. + canvas.Reset() + view.Paint(canvas, paint) + + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + canvas.Reset() + view.Paint(canvas, paint) + } +} diff --git a/tools/docs/catalog.go b/tools/docs/catalog.go index 8709dfdfe..41e293e03 100644 --- a/tools/docs/catalog.go +++ b/tools/docs/catalog.go @@ -224,7 +224,7 @@ func loadPages(root string) ([]Page, Manifest, error) { if file.Name() == "doc.go" || file.Name() == "direction.go" || file.Name() == "menu_typeahead.go" || file.Name() == "code_diff_model.go" || file.Name() == "code_diff_inline.go" || file.Name() == "code_editor_layout.go" || file.Name() == "code_editor_decorations.go" || file.Name() == "code_editor_shaped.go" || file.Name() == "caret_blink.go" || file.Name() == "find_bar.go" || file.Name() == "go_to_line.go" || file.Name() == "hierarchy_menu.go" || - file.Name() == "graph_sim.go" || file.Name() == "markdown_anchor.go" || file.Name() == "text_selection.go" { + file.Name() == "graph_sim.go" || file.Name() == "markdown_anchor.go" || file.Name() == "markdown_index.go" || file.Name() == "text_selection.go" { continue } id := strings.ReplaceAll(strings.TrimSuffix(file.Name(), ".go"), "_", "-") From a3eda45771f548e9857872045ef9885f1b5a3391 Mon Sep 17 00:00:00 2001 From: Xiaoyumuxi <23722032@bjtu.edu.cn> Date: Sun, 29 Nov 2026 14:04:58 +0800 Subject: [PATCH 4/5] fix(base): keep a text that fits exactly when rounding falls short --- base/flex_test.go | 38 ++++++++++++++++++++++++++++++++++++++ base/layout.go | 24 ++++++++++++++++++++++-- 2 files changed, 60 insertions(+), 2 deletions(-) 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] From a3ba5df6ba4094eb271c54f6b337d0226b88f898 Mon Sep 17 00:00:00 2001 From: jakey <267309453@qq.com> Date: Sun, 29 Nov 2026 14:24:44 +0800 Subject: [PATCH 5/5] feat(video): add shared-texture video playback and GIF/APNG decoders --- .github/workflows/ci.yml | 10 + cmd/viva/initfiles/AGENTS.md.txt | 2 +- docs/README.md | 2 + docs/maintaining-controls.md | 2 +- docs/skills/building-with-viva/SKILL.md | 2 +- docs/video.md | 112 +++ examples/guides/video/colors.mp4 | Bin 0 -> 68348 bytes examples/guides/video/main.go | 174 ++++ examples/guides/video/main_test.go | 123 +++ examples/guides/video/waves.gif | Bin 0 -> 118254 bytes gfx/canvas.go | 48 +- gfx/texture_test.go | 66 ++ internal/framebuild/framebuild.go | 63 ++ internal/framebuild/texture_native_test.go | 97 ++ internal/media/av_darwin.go | 550 +++++++++++ internal/media/av_darwin.h | 59 ++ internal/media/av_darwin.m | 449 +++++++++ internal/media/av_darwin_test.go | 367 ++++++++ internal/media/device_windows.go | 249 +++++ internal/media/device_windows_test.go | 54 ++ internal/media/float_windows_amd64.go | 30 + internal/media/float_windows_arm64.go | 71 ++ internal/media/media.go | 81 ++ internal/media/media_unsupported.go | 10 + internal/media/mf_windows.go | 872 ++++++++++++++++++ internal/media/mf_windows_test.go | 142 +++ internal/media/shared_windows_other.go | 7 + internal/media/testdata/colors.mp4 | Bin 0 -> 68348 bytes internal/platform/contract.go | 11 + internal/platform/darwin/composite_test.go | 8 +- internal/platform/darwin/core.h | 14 + internal/platform/darwin/core_render.m | 117 ++- internal/platform/darwin/native.h | 13 + internal/platform/darwin/platform.go | 14 +- .../platform/darwin/shared_darwin_test.go | 115 +++ internal/platform/label_validate.go | 10 +- internal/platform/label_validate_test.go | 37 + internal/platform/native_textures_darwin.go | 8 + internal/platform/native_textures_other.go | 8 + internal/platform/native_textures_windows.go | 8 + internal/platform/windows/renderer_windows.go | 30 +- internal/platform/windows/shared_windows.go | 236 +++++ .../platform/windows/shared_windows_test.go | 159 ++++ internal/platform/windows/text_windows.go | 11 + ui/video/apng.go | 481 ++++++++++ ui/video/apng_test.go | 389 ++++++++ ui/video/decode.go | 73 ++ ui/video/decoder.go | 436 +++++++++ ui/video/fit.go | 35 + ui/video/fit_test.go | 46 + ui/video/gif.go | 415 +++++++++ ui/video/gif_test.go | 320 +++++++ ui/video/player.go | 443 +++++++++ ui/video/player_test.go | 473 ++++++++++ ui/video/video.go | 85 ++ ui/video/video_test.go | 41 + ui/video/view.go | 21 + ui/video/view_test.go | 222 +++++ website/content/guides/en/components.md | 184 +++- website/content/guides/zh/components.md | 184 +++- 60 files changed, 8265 insertions(+), 24 deletions(-) create mode 100644 docs/video.md create mode 100644 examples/guides/video/colors.mp4 create mode 100644 examples/guides/video/main.go create mode 100644 examples/guides/video/main_test.go create mode 100644 examples/guides/video/waves.gif create mode 100644 gfx/texture_test.go create mode 100644 internal/framebuild/texture_native_test.go create mode 100644 internal/media/av_darwin.go create mode 100644 internal/media/av_darwin.h create mode 100644 internal/media/av_darwin.m create mode 100644 internal/media/av_darwin_test.go create mode 100644 internal/media/device_windows.go create mode 100644 internal/media/device_windows_test.go create mode 100644 internal/media/float_windows_amd64.go create mode 100644 internal/media/float_windows_arm64.go create mode 100644 internal/media/media.go create mode 100644 internal/media/media_unsupported.go create mode 100644 internal/media/mf_windows.go create mode 100644 internal/media/mf_windows_test.go create mode 100644 internal/media/shared_windows_other.go create mode 100644 internal/media/testdata/colors.mp4 create mode 100644 internal/platform/darwin/shared_darwin_test.go create mode 100644 internal/platform/label_validate_test.go create mode 100644 internal/platform/native_textures_darwin.go create mode 100644 internal/platform/native_textures_other.go create mode 100644 internal/platform/native_textures_windows.go create mode 100644 internal/platform/windows/shared_windows.go create mode 100644 internal/platform/windows/shared_windows_test.go create mode 100644 ui/video/apng.go create mode 100644 ui/video/apng_test.go create mode 100644 ui/video/decode.go create mode 100644 ui/video/decoder.go create mode 100644 ui/video/fit.go create mode 100644 ui/video/fit_test.go create mode 100644 ui/video/gif.go create mode 100644 ui/video/gif_test.go create mode 100644 ui/video/player.go create mode 100644 ui/video/player_test.go create mode 100644 ui/video/video.go create mode 100644 ui/video/video_test.go create mode 100644 ui/video/view.go create mode 100644 ui/video/view_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 96797e145..cb02f5be8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -393,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/cmd/viva/initfiles/AGENTS.md.txt b/cmd/viva/initfiles/AGENTS.md.txt index a870fd4e5..0400fd01c 100644 --- a/cmd/viva/initfiles/AGENTS.md.txt +++ b/cmd/viva/initfiles/AGENTS.md.txt @@ -228,7 +228,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`, 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 0000000000000000000000000000000000000000..359037b8949207385f15a1e25759034a4b210f02 GIT binary patch literal 68348 zcmeI5OKclO7{|wXv<)g!su+k=BZ3rhAqfpsd6lFImEEjELcO)?-9`$B zl9oqXN)I5!2_f~!4S`6HTq=;bl~dIq(PM6;JbD2&d^2mqHpwAXq?yF?TWP%G-Pu`x z-_Fkb|KIH2tCY%3#dDRJs2nQQr1V`+D8x!-zE$lzWwp?r zKl#yO;hD~B3%~xb`0n2DpYX~pviN~Uz|BBUK#$09z_17=*!I}yZ;ka{Uw&%E`f^8~ zc_8oX%+72cbY}CQGn!9V#pQPTo`Z$um_ykJm}2kL1#7(IkS1lna#t_Y#w%I z^N2H>M_k!lC(NQ4f-plAA&L-1h$2K0q6krJB%;XGO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Y`{=jY=Aq^p>QzC23F1N%}yN zZc3j?%1Qn5Q_Z6Nqm!IlubZTiMDLhA$%kxj`$MvN+Xhp*eA}NJKTg-5E}yPvBj-++ zPv^Zj_SQZ6IaR(bmEVxBQsvuzzsK{Y%V(o_vMk5zMYq8oNrh8ET#)rxSTt+Nsz=k^ qj&xPkLZza6hX0nHnWS&){wgl(3Ufih9IPu= 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 0000000000000000000000000000000000000000..4cd28da47ccd7923becba4092acab6dba4ad63dc GIT binary patch literal 118254 zcmeFZ)mPik_dOikDek4XLvb$!N^vMq9NJR6Kq*q3;u72;3GTrO8WP+kP>NeAR3CzdryH0DvO^00sb1008>mOhN)6;Ruib10+xY3G}~3M+tzV zBft?1a6|zd(f{^>B>-SY02mAaqX1y^zoRG#0Ll@70s~Me01AzX1VBpw(2f8!7=T6r z(3lA(HYPMC7UnQ!H~L?mf5TBi0xThcl8`|EON*H~I!ZW#B^*%_j_7|VFpFSE2{2d! zjFJGO|AE5nML9~Kz!E5w1PYD8h&d{Oc9cMaCD14dG$tzsH6|DaGzKLG7G@2T7!w;4 z8WRh182zuHe{;+LJ368q9nt^l!=%N`z+gu($`OqIS1twxW)TH;M4=o}XiW7OP?)`r zXs{z1<%q_Vhv^3fCgwDz9hmwtATSkTP-B8&Kx0s1wqkH#5@TXxLStf~|8?%)GG>k$ zC@>iPuaTJgFljL}6bg(&WBQ6I7lQ(`2u7p8XiOh5oyIf(gA21A(`Zb!m{wx?fq{uR zjcEr46Q*EHg&5SBU>MMtlNeYS9GJwI*qG4he^>NxH)a_##|$*)#xRY<)Q3rnnW50= ze;4@Q_5VZh-;Mse&;KszAE^KO{_lGKYvn(T|8?izZU0yBKgj>p@bB{fgY~b1|1x1h zV_puJTf#ICQ`3K`{(B|<|Nesz4WK1r(KJY_i6o@v$Q*7g9*8Bc)XLLL+p0-uuz9xz zPfHs~Nm7l`eb!W_#mV=wT9?11e1cNcZahybV>c~V)_co(pm~o;N|}V%MDv_&u#{9# z;1wjT^kov;b8RULDkvn&+_1ZLto2AY-{!+@i%VAOaSaq+bK?8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M=dfb{ literal 0 HcmV?d00001 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/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 0000000000000000000000000000000000000000..359037b8949207385f15a1e25759034a4b210f02 GIT binary patch literal 68348 zcmeI5OKclO7{|wXv<)g!su+k=BZ3rhAqfpsd6lFImEEjELcO)?-9`$B zl9oqXN)I5!2_f~!4S`6HTq=;bl~dIq(PM6;JbD2&d^2mqHpwAXq?yF?TWP%G-Pu`x z-_Fkb|KIH2tCY%3#dDRJs2nQQr1V`+D8x!-zE$lzWwp?r zKl#yO;hD~B3%~xb`0n2DpYX~pviN~Uz|BBUK#$09z_17=*!I}yZ;ka{Uw&%E`f^8~ zc_8oX%+72cbY}CQGn!9V#pQPTo`Z$um_ykJm}2kL1#7(IkS1lna#t_Y#w%I z^N2H>M_k!lC(NQ4f-plAA&L-1h$2K0q6krJB%;XGOs=LO%zi3{%)F2&hQ18X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N%}yN zZc3j?%1Qn5Q_Z6Nqm!IlubZTiMDLhA$%kxj`$MvN+Xhp*eA}NJKTg-5E}yPvBj-++ zPv^Zj_SQZ6IaR(bmEVxBQsvuzzsK{Y%V(o_vMk5zMYq8oNrh8ET#)rxSTt+Nsz=k^ qj&xPkLZza6hX0nHnWS&){wgl(3Ufih9IPu #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/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。