feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
# render
Videos of [MyGo](https://github.com/egoist/mygo)'s native UI: a
composition is a view of package `ui` that builds each frame from the
frame's number, drawn on the GPU (Metal, Direct3D 11, OpenGL through EGL)
or the CPU, and encoded with the system's encoders, with sound, into MP4,
QuickTime or WebM; or into PNGs and JPEGs.
```go
import "github.com/egoist/mygo/plugins/render"
comp := render.Composition{
Width: 1920, Height: 1080, FPS: 30, Frames: 90, Scale: 2,
View: func(c *ui.Context, f render.Frame) {
ui.Text(c, "Hello").FontSize(64).
Opacity(float32(f.Interpolate([]float64{0, 20}, []float64{0, 1})))
},
}
err := render.Video(ctx, comp, "hello.mp4", render.Options{})
```
See [the documentation](../../docs/plugins/render.md), and
`examples/render`.
+341
View File
@@ -0,0 +1,341 @@
package render
import (
"bytes"
"errors"
"io"
"math"
"os"
"sync"
"time"
"github.com/egoist/mygo/audio"
)
// sampleRate is the rate of the sound videos carry: 48 kHz, stereo.
const sampleRate = 48000
// A Sound is audio a composition plays (Frame.Audio), decoded into memory
// once, so that any part of it plays at any frame. WAV decodes out of
// the box; import audio/mp3, audio/vorbis, audio/flac or audio/aac for
// theirs, as package audio's formats register.
type Sound struct {
// samples are interleaved frames of channels samples, at rate.
samples []float32
channels int
rate int
frames int
}
// OpenSound decodes the audio file at path.
func OpenSound(path string) (*Sound, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
d, _, err := audio.NewDecoder(f)
if err != nil {
return nil, err
}
return NewSound(d)
}
// DecodeSound decodes audio in memory, as a file embedded in the program.
func DecodeSound(data []byte) (*Sound, error) {
d, _, err := audio.NewDecoder(bytes.NewReader(data))
if err != nil {
return nil, err
}
return NewSound(d)
}
// NewSound decodes all d has, as sound an app makes itself.
func NewSound(d audio.Decoder) (*Sound, error) {
ch, rate := d.Channels(), d.SampleRate()
if ch < 1 || rate <= 0 {
return nil, errors.New("render: a sound of no channels or sample rate")
}
keep := min(ch, 2)
var samples []float32
if n := d.Len(); n > 0 && n < 1<<26 {
samples = make([]float32, 0, n*int64(keep))
}
buf := make([]float32, 4096/ch*ch)
for {
n, err := d.Read(buf)
n -= n % ch
for i := 0; i < n; i += ch {
samples = append(samples, buf[i:i+keep]...)
}
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if n == 0 {
return nil, io.ErrNoProgress
}
}
return &Sound{samples: samples, channels: keep, rate: rate, frames: len(samples) / keep}, nil
}
// SoundOf returns a sound of samples, interleaved frames of channels (1
// or 2) samples in [-1, 1] at rate frames a second, as an app makes them.
func SoundOf(rate, channels int, samples []float32) *Sound {
if channels != 1 && channels != 2 {
panic("render: SoundOf takes 1 or 2 channels")
}
if rate <= 0 {
panic("render: SoundOf takes a positive rate")
}
samples = samples[:len(samples)/channels*channels]
return &Sound{samples: samples, channels: channels, rate: rate, frames: len(samples) / channels}
}
// Duration returns how long the sound plays.
func (s *Sound) Duration() time.Duration {
return time.Duration(float64(s.frames) * float64(time.Second) / float64(s.rate))
}
// AudioOptions are how Frame.Audio plays a sound.
type AudioOptions struct {
// Volume scales the sound, 1 when zero; it may change from frame to
// frame, as a fade, and moves smoothly across each.
Volume float64
// Start is where in the sound it starts playing, cutting what comes
// before.
Start time.Duration
// Loop plays the sound again from Start each time it ends, rather
// than fall silent.
Loop bool
}
// Audio plays s during the frame, from where it is at this frame of the
// composition or the sequence playing it: the sound starts at its frame
// 0, so that a sound played inside a Sequence starts with the sequence.
// A view plays a sound in each frame it is heard, as it shows an element
// in each frame it is seen:
//
// f.Audio(music, render.AudioOptions{Volume: f.Interpolate([]float64{0, 30}, []float64{0, 1})})
//
// Sounds played in the frames of Images, Frames and Still are not
// written anywhere.
func (f Frame) Audio(s *Sound, o ...AudioOptions) {
if f.s == nil || s == nil || f.Index < 0 {
return
}
var opt AudioOptions
if len(o) > 0 {
opt = o[0]
}
vol := opt.Volume
if vol == 0 {
vol = 1
}
if vol < 0 || math.IsNaN(vol) || math.IsInf(vol, 0) {
panic("render: Volume must be a finite number, 0 or more")
}
// The frame of the composition its frame 0 is: the sound played from
// one start is one voice, whose volume moves smoothly.
origin := f.at - f.Index
f.s.plays = append(f.s.plays, play{
sound: s,
// When, in the composition, the sound is at 0: each sample's place
// in the sound follows from its own time, so that frames of rates
// whose samples do not divide evenly join without a jump.
zero: float64(int64(origin)*f.s.den)/float64(f.s.num) - opt.Start.Seconds(),
origin: origin,
start: opt.Start,
volume: vol,
loop: opt.Loop,
})
}
// play is a sound a frame plays, at 0 zero seconds into the composition.
type play struct {
sound *Sound
zero float64
origin int
start time.Duration
volume float64
loop bool
}
// voice is a sound played from a start: what moves smoothly from frame to
// frame.
type voice struct {
sound *Sound
origin int
start time.Duration
}
// mixer mixes the sounds each frame plays into stereo at 48 kHz.
type mixer struct {
num, den int64
// start is the first frame written: the sound starts there.
start int
// volumes are the voices' volumes at the end of the frame mixed last.
volumes, next map[voice]float64
out []float32
}
func newMixer(num, den int64) *mixer {
return &mixer{num: num, den: den, volumes: map[voice]float64{}, next: map[voice]float64{}}
}
// sampleAt returns the first sample of frame i of the video.
func (m *mixer) sampleAt(i int) int64 { return int64(i) * sampleRate * m.den / m.num }
// frame returns the sound of frame i: interleaved stereo samples, until
// the next call.
func (m *mixer) frame(i int, plays []play) []float32 {
n := int(m.sampleAt(i+1) - m.sampleAt(i))
m.out = append(m.out[:0], make([]float32, 2*n)...)
out := m.out
clear(m.next)
for _, p := range plays {
v := voice{p.sound, p.origin, p.start}
from, ok := m.volumes[v]
if !ok {
from = p.volume
}
if _, dup := m.next[v]; dup {
// The same sound played twice from one start: once.
continue
}
m.next[v] = p.volume
at := float64(m.sampleAt(i))/sampleRate - p.zero
p.sound.mix(out, at, n, from, p.volume, p.loop, p.start.Seconds())
}
m.volumes, m.next = m.next, m.volumes
for j, x := range out {
out[j] = max(-1, min(x, 1))
}
return out
}
// mix adds n frames of the sound from at seconds into it to out, stereo
// at 48 kHz, its volume going from v0 to v1; looped, it goes on from loopAt
// seconds at its end.
func (s *Sound) mix(out []float32, at float64, n int, v0, v1 float64, loop bool, loopAt float64) {
if s.frames == 0 {
return
}
length := float64(s.frames) / float64(s.rate)
step := float64(s.rate) / sampleRate
pos := at * float64(s.rate)
whole := s.rate == sampleRate && math.Abs(pos-math.Round(pos)) < 1e-6
for k := range n {
t := at + float64(k)/sampleRate
if t >= length {
if !loop || length <= loopAt {
break
}
t = loopAt + math.Mod(t-loopAt, length-loopAt)
}
if t < 0 {
continue
}
vol := float32(v0 + (v1-v0)*float64(k+1)/float64(n))
var l, r float32
if whole && !loop {
i := int(math.Round(pos)) + k
l, r = s.frame(i)
} else {
l, r = s.resample(t*float64(s.rate), step)
}
out[2*k] += l * vol
out[2*k+1] += r * vol
}
}
// frame returns the samples of frame i of the sound, left and right.
func (s *Sound) frame(i int) (l, r float32) {
if i < 0 || i >= s.frames {
return 0, 0
}
if s.channels == 1 {
v := s.samples[i]
return v, v
}
return s.samples[2*i], s.samples[2*i+1]
}
// The kernel resampling sounds of other rates: a sinc windowed by Kaiser
// over reach frames of the output either side, its cutoff a little below
// the lower of the two rates' Nyquist frequencies.
const (
reach = 16
kaiserB = 8.0
kernelRes = 512 // entries of the kernel a frame
)
var (
kernelOnce sync.Once
kernel []float32 // the window at distances 0 to reach, kernelRes a frame
)
func windowAt(d float64) float32 {
kernelOnce.Do(func() {
kernel = make([]float32, reach*kernelRes+2)
for i := range kernel {
x := float64(i) / kernelRes / reach
if x > 1 {
continue
}
kernel[i] = float32(bessel0(kaiserB*math.Sqrt(1-x*x)) / bessel0(kaiserB))
}
})
d = math.Abs(d) * kernelRes
i := int(d)
if i+1 >= len(kernel) {
return 0
}
f := float32(d - float64(i))
return kernel[i]*(1-f) + kernel[i+1]*f
}
func bessel0(x float64) float64 {
sum, term := 1.0, 1.0
for k := 1; k < 50; k++ {
term *= (x / (2 * float64(k))) * (x / (2 * float64(k)))
sum += term
if term < 1e-12*sum {
break
}
}
return sum
}
// resample returns the sound at frame position p, between its frames, as
// a band-limited interpolation does: step is the sound's frames an output
// frame, above 1 for sounds of higher rates, whose kernel widens and
// cuts off lower.
func (s *Sound) resample(p, step float64) (l, r float32) {
scale := max(step, 1)
cutoff := 0.95 / scale
width := reach * scale
c := int(math.Floor(p))
var sl, sr float64
for i := c - int(width) + 1; i <= c+int(width); i++ {
d := p - float64(i)
w := float64(windowAt(d/width*reach)) * sincf(d*cutoff) * cutoff
if w == 0 {
continue
}
a, b := s.frame(i)
sl += float64(a) * w
sr += float64(b) * w
}
return float32(sl), float32(sr)
}
func sincf(x float64) float64 {
if x == 0 {
return 1
}
x *= math.Pi
return math.Sin(x) / x
}
+202
View File
@@ -0,0 +1,202 @@
package render
import (
"bufio"
"bytes"
"context"
"encoding/binary"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
)
// ffmpegSink pipes the frames to ffmpeg, as raw BGRA, and the sound
// track from a file it reads as a second input.
type ffmpegSink struct {
spec videoSpec
cmd *exec.Cmd
in io.WriteCloser
w *bufio.Writer
errs bytes.Buffer
sound string // the file of the sound track, "" for none
buf []byte
}
func newFFmpegSink(ctx context.Context, spec videoSpec) (_ sink, err error) {
bin := spec.ffmpeg
if bin == "" {
bin = "ffmpeg"
}
path, err := exec.LookPath(bin)
if err != nil {
return nil, fmt.Errorf("render: no ffmpeg: %w", err)
}
s := &ffmpegSink{spec: spec}
defer func() {
if err != nil {
s.abort()
}
}()
args := []string{"-hide_banner", "-loglevel", "error", "-nostdin", "-y",
"-f", "rawvideo", "-pix_fmt", "bgra", "-s", fmt.Sprintf("%dx%d", spec.w, spec.h),
"-framerate", fmt.Sprintf("%d/%d", spec.num, spec.den), "-i", "pipe:0"}
if spec.sound != nil {
if s.sound, err = writeRaw(filepath.Dir(spec.path), spec.sound); err != nil {
return nil, err
}
args = append(args, "-f", "s16le", "-ar", strconv.Itoa(sampleRate), "-ac", "2", "-i", s.sound,
"-map", "0:v", "-map", "1:a")
if spec.container == webm {
args = append(args, "-c:a", "libopus")
} else {
args = append(args, "-c:a", "aac")
}
args = append(args, "-b:a", strconv.Itoa(spec.audioBitrate))
}
args = append(args, s.videoArgs()...)
args = append(args, "-color_primaries", "bt709", "-color_trc", "bt709", "-colorspace", "bt709", spec.path)
// -nostdin keeps ffmpeg from reading keys; the frames come on its
// standard input all the same, as pipe:0.
s.cmd = exec.CommandContext(ctx, path, args...)
s.cmd.Stderr = &s.errs
if s.in, err = s.cmd.StdinPipe(); err != nil {
return nil, err
}
if err := s.cmd.Start(); err != nil {
return nil, fmt.Errorf("render: ffmpeg: %w", err)
}
s.w = bufio.NewWriterSize(s.in, 1<<20)
return s, nil
}
// writeRaw writes the sound track into a file of its own in dir.
func writeRaw(dir string, track []int16) (string, error) {
f, err := os.CreateTemp(dir, ".render-sound-*.raw")
if err != nil {
return "", err
}
w := bufio.NewWriterSize(f, 1<<16)
err = binary.Write(w, binary.LittleEndian, track)
if err == nil {
err = w.Flush()
}
if cerr := f.Close(); err == nil {
err = cerr
}
if err != nil {
os.Remove(f.Name())
return "", err
}
return f.Name(), nil
}
// videoArgs returns ffmpeg's arguments for the codec: a bitrate if one
// was asked for, else a constant quality, as x264's CRF 18.
func (s *ffmpegSink) videoArgs() []string {
sp := s.spec
rate := func(crf string) []string {
if sp.bitrate > 0 {
return []string{"-b:v", strconv.Itoa(sp.bitrate)}
}
return []string{"-crf", crf}
}
var a []string
switch sp.codec {
case H264:
a = append([]string{"-c:v", "libx264", "-preset", "medium", "-pix_fmt", "yuv420p"}, rate("18")...)
case HEVC:
a = append([]string{"-c:v", "libx265", "-preset", "medium", "-pix_fmt", "yuv420p", "-tag:v", "hvc1"}, rate("22")...)
case ProRes:
a = []string{"-c:v", "prores_ks", "-profile:v", "3", "-pix_fmt", "yuv422p10le"}
case ProRes4444:
pf := "yuv444p10le"
if sp.alpha {
pf = "yuva444p10le"
}
a = []string{"-c:v", "prores_ks", "-profile:v", "4", "-pix_fmt", pf}
case VP9:
pf := "yuv420p"
if sp.alpha {
pf = "yuva420p"
}
a = []string{"-c:v", "libvpx-vp9", "-pix_fmt", pf, "-row-mt", "1"}
if sp.bitrate > 0 {
a = append(a, "-b:v", strconv.Itoa(sp.bitrate))
} else {
a = append(a, "-crf", "31", "-b:v", "0")
}
}
if sp.container == mp4 {
a = append(a, "-movflags", "+faststart")
}
return a
}
func (s *ffmpegSink) frame(_ int, pix []byte) error {
if s.spec.alpha {
// ffmpeg's BGRA is straight.
if len(s.buf) < len(pix) {
s.buf = make([]byte, len(pix))
}
unpremultiplyBGRA(s.buf, pix)
pix = s.buf[:len(pix)]
}
if _, err := s.w.Write(pix); err != nil {
return s.failed(err)
}
return nil
}
// unpremultiplyBGRA copies premultiplied BGRA pixels into straight ones.
func unpremultiplyBGRA(dst, src []byte) {
unpremultiply(dst, src)
// unpremultiply swapped red and blue, for RGBA: swap them back.
for i := 0; i+3 < len(dst); i += 4 {
dst[i], dst[i+2] = dst[i+2], dst[i]
}
}
// failed returns what ffmpeg said once it stopped, after err.
func (s *ffmpegSink) failed(err error) error {
s.in.Close()
s.cmd.Wait()
if msg := strings.TrimSpace(s.errs.String()); msg != "" {
return errors.New("render: ffmpeg: " + msg)
}
return fmt.Errorf("render: ffmpeg: %w", err)
}
func (s *ffmpegSink) close() error {
defer s.removeSound()
if err := s.w.Flush(); err != nil {
return s.failed(err)
}
s.in.Close()
if err := s.cmd.Wait(); err != nil {
return s.failed(err)
}
return nil
}
func (s *ffmpegSink) removeSound() {
if s.sound != "" {
os.Remove(s.sound)
s.sound = ""
}
}
func (s *ffmpegSink) abort() {
if s.in != nil {
s.in.Close()
}
if s.cmd != nil && s.cmd.Process != nil {
s.cmd.Process.Kill()
s.cmd.Wait()
}
s.removeSound()
}
+233
View File
@@ -0,0 +1,233 @@
package render
import (
"math"
"time"
"github.com/egoist/mygo/ui"
)
// A Frame is the frame of a composition a view builds: its Index, counted
// from 0 at the start of the composition, or of the sequence showing the
// view (Sequence, Shift), of Count frames at FPS frames a second.
//
// What a view shows follows from the frame alone, as a function of
// Index: Interpolate and Spring turn it into positions, opacities and
// colors, and Sequence shows a part of the video during some of its
// frames. ui's own animations (Animate, Spring, Transition) move with the
// video's clock too, but from what the frames before showed.
type Frame struct {
// Index is the frame's, from 0, and Count the frames of the
// composition or sequence.
Index, Count int
// FPS is the frames a second.
FPS float64
// s is the render the frame is of, nil for a Frame made by hand; at is
// the index in the composition of this frame.
s *session
at int
// sub is how far, in frames, the time the view builds is from Index's:
// before it, below 0, while motion blur samples the shutter's time.
sub float64
}
// Exact returns where the frame is, in frames: Index, or a fraction
// before it while motion blur samples the time the shutter is open
// before the frame (Composition.MotionBlur). What moves with Exact,
// Seconds, Time, Interpolate and Spring blurs; what moves with Index,
// a whole number, does not.
func (f Frame) Exact() float64 { return float64(f.Index) + f.sub }
// Time returns how long after the start of the composition, or sequence,
// the frame shows.
func (f Frame) Time() time.Duration {
return time.Duration(math.Round(f.Exact() * float64(time.Second) / f.fps()))
}
// Seconds returns Time in seconds.
func (f Frame) Seconds() float64 { return f.Exact() / f.fps() }
// Progress returns how far into its Count frames the frame is: 0 for the
// first, 1 for the last.
func (f Frame) Progress() float64 {
if f.Count <= 1 {
return 1
}
return min(max(f.Exact()/float64(f.Count-1), 0), 1)
}
func (f Frame) fps() float64 {
if f.FPS > 0 {
return f.FPS
}
return defaultFPS
}
// Frames returns how many frames d lasts at the frame's FPS, rounded.
func (f Frame) Frames(d time.Duration) int {
return int(math.Round(d.Seconds() * f.fps()))
}
// Shift returns the frame as a sequence of count frames starting at from
// sees it, and whether the sequence shows then: Index is f.Index-from,
// within 0 and count. A count of 0 or less lasts to the end of f's.
func (f Frame) Shift(from, count int) (Frame, bool) {
if count <= 0 {
count = f.Count - from
}
g := f
g.Index, g.Count = f.Index-from, count
return g, g.Index >= 0 && g.Index < count
}
// Loop returns the frame as a sequence of count frames playing again and
// again sees it: Index is f.Index modulo count.
func (f Frame) Loop(count int) Frame {
if count <= 0 {
panic("render: Loop takes a positive count")
}
g := f
g.Index, g.Count = ((f.Index%count)+count)%count, count
if g.Index == 0 && f.sub < 0 && f.Index != 0 {
// A sample just before the loop starts again is at its end.
g.Index = count
}
return g
}
// Sequence shows view during count frames from from, given the frame as
// the sequence sees it (Shift), in a layer that fills the parent, above
// the layers before it, as video editors stack clips. A count of 0 or
// less lasts to the end of f's. The layer stays in the layout while the
// sequence does not show, empty, so that the elements after it keep their
// identities.
func (f Frame) Sequence(c *ui.Context, from, count int, view func(f Frame)) {
g, ok := f.Shift(from, count)
Layer(c).Children(func() {
if ok {
view(g)
}
})
}
// Layer returns a box filling its parent, laid out apart from its
// siblings, over those before it: for what overlaps, as the layers of a
// video.
func Layer(c *ui.Context) ui.Element {
return ui.Box(c).Absolute().Top(0).Right(0).Bottom(0).Left(0)
}
// Interpolate maps f.Index from the frames in to the values out, as the
// package's Interpolate does.
func (f Frame) Interpolate(in, out []float64, o ...Interpolation) float64 {
return Interpolate(f.Exact(), in, out, o...)
}
// Spring returns where a spring of o going from 0 to 1, starting at the
// first frame, is at this one: 0 at the start, past 1 where it
// overshoots, 1 once it rests (ui.SpringOptions.Progress). ui.Smooth,
// ui.Snappy and ui.Bouncy have the springs of ui's animations.
func (f Frame) Spring(o ui.SpringOptions) float64 {
return o.Progress(f.Time())
}
// SpringIn returns where a spring of o is at this frame, as Spring does,
// its time stretched or shrunk so that it comes to rest in frames frames
// (ui.SpringOptions.SettleTime).
func (f Frame) SpringIn(o ui.SpringOptions, frames int) float64 {
if frames <= 0 {
return 1
}
settle := o.SettleTime()
t := time.Duration(float64(settle) * f.Exact() / float64(frames))
return o.Progress(t)
}
// Extrapolate says what Interpolate returns outside the range of its
// input.
type Extrapolate uint8
const (
// Clamp keeps the value at the end of the output range.
Clamp Extrapolate = iota
// Extend goes on as the nearest segment goes.
Extend
// Identity returns the input.
Identity
)
// Interpolation describes how Interpolate goes from value to value: along
// Easing, linear when nil, between each two, and Left and Right before
// and after the input's range, Clamp by default.
type Interpolation struct {
Easing ui.Easing
Left, Right Extrapolate
}
// Interpolate maps x from the increasing values in to those of out, of
// the same length, two at least: between in[i] and in[i+1] it goes from
// out[i] to out[i+1] along o's Easing. A view fades in over its first
// half second with
//
// opacity := f.Interpolate([]float64{0, 15}, []float64{0, 1})
func Interpolate(x float64, in, out []float64, o ...Interpolation) float64 {
if len(in) < 2 || len(in) != len(out) {
panic("render: Interpolate takes as many inputs as outputs, two at least")
}
for i := 1; i < len(in); i++ {
if !(in[i] > in[i-1]) {
panic("render: Interpolate's inputs must increase")
}
}
var opt Interpolation
if len(o) > 0 {
opt = o[0]
}
if x < in[0] {
switch opt.Left {
case Clamp:
return out[0]
case Identity:
return x
}
}
last := len(in) - 1
if x > in[last] {
switch opt.Right {
case Clamp:
return out[last]
case Identity:
return x
}
}
i := 0
for i < last-1 && x > in[i+1] {
i++
}
t := (x - in[i]) / (in[i+1] - in[i])
if opt.Easing != nil && t >= 0 && t <= 1 {
t = float64(opt.Easing(float32(t)))
}
return out[i] + t*(out[i+1]-out[i])
}
// InterpolateColor maps x from in to the colors out as Interpolate maps
// it to numbers, mixing them in sRGB, outside in's range clamped.
func InterpolateColor(x float64, in []float64, out []ui.Color, o ...Interpolation) ui.Color {
if len(in) < 2 || len(in) != len(out) {
panic("render: InterpolateColor takes as many inputs as outputs, two at least")
}
idx := make([]float64, len(in))
for i := range idx {
idx[i] = float64(i)
}
var opt Interpolation
if len(o) > 0 {
opt = o[0]
}
// Where x is, in segments: the easing applies within one.
p := Interpolate(x, in, idx, Interpolation{Easing: opt.Easing})
i := min(int(p), len(out)-2)
return out[i].Mix(out[i+1], float32(p-float64(i)))
}
+40
View File
@@ -0,0 +1,40 @@
//go:build darwin && !ios
package render
import (
"github.com/egoist/mygo/internal/gpu/metal"
"github.com/egoist/mygo/internal/scene"
)
// metalDrawer draws frames with Metal, into a texture whose pixels it
// reads back, or into the encoder's pixel buffers (avSceneSink).
type metalDrawer struct {
f *metal.Frames
gpu string
pix []byte
w, h int
}
func newGPUDrawer(w, h int, _ bool) (drawer, error) {
f, err := metal.NewFrames()
if err != nil {
return nil, err
}
return &metalDrawer{f: f, gpu: f.Name(), w: w, h: h}, nil
}
func (d *metalDrawer) submit(s *scene.Scene) error { return d.f.Draw(s) }
func (d *metalDrawer) pixels() ([]byte, error) {
if err := d.f.Wait(); err != nil {
return nil, err
}
if n := d.w * d.h * 4; len(d.pix) != n {
d.pix = make([]byte, n)
}
return d.pix, d.f.Read(d.pix)
}
func (d *metalDrawer) name() string { return "Metal (" + d.gpu + ")" }
func (d *metalDrawer) release() { d.f.Release() }
+55
View File
@@ -0,0 +1,55 @@
//go:build linux && !android && (amd64 || arm64)
package render
import (
"strings"
"github.com/egoist/mygo/internal/gpu/gl"
"github.com/egoist/mygo/internal/scene"
)
// glDrawer draws frames with OpenGL in a context of EGL without a
// display (Mesa's surfaceless platform), current on the rendering thread.
type glDrawer struct {
o *gl.Offscreen
info string
pix []byte
w, h int
}
// newGPUDrawer returns an OpenGL 3.3 drawer, else an OpenGL ES 3.0 one.
// Mesa without a GPU draws with llvmpipe, on the CPU, slower than MyGo's
// own CPU renderer, which redraws only what changed: Auto takes that
// instead, GPU takes llvmpipe.
func newGPUDrawer(w, h int, required bool) (drawer, error) {
var first error
for _, es := range []bool{false, true} {
o, err := gl.NewOffscreen(es, w, h)
if err != nil {
if first == nil {
first = err
}
continue
}
info := o.Info()
if soft := strings.Contains(info, "llvmpipe") || strings.Contains(info, "softpipe") || strings.Contains(info, "SwiftShader"); soft && !required {
o.Release()
return nil, nil
}
return &glDrawer{o: o, info: info, w: w, h: h}, nil
}
return nil, first
}
func (d *glDrawer) submit(s *scene.Scene) error { return d.o.Draw(s) }
func (d *glDrawer) pixels() ([]byte, error) {
if n := d.w * d.h * 4; len(d.pix) != n {
d.pix = make([]byte, n)
}
return d.pix, d.o.Read(d.pix)
}
func (d *glDrawer) name() string { return "OpenGL (" + d.info + ")" }
func (d *glDrawer) release() { d.o.Release() }
+6
View File
@@ -0,0 +1,6 @@
//go:build !(darwin && !ios) && !windows && !(linux && !android && (amd64 || arm64))
package render
// newGPUDrawer returns none: frames draw on the CPU.
func newGPUDrawer(w, h int, required bool) (drawer, error) { return nil, nil }
+44
View File
@@ -0,0 +1,44 @@
//go:build windows
package render
import (
"github.com/egoist/mygo/internal/gpu/d3d11"
"github.com/egoist/mygo/internal/scene"
)
// d3dDrawer draws frames with Direct3D 11, into a window that never shows,
// whose frames it reads back through a staging texture.
type d3dDrawer struct {
f *d3d11.Frames
gpu string
pix []byte
w, h int
}
// newGPUDrawer returns a Direct3D 11 drawer. Without a GPU, Direct3D draws
// with WARP, on the CPU, slower than MyGo's own CPU renderer, which
// redraws only what changed: Auto takes that instead, GPU takes WARP.
func newGPUDrawer(w, h int, required bool) (drawer, error) {
f, err := d3d11.NewFrames(w, h)
if err != nil {
return nil, err
}
if f.Software() && !required {
f.Release()
return nil, nil
}
return &d3dDrawer{f: f, gpu: f.Name(), w: w, h: h}, nil
}
func (d *d3dDrawer) submit(s *scene.Scene) error { return d.f.Draw(s) }
func (d *d3dDrawer) pixels() ([]byte, error) {
if n := d.w * d.h * 4; len(d.pix) != n {
d.pix = make([]byte, n)
}
return d.pix, d.f.Read(d.pix, d.w, d.h)
}
func (d *d3dDrawer) name() string { return "Direct3D 11 (" + d.gpu + ")" }
func (d *d3dDrawer) release() { d.f.Release() }
+203
View File
@@ -0,0 +1,203 @@
package render
import (
"bufio"
"context"
"errors"
"fmt"
"image"
"image/jpeg"
"image/png"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"github.com/egoist/mygo/internal/raster"
"github.com/egoist/mygo/internal/scene"
)
// Images renders the composition's frames into image files named by
// pattern, a path with a verb of fmt for the frame's number, as
// "frames/%04d.png": PNGs, with the alpha of a Transparent composition,
// or JPEGs (.jpg, .jpeg) of Options.Quality. The directory is made if
// need be. Files are encoded on as many cores as there are, while the
// next frames draw.
func Images(ctx context.Context, comp Composition, pattern string, o Options) error {
if err := comp.validate(); err != nil {
return err
}
if n := strings.Count(strings.ReplaceAll(pattern, "%%", ""), "%"); n != 1 {
return errors.New("render: name the frames' files with one verb for their number, as frame-%04d.png")
}
jpg := false
switch strings.ToLower(filepath.Ext(pattern)) {
case ".png":
case ".jpg", ".jpeg":
jpg = true
default:
return fmt.Errorf("render: no image format for %q: name .png or .jpg files", filepath.Ext(pattern))
}
quality := o.Quality
if quality == 0 {
quality = 90
}
if quality < 1 || quality > 100 {
return errors.New("render: Quality is between 1 and 100")
}
if dir := filepath.Dir(fmt.Sprintf(pattern, 0)); dir != "" {
if err := os.MkdirAll(dir, 0o755); err != nil {
return err
}
}
return run(ctx, comp, o, func(*session, drawer) (sink, error) {
return newImageSink(pattern, comp.Width, comp.Height, jpg, quality, comp.Transparent && !jpg), nil
})
}
// imageSink encodes frames into files on workers of its own.
type imageSink struct {
pattern string
w, h int
jpg bool
quality int
alpha bool
jobs chan imageJob
stop sync.Once
wg sync.WaitGroup
free sync.Pool
mu sync.Mutex
err error
}
type imageJob struct {
i int
pix *[]byte
}
func newImageSink(pattern string, w, h int, jpg bool, quality int, alpha bool) *imageSink {
s := &imageSink{pattern: pattern, w: w, h: h, jpg: jpg, quality: quality, alpha: alpha}
workers := max(runtime.GOMAXPROCS(0), 1)
s.jobs = make(chan imageJob, workers)
for range workers {
s.wg.Add(1)
go s.work()
}
return s
}
func (s *imageSink) frame(i int, pix []byte) error {
if err := s.failed(); err != nil {
return err
}
buf, _ := s.free.Get().(*[]byte)
if buf == nil {
b := make([]byte, len(pix))
buf = &b
}
copy(*buf, pix)
s.jobs <- imageJob{i, buf}
return nil
}
func (s *imageSink) failed() error {
s.mu.Lock()
defer s.mu.Unlock()
return s.err
}
func (s *imageSink) work() {
defer s.wg.Done()
for j := range s.jobs {
if s.failed() == nil {
if err := s.write(j.i, *j.pix); err != nil {
s.mu.Lock()
if s.err == nil {
s.err = err
}
s.mu.Unlock()
}
}
s.free.Put(j.pix)
}
}
// write encodes frame i's pixels, BGRA, into its file.
func (s *imageSink) write(i int, pix []byte) error {
r := image.Rect(0, 0, s.w, s.h)
var img image.Image
if s.alpha {
m := image.NewNRGBA(r)
unpremultiply(m.Pix, pix)
img = m
} else {
m := image.NewRGBA(r)
bgraToRGBA(m.Pix, pix)
for k := 3; k < len(m.Pix); k += 4 {
// Opaque frames: what the view left transparent is black, as
// in a video.
m.Pix[k] = 255
}
img = m
}
f, err := os.Create(fmt.Sprintf(s.pattern, i))
if err != nil {
return err
}
w := bufio.NewWriterSize(f, 1<<16)
if s.jpg {
err = jpeg.Encode(w, img, &jpeg.Options{Quality: s.quality})
} else {
err = (&png.Encoder{CompressionLevel: png.BestSpeed}).Encode(w, img)
}
if err == nil {
err = w.Flush()
}
if cerr := f.Close(); err == nil {
err = cerr
}
return err
}
// unpremultiply copies premultiplied BGRA pixels into straight RGBA ones.
func unpremultiply(dst, src []byte) {
for i := 0; i+3 < len(src); i += 4 {
a := src[i+3]
switch a {
case 0:
dst[i], dst[i+1], dst[i+2], dst[i+3] = 0, 0, 0, 0
case 255:
dst[i], dst[i+1], dst[i+2], dst[i+3] = src[i+2], src[i+1], src[i], 255
default:
un := func(c byte) byte { return byte(min((int(c)*255+int(a)/2)/int(a), 255)) }
dst[i], dst[i+1], dst[i+2], dst[i+3] = un(src[i+2]), un(src[i+1]), un(src[i]), a
}
}
}
func (s *imageSink) close() error {
s.stop.Do(func() { close(s.jobs) })
s.wg.Wait()
return s.failed()
}
func (s *imageSink) abort() {
s.mu.Lock()
if s.err == nil {
s.err = context.Canceled
}
s.mu.Unlock()
s.stop.Do(func() { close(s.jobs) })
s.wg.Wait()
}
// cpuDrawer draws frames with the CPU renderer, which redraws only what
// changed from frame to frame.
type cpuDrawer struct{ r raster.Renderer }
func (d *cpuDrawer) submit(s *scene.Scene) error { d.r.Render(s); return nil }
func (d *cpuDrawer) pixels() ([]byte, error) { return d.r.Image.Pix, nil }
func (d *cpuDrawer) name() string { return "CPU" }
func (d *cpuDrawer) release() { d.r.Release() }
+64
View File
@@ -0,0 +1,64 @@
package render
import (
"runtime"
"sync"
)
// accumulator sums the pixels of a frame's motion blur samples, on all
// cores, and returns their mean.
type accumulator struct {
sum []uint16
out []byte
}
// parts runs fn on n bytes in a band per core, of whole pixels.
func parts(n int, fn func(from, to int)) {
workers := max(1, min(runtime.GOMAXPROCS(0), n/(1<<16)))
var wg sync.WaitGroup
pixels := n / 4
for k := range workers {
from, to := 4*(pixels*k/workers), 4*(pixels*(k+1)/workers)
wg.Add(1)
go func() {
defer wg.Done()
fn(from, to)
}()
}
wg.Wait()
}
// add adds a sample's pixels; first starts a new sum.
func (a *accumulator) add(pix []byte, first bool) {
if len(a.sum) != len(pix) {
a.sum = make([]uint16, len(pix))
first = true
}
parts(len(pix), func(from, to int) {
sum, src := a.sum[from:to], pix[from:to]
if first {
for i, v := range src {
sum[i] = uint16(v)
}
return
}
for i, v := range src {
sum[i] += uint16(v)
}
})
}
// mean returns the mean of the n samples added, rounded: premultiplied
// pixels average as the light of the shutter's time does.
func (a *accumulator) mean(n int) []byte {
if len(a.out) != len(a.sum) {
a.out = make([]byte, len(a.sum))
}
half := uint32(n / 2)
parts(len(a.sum), func(from, to int) {
for i, v := range a.sum[from:to] {
a.out[from+i] = byte((uint32(v) + half) / uint32(n))
}
})
return a.out
}
+64
View File
@@ -0,0 +1,64 @@
package render
import (
"runtime"
"sync"
)
// bgraToNV12 converts premultiplied BGRA pixels, w×h with even sizes, to
// NV12 of BT.709 in the limited range, as H.264 and HEVC carry them: a
// plane of luma, then one of the chroma of each 2×2 block, interleaved
// Cb, Cr. What alpha leaves out is black, as premultiplied values are.
// The rows are converted on all cores.
func bgraToNV12(dst, src []byte, w, h int) {
workers := min(max(runtime.GOMAXPROCS(0), 1), h/2)
var wg sync.WaitGroup
pairs := h / 2
for k := range workers {
from, to := pairs*k/workers, pairs*(k+1)/workers
wg.Add(1)
go func() {
defer wg.Done()
for p := from; p < to; p++ {
nv12Rows(dst, src, w, h, p)
}
}()
}
wg.Wait()
}
// The BT.709 coefficients in the limited range, scaled by 2^16, for
// values of 0 to 255: Y = 16 + 219/255 (Kr R + Kg G + Kb B), Cb and Cr
// 128 + 224/255 of the color differences (B - Y) / 1.8556 and
// (R - Y) / 1.5748.
const (
yR, yG, yB = 11966, 40254, 4064
cbR, cbG, cbB = -6596, -22189, 28784
crR, crG, crB = 28784, -26145, -2639
)
// nv12Rows converts the pair of rows p.
func nv12Rows(dst, src []byte, w, h, p int) {
stride := 4 * w
y0 := 2 * p
r0, r1 := src[y0*stride:(y0+1)*stride], src[(y0+1)*stride:(y0+2)*stride]
l0, l1 := dst[y0*w:(y0+1)*w], dst[(y0+1)*w:(y0+2)*w]
c := dst[w*h+p*w : w*h+(p+1)*w]
luma := func(px []byte) byte {
b, g, r := int32(px[0]), int32(px[1]), int32(px[2])
return byte((16<<16 + yR*r + yG*g + yB*b + 1<<15) >> 16)
}
for x := 0; x < w; x += 2 {
i := 4 * x
a, b, d, e := r0[i:i+4], r0[i+4:i+8], r1[i:i+4], r1[i+4:i+8]
l0[x], l0[x+1], l1[x], l1[x+1] = luma(a), luma(b), luma(d), luma(e)
// The block's mean color, of four: its chroma.
sb := int32(a[0]) + int32(b[0]) + int32(d[0]) + int32(e[0])
sg := int32(a[1]) + int32(b[1]) + int32(d[1]) + int32(e[1])
sr := int32(a[2]) + int32(b[2]) + int32(d[2]) + int32(e[2])
c[x] = byte(clamp8((128<<18 + cbR*sr + cbG*sg + cbB*sb + 1<<17) >> 18))
c[x+1] = byte(clamp8((128<<18 + crR*sr + crG*sg + crB*sb + 1<<17) >> 18))
}
}
func clamp8(v int32) int32 { return min(max(v, 0), 255) }
+110
View File
@@ -0,0 +1,110 @@
package render
import (
"image"
"io"
"math"
"time"
"github.com/egoist/mygo/ui"
)
// NewPlayer returns a player of the composition, for ui.Video to show in
// a window, as a preview of the video while it is made: its frames are
// the video's, built at their times and drawn on the CPU on a goroutine
// of the player's, a few ahead as they come due, and a seek builds the
// frames before the one it goes to without drawing them. Play, Pause,
// Seek and SetLoop control it as any video's; it plays no sound.
//
// player, err := render.NewPlayer(comp)
// ...
// ui.Video(c, player).FillWidth()
func NewPlayer(comp Composition) (*ui.VideoPlayer, error) {
if err := comp.validate(); err != nil {
return nil, err
}
d := &compDecoder{comp: comp}
d.reset()
return ui.NewVideoPlayer(d)
}
// compDecoder decodes a composition's frames, for a ui.VideoPlayer.
type compDecoder struct {
comp Composition
s *session
r cpuDrawer
img *image.RGBA
// next is the frame Next draws, which the session builds next.
next int
}
// reset starts again from the first frame, with a session of its own:
// what ui animates goes on from the frames built before.
func (d *compDecoder) reset() {
if d.s != nil {
d.s.rec.Close()
}
d.s, d.next = newSession(d.comp), 0
}
func (d *compDecoder) Next() (ui.VideoFrame, error) {
if d.next >= d.comp.Frames {
return ui.VideoFrame{}, io.EOF
}
var pix []byte
if n, _ := d.comp.MotionBlur.shutter(); n > 1 {
var err error
if pix, err = d.s.blurred(d.next, &d.r); err != nil {
return ui.VideoFrame{}, err
}
} else {
d.r.submit(d.s.build(d.next))
pix, _ = d.r.pixels()
}
if d.img == nil {
d.img = image.NewRGBA(image.Rect(0, 0, d.comp.Width, d.comp.Height))
}
bgraToRGBA(d.img.Pix, pix)
dur := d.s.at(d.next+1) - d.s.at(d.next)
d.next++
return ui.VideoFrame{Image: d.img, Duration: dur}, nil
}
func (d *compDecoder) Rewind() error {
d.reset()
return nil
}
// Seek goes to the frame showing at t, building those before it.
func (d *compDecoder) Seek(t time.Duration) (time.Duration, error) {
target := min(int(int64(t)*d.s.num/(d.s.den*int64(time.Second))), d.comp.Frames-1)
target = max(target, 0)
// Frames start at times rounded to the nanosecond: one starting at t
// is the frame at t.
if target+1 < d.comp.Frames && d.s.at(target+1) <= t {
target++
}
if target < d.next {
d.reset()
}
for ; d.next < target; d.next++ {
d.s.build(d.next)
}
return d.s.at(target), nil
}
// Duration returns the length of the composition.
func (d *compDecoder) Duration() time.Duration {
num, den := d.comp.rate()
return time.Duration(math.Round(float64(d.comp.Frames) * float64(den) * float64(time.Second) / float64(num)))
}
// Close drops the session and the frames' memory, as the player closes.
func (d *compDecoder) Close() error {
if d.s != nil {
d.s.rec.Close()
d.s = nil
}
d.r.release()
return nil
}
+527
View File
@@ -0,0 +1,527 @@
// Package render makes videos of native UI: a composition is a view of
// package ui that draws each frame of a video from the frame's number,
// and Video draws its frames on the GPU, or on the CPU where there is
// none, and encodes them with the system's own encoders, in hardware
// where it has them, into an MP4 or a QuickTime movie, with sound:
//
// comp := render.Composition{
// Width: 1920, Height: 1080, FPS: 30, Frames: 90,
// View: func(c *ui.Context, f render.Frame) {
// ui.Text(c, "Hello").FontSize(96).
// Opacity(float32(f.Interpolate([]float64{0, 20}, []float64{0, 1})))
// },
// }
// err := render.Video(ctx, comp, "hello.mp4", render.Options{})
//
// Frames are built, laid out and painted by package ui, as a window's
// are, then drawn by its renderers: Metal on macOS, Direct3D 11 on
// Windows, OpenGL on Linux (through EGL, without a display), or the CPU
// renderer, which draws the same pixels, where the GPU's cannot run. No
// browser is involved: a frame costs what a frame of a window costs.
//
// Images writes the frames as PNG or JPEG files, Still one frame, and
// Frames hands each to a function. Nothing opens a window, and none of it
// needs mygo.App.
package render
import (
"context"
"errors"
"fmt"
"image"
"math"
"runtime"
"time"
"github.com/egoist/mygo/internal/scene"
"github.com/egoist/mygo/ui"
)
// defaultFPS is the frames a second of a Composition that gives none.
const defaultFPS = 30
// A Composition is a video: its size, its frames, and the view that
// builds each of them.
type Composition struct {
// Width and Height are the size of the video in pixels, even for
// H.264, HEVC and VP9, whose chroma has half the size.
Width, Height int
// FPS is how many frames a second the video shows, 30 when zero.
// Rates of NTSC, as 29.97, are 30000/1001 to encoders.
FPS float64
// Frames is the length of the video in frames.
Frames int
// Scale is how many pixels a DIP is, 1 when zero: the view lays out
// in Width/Scale × Height/Scale DIPs, as a window at that scale, so
// that a 1920×1080 video at scale 2 is laid out as a 960×540 window
// of a Retina display.
Scale float32
// View builds the frame f.
View func(c *ui.Context, f Frame)
// Background fills the frames behind the view; zero is the theme's
// background. Transparent leaves what the view does not paint
// transparent instead, for the codecs with alpha (ProRes4444) and
// PNGs; other codecs show it black.
Background ui.Color
Transparent bool
// Dark builds the view in the dark appearance, Preferences with the
// desktop's settings that controls follow, and Locale in a language
// (Context.Locale), "" for the system's default.
Dark bool
Preferences ui.Preferences
Locale string
// MotionBlur blurs what moves, as a camera's shutter does, when its
// Samples are more than 1.
MotionBlur MotionBlur
}
// MotionBlur is a camera's motion blur, as Remotion's CameraMotionBlur
// makes it: each frame is the mean of Samples frames built at times
// spread over the time the shutter is open before it, which Shutter
// gives in degrees of the frame's time, 180 (half of it) when zero, up to
// 360. Each sample is built and drawn, so a frame costs Samples times
// as much; 5 to 10 samples blur smoothly.
//
// The samples' times are fractions of a frame before it: what moves with
// time blurs, the view's Interpolate, Spring, Exact and Seconds, and ui's
// own animations, which follow the clock; what moves with the whole
// Frame.Index does not.
type MotionBlur struct {
Samples int
Shutter float64
}
// shutter returns the samples and the fraction of a frame they spread
// over, 1 sample for none.
func (m MotionBlur) shutter() (int, float64) {
if m.Samples <= 1 {
return 1, 0
}
angle := m.Shutter
if angle == 0 {
angle = 180
}
return m.Samples, angle / 360
}
// rate returns the frames a second as a fraction num/den.
func (c *Composition) rate() (num, den int64) {
fps := c.FPS
if fps <= 0 {
fps = defaultFPS
}
if fps == math.Trunc(fps) {
return int64(fps), 1
}
if n := math.Round(fps * 1001); math.Abs(n/1001-fps) < 1e-3 && math.Mod(n, 1000) == 0 {
return int64(n), 1001
}
return int64(math.Round(fps * 1000)), 1000
}
func (c *Composition) validate() error {
switch {
case c.Width <= 0 || c.Height <= 0:
return errors.New("render: a composition needs a Width and a Height")
case c.Width > 16384 || c.Height > 16384:
return errors.New("render: a composition is at most 16384 pixels wide and high")
case c.Frames <= 0:
return errors.New("render: a composition needs Frames")
case c.FPS != 0 && !(c.FPS >= 0.01 && c.FPS <= 1000):
return errors.New("render: FPS must be between 0.01 and 1000")
case c.Scale < 0:
return errors.New("render: Scale must not be negative")
case c.View == nil:
return errors.New("render: a composition needs a View")
case c.MotionBlur.Samples < 0 || c.MotionBlur.Samples > 64:
return errors.New("render: MotionBlur takes 0 to 64 Samples")
case c.MotionBlur.Shutter < 0 || c.MotionBlur.Shutter > 360 || math.IsNaN(c.MotionBlur.Shutter):
return errors.New("render: MotionBlur's Shutter is 0 to 360 degrees")
}
return nil
}
// Renderer chooses what draws the frames.
type Renderer uint8
const (
// Auto draws on the GPU, or on the CPU where no GPU renderer starts,
// as on a server without one.
Auto Renderer = iota
// GPU draws on the GPU, and fails where none starts.
GPU
// CPU draws on the CPU, with the renderer windows fall back to.
CPU
)
// Options are how Video, Images, Frames and Still make a composition's
// frames.
type Options struct {
// From and To are the frames rendered: those from From to before To,
// all when To is zero. The frames before From are built, not drawn,
// so that what ui animates from frame to frame is where it would be.
From, To int
// Renderer chooses what draws the frames.
Renderer Renderer
// Progress is called after each frame written, on the goroutine
// rendering.
Progress func(Progress)
// Codec encodes the video, by default H264, or VP9 into WebM.
// Bitrate is its bits a second, chosen for the size and rate when
// zero; AudioBitrate the sound's, 192 kb/s when zero. ProRes takes
// neither.
Codec Codec
Bitrate int
AudioBitrate int
// Encoder is what encodes Video's frames: the system's media
// framework, or ffmpeg (FFmpeg), for formats the system has no
// encoder of.
Encoder Encoder
// FFmpeg is the path of ffmpeg for the FFmpeg Encoder, "ffmpeg" from
// PATH when empty.
FFmpeg string
// Quality is that of the JPEGs of Images, from 1 to 100, 90 when
// zero.
Quality int
}
// Progress tells how a render goes.
type Progress struct {
// Frame is the frame written last, Done how many were written, of
// Frames.
Frame, Done, Frames int
// Elapsed is the time since the render started.
Elapsed time.Duration
// Renderer names what draws the frames, as "Metal (Apple M2)" or
// "CPU".
Renderer string
}
// Still draws frame of the composition, after building the frames before
// it, and returns its pixels.
func Still(comp Composition, frame int, o Options) (*image.RGBA, error) {
var img *image.RGBA
o.From, o.To = frame, frame+1
err := Frames(context.Background(), comp, o, func(_ int, m *image.RGBA) error {
img = m
return nil
})
return img, err
}
// Frames draws the frames of the composition Options choose and calls fn
// with each, in order, on the goroutine rendering: its pixels, with
// premultiplied alpha, are fn's to keep. An error from fn stops the
// render, and Frames returns it.
func Frames(ctx context.Context, comp Composition, o Options, fn func(frame int, img *image.RGBA) error) error {
return run(ctx, comp, o, func(*session, drawer) (sink, error) {
return &funcSink{w: comp.Width, h: comp.Height, fn: fn}, nil
})
}
// funcSink hands the frames to a function.
type funcSink struct {
w, h int
fn func(int, *image.RGBA) error
}
func (f *funcSink) frame(i int, pix []byte) error {
img := image.NewRGBA(image.Rect(0, 0, f.w, f.h))
bgraToRGBA(img.Pix, pix)
return f.fn(i, img)
}
func (f *funcSink) close() error { return nil }
func (f *funcSink) abort() {}
// bgraToRGBA copies BGRA pixels into RGBA ones.
func bgraToRGBA(dst, src []byte) {
for i := 0; i+3 < len(src) && i+3 < len(dst); i += 4 {
dst[i], dst[i+1], dst[i+2], dst[i+3] = src[i+2], src[i+1], src[i], src[i+3]
}
}
// A sink takes the frames drawn, in order.
type sink interface {
// frame takes frame i's pixels: premultiplied BGRA rows from the top,
// 4×Width bytes each, which change once it returns.
frame(i int, pix []byte) error
// close finishes what the sink writes, abort gives it up.
close() error
abort()
}
// A sceneSink draws frames itself into the buffers its encoder takes, on
// the GPU of the drawer it was opened with: without copying them through
// memory. A sink is one only when it can.
type sceneSink interface {
sink
// scene draws frame i, and writes the frame before it, which the GPU
// drew meanwhile.
scene(i int, s *scene.Scene) error
// flush writes the last frame.
flush() error
}
// A drawer draws the frames on the GPU or the CPU.
type drawer interface {
// submit starts drawing s; pixels waits for it and returns its
// pixels: premultiplied BGRA rows from the top, valid until the next
// submit.
submit(s *scene.Scene) error
pixels() ([]byte, error)
// name names the renderer, as "Metal (Apple M2)".
name() string
release()
}
// newDrawer returns the drawer o asks for, of frames of w×h pixels.
func newDrawer(r Renderer, w, h int) (drawer, error) {
if r != CPU {
d, err := newGPUDrawer(w, h, r == GPU)
if err == nil && d != nil {
return d, nil
}
if r == GPU {
if err == nil {
err = errors.New("render: no GPU renderer on this system")
}
return nil, err
}
}
return &cpuDrawer{}, nil
}
// session is a render: the composition's recorder, and what it heard.
type session struct {
comp Composition
num, den int64 // frames a second, num/den
rec *ui.Recorder
// frame is the frame the view builds.
frame Frame
// plays are the sounds the view played in the frame it built last.
plays []play
mix *mixer
// acc sums the samples of motion blur.
acc accumulator
}
func newSession(comp Composition) *session {
s := &session{comp: comp}
s.num, s.den = comp.rate()
s.mix = newMixer(s.num, s.den)
view := comp.View
bg, transparent := comp.Background, comp.Transparent
s.rec = ui.NewRecorder(func(c *ui.Context) {
// Each pass of a frame plays what it builds: the last one's count.
s.plays = s.plays[:0]
if transparent || bg != (ui.Color{}) {
t := *c.Theme()
t.Background = bg
if transparent {
t.Background = ui.Transparent
}
c.SetTheme(&t)
}
view(c, s.frame)
}, ui.RecorderOptions{
Width: comp.Width, Height: comp.Height, Scale: comp.Scale,
Dark: comp.Dark, Preferences: comp.Preferences, Locale: comp.Locale,
FrameRate: float64(s.num) / float64(s.den),
})
return s
}
// at returns the time of frame i.
func (s *session) at(i int) time.Duration {
return time.Duration(math.Round(float64(i) * float64(s.den) * float64(time.Second) / float64(s.num)))
}
// build builds frame i and returns its scene.
func (s *session) build(i int) *scene.Scene { return s.buildAt(i, 0) }
// buildAt builds frame i at sub frames from its time, as a sample of
// motion blur does.
func (s *session) buildAt(i int, sub float64) *scene.Scene {
s.frame = Frame{Index: i, Count: s.comp.Frames, FPS: float64(s.num) / float64(s.den), s: s, at: i, sub: sub}
at := s.at(i)
if sub != 0 {
at = time.Duration(math.Round((float64(i) + sub) * float64(s.den) * float64(time.Second) / float64(s.num)))
}
return s.rec.Frame(at)
}
// blurred draws frame i as the mean of its motion blur's samples, the
// earliest first, and returns its pixels, valid until the next call.
func (s *session) blurred(i int, d drawer) ([]byte, error) {
n, shutter := s.comp.MotionBlur.shutter()
for k := n - 1; k >= 0; k-- {
if err := d.submit(s.buildAt(i, -shutter*float64(k)/float64(n))); err != nil {
return nil, err
}
pix, err := d.pixels()
if err != nil {
return nil, err
}
s.acc.add(pix, k == n-1)
}
return s.acc.mean(n), nil
}
// run renders the frames o chooses of comp into the sink open returns.
func run(ctx context.Context, comp Composition, o Options, open func(*session, drawer) (sink, error)) (err error) {
if err := comp.validate(); err != nil {
return err
}
from, to, err := comp.span(o)
if err != nil {
return err
}
// One thread draws: OpenGL's context is current on it.
runtime.LockOSThread()
defer runtime.UnlockOSThread()
s := newSession(comp)
defer s.rec.Close()
d, err := newDrawer(o.Renderer, comp.Width, comp.Height)
if err != nil {
return err
}
defer d.release()
s.mix.start = from
out, err := open(s, d)
if err != nil {
return err
}
defer func() {
if err != nil {
out.abort()
}
}()
scenes, _ := out.(sceneSink)
samples, _ := comp.MotionBlur.shutter()
if samples > 1 {
// The samples are averaged in memory.
scenes = nil
}
start := time.Now()
report := func(i int) {
if o.Progress != nil {
o.Progress(Progress{Frame: i, Done: i - from + 1, Frames: to - from, Elapsed: time.Since(start), Renderer: d.name()})
}
}
// The frames before From, built for what ui animates.
for i := range from {
if err := ctx.Err(); err != nil {
return err
}
s.build(i)
}
prev := -1
for i := from; i < to; i++ {
if err := ctx.Err(); err != nil {
return err
}
if samples > 1 {
pix, err := s.blurred(i, d)
if err != nil {
return err
}
if err := out.frame(i, pix); err != nil {
return err
}
report(i)
continue
}
sc := s.build(i)
if scenes != nil {
if err := scenes.scene(i, sc); err != nil {
return err
}
if prev >= 0 {
report(prev)
}
prev = i
continue
}
// The GPU draws the frame before while this one built: its pixels
// first, then this one's drawing.
if prev >= 0 {
if err := writePixels(d, out, prev); err != nil {
return err
}
report(prev)
}
if err := d.submit(sc); err != nil {
return err
}
prev = i
}
switch {
case samples > 1:
// Each frame was written as it was drawn.
return out.close()
case scenes != nil:
err = scenes.flush()
default:
err = writePixels(d, out, prev)
}
if err != nil {
return err
}
report(prev)
return out.close()
}
// span returns the frames o renders, from to before to.
func (c *Composition) span(o Options) (from, to int, err error) {
from, to = o.From, o.To
if to == 0 {
to = c.Frames
}
if from < 0 || to > c.Frames || from >= to {
return 0, 0, fmt.Errorf("render: frames %d to %d are not in the composition's %d", from, to, c.Frames)
}
return from, to, nil
}
// soundtrack builds the frames before to and mixes the sound those from
// from play (Frame.Audio): interleaved stereo samples at 48 kHz, of the
// frames from from to before to, or nil when they play none. The system's
// writers take their tracks before the first frame, and interleave the
// sound with the video ahead of it: the sound is mixed before the frames
// are drawn, from frames built without drawing them, which costs a
// fraction of drawing them.
func soundtrack(ctx context.Context, comp Composition, from, to int) ([]int16, error) {
s := newSession(comp)
defer s.rec.Close()
var track []int16
heard := false
for i := range to {
if err := ctx.Err(); err != nil {
return nil, err
}
s.build(i)
if i < from {
continue
}
heard = heard || len(s.plays) > 0
for _, x := range s.mix.frame(i, s.plays) {
track = append(track, int16(math.Round(float64(x)*32767)))
}
}
if !heard {
return nil, nil
}
return track, nil
}
func writePixels(d drawer, out sink, i int) error {
pix, err := d.pixels()
if err != nil {
return err
}
return out.frame(i, pix)
}
+891
View File
@@ -0,0 +1,891 @@
package render
import (
"context"
"encoding/binary"
"errors"
"fmt"
"image"
"image/png"
"math"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
"time"
"github.com/egoist/mygo/ui"
)
func TestInterpolate(t *testing.T) {
in, out := []float64{0, 10, 20}, []float64{0, 1, 0}
for _, c := range []struct {
x float64
o Interpolation
want float64
}{
{5, Interpolation{}, 0.5},
{10, Interpolation{}, 1},
{15, Interpolation{}, 0.5},
{-5, Interpolation{}, 0},
{25, Interpolation{}, 0},
{-5, Interpolation{Left: Extend}, -0.5},
{25, Interpolation{Right: Extend}, -0.5},
{-5, Interpolation{Left: Identity}, -5},
{5, Interpolation{Easing: func(t float32) float32 { return t * t }}, 0.25},
} {
if got := Interpolate(c.x, in, out, c.o); math.Abs(got-c.want) > 1e-9 {
t.Errorf("Interpolate(%v, %+v) = %v, want %v", c.x, c.o, got, c.want)
}
}
for _, bad := range [][2][]float64{{{0}, {0}}, {{0, 1}, {0}}, {{1, 0}, {0, 1}}, {{0, 0}, {0, 1}}} {
func() {
defer func() {
if recover() == nil {
t.Errorf("Interpolate(%v, %v) did not panic", bad[0], bad[1])
}
}()
Interpolate(0, bad[0], bad[1])
}()
}
red, blue := ui.RGB(255, 0, 0), ui.RGB(0, 0, 255)
if c := InterpolateColor(5, []float64{0, 10}, []ui.Color{red, blue}); c != red.Mix(blue, 0.5) {
t.Errorf("InterpolateColor = %v", c)
}
if c := InterpolateColor(20, []float64{0, 10}, []ui.Color{red, blue}); c != blue {
t.Errorf("InterpolateColor beyond the range = %v", c)
}
}
func TestFrame(t *testing.T) {
f := Frame{Index: 45, Count: 90, FPS: 30}
if f.Time() != 1500*time.Millisecond || f.Seconds() != 1.5 {
t.Errorf("Time = %v, Seconds = %v", f.Time(), f.Seconds())
}
if f.Frames(2*time.Second) != 60 {
t.Errorf("Frames(2s) = %d", f.Frames(2*time.Second))
}
if g, ok := f.Shift(30, 30); !ok || g.Index != 15 || g.Count != 30 {
t.Errorf("Shift(30, 30) = %+v, %v", g, ok)
}
if _, ok := f.Shift(60, 10); ok {
t.Error("a sequence that starts later shows")
}
if _, ok := f.Shift(0, 45); ok {
t.Error("a sequence that ended shows")
}
if g, ok := f.Shift(40, 0); !ok || g.Index != 5 || g.Count != 50 {
t.Errorf("Shift(40, 0) = %+v, %v: lasts to the end", g, ok)
}
if g := f.Loop(20); g.Index != 5 || g.Count != 20 {
t.Errorf("Loop(20) = %+v", g)
}
if p := (Frame{Index: 89, Count: 90}).Progress(); p != 1 {
t.Errorf("Progress of the last frame = %v", p)
}
if n, d := (&Composition{FPS: 29.97}).rate(); n != 30000 || d != 1001 {
t.Errorf("29.97 fps = %d/%d", n, d)
}
if n, d := (&Composition{}).rate(); n != 30 || d != 1 {
t.Errorf("the default rate = %d/%d", n, d)
}
}
func TestSpring(t *testing.T) {
o := ui.Snappy.Spring
f := Frame{FPS: 60}
last := -1.0
for i := range 20 {
f.Index = i
v := f.Spring(o)
if v < last {
t.Fatalf("the spring went back at frame %d: %v after %v", i, v, last)
}
last = v
}
settle := f.Frames(o.SettleTime())
f.Index = settle
if v := f.Spring(o); math.Abs(v-1) > 0.002 {
t.Errorf("at rest the spring is at %v", v)
}
f.Index = 30
if v := f.SpringIn(o, 30); math.Abs(v-1) > 0.002 {
t.Errorf("SpringIn(30) at frame 30 = %v", v)
}
f.Index = 0
if v := f.Spring(o); v != 0 {
t.Errorf("the spring starts at %v", v)
}
}
// boxes is a composition of a blue box on red, moving right one pixel a
// frame, of w×h pixels.
func boxes(w, h, frames int) Composition {
return Composition{
Width: w, Height: h, FPS: 30, Frames: frames, Background: ui.RGB(255, 0, 0),
View: func(c *ui.Context, f Frame) {
ui.Box(c).Size(20, 20).Background(ui.RGB(0, 0, 255)).Translate(float32(f.Index), 0)
},
}
}
func at(img *image.RGBA, x, y int) [4]uint8 {
i := img.PixOffset(x, y)
return [4]uint8(img.Pix[i : i+4])
}
func TestStill(t *testing.T) {
img, err := Still(boxes(64, 48, 30), 10, Options{Renderer: CPU})
if err != nil {
t.Fatal(err)
}
if b := img.Bounds(); b.Dx() != 64 || b.Dy() != 48 {
t.Fatalf("a still of %v", b)
}
if p := at(img, 15, 10); p != [4]uint8{0, 0, 255, 255} {
t.Errorf("in the box at frame 10: %v", p)
}
if p := at(img, 5, 10); p != [4]uint8{255, 0, 0, 255} {
t.Errorf("left of the box at frame 10: %v", p)
}
if _, err := Still(boxes(64, 48, 30), 30, Options{}); err == nil {
t.Error("a still after the end")
}
}
func TestScale(t *testing.T) {
// 90×60 at scale 1.5 is a view of 60×40 DIPs, the box 30 pixels wide.
comp := boxes(90, 60, 1)
comp.Scale = 1.5
img, err := Still(comp, 0, Options{Renderer: CPU})
if err != nil {
t.Fatal(err)
}
if b := img.Bounds(); b.Dx() != 90 || b.Dy() != 60 {
t.Fatalf("a still of %v", b)
}
if at(img, 28, 5)[2] != 255 || at(img, 31, 5)[0] != 255 {
t.Errorf("the box is not 30 pixels wide: %v %v", at(img, 28, 5), at(img, 31, 5))
}
}
func TestTransparent(t *testing.T) {
comp := boxes(40, 30, 1)
comp.Transparent = true
img, err := Still(comp, 0, Options{Renderer: CPU})
if err != nil {
t.Fatal(err)
}
if p := at(img, 30, 25); p[3] != 0 {
t.Errorf("outside the box: %v, want transparent", p)
}
if p := at(img, 5, 5); p != [4]uint8{0, 0, 255, 255} {
t.Errorf("in the box: %v", p)
}
}
// TestGPU draws the same frames on the GPU as on the CPU.
func TestGPU(t *testing.T) {
comp := Composition{
Width: 160, Height: 90, Frames: 20, Background: ui.RGB(250, 250, 250),
View: func(c *ui.Context, f Frame) {
ui.Column(c).Fill().Padding(10).Gap(6).Children(func() {
ui.Box(c).Size(40, 20).Background(ui.Hex("#2563eb")).Radius(6).Opacity(float32(f.Progress()))
ui.Text(c, "MyGo").FontSize(20)
})
},
}
var cpu []*image.RGBA
if err := Frames(context.Background(), comp, Options{Renderer: CPU}, func(_ int, img *image.RGBA) error {
cpu = append(cpu, img)
return nil
}); err != nil {
t.Fatal(err)
}
name := ""
i := 0
err := Frames(context.Background(), comp, Options{Renderer: GPU, Progress: func(p Progress) { name = p.Renderer }}, func(_ int, img *image.RGBA) error {
if d := maxDiff(img, cpu[i]); d > 64 {
t.Errorf("frame %d differs by %d from the CPU's", i, d)
}
i++
return nil
})
if err != nil {
t.Skip("no GPU renderer:", err)
}
if i != len(cpu) {
t.Errorf("%d frames on the GPU, %d on the CPU", i, len(cpu))
}
t.Log(name)
}
func maxDiff(a, b *image.RGBA) int {
d := 0
for i := range a.Pix {
d = max(d, int(a.Pix[i])-int(b.Pix[i]), int(b.Pix[i])-int(a.Pix[i]))
}
return d
}
// TestDeterministic renders the same frames each time, and a range the
// same frames a whole render does, ui's animations included, which move
// with the composition's clock.
func TestDeterministic(t *testing.T) {
var values []float32
comp := Composition{
Width: 80, Height: 40, FPS: 60, Frames: 60,
View: func(c *ui.Context, f Frame) {
show := f.Index >= 10
b := ui.Box(c).Size(40, 40).Background(ui.RGB(0, 128, 0))
target := float32(0)
if show {
target = 1
}
o := b.AnimateWith("o", target, 500*time.Millisecond, ui.Linear)
b.Opacity(o)
values = append(values, o)
},
}
render := func(o Options) []*image.RGBA {
values = values[:0]
var out []*image.RGBA
if err := Frames(context.Background(), comp, o, func(_ int, img *image.RGBA) error {
out = append(out, img)
return nil
}); err != nil {
t.Fatal(err)
}
return out
}
a := render(Options{Renderer: CPU})
// The value moves from frame 10 for half a second, 30 frames.
if v := values[len(values)-60+25]; math.Abs(float64(v)-0.5) > 0.02 {
t.Errorf("15 frames into a half second animation at 60 fps: %v", v)
}
b := render(Options{Renderer: CPU})
for i := range a {
if maxDiff(a[i], b[i]) != 0 {
t.Fatalf("frame %d differs between renders", i)
}
}
part := render(Options{Renderer: CPU, From: 20, To: 30})
if len(part) != 10 {
t.Fatalf("%d frames from 20 to 30", len(part))
}
for i, img := range part {
if maxDiff(img, a[20+i]) != 0 {
t.Errorf("frame %d of a range differs from the whole render's", 20+i)
}
}
}
func TestCancel(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
n := 0
err := Frames(ctx, boxes(32, 32, 100), Options{Renderer: CPU}, func(int, *image.RGBA) error {
n++
if n == 5 {
cancel()
}
return nil
})
if !errors.Is(err, context.Canceled) || n > 6 {
t.Errorf("canceled after 5 frames: %v, %d frames", err, n)
}
stop := errors.New("stop")
if err := Frames(context.Background(), boxes(32, 32, 10), Options{}, func(int, *image.RGBA) error { return stop }); err != stop {
t.Errorf("fn's error: %v", err)
}
}
func TestImages(t *testing.T) {
dir := t.TempDir()
comp := boxes(40, 30, 6)
comp.Transparent = true
if err := Images(context.Background(), comp, filepath.Join(dir, "frames", "f-%03d.png"), Options{Renderer: CPU}); err != nil {
t.Fatal(err)
}
for i := range 6 {
f, err := os.Open(filepath.Join(dir, "frames", fmt.Sprintf("f-%03d.png", i)))
if err != nil {
t.Fatal(err)
}
img, err := png.Decode(f)
f.Close()
if err != nil {
t.Fatal(err)
}
r, g, b, a := img.At(i+5, 5).RGBA()
if b>>8 != 255 || a>>8 != 255 || r != 0 || g != 0 {
t.Errorf("frame %d: the box is %v %v %v %v", i, r>>8, g>>8, b>>8, a>>8)
}
if _, _, _, a := img.At(35, 25).RGBA(); a != 0 {
t.Errorf("frame %d: transparent outside the box, alpha %d", i, a>>8)
}
}
if err := Images(context.Background(), comp, filepath.Join(dir, "x.png"), Options{}); err == nil {
t.Error("a pattern without a verb")
}
if err := Images(context.Background(), comp, filepath.Join(dir, "%d.jpg"), Options{Renderer: CPU, Quality: 80}); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(dir, "5.jpg")); err != nil {
t.Error(err)
}
}
// tone returns a second of a sine at hz, mono, at rate.
func tone(hz float64, rate int) *Sound {
pcm := make([]float32, rate)
for i := range pcm {
pcm[i] = 0.5 * float32(math.Sin(2*math.Pi*hz*float64(i)/float64(rate)))
}
return SoundOf(rate, 1, pcm)
}
// beeping is a composition playing a beep in its frames 10 to 30.
func beeping(w, h, frames int, beep *Sound) Composition {
comp := boxes(w, h, frames)
view := comp.View
comp.View = func(c *ui.Context, f Frame) {
view(c, f)
f.Sequence(c, 10, 20, func(f Frame) { f.Audio(beep) })
}
return comp
}
func TestSoundtrack(t *testing.T) {
beep := tone(440, sampleRate)
track, err := soundtrack(context.Background(), beeping(32, 32, 60, beep), 0, 60)
if err != nil {
t.Fatal(err)
}
if len(track) != 2*2*sampleRate {
t.Fatalf("%d samples for 2 seconds", len(track))
}
// Frames 10 to 30 at 30 fps: from a third of a second for two thirds.
start, end := sampleRate/3, sampleRate
for i := 0; i < len(track)/2; i++ {
l, r := track[2*i], track[2*i+1]
if l != r {
t.Fatalf("a mono sound differs between channels at %d", i)
}
in := i >= start && i < end
if !in && l != 0 {
t.Fatalf("sound at %d, outside the sequence", i)
}
if in {
want := math.Round(0.5 * math.Sin(2*math.Pi*440*float64(i-start)/sampleRate) * 32767)
if math.Abs(float64(l)-want) > 2 {
t.Fatalf("at %d: %d, want %v", i, l, want)
}
}
}
if track, _ := soundtrack(context.Background(), boxes(32, 32, 10), 0, 10); track != nil {
t.Error("a sound track for a silent composition")
}
// A range: the track starts at its first frame.
part, _ := soundtrack(context.Background(), beeping(32, 32, 60, beep), 20, 40)
if len(part) != 2*2*sampleRate/3 || part[0] == 0 && part[2] == 0 {
t.Errorf("a range's track: %d samples, starting %v", len(part), part[:4])
}
}
func TestVolume(t *testing.T) {
beep := tone(440, sampleRate)
comp := Composition{Width: 16, Height: 16, Frames: 30, View: func(c *ui.Context, f Frame) {
f.Audio(beep, AudioOptions{Volume: f.Interpolate([]float64{0, 29}, []float64{0.001, 1})})
}}
track, err := soundtrack(context.Background(), comp, 0, 30)
if err != nil {
t.Fatal(err)
}
peak := func(from, to int) (p int16) {
for _, x := range track[2*from : 2*to] {
p = max(p, x)
}
return p
}
if a, b := peak(0, 1600), peak(len(track)/2-1600, len(track)/2); a >= b/4 {
t.Errorf("a fade in: %d at the start, %d at the end", a, b)
}
}
func TestResample(t *testing.T) {
// A sine at 44.1 kHz, resampled, is the same sine at 48 kHz.
s := tone(1000, 44100)
out := make([]float32, 2*4800)
s.mix(out, 0.25, 4800, 1, 1, false, 0)
for k := 0; k < 4800; k += 7 {
want := 0.5 * math.Sin(2*math.Pi*1000*(0.25+float64(k)/sampleRate))
if d := math.Abs(float64(out[2*k]) - want); d > 0.01 {
t.Fatalf("at %d: %v, want %v", k, out[2*k], want)
}
}
}
// mp4Tracks returns the handler type and sample count of each track of
// an MP4 or QuickTime file.
func mp4Tracks(t *testing.T, path string) map[string]int {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
tracks := map[string]int{}
var walk func(b []byte, handler *string)
walk = func(b []byte, handler *string) {
for len(b) >= 8 {
size := int(binary.BigEndian.Uint32(b))
kind := string(b[4:8])
head := 8
if size == 1 && len(b) >= 16 {
size, head = int(binary.BigEndian.Uint64(b[8:])), 16
} else if size == 0 {
size = len(b)
}
if size < head || size > len(b) {
return
}
body := b[head:size]
switch kind {
case "moov", "mdia", "minf", "stbl":
walk(body, handler)
case "trak":
var h string
walk(body, &h)
case "hdlr":
// The media's; QuickTime's minf has one of its data too.
if len(body) >= 12 && handler != nil && *handler == "" {
*handler = string(body[8:12])
}
case "stsz":
if len(body) >= 12 && handler != nil {
tracks[*handler] = int(binary.BigEndian.Uint32(body[8:]))
}
}
b = b[size:]
}
}
walk(data, nil)
return tracks
}
func TestVideo(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "beep.mp4")
comp := beeping(320, 180, 45, tone(440, sampleRate))
err := Video(context.Background(), comp, path, Options{})
if errors.Is(err, errors.ErrUnsupported) {
t.Skip(err)
}
if err != nil {
t.Fatal(err)
}
if out := os.Getenv("MYGO_RENDER_OUT"); out != "" {
// For a look at what the system's encoder made.
if data, err := os.ReadFile(path); err == nil {
os.WriteFile(filepath.Join(out, "beep.mp4"), data, 0o644)
}
}
tracks := mp4Tracks(t, path)
if tracks["vide"] != 45 {
t.Errorf("%d video frames, want 45: %v", tracks["vide"], tracks)
}
if tracks["soun"] == 0 {
t.Errorf("no sound: %v", tracks)
}
// No file but the video is left behind.
entries, _ := os.ReadDir(dir)
if len(entries) != 1 {
t.Errorf("files left: %v", entries)
}
// Without sound, no sound track; a range, its frames.
silent := filepath.Join(dir, "silent.mp4")
if err := Video(context.Background(), boxes(320, 180, 45), silent, Options{From: 15, To: 30, Renderer: CPU}); err != nil {
t.Fatal(err)
}
if tracks := mp4Tracks(t, silent); tracks["vide"] != 15 || tracks["soun"] != 0 {
t.Errorf("a silent range: %v", tracks)
}
if err := Video(context.Background(), boxes(321, 180, 10), filepath.Join(dir, "odd.mp4"), Options{}); err == nil {
t.Error("H.264 of an odd width")
}
if err := Video(context.Background(), boxes(320, 180, 10), filepath.Join(dir, "x.avi"), Options{}); err == nil {
t.Error("an .avi")
}
}
// mp4FrameTimes returns the time scale of the video track of an MP4 or a
// QuickTime movie, and how long its frames last in it: the runs of its
// stts, each a count of frames and their duration.
func mp4FrameTimes(t *testing.T, path string) (scale uint32, runs [][2]uint32) {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
type track struct {
handler string
scale uint32
runs [][2]uint32
}
var walk func(b []byte, tr *track)
walk = func(b []byte, tr *track) {
for len(b) >= 8 {
size := int(binary.BigEndian.Uint32(b))
kind := string(b[4:8])
head := 8
if size == 1 && len(b) >= 16 {
size, head = int(binary.BigEndian.Uint64(b[8:])), 16
} else if size == 0 {
size = len(b)
}
if size < head || size > len(b) {
return
}
body := b[head:size]
switch {
case kind == "moov", kind == "mdia", kind == "minf", kind == "stbl":
walk(body, tr)
case kind == "trak":
var found track
walk(body, &found)
if found.handler == "vide" {
scale, runs = found.scale, found.runs
}
case tr == nil:
case kind == "hdlr" && len(body) >= 12 && tr.handler == "":
tr.handler = string(body[8:12])
case kind == "mdhd" && len(body) >= 24:
// After the times of its making, of 8 bytes each in version 1.
at := 12
if body[0] == 1 {
at = 20
}
tr.scale = binary.BigEndian.Uint32(body[at:])
case kind == "stts" && len(body) >= 8:
for b := body[8:]; len(b) >= 8; b = b[8:] {
tr.runs = append(tr.runs, [2]uint32{binary.BigEndian.Uint32(b), binary.BigEndian.Uint32(b[4:])})
}
}
b = b[size:]
}
}
walk(data, nil)
return scale, runs
}
// TestVideoFrameTimes checks that every frame of a video lasts what its
// rate says: 1001/30000 s at 29.97 frames a second, which a track counted
// in the 1/600 s of AVFoundation cannot say.
func TestVideoFrameTimes(t *testing.T) {
if runtime.GOOS == "windows" {
// Media Foundation takes times in 100 ns, which 1001/30000 s is no
// whole number of either: what it writes is not known here.
t.Skip("not checked with Media Foundation")
}
dir := t.TempDir()
const frames = 30
for _, fps := range []float64{30, 29.97, 23.976, 59.94, 48, 240} {
for _, name := range []string{"frames.mp4", "frames.mov"} {
comp := boxes(320, 180, frames)
comp.FPS = fps
path := filepath.Join(dir, name)
err := Video(context.Background(), comp, path, Options{Renderer: CPU})
if errors.Is(err, errors.ErrUnsupported) {
t.Skip(err)
}
if err != nil {
t.Fatal(err)
}
num, den := comp.rate()
scale, runs := mp4FrameTimes(t, path)
if len(runs) != 1 || runs[0][0] != frames || int64(runs[0][1])*num != den*int64(scale) {
t.Errorf("%v frames a second in %s: frames last %v (count, duration) of 1/%d s, want %d of %d/%d s", fps, name, runs, scale, frames, den, num)
}
}
}
}
func TestVideoCanceled(t *testing.T) {
// Canceled while the sound is mixed, and while the frames draw.
for _, mixing := range []bool{true, false} {
dir := t.TempDir()
ctx, cancel := context.WithCancel(context.Background())
comp := beeping(320, 180, 300, tone(440, sampleRate))
o := Options{Renderer: CPU}
if mixing {
view := comp.View
comp.View = func(c *ui.Context, f Frame) {
view(c, f)
if f.Index == 20 {
cancel()
}
}
} else {
o.Progress = func(p Progress) {
if p.Frame == 20 {
cancel()
}
}
}
err := Video(ctx, comp, filepath.Join(dir, "canceled.mp4"), o)
if errors.Is(err, errors.ErrUnsupported) {
t.Skip(err)
}
if !errors.Is(err, context.Canceled) {
t.Errorf("canceled: %v", err)
}
if entries, _ := os.ReadDir(dir); len(entries) != 0 {
t.Errorf("files left: %v", entries)
}
}
}
// TestCodecs writes each codec the system has into its container.
func TestCodecs(t *testing.T) {
dir := t.TempDir()
for _, c := range []struct {
name string
codec Codec
}{{"hevc.mp4", HEVC}, {"hevc.mov", HEVC}, {"h264.mov", H264}, {"prores.mov", ProRes}, {"alpha.mov", ProRes4444}} {
comp := beeping(160, 90, 20, tone(440, sampleRate))
comp.Transparent = c.codec == ProRes4444
path := filepath.Join(dir, c.name)
err := Video(context.Background(), comp, path, Options{Codec: c.codec})
if errors.Is(err, errors.ErrUnsupported) {
t.Logf("%s: %v", c.name, err)
continue
}
if err != nil {
t.Errorf("%s: %v", c.name, err)
continue
}
if tracks := mp4Tracks(t, path); tracks["vide"] != 20 || tracks["soun"] == 0 {
t.Errorf("%s: %v", c.name, tracks)
}
}
for _, bad := range []struct {
name string
codec Codec
}{{"prores.mp4", ProRes}, {"vp9.mp4", VP9}, {"h264.webm", H264}} {
if err := Video(context.Background(), boxes(160, 90, 2), filepath.Join(dir, bad.name), Options{Codec: bad.codec}); err == nil || errors.Is(err, errors.ErrUnsupported) {
t.Errorf("%s: %v, want an error of the format", bad.name, err)
}
}
}
func TestFFmpeg(t *testing.T) {
if _, err := exec.LookPath("ffmpeg"); err != nil {
t.Skip("no ffmpeg")
}
dir := t.TempDir()
for _, name := range []string{"beep.mp4", "beep.webm"} {
path := filepath.Join(dir, name)
if err := Video(context.Background(), beeping(160, 90, 40, tone(440, sampleRate)), path, Options{Encoder: FFmpeg, Renderer: CPU}); err != nil {
t.Fatal(err)
}
if filepath.Ext(name) == ".mp4" {
if tracks := mp4Tracks(t, path); tracks["vide"] != 40 || tracks["soun"] == 0 {
t.Errorf("%s: %v", name, tracks)
}
} else if fi, err := os.Stat(path); err != nil || fi.Size() == 0 {
t.Errorf("%s: %v", name, err)
}
}
if entries, _ := os.ReadDir(dir); len(entries) != 2 {
t.Errorf("files left: %v", entries)
}
}
// TestPlayer shows a composition's frames in a window, as the video has
// them, and seeks without drawing the frames before.
func TestPlayer(t *testing.T) {
comp := Composition{Width: 40, Height: 40, FPS: 10, Frames: 30, View: func(c *ui.Context, f Frame) {
ui.Box(c).Fill().Background(InterpolateColor(float64(f.Index), []float64{0, 29}, []ui.Color{ui.RGB(255, 0, 0), ui.RGB(0, 0, 255)}))
}}
p, err := NewPlayer(comp)
if err != nil {
t.Fatal(err)
}
defer p.Close()
if p.Duration() != 3*time.Second {
t.Errorf("a duration of %v", p.Duration())
}
tt := ui.NewTester(func(c *ui.Context) { ui.Video(c, p).Size(40, 40) }, 40, 40)
p.Pause()
for _, c := range []struct {
at time.Duration
frame int
}{{2050 * time.Millisecond, 20}, {500 * time.Millisecond, 5}, {time.Hour, 29}} {
p.Seek(c.at)
tt.Frame()
want := InterpolateColor(float64(c.frame), []float64{0, 29}, []ui.Color{ui.RGB(255, 0, 0), ui.RGB(0, 0, 255)})
got := tt.Image().RGBAAt(20, 20)
if d := max(absDiff(got.R, want.R), absDiff(got.B, want.B)); d > 2 {
t.Errorf("sought to %v: %v, want frame %d's %v", c.at, got, c.frame, want)
}
}
}
func absDiff(a, b uint8) int { return max(int(a)-int(b), int(b)-int(a)) }
// TestNV12 converts colors as BT.709 in the limited range has them.
func TestNV12(t *testing.T) {
for _, c := range []struct {
bgra [4]byte
y, cb, cr byte
}{
{[4]byte{0, 0, 0, 255}, 16, 128, 128},
{[4]byte{255, 255, 255, 255}, 235, 128, 128},
{[4]byte{0, 0, 255, 255}, 63, 102, 240}, // red
{[4]byte{0, 255, 0, 255}, 173, 42, 26}, // green
{[4]byte{255, 0, 0, 255}, 32, 240, 118}, // blue
{[4]byte{0, 0, 0, 0}, 16, 128, 128}, // transparent: black
} {
src := make([]byte, 4*4*2)
for i := 0; i < len(src); i += 4 {
copy(src[i:], c.bgra[:])
}
dst := make([]byte, 4*2*3/2)
bgraToNV12(dst, src, 4, 2)
if dst[0] != c.y || dst[7] != c.y || dst[8] != c.cb || dst[9] != c.cr {
t.Errorf("%v: Y %d, Cb %d, Cr %d, want %d %d %d", c.bgra, dst[0], dst[8], dst[9], c.y, c.cb, c.cr)
}
}
}
// TestPlayerSeeksToFrameStarts seeks to the time a frame starts at, as
// stepping frame by frame does, without ending the video.
func TestPlayerSeeksToFrameStarts(t *testing.T) {
comp := boxes(32, 32, 90)
p, err := NewPlayer(comp)
if err != nil {
t.Fatal(err)
}
defer p.Close()
tt := ui.NewTester(func(c *ui.Context) { ui.Video(c, p).Size(32, 32) }, 32, 32)
p.Pause()
s := newSession(comp)
defer s.rec.Close()
for _, i := range []int{1, 2, 45, 88} {
p.Seek(s.at(i))
tt.Frame()
if p.Ended() || p.Position() != s.at(i) {
t.Errorf("sought to frame %d's start: ended %v at %v", i, p.Ended(), p.Position())
}
}
}
// TestSoundAcrossFrames plays a sound without a jump where frames meet,
// at a rate whose frames do not hold whole samples.
func TestSoundAcrossFrames(t *testing.T) {
beep := tone(1000, sampleRate)
comp := Composition{Width: 16, Height: 16, FPS: 29.97, Frames: 20, View: func(c *ui.Context, f Frame) {
f.Sequence(c, 3, 0, func(f Frame) { f.Audio(beep) })
}}
track, err := soundtrack(context.Background(), comp, 0, 20)
if err != nil {
t.Fatal(err)
}
m := newMixer(30000, 1001)
start := m.sampleAt(3)
// From past the kernel's reach of the sound's onset.
for k := int(start) + reach; k < len(track)/2; k++ {
// The sound started at frame 3's time, between two samples.
at := float64(k)/sampleRate - 3*1001.0/30000
if at >= 1 {
break
}
want := 0.0
if at >= 0 {
want = 32767 * 0.5 * math.Sin(2*math.Pi*1000*at)
}
if d := math.Abs(float64(track[2*k]) - want); d > 60 {
t.Fatalf("sample %d: %d, want %.0f", k, track[2*k], want)
}
}
}
// TestMotionBlur makes each frame the mean of samples over the shutter's
// time: a box moving 4 pixels a frame covers, at frame 5 with 4 samples
// over the whole frame, the pixels from 17 to 28, the more the later.
func TestMotionBlur(t *testing.T) {
comp := Composition{
Width: 48, Height: 8, Frames: 10, Background: ui.RGB(255, 255, 255),
MotionBlur: MotionBlur{Samples: 4, Shutter: 360},
View: func(c *ui.Context, f Frame) {
ui.Box(c).Size(8, 8).Background(ui.RGB(0, 0, 0)).Translate(float32(4*f.Exact()), 0)
ui.Box(c).Absolute().Left(40).Top(0).Size(8, 8).Background(ui.RGB(255, 0, 0)) // still
},
}
for _, r := range []Renderer{CPU, GPU} {
img, err := Still(comp, 5, Options{Renderer: r})
if r == GPU && err != nil {
t.Log("no GPU:", err)
continue
}
if err != nil {
t.Fatal(err)
}
// Samples at frames 4.25, 4.5, 4.75 and 5: the box at 17, 18, 19, 20.
for x, covered := range map[int]int{16: 0, 17: 1, 18: 2, 19: 3, 20: 4, 24: 4, 25: 3, 26: 2, 27: 1, 28: 0} {
want := 255 - (255*covered+2)/4
if got := int(at(img, x, 4)[0]); absDiff(uint8(got), uint8(want)) > 2 {
t.Errorf("%v: x %d: %d, want %d (%d of 4 samples)", r, x, got, want, covered)
}
}
if p := at(img, 44, 4); p != [4]uint8{255, 0, 0, 255} {
t.Errorf("%v: what stands still blurs: %v", r, p)
}
}
comp.MotionBlur = MotionBlur{Samples: 100}
if _, err := Still(comp, 0, Options{}); err == nil {
t.Error("100 samples")
}
}
// TestMotionBlurOfUI blurs ui's own animations, which follow the clock,
// and writes a video of it.
func TestMotionBlurOfUI(t *testing.T) {
comp := Composition{
Width: 64, Height: 16, Frames: 12, MotionBlur: MotionBlur{Samples: 5},
View: func(c *ui.Context, f Frame) {
b := ui.Box(c).Size(16, 16).Background(ui.RGB(0, 0, 255))
x := b.AnimateWith("x", float32(min(f.Index, 1)*48), 300*time.Millisecond, ui.Linear)
b.Translate(x, 0)
},
}
img, err := Still(comp, 4, Options{Renderer: CPU})
if err != nil {
t.Fatal(err)
}
partial := 0
for x := range 64 {
// Red: none in the box, all in the light background.
if r := at(img, x, 8)[0]; r > 10 && r < 235 {
partial++
}
}
if partial < 2 {
t.Errorf("a box moving with ui's animation shows no blur: %d pixels between", partial)
}
dir := t.TempDir()
// As large as Media Foundation's encoder takes.
comp.Width, comp.Height = 160, 96
err = Video(context.Background(), comp, filepath.Join(dir, "blur.mp4"), Options{})
if errors.Is(err, errors.ErrUnsupported) {
return
}
if err != nil {
t.Fatal(err)
}
if tracks := mp4Tracks(t, filepath.Join(dir, "blur.mp4")); tracks["vide"] != 12 {
t.Errorf("a video with motion blur: %v", tracks)
}
}
+609
View File
@@ -0,0 +1,609 @@
//go:build darwin && !ios
package render
import (
"errors"
"fmt"
"math"
"runtime"
"sync"
"time"
"unsafe"
"github.com/ebitengine/purego"
"github.com/ebitengine/purego/objc"
"github.com/egoist/mygo/internal/scene"
)
// On macOS, an AVAssetWriter writes the video: VideoToolbox encodes H.264
// and HEVC, in hardware, and ProRes, from CVPixelBuffers in BGRA backed by
// IOSurfaces, which the pool of its pixel buffer adaptor gives. Metal
// draws each frame straight into one (metal.Frames.DrawSurface): no frame
// is copied through memory. The sound goes to an input of its own,
// encoded in AAC.
var (
avOnce sync.Once
avErr error
msgAppendPixels func(obj objc.ID, s objc.SEL, pb uintptr, t cmTime) bool
msgStartSession func(obj objc.ID, s objc.SEL, t cmTime)
msgBool func(obj objc.ID, s objc.SEL) bool
msgSetBool func(obj objc.ID, s objc.SEL, v bool)
msgInt func(obj objc.ID, s objc.SEL) int
cvPoolCreatePixelBuffer func(alloc, pool uintptr, out *uintptr) int32
cvPixelBufferRelease func(pb uintptr)
cvPixelBufferGetIOSurface func(pb uintptr) uintptr
cvLock func(pb uintptr, flags uint64) int32
cvUnlock func(pb uintptr, flags uint64) int32
cvBase func(pb uintptr) unsafe.Pointer
cvStride func(pb uintptr) uint
cvSetAttachment func(buf, key, value uintptr, mode uint32)
cmAudioFormatCreate func(alloc uintptr, asbd *audioFormat, layoutSize uint, layout uintptr, cookieSize uint, cookie uintptr, ext uintptr, out *uintptr) int32
cmBlockCreate func(alloc, block uintptr, length uint, blockAlloc, custom uintptr, offset, dataLength uint, flags uint32, out *uintptr) int32
cmBlockReplace func(src unsafe.Pointer, dest uintptr, offset, length uint) int32
cmAudioSampleCreate func(alloc, data, format uintptr, n int, pts cmTime, descs uintptr, out *uintptr) int32
cfRelease func(obj uintptr)
cfRetain func(obj uintptr) uintptr
poolPush func() uintptr
poolPop func(pool uintptr)
// avKeys are the constants of AVFoundation and CoreVideo, by name.
avKeys = map[string]uintptr{}
)
// cmTime is a CMTime.
type cmTime struct {
Value int64
Timescale int32
Flags uint32
Epoch int64
}
// audioFormat is an AudioStreamBasicDescription.
type audioFormat struct {
SampleRate float64
FormatID, FormatFlags, BytesPerPacket uint32
FramesPerPacket, BytesPerFrame, Channels uint32
BitsPerChannel, Reserved uint32
}
const (
cmTimeValid = 1
pixelFormatBGRA = 0x42475241 // kCVPixelFormatType_32BGRA
formatLinearPCM = 0x6c70636d // 'lpcm'
formatAAC = 0x61616320 // 'aac '
formatIntPacked = 4 | 8 // kAudioFormatFlagIsSignedInteger | IsPacked
writerStatusDone = 2
writerStatusFailed = 3
attachmentPropagate = 1
)
func loadAV() error {
avOnce.Do(func() {
defer func() {
if v := recover(); v != nil {
avErr = fmt.Errorf("render: AVFoundation: %v", v)
}
}()
open := func(path string) uintptr {
h, err := purego.Dlopen(path, purego.RTLD_GLOBAL|purego.RTLD_NOW)
if err != nil {
panic(err)
}
return h
}
objcLib := open("/usr/lib/libobjc.A.dylib")
open("/System/Library/Frameworks/Foundation.framework/Foundation")
av := open("/System/Library/Frameworks/AVFoundation.framework/AVFoundation")
cv := open("/System/Library/Frameworks/CoreVideo.framework/CoreVideo")
cm := open("/System/Library/Frameworks/CoreMedia.framework/CoreMedia")
cf := open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
msgSend, err := purego.Dlsym(objcLib, "objc_msgSend")
if err != nil {
panic(err)
}
purego.RegisterFunc(&msgAppendPixels, msgSend)
purego.RegisterFunc(&msgStartSession, msgSend)
purego.RegisterFunc(&msgBool, msgSend)
purego.RegisterFunc(&msgSetBool, msgSend)
purego.RegisterFunc(&msgInt, msgSend)
purego.RegisterLibFunc(&poolPush, objcLib, "objc_autoreleasePoolPush")
purego.RegisterLibFunc(&poolPop, objcLib, "objc_autoreleasePoolPop")
purego.RegisterLibFunc(&cvPoolCreatePixelBuffer, cv, "CVPixelBufferPoolCreatePixelBuffer")
purego.RegisterLibFunc(&cvPixelBufferRelease, cv, "CVPixelBufferRelease")
purego.RegisterLibFunc(&cvPixelBufferGetIOSurface, cv, "CVPixelBufferGetIOSurface")
purego.RegisterLibFunc(&cvLock, cv, "CVPixelBufferLockBaseAddress")
purego.RegisterLibFunc(&cvUnlock, cv, "CVPixelBufferUnlockBaseAddress")
purego.RegisterLibFunc(&cvBase, cv, "CVPixelBufferGetBaseAddress")
purego.RegisterLibFunc(&cvStride, cv, "CVPixelBufferGetBytesPerRow")
purego.RegisterLibFunc(&cvSetAttachment, cv, "CVBufferSetAttachment")
purego.RegisterLibFunc(&cmAudioFormatCreate, cm, "CMAudioFormatDescriptionCreate")
purego.RegisterLibFunc(&cmBlockCreate, cm, "CMBlockBufferCreateWithMemoryBlock")
purego.RegisterLibFunc(&cmBlockReplace, cm, "CMBlockBufferReplaceDataBytes")
purego.RegisterLibFunc(&cmAudioSampleCreate, cm, "CMAudioSampleBufferCreateReadyWithPacketDescriptions")
purego.RegisterLibFunc(&cfRelease, cf, "CFRelease")
purego.RegisterLibFunc(&cfRetain, cf, "CFRetain")
for lib, names := range map[uintptr][]string{
av: {"AVFileTypeMPEG4", "AVFileTypeQuickTimeMovie", "AVMediaTypeVideo", "AVMediaTypeAudio",
"AVVideoCodecKey", "AVVideoCodecTypeH264", "AVVideoCodecTypeHEVC", "AVVideoCodecTypeAppleProRes422HQ",
"AVVideoCodecTypeAppleProRes4444", "AVVideoWidthKey", "AVVideoHeightKey", "AVVideoCompressionPropertiesKey",
"AVVideoAverageBitRateKey", "AVVideoExpectedSourceFrameRateKey", "AVVideoMaxKeyFrameIntervalKey",
"AVVideoProfileLevelKey", "AVVideoProfileLevelH264HighAutoLevel", "AVVideoColorPropertiesKey",
"AVVideoColorPrimariesKey", "AVVideoColorPrimaries_ITU_R_709_2", "AVVideoTransferFunctionKey",
"AVVideoTransferFunction_ITU_R_709_2", "AVVideoYCbCrMatrixKey", "AVVideoYCbCrMatrix_ITU_R_709_2",
"AVFormatIDKey", "AVSampleRateKey", "AVNumberOfChannelsKey", "AVEncoderBitRateKey"},
cv: {"kCVPixelBufferPixelFormatTypeKey", "kCVPixelBufferWidthKey", "kCVPixelBufferHeightKey",
"kCVPixelBufferIOSurfacePropertiesKey", "kCVPixelBufferMetalCompatibilityKey"},
} {
for _, name := range names {
p, err := purego.Dlsym(lib, name)
if err != nil || p == 0 {
panic("no " + name)
}
avKeys[name] = *(*uintptr)(cptr(p))
}
}
// The alpha mode of ProRes 4444's pixel buffers, from macOS 12.
for _, name := range []string{"kCVImageBufferAlphaChannelModeKey", "kCVImageBufferAlphaChannelMode_PremultipliedAlpha"} {
if p, err := purego.Dlsym(cv, name); err == nil && p != 0 {
avKeys[name] = *(*uintptr)(cptr(p))
}
}
if class("AVAssetWriter") == 0 {
panic("no AVAssetWriter")
}
})
return avErr
}
var sels sync.Map
func sel(name string) objc.SEL {
if s, ok := sels.Load(name); ok {
return s.(objc.SEL)
}
s := objc.RegisterName(name)
sels.Store(name, s)
return s
}
func send(obj objc.ID, name string, args ...any) objc.ID { return obj.Send(sel(name), args...) }
func class(name string) objc.ID { return objc.ID(objc.GetClass(name)) }
func key(name string) objc.ID { return objc.ID(avKeys[name]) }
func nsString(s string) objc.ID { return send(class("NSString"), "stringWithUTF8String:", s) }
func nsInt(n int64) objc.ID { return send(class("NSNumber"), "numberWithLongLong:", n) }
// nsDict returns an autoreleased dictionary of the keys and values.
func nsDict(kv ...objc.ID) objc.ID {
n := len(kv) / 2
keys, values := make([]objc.ID, n), make([]objc.ID, n)
for i := range n {
keys[i], values[i] = kv[2*i], kv[2*i+1]
}
return send(class("NSDictionary"), "dictionaryWithObjects:forKeys:count:", unsafe.Pointer(&values[0]), unsafe.Pointer(&keys[0]), uint(n))
}
func goString(str objc.ID) string {
if str == 0 {
return ""
}
p := uintptr(send(str, "UTF8String"))
if p == 0 {
return ""
}
n := 0
for *(*byte)(cptr(p + uintptr(n))) != 0 {
n++
}
return string(unsafe.Slice((*byte)(cptr(p)), n))
}
// cptr is the pointer of an address of native memory.
func cptr(a uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&a)) }
// pooled runs fn in an autorelease pool.
func pooled(fn func() error) error {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
p := poolPush()
defer poolPop(p)
return fn()
}
// avSink writes a video with an AVAssetWriter.
type avSink struct {
spec videoSpec
writer, video, adaptor, snd objc.ID
pool, format uintptr
// frames are the frames the video input did not take yet, in order.
frames []avFrame
written int64 // video frames queued
samples int64 // frames of the sound track given to the writer
// soundDone is set once the sound input is finished.
soundDone bool
alpha bool
}
type avFrame struct {
pb uintptr
n int64 // frames from the first
}
// avSceneSink is an avSink whose frames Metal draws into its pixel buffers.
type avSceneSink struct {
*avSink
d *metalDrawer
// pending is the pixel buffer of the frame the GPU draws, 0 for none.
pending avFrame
}
func newVideoSink(spec videoSpec, d drawer) (sink, error) {
if spec.container == webm {
return nil, fmt.Errorf("render: %w: macOS has no WebM encoder: encode it with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported)
}
if err := loadAV(); err != nil {
return nil, err
}
s := &avSink{spec: spec, alpha: spec.alpha && avKeys["kCVImageBufferAlphaChannelModeKey"] != 0}
if err := pooled(s.open); err != nil {
s.abort()
return nil, err
}
if md, ok := d.(*metalDrawer); ok {
return &avSceneSink{avSink: s, d: md}, nil
}
return s, nil
}
// mediaTimeScale is the time scale of the video's track, and of the movie,
// for frames at num/den a second: the smallest multiple of num from
// AVFoundation's own 600 on, in which each frame lasts a whole number of
// units. In 1/600 s a frame at 29.97 a second, 1001/30000 s, does not.
func mediaTimeScale(num int64) int32 {
const usual = 600
return int32(num * ((usual + num - 1) / num))
}
func (s *avSink) open() error {
sp := s.spec
url := send(class("NSURL"), "fileURLWithPath:", nsString(sp.path))
fileType := key("AVFileTypeMPEG4")
if sp.container == mov {
fileType = key("AVFileTypeQuickTimeMovie")
}
var nserr objc.ID
s.writer = send(send(class("AVAssetWriter"), "alloc"), "initWithURL:fileType:error:", url, fileType, unsafe.Pointer(&nserr))
if s.writer == 0 {
return fmt.Errorf("render: cannot write %s: %s", sp.path, describe(nserr))
}
if sp.container == mp4 {
msgSetBool(s.writer, sel("setShouldOptimizeForNetworkUse:"), true)
}
send(s.writer, "setMovieTimeScale:", mediaTimeScale(sp.num))
codec := map[Codec]string{H264: "AVVideoCodecTypeH264", HEVC: "AVVideoCodecTypeHEVC",
ProRes: "AVVideoCodecTypeAppleProRes422HQ", ProRes4444: "AVVideoCodecTypeAppleProRes4444"}[sp.codec]
settings := []objc.ID{
key("AVVideoCodecKey"), key(codec),
key("AVVideoWidthKey"), nsInt(int64(sp.w)),
key("AVVideoHeightKey"), nsInt(int64(sp.h)),
key("AVVideoColorPropertiesKey"), nsDict(
key("AVVideoColorPrimariesKey"), key("AVVideoColorPrimaries_ITU_R_709_2"),
key("AVVideoTransferFunctionKey"), key("AVVideoTransferFunction_ITU_R_709_2"),
key("AVVideoYCbCrMatrixKey"), key("AVVideoYCbCrMatrix_ITU_R_709_2")),
}
if sp.codec == H264 || sp.codec == HEVC {
fps := max((sp.num+sp.den/2)/sp.den, 1)
props := []objc.ID{
key("AVVideoAverageBitRateKey"), nsInt(int64(sp.bitrate)),
key("AVVideoExpectedSourceFrameRateKey"), nsInt(fps),
key("AVVideoMaxKeyFrameIntervalKey"), nsInt(2 * fps),
}
if sp.codec == H264 {
props = append(props, key("AVVideoProfileLevelKey"), key("AVVideoProfileLevelH264HighAutoLevel"))
}
settings = append(settings, key("AVVideoCompressionPropertiesKey"), nsDict(props...))
}
s.video = send(send(class("AVAssetWriterInput"), "assetWriterInputWithMediaType:outputSettings:", key("AVMediaTypeVideo"), nsDict(settings...)), "retain")
if s.video == 0 {
return errors.New("render: AVFoundation takes no input of these settings")
}
msgSetBool(s.video, sel("setExpectsMediaDataInRealTime:"), false)
send(s.video, "setMediaTimeScale:", mediaTimeScale(sp.num))
attrs := nsDict(
key("kCVPixelBufferPixelFormatTypeKey"), nsInt(pixelFormatBGRA),
key("kCVPixelBufferWidthKey"), nsInt(int64(sp.w)),
key("kCVPixelBufferHeightKey"), nsInt(int64(sp.h)),
key("kCVPixelBufferIOSurfacePropertiesKey"), send(class("NSDictionary"), "dictionary"),
key("kCVPixelBufferMetalCompatibilityKey"), send(class("NSNumber"), "numberWithBool:", true),
)
s.adaptor = send(send(class("AVAssetWriterInputPixelBufferAdaptor"), "assetWriterInputPixelBufferAdaptorWithAssetWriterInput:sourcePixelBufferAttributes:", s.video, attrs), "retain")
if byte(send(s.writer, "canAddInput:", s.video)) == 0 {
return fmt.Errorf("render: AVFoundation cannot write %v into this file", sp.codec)
}
send(s.writer, "addInput:", s.video)
if sp.sound != nil {
settings := nsDict(
key("AVFormatIDKey"), nsInt(formatAAC),
key("AVSampleRateKey"), nsInt(sampleRate),
key("AVNumberOfChannelsKey"), nsInt(2),
key("AVEncoderBitRateKey"), nsInt(int64(sp.audioBitrate)),
)
s.snd = send(send(class("AVAssetWriterInput"), "assetWriterInputWithMediaType:outputSettings:", key("AVMediaTypeAudio"), settings), "retain")
msgSetBool(s.snd, sel("setExpectsMediaDataInRealTime:"), false)
if s.snd == 0 || byte(send(s.writer, "canAddInput:", s.snd)) == 0 {
return errors.New("render: AVFoundation cannot write the sound into this file")
}
send(s.writer, "addInput:", s.snd)
af := audioFormat{SampleRate: sampleRate, FormatID: formatLinearPCM, FormatFlags: formatIntPacked,
BytesPerPacket: 4, FramesPerPacket: 1, BytesPerFrame: 4, Channels: 2, BitsPerChannel: 16}
if st := cmAudioFormatCreate(0, &af, 0, 0, 0, 0, 0, &s.format); st != 0 {
return fmt.Errorf("render: no audio format: %d", st)
}
}
if !msgBool(s.writer, sel("startWriting")) {
return s.failure("cannot start writing")
}
msgStartSession(s.writer, sel("startSessionAtSourceTime:"), cmTime{Timescale: 1, Flags: cmTimeValid})
// The adaptor's pool, retained: the adaptor returns it autoreleased.
s.pool = uintptr(send(s.adaptor, "pixelBufferPool"))
if s.pool == 0 {
return s.failure("no pixel buffers")
}
cfRetain(s.pool)
return nil
}
func describe(nserr objc.ID) string {
if nserr == 0 {
return "unknown error"
}
msg := goString(send(nserr, "localizedDescription"))
if reason := goString(send(nserr, "localizedFailureReason")); reason != "" {
msg += ": " + reason
}
return msg
}
// failure returns the writer's error, after what.
func (s *avSink) failure(what string) error {
return fmt.Errorf("render: AVFoundation: %s: %s", what, describe(send(s.writer, "error")))
}
// buffer returns a pixel buffer from the pool, owned.
func (s *avSink) buffer() (uintptr, error) {
var pb uintptr
if st := cvPoolCreatePixelBuffer(0, s.pool, &pb); st != 0 || pb == 0 {
return 0, fmt.Errorf("render: no pixel buffer: %d", st)
}
if s.alpha {
cvSetAttachment(pb, avKeys["kCVImageBufferAlphaChannelModeKey"], avKeys["kCVImageBufferAlphaChannelMode_PremultipliedAlpha"], attachmentPropagate)
}
return pb, nil
}
func (s *avSink) frame(i int, pix []byte) error {
return pooled(func() error {
pb, err := s.buffer()
if err != nil {
return err
}
cvLock(pb, 0)
base, stride := cvBase(pb), int(cvStride(pb))
row := s.spec.w * 4
for y := range s.spec.h {
copy(unsafe.Slice((*byte)(unsafe.Add(base, y*stride)), row), pix[y*row:(y+1)*row])
}
cvUnlock(pb, 0)
return s.queueFrame(pb)
})
}
// queueFrame gives the writer the pixel buffer of the next frame, which
// it owns.
func (s *avSink) queueFrame(pb uintptr) error {
s.frames = append(s.frames, avFrame{pb, s.written})
s.written++
return s.pump(3)
}
// soundBuffer returns a sample buffer of the sound track's next frames,
// up to n, owned, or 0 at its end.
func (s *avSink) soundBuffer(n int) (uintptr, error) {
track := s.spec.sound
at := int(s.samples) * 2
if at >= len(track) {
return 0, nil
}
pcm := track[at:min(at+2*n, len(track))]
size := uint(len(pcm) * 2)
var block, sb uintptr
if st := cmBlockCreate(0, 0, size, 0, 0, 0, size, 1, &block); st != 0 {
return 0, fmt.Errorf("render: no audio buffer: %d", st)
}
defer cfRelease(block)
cmBlockReplace(unsafe.Pointer(&pcm[0]), block, 0, size)
frames := len(pcm) / 2
pts := cmTime{Value: s.samples, Timescale: sampleRate, Flags: cmTimeValid}
if st := cmAudioSampleCreate(0, block, s.format, frames, pts, 0, &sb); st != 0 {
return 0, fmt.Errorf("render: no audio sample buffer: %d", st)
}
s.samples += int64(frames)
return sb, nil
}
// pump gives the inputs what they take: the queued frames, until at
// most frames are left, and the sound, as far as a second ahead of the
// frames given, or to its end once all are (frames < 0). The writer
// interleaves the two: the video input takes nothing more until the
// sound caught up with it.
func (s *avSink) pump(frames int) error {
// lead is how far ahead of the video the sound goes, a second, and
// more while the video input waits for it.
lead := int64(sampleRate)
for wait := time.Duration(0); ; {
moved := false
if s.snd != 0 {
ahead := int64(math.MaxInt64)
if frames >= 0 {
ahead = (s.written-int64(len(s.frames)))*s.spec.den*sampleRate/s.spec.num + lead
}
for !s.soundDone && s.samples < ahead && msgBool(s.snd, sel("isReadyForMoreMediaData")) {
sb, err := s.soundBuffer(4800)
if err != nil {
return err
}
if sb == 0 {
// The whole track: the writer waits for more sound to
// interleave the video with until it is finished.
if !s.soundDone {
send(s.snd, "markAsFinished")
s.soundDone = true
}
break
}
ok := byte(send(s.snd, "appendSampleBuffer:", sb)) != 0
cfRelease(sb)
if !ok {
return s.failure("cannot write the sound")
}
moved = true
}
}
for len(s.frames) > 0 && msgBool(s.video, sel("isReadyForMoreMediaData")) {
f := s.frames[0]
ok := msgAppendPixels(s.adaptor, sel("appendPixelBuffer:withPresentationTime:"), f.pb,
cmTime{Value: f.n * s.spec.den, Timescale: int32(s.spec.num), Flags: cmTimeValid})
cvPixelBufferRelease(f.pb)
s.frames = s.frames[1:]
if !ok {
return s.failure("cannot write a frame")
}
moved = true
}
if msgInt(s.writer, sel("status")) == writerStatusFailed {
return s.failure("writing failed")
}
soundDone := s.snd == 0 || frames >= 0 || s.soundDone
if len(s.frames) <= max(frames, 0) && soundDone {
return nil
}
if moved {
wait = 0
continue
}
lead += sampleRate / 2
// The encoder works through what it took: a little while.
wait = min(max(wait*2, 100*time.Microsecond), 5*time.Millisecond)
time.Sleep(wait)
}
}
func (s *avSink) close() error {
return pooled(func() error {
// The frames, then the rest of the sound, which the writer takes
// only once the video is finished.
if err := s.pump(0); err != nil {
return err
}
send(s.video, "markAsFinished")
if s.snd != 0 {
if err := s.pump(-1); err != nil {
return err
}
}
done := make(chan struct{})
block := objc.NewBlock(func(objc.Block) { close(done) })
send(s.writer, "finishWritingWithCompletionHandler:", block)
<-done
block.Release()
ok := msgInt(s.writer, sel("status")) == writerStatusDone
var err error
if !ok {
err = s.failure("cannot finish the file")
}
s.release()
return err
})
}
func (s *avSink) abort() {
pooled(func() error {
if s.writer != 0 && msgInt(s.writer, sel("status")) == 1 {
send(s.writer, "cancelWriting")
}
s.release()
return nil
})
}
// release frees what the sink holds.
func (s *avSink) release() {
for _, f := range s.frames {
cvPixelBufferRelease(f.pb)
}
s.frames = nil
if s.format != 0 {
cfRelease(s.format)
s.format = 0
}
if s.pool != 0 {
cfRelease(s.pool)
s.pool = 0
}
for _, o := range []*objc.ID{&s.adaptor, &s.video, &s.snd, &s.writer} {
if *o != 0 {
send(*o, "release")
*o = 0
}
}
}
func (s *avSceneSink) scene(i int, sc *scene.Scene) error {
return pooled(func() error {
pb, err := s.buffer()
if err != nil {
return err
}
// Drawing it waits for the GPU to finish the frame before, whose
// buffer then holds it.
if err := s.d.f.DrawSurface(sc, cvPixelBufferGetIOSurface(pb)); err != nil {
cvPixelBufferRelease(pb)
return err
}
prev := s.pending.pb
s.pending.pb = pb
if prev != 0 {
return s.queueFrame(prev)
}
return nil
})
}
func (s *avSceneSink) flush() error {
if err := s.d.f.Wait(); err != nil {
return err
}
pb := s.pending.pb
s.pending.pb = 0
if pb == 0 {
return nil
}
return pooled(func() error { return s.queueFrame(pb) })
}
func (s *avSceneSink) abort() {
s.d.f.Wait()
if s.pending.pb != 0 {
cvPixelBufferRelease(s.pending.pb)
s.pending.pb = 0
}
s.avSink.abort()
}
+412
View File
@@ -0,0 +1,412 @@
//go:build linux && !android && (amd64 || arm64)
package render
import (
"errors"
"fmt"
"strconv"
"strings"
"sync"
"unsafe"
"github.com/ebitengine/purego"
)
// On Linux, a GStreamer pipeline writes the video: appsrc elements take
// the frames, as BGRA, and the sound track, videoconvert makes YUV of the
// frames, and the first encoder of the codec that encodes a test frame
// on this system encodes them: VA-API's (vah264enc, vaapih264enc) or
// NVENC's in hardware where there are, x264 or OpenH264 on the CPU
// otherwise.
var (
gstOnce sync.Once
gstErr error
gstInit func(argc, argv uintptr)
gstParseLaunch func(desc string, err *uintptr) uintptr
gstBinGetByName func(bin uintptr, name string) uintptr
gstElementSetState func(el uintptr, state int32) int32
gstElementGetBus func(el uintptr) uintptr
gstBusTimedPopFiltered func(bus uintptr, timeout uint64, types uint32) uintptr
gstMessageParseError func(msg uintptr, gerr, debug *uintptr)
gstMiniObjectUnref func(obj uintptr)
gstObjectUnref func(obj uintptr)
gstBufferNewAllocate func(alloc uintptr, size uint, params uintptr) uintptr
gstBufferFill func(buf uintptr, offset uint, src unsafe.Pointer, size uint) uint
gstElementFactoryFind func(name string) uintptr
gstAppSrcPushBuffer func(src, buf uintptr) int32
gstAppSrcEndOfStream func(src uintptr) int32
gErrorFree func(err uintptr)
gFree func(p uintptr)
)
const (
gstStateNull = 1
gstStatePlaying = 4
gstMessageEOS = 1 << 0
gstMessageError = 1 << 1
gstClockNone = ^uint64(0)
// The offsets of a GstBuffer's PTS and duration, after its
// GstMiniObject and pool (GST_BUFFER_PTS, GST_BUFFER_DURATION).
gstBufferPTSOffset = 72
gstBufferDurationOffset = 88
)
func loadGStreamer() error {
gstOnce.Do(func() {
var libs [4]uintptr
for i, name := range []string{"libgstreamer-1.0.so.0", "libgstapp-1.0.so.0", "libgobject-2.0.so.0", "libglib-2.0.so.0"} {
h, err := purego.Dlopen(name, purego.RTLD_NOW|purego.RTLD_GLOBAL)
if err != nil {
gstErr = fmt.Errorf("render: %w: no GStreamer (%v): install it, or encode with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported, err)
return
}
libs[i] = h
}
defer func() {
if v := recover(); v != nil {
gstErr = fmt.Errorf("render: %w: GStreamer: %v", errors.ErrUnsupported, v)
}
}()
gst, app, glib := libs[0], libs[1], libs[3]
purego.RegisterLibFunc(&gstInit, gst, "gst_init")
purego.RegisterLibFunc(&gstParseLaunch, gst, "gst_parse_launch")
purego.RegisterLibFunc(&gstBinGetByName, gst, "gst_bin_get_by_name")
purego.RegisterLibFunc(&gstElementSetState, gst, "gst_element_set_state")
purego.RegisterLibFunc(&gstElementGetBus, gst, "gst_element_get_bus")
purego.RegisterLibFunc(&gstBusTimedPopFiltered, gst, "gst_bus_timed_pop_filtered")
purego.RegisterLibFunc(&gstMessageParseError, gst, "gst_message_parse_error")
purego.RegisterLibFunc(&gstMiniObjectUnref, gst, "gst_mini_object_unref")
purego.RegisterLibFunc(&gstObjectUnref, gst, "gst_object_unref")
purego.RegisterLibFunc(&gstBufferNewAllocate, gst, "gst_buffer_new_allocate")
purego.RegisterLibFunc(&gstBufferFill, gst, "gst_buffer_fill")
purego.RegisterLibFunc(&gstElementFactoryFind, gst, "gst_element_factory_find")
purego.RegisterLibFunc(&gstAppSrcPushBuffer, app, "gst_app_src_push_buffer")
purego.RegisterLibFunc(&gstAppSrcEndOfStream, app, "gst_app_src_end_of_stream")
purego.RegisterLibFunc(&gErrorFree, glib, "g_error_free")
purego.RegisterLibFunc(&gFree, glib, "g_free")
gstInit(0, 0)
})
return gstErr
}
func cptr(a uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&a)) }
func cString(p uintptr) string {
if p == 0 {
return ""
}
n := 0
for *(*byte)(unsafe.Add(cptr(p), n)) != 0 {
n++
}
return string(unsafe.Slice((*byte)(cptr(p)), n))
}
// gerror returns the message of a GError, and frees it.
func gerror(gerr uintptr) string {
if gerr == 0 {
return ""
}
msg := cString(*(*uintptr)(unsafe.Add(cptr(gerr), 8)))
gErrorFree(gerr)
return msg
}
// gstEncoder is an encoder element: its description, with %k the bitrate
// in kb/s, %b in b/s and %g the frames between keyframes, the raw format
// it takes, and the parser after it.
type gstEncoder struct {
name, desc, format, parser string
}
var gstEncoders = map[Codec][]gstEncoder{
H264: {
{"vah264enc", "vah264enc bitrate=%k key-int-max=%g", "NV12", "h264parse"},
{"vaapih264enc", "vaapih264enc bitrate=%k keyframe-period=%g", "NV12", "h264parse"},
{"nvh264enc", "nvh264enc bitrate=%k gop-size=%g", "NV12", "h264parse"},
{"x264enc", "x264enc bitrate=%k key-int-max=%g speed-preset=medium", "I420", "h264parse"},
{"openh264enc", "openh264enc bitrate=%b gop-size=%g", "I420", "h264parse"},
},
HEVC: {
{"vah265enc", "vah265enc bitrate=%k key-int-max=%g", "NV12", "h265parse"},
{"vaapih265enc", "vaapih265enc bitrate=%k keyframe-period=%g", "NV12", "h265parse"},
{"nvh265enc", "nvh265enc bitrate=%k gop-size=%g", "NV12", "h265parse"},
{"x265enc", "x265enc bitrate=%k key-int-max=%g speed-preset=medium", "I420", "h265parse"},
},
VP9: {
{"vavp9enc", "vavp9enc bitrate=%k key-int-max=%g", "NV12", ""},
{"vp9enc", "vp9enc target-bitrate=%b keyframe-max-dist=%g end-usage=vbr deadline=1 cpu-used=4 row-mt=true", "I420", ""},
},
}
// The encoders of the sound, by container.
var gstAudioEncoders = map[container][]string{
mp4: {"fdkaacenc bitrate=%b", "avenc_aac bitrate=%b", "voaacenc bitrate=%b", "faac bitrate=%b"},
mov: {"fdkaacenc bitrate=%b", "avenc_aac bitrate=%b", "voaacenc bitrate=%b", "faac bitrate=%b"},
webm: {"opusenc bitrate=%b"},
}
// expand fills an element's description with the bitrate and the frames
// between keyframes.
func expand(desc string, bitrate, gop int) string {
return strings.NewReplacer("%k", strconv.Itoa(max(bitrate/1000, 1)), "%b", strconv.Itoa(bitrate), "%g", strconv.Itoa(gop)).Replace(desc)
}
func hasElement(name string) bool {
f := gstElementFactoryFind(name)
if f == 0 {
return false
}
gstObjectUnref(f)
return true
}
// runPipeline runs a pipeline that ends by itself to its end, and returns
// its error.
func runPipeline(desc string) error {
var gerr uintptr
p := gstParseLaunch(desc, &gerr)
if p == 0 || gerr != 0 {
msg := gerror(gerr)
if p != 0 {
gstObjectUnref(p)
}
return errors.New(msg)
}
defer gstObjectUnref(p)
defer gstElementSetState(p, gstStateNull)
bus := gstElementGetBus(p)
defer gstObjectUnref(bus)
if gstElementSetState(p, gstStatePlaying) == 0 {
return errors.New("cannot play")
}
return busError(bus, gstClockNone)
}
// busError waits up to timeout for the end of the stream or an error, and
// returns the error; nil at the end, or when neither came.
func busError(bus uintptr, timeout uint64) error {
msg := gstBusTimedPopFiltered(bus, timeout, gstMessageEOS|gstMessageError)
if msg == 0 {
return nil
}
defer gstMiniObjectUnref(msg)
if *(*uint32)(unsafe.Add(cptr(msg), 64)) != gstMessageError {
return nil
}
var gerr, debug uintptr
gstMessageParseError(msg, &gerr, &debug)
text := gerror(gerr)
if debug != 0 {
gFree(debug)
}
if text == "" {
text = "the pipeline failed"
}
return errors.New(text)
}
var (
probeMu sync.Mutex
probed = map[string]error{}
)
// probe reports whether an encoder encodes frames of w×h on this system:
// a hardware encoder's element is there without the hardware.
func probe(e gstEncoder, w, h int) error {
if !hasElement(e.name) {
return errors.New("no " + e.name)
}
key := fmt.Sprintf("%s %dx%d", e.name, w, h)
probeMu.Lock()
defer probeMu.Unlock()
if err, ok := probed[key]; ok {
return err
}
err := runPipeline(fmt.Sprintf("videotestsrc num-buffers=2 ! video/x-raw,format=%s,width=%d,height=%d,framerate=30/1 ! %s ! fakesink",
e.format, w, h, expand(e.desc, 2_000_000, 30)))
probed[key] = err
return err
}
// gstSink writes a video with a GStreamer pipeline.
type gstSink struct {
spec videoSpec
pipe, bus uintptr
video, audio uintptr
sound sync.WaitGroup
soundErr error
n int64
stop sync.Once
}
func newVideoSink(spec videoSpec, _ drawer) (sink, error) {
if err := loadGStreamer(); err != nil {
return nil, err
}
if spec.codec == ProRes || spec.codec == ProRes4444 {
return nil, fmt.Errorf("render: %w: GStreamer has no %v encoder: encode it with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported, spec.codec)
}
var enc *gstEncoder
var tried []string
for _, e := range gstEncoders[spec.codec] {
if err := probe(e, spec.w, spec.h); err != nil {
tried = append(tried, e.name+": "+err.Error())
continue
}
enc = &e
break
}
if enc == nil {
return nil, fmt.Errorf("render: %w: no GStreamer encoder of %v works here (%s): install gstreamer1.0-plugins-ugly (x264, x265) or a VA-API driver, or encode with Options{Encoder: render.FFmpeg}",
errors.ErrUnsupported, spec.codec, strings.Join(tried, "; "))
}
parser := ""
if enc.parser != "" {
if !hasElement(enc.parser) {
return nil, fmt.Errorf("render: %w: GStreamer has no %s: install gstreamer1.0-plugins-bad", errors.ErrUnsupported, enc.parser)
}
parser = " ! " + enc.parser
}
mux := map[container]string{mp4: "mp4mux faststart=true", mov: "qtmux", webm: "webmmux"}[spec.container]
if !hasElement(strings.Fields(mux)[0]) {
return nil, fmt.Errorf("render: %w: GStreamer has no %s: install gstreamer1.0-plugins-good", errors.ErrUnsupported, strings.Fields(mux)[0])
}
gop := int(2 * (spec.num + spec.den/2) / spec.den)
frame := spec.w * spec.h * 4
desc := fmt.Sprintf("appsrc name=video format=time block=true max-bytes=%d caps=\"video/x-raw,format=BGRA,width=%d,height=%d,framerate=%d/%d,pixel-aspect-ratio=1/1\""+
" ! videoconvert ! video/x-raw,format=%s,colorimetry=bt709 ! queue ! %s%s ! %s name=mux ! filesink location=%s",
3*frame, spec.w, spec.h, spec.num, spec.den, enc.format, expand(enc.desc, spec.bitrate, gop), parser, mux, quote(spec.path))
if spec.sound != nil {
var aenc string
for _, a := range gstAudioEncoders[spec.container] {
if hasElement(strings.Fields(a)[0]) {
aenc = expand(a, spec.audioBitrate, 0)
break
}
}
if aenc == "" {
return nil, fmt.Errorf("render: %w: GStreamer has no encoder of the sound: install gstreamer1.0-libav, or encode with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported)
}
desc += " appsrc name=audio format=time block=true max-bytes=192000 caps=\"audio/x-raw,format=S16LE,rate=48000,channels=2,layout=interleaved\"" +
" ! audioconvert ! " + aenc + " ! queue ! mux."
}
s := &gstSink{spec: spec}
var gerr uintptr
s.pipe = gstParseLaunch(desc, &gerr)
if s.pipe == 0 || gerr != 0 {
msg := gerror(gerr)
if s.pipe != 0 {
gstObjectUnref(s.pipe)
}
return nil, errors.New("render: GStreamer: " + msg)
}
s.bus = gstElementGetBus(s.pipe)
s.video = gstBinGetByName(s.pipe, "video")
if spec.sound != nil {
s.audio = gstBinGetByName(s.pipe, "audio")
}
if gstElementSetState(s.pipe, gstStatePlaying) == 0 {
err := busError(s.bus, 0)
s.abort()
if err == nil {
err = errors.New("cannot start the pipeline")
}
return nil, fmt.Errorf("render: GStreamer: %w", err)
}
if s.audio != 0 {
s.sound.Add(1)
go s.pushSound()
}
return s, nil
}
// quote quotes a value of gst_parse_launch's.
func quote(s string) string {
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(s) + `"`
}
// push gives an appsrc a buffer of data at pts for duration, in ns.
func push(src uintptr, data unsafe.Pointer, size int, pts, duration int64) int32 {
buf := gstBufferNewAllocate(0, uint(size), 0)
gstBufferFill(buf, 0, data, uint(size))
*(*int64)(unsafe.Add(cptr(buf), gstBufferPTSOffset)) = pts
*(*int64)(unsafe.Add(cptr(buf), gstBufferDurationOffset)) = duration
return gstAppSrcPushBuffer(src, buf) // takes the buffer
}
// pushSound gives the pipeline the sound track, on a goroutine of its own:
// the muxer interleaves it with the frames, and blocks either while it
// waits for the other.
func (s *gstSink) pushSound() {
defer s.sound.Done()
track := s.spec.sound
const chunk = 4800 // frames
for at := 0; at < len(track); at += 2 * chunk {
pcm := track[at:min(at+2*chunk, len(track))]
n := int64(len(pcm) / 2)
pts := int64(at/2) * 1_000_000_000 / sampleRate
if r := push(s.audio, unsafe.Pointer(&pcm[0]), len(pcm)*2, pts, n*1_000_000_000/sampleRate); r != 0 {
if r != -2 { // GST_FLOW_FLUSHING: stopped
s.soundErr = fmt.Errorf("render: GStreamer took no sound (%d)", r)
}
return
}
}
gstAppSrcEndOfStream(s.audio)
}
func (s *gstSink) frame(_ int, pix []byte) error {
pts := s.n * s.spec.den * 1_000_000_000 / s.spec.num
next := (s.n + 1) * s.spec.den * 1_000_000_000 / s.spec.num
s.n++
if r := push(s.video, unsafe.Pointer(&pix[0]), len(pix), pts, next-pts); r != 0 {
if err := busError(s.bus, 0); err != nil {
return fmt.Errorf("render: GStreamer: %w", err)
}
return fmt.Errorf("render: GStreamer took no frame (%d)", r)
}
if err := busError(s.bus, 0); err != nil {
return fmt.Errorf("render: GStreamer: %w", err)
}
return nil
}
func (s *gstSink) close() error {
gstAppSrcEndOfStream(s.video)
err := busError(s.bus, gstClockNone)
if err != nil {
// The muxer takes no more: stopping the pipeline flushes the
// sound's appsrc, whose push may be blocked.
s.free()
}
s.sound.Wait()
if err == nil {
err = s.soundErr
}
s.free()
if err != nil {
return fmt.Errorf("render: GStreamer: %w", err)
}
return nil
}
func (s *gstSink) abort() { s.free() }
func (s *gstSink) free() {
s.stop.Do(func() {
if s.pipe != 0 {
// Stopping flushes the appsrcs: a push blocked returns.
gstElementSetState(s.pipe, gstStateNull)
}
s.sound.Wait()
for _, o := range []uintptr{s.video, s.audio, s.bus, s.pipe} {
if o != 0 {
gstObjectUnref(o)
}
}
})
}
+14
View File
@@ -0,0 +1,14 @@
//go:build !(darwin && !ios) && !windows && !(linux && !android && (amd64 || arm64))
package render
import (
"errors"
"fmt"
)
// newVideoSink returns none: the system has no media framework MyGo
// encodes video with.
func newVideoSink(spec videoSpec, d drawer) (sink, error) {
return nil, fmt.Errorf("render: %w: no video encoder on this system: encode with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported)
}
+405
View File
@@ -0,0 +1,405 @@
//go:build windows
package render
import (
"errors"
"fmt"
"sync"
"syscall"
"unsafe"
"github.com/egoist/mygo/internal/gpu/d3d11/device"
)
// On Windows, a Media Foundation sink writer writes the video, into an
// MP4: it takes the frames in RGB32 (BGRA), converts them with the video
// processor and encodes them with the system's H.264 or HEVC encoder, the
// GPU's where it has one (MF_READWRITE_ENABLE_HARDWARE_TRANSFORMS), and
// the sound track in PCM, which its AAC encoder encodes.
var (
mfOnce sync.Once
mfErr error
mfplat = syscall.NewLazyDLL(device.SystemDir() + `\mfplat.dll`)
mfreadwrite = syscall.NewLazyDLL(device.SystemDir() + `\mfreadwrite.dll`)
ole32 = syscall.NewLazyDLL(device.SystemDir() + `\ole32.dll`)
procMFStartup = mfplat.NewProc("MFStartup")
procMFCreateAttributes = mfplat.NewProc("MFCreateAttributes")
procMFCreateMediaType = mfplat.NewProc("MFCreateMediaType")
procMFCreateSample = mfplat.NewProc("MFCreateSample")
procMFCreateMemoryBuffer = mfplat.NewProc("MFCreateMemoryBuffer")
procMFCreateSinkWriterFromURL = mfreadwrite.NewProc("MFCreateSinkWriterFromURL")
procCoInitializeEx = ole32.NewProc("CoInitializeEx")
)
type guid struct {
Data1 uint32
Data2 uint16
Data3 uint16
Data4 [8]byte
}
// mfGUID returns the GUID of a Media Foundation format, from its FOURCC
// or D3DFORMAT: {xxxxxxxx-0000-0010-8000-00AA00389B71}.
func mfGUID(fourcc uint32) guid {
return guid{fourcc, 0, 0x10, [8]byte{0x80, 0, 0, 0xaa, 0, 0x38, 0x9b, 0x71}}
}
var (
mfMTMajorType = guid{0x48eba18e, 0xf8c9, 0x4687, [8]byte{0xbf, 0x11, 0x0a, 0x74, 0xc9, 0xf9, 0x6a, 0x8f}}
mfMTSubtype = guid{0xf7e34c9a, 0x42e8, 0x4714, [8]byte{0xb7, 0x4b, 0xcb, 0x29, 0xd7, 0x2c, 0x35, 0xe5}}
mfMTAvgBitrate = guid{0x20332624, 0xfb0d, 0x4d9e, [8]byte{0xbd, 0x0d, 0xcb, 0xf6, 0x78, 0x6c, 0x10, 0x2e}}
mfMTInterlaceMode = guid{0xe2724bb8, 0xe676, 0x4806, [8]byte{0xb4, 0xb2, 0xa8, 0xd6, 0xef, 0xb4, 0x4c, 0xcd}}
mfMTFrameSize = guid{0x1652c33d, 0xd6b2, 0x4012, [8]byte{0xb8, 0x34, 0x72, 0x03, 0x08, 0x49, 0xa3, 0x7d}}
mfMTFrameRate = guid{0xc459a2e8, 0x3d2c, 0x4e44, [8]byte{0xb1, 0x32, 0xfe, 0xe5, 0x15, 0x6c, 0x7b, 0xb0}}
mfMTPixelAspectRatio = guid{0xc6376a1e, 0x8d0a, 0x4027, [8]byte{0xbe, 0x45, 0x6d, 0x9a, 0x0a, 0xd3, 0x9b, 0xb6}}
mfMTDefaultStride = guid{0x644b4e48, 0x1e02, 0x4516, [8]byte{0xb0, 0xeb, 0xc0, 0x1c, 0xa9, 0xd4, 0x9a, 0xc6}}
mfMTMPEG2Profile = guid{0xad76a80b, 0x2d5c, 0x4e0b, [8]byte{0xb3, 0x75, 0x64, 0xe5, 0x20, 0x13, 0x70, 0x36}}
mfMTVideoPrimaries = guid{0xdbfbe4d7, 0x0740, 0x4ee0, [8]byte{0x81, 0x92, 0x85, 0x0a, 0xb0, 0xe2, 0x19, 0x35}}
mfMTTransferFunction = guid{0x5fb0fce9, 0xbe5c, 0x4935, [8]byte{0xa8, 0x11, 0xec, 0x83, 0x8f, 0x8e, 0xed, 0x93}}
mfMTYUVMatrix = guid{0x3e23d450, 0x2c75, 0x4d25, [8]byte{0xa0, 0x0e, 0xb9, 0x16, 0x70, 0xd1, 0x23, 0x27}}
mfMTNominalRange = guid{0xc21b8ee5, 0xb956, 0x4071, [8]byte{0x8d, 0xaf, 0x32, 0x5e, 0xdf, 0x5c, 0xab, 0x11}}
mfMTAudioBitsPerSample = guid{0xf2deb57f, 0x40fa, 0x4764, [8]byte{0xaa, 0x33, 0xed, 0x4f, 0x2d, 0x1f, 0xf6, 0x69}}
mfMTAudioSampleRate = guid{0x5faeeae7, 0x0290, 0x4c31, [8]byte{0x9e, 0x8a, 0xc5, 0x34, 0xf6, 0x8d, 0x9d, 0xba}}
mfMTAudioChannels = guid{0x37e48bf5, 0x645e, 0x4c5b, [8]byte{0x89, 0xde, 0xad, 0xa9, 0xe2, 0x9b, 0x69, 0x6a}}
mfMTAudioBytesPerSec = guid{0x1aab75c8, 0xcfef, 0x451c, [8]byte{0xab, 0x95, 0xac, 0x03, 0x4b, 0x8e, 0x17, 0x31}}
mfMTAudioBlockAlign = guid{0x322de230, 0x9eeb, 0x43bd, [8]byte{0xab, 0x7a, 0xff, 0x41, 0x22, 0x51, 0x54, 0x1d}}
mfReadwriteHardware = guid{0xa634a91c, 0x822b, 0x41b9, [8]byte{0xa4, 0x94, 0x4d, 0xe4, 0x64, 0x36, 0x12, 0xb0}}
mfTranscodeContainer = guid{0x150ff23f, 0x4abc, 0x478b, [8]byte{0xac, 0x4f, 0xe1, 0x91, 0x6f, 0xba, 0x1c, 0xca}}
mfContainerMPEG4 = guid{0xdc6cd05d, 0xb9d0, 0x40ef, [8]byte{0xbd, 0x35, 0xfa, 0x62, 0x2c, 0x1a, 0xb2, 0x8a}}
mfMediaTypeVideo = mfGUID(0x73646976) // 'vids'
mfMediaTypeAudio = mfGUID(0x73647561) // 'auds'
mfVideoFormatH264 = mfGUID(0x34363248) // 'H264'
mfVideoFormatHEVC = mfGUID(0x43564548) // 'HEVC'
mfVideoFormatNV12 = mfGUID(0x3231564e) // 'NV12'
mfAudioFormatAAC = mfGUID(0x1610) // WAVE_FORMAT_MPEG_HEAAC
mfAudioFormatPCM = mfGUID(1)
)
// The methods of the interfaces, by their places in the vtables.
const (
comRelease = 2
attrSetUINT32 = 21
attrSetUINT64 = 22
attrSetGUID = 24
writerAddStream = 3
writerSetInputMediaType = 4
writerBeginWriting = 5
writerWriteSample = 6
writerFinalize = 11
sampleSetTime = 36
sampleSetDuration = 38
sampleAddBuffer = 42
bufferLock = 3
bufferUnlock = 4
bufferSetCurrentLength = 6
)
// mfCodecNotFound is MF_E_TOPO_CODEC_NOT_FOUND: no encoder of the format.
const mfCodecNotFound = 0xc00d5212
func failed(hr uintptr) bool { return int32(uint32(hr)) < 0 }
func cptr(a uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&a)) }
// call calls method i of COM object obj. Pointers converted to uintptr in
// the call stay valid until it returns (go:uintptrescapes).
//
//go:uintptrescapes
func call(obj uintptr, i int, args ...uintptr) uintptr {
vtbl := *(*uintptr)(cptr(obj))
fn := *(*uintptr)(cptr(vtbl + uintptr(i)*unsafe.Sizeof(uintptr(0))))
r, _, _ := syscall.SyscallN(fn, append([]uintptr{obj}, args...)...)
return r
}
func free(p *uintptr) {
if *p != 0 {
call(*p, comRelease)
*p = 0
}
}
func loadMF() error {
mfOnce.Do(func() {
for _, p := range []*syscall.LazyProc{procMFStartup, procMFCreateAttributes, procMFCreateMediaType, procMFCreateSample,
procMFCreateMemoryBuffer, procMFCreateSinkWriterFromURL, procCoInitializeEx} {
if err := p.Find(); err != nil {
// Windows Server without its Media Foundation feature, or
// an N edition without the Media Feature Pack.
mfErr = fmt.Errorf("render: %w: no Media Foundation (%v): encode with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported, err)
return
}
}
const mfVersion, mfStartupFull = 0x00020070, 0
if hr, _, _ := procMFStartup.Call(mfVersion, mfStartupFull); failed(hr) {
mfErr = fmt.Errorf("render: %w: MFStartup: %#x", errors.ErrUnsupported, uint32(hr))
}
})
return mfErr
}
// attrs sets attributes of an IMFAttributes: GUID values, uint32s and
// uint64s, by their keys.
type attr struct {
key *guid
guid *guid
value uint64
wide bool
}
func setAttrs(obj uintptr, as ...attr) error {
for _, a := range as {
var hr uintptr
switch {
case a.guid != nil:
hr = call(obj, attrSetGUID, uintptr(unsafe.Pointer(a.key)), uintptr(unsafe.Pointer(a.guid)))
case a.wide:
hr = call(obj, attrSetUINT64, uintptr(unsafe.Pointer(a.key)), uintptr(a.value))
default:
hr = call(obj, attrSetUINT32, uintptr(unsafe.Pointer(a.key)), uintptr(uint32(a.value)))
}
if failed(hr) {
return fmt.Errorf("render: Media Foundation: an attribute: %#x", uint32(hr))
}
}
return nil
}
func mediaType(as ...attr) (uintptr, error) {
var t uintptr
if hr, _, _ := procMFCreateMediaType.Call(uintptr(unsafe.Pointer(&t))); failed(hr) {
return 0, fmt.Errorf("render: Media Foundation: no media type: %#x", uint32(hr))
}
if err := setAttrs(t, as...); err != nil {
free(&t)
return 0, err
}
return t, nil
}
// mfSink writes a video with a Media Foundation sink writer.
type mfSink struct {
spec videoSpec
writer uintptr
video, audio uint32
n, samples int64
hasSound bool
finalized bool
}
func newVideoSink(spec videoSpec, _ drawer) (sink, error) {
if spec.container != mp4 {
return nil, fmt.Errorf("render: %w: Media Foundation writes MP4 alone: encode a .mov or .webm with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported)
}
if spec.codec != H264 && spec.codec != HEVC {
return nil, fmt.Errorf("render: %w: Media Foundation has no %v encoder: encode it with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported, spec.codec)
}
if err := loadMF(); err != nil {
return nil, err
}
const coinitMultithreaded = 0
procCoInitializeEx.Call(0, coinitMultithreaded)
s := &mfSink{spec: spec, hasSound: spec.sound != nil}
if err := s.open(); err != nil {
s.abort()
return nil, err
}
return s, nil
}
func (s *mfSink) open() error {
sp := s.spec
var attrs uintptr
if hr, _, _ := procMFCreateAttributes.Call(uintptr(unsafe.Pointer(&attrs)), 2); failed(hr) {
return fmt.Errorf("render: Media Foundation: no attributes: %#x", uint32(hr))
}
defer free(&attrs)
if err := setAttrs(attrs, attr{key: &mfReadwriteHardware, value: 1}, attr{key: &mfTranscodeContainer, guid: &mfContainerMPEG4}); err != nil {
return err
}
path, err := syscall.UTF16PtrFromString(sp.path)
if err != nil {
return err
}
if hr, _, _ := procMFCreateSinkWriterFromURL.Call(uintptr(unsafe.Pointer(path)), 0, attrs, uintptr(unsafe.Pointer(&s.writer))); failed(hr) {
return fmt.Errorf("render: Media Foundation cannot write %s: %#x", sp.path, uint32(hr))
}
const progressive, bt709Primaries, bt709Transfer, bt709Matrix, range16to235, h264High, hevcMain = 2, 2, 5, 1, 2, 100, 1
format, profile := &mfVideoFormatH264, uint64(h264High)
if sp.codec == HEVC {
format, profile = &mfVideoFormatHEVC, hevcMain
}
size := uint64(sp.w)<<32 | uint64(sp.h)
rate := uint64(sp.num)<<32 | uint64(sp.den)
common := []attr{
{key: &mfMTMajorType, guid: &mfMediaTypeVideo},
{key: &mfMTInterlaceMode, value: progressive},
{key: &mfMTFrameSize, value: size, wide: true},
{key: &mfMTFrameRate, value: rate, wide: true},
{key: &mfMTPixelAspectRatio, value: 1<<32 | 1, wide: true},
}
out, err := mediaType(append(common,
attr{key: &mfMTSubtype, guid: format},
attr{key: &mfMTAvgBitrate, value: uint64(sp.bitrate)},
attr{key: &mfMTMPEG2Profile, value: profile},
attr{key: &mfMTVideoPrimaries, value: bt709Primaries},
attr{key: &mfMTTransferFunction, value: bt709Transfer},
attr{key: &mfMTYUVMatrix, value: bt709Matrix},
attr{key: &mfMTNominalRange, value: range16to235})...)
if err != nil {
return err
}
defer free(&out)
if hr := call(s.writer, writerAddStream, out, uintptr(unsafe.Pointer(&s.video))); failed(hr) {
if uint32(hr) == mfCodecNotFound {
return fmt.Errorf("render: %w: Windows has no %v encoder: encode it with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported, sp.codec)
}
return fmt.Errorf("render: Media Foundation has no %v encoder of %d×%d: %#x", sp.codec, sp.w, sp.h, uint32(hr))
}
// The frames come in NV12 of BT.709, converted in Go (bgraToNV12), as
// the encoder takes them: the sink writer's own conversion of RGB32
// takes BT.601's matrix.
in, err := mediaType(append(common,
attr{key: &mfMTSubtype, guid: &mfVideoFormatNV12},
attr{key: &mfMTDefaultStride, value: uint64(sp.w)},
attr{key: &mfMTVideoPrimaries, value: bt709Primaries},
attr{key: &mfMTTransferFunction, value: bt709Transfer},
attr{key: &mfMTYUVMatrix, value: bt709Matrix},
attr{key: &mfMTNominalRange, value: range16to235})...)
if err != nil {
return err
}
defer free(&in)
if hr := call(s.writer, writerSetInputMediaType, uintptr(s.video), in, 0); failed(hr) {
if uint32(hr) == mfCodecNotFound {
return fmt.Errorf("render: %w: Windows has no %v encoder (for HEVC, the HEVC Video Extensions): encode it with Options{Encoder: render.FFmpeg}", errors.ErrUnsupported, sp.codec)
}
return fmt.Errorf("render: Media Foundation's %v encoder takes no frames of %d×%d: %#x", sp.codec, sp.w, sp.h, uint32(hr))
}
if s.hasSound {
// The AAC encoder takes 96, 128, 160 or 192 kb/s.
bytes := uint64(24000)
for _, b := range []uint64{12000, 16000, 20000} {
if uint64(sp.audioBitrate)/8 <= b {
bytes = b
break
}
}
out, err := mediaType(
attr{key: &mfMTMajorType, guid: &mfMediaTypeAudio}, attr{key: &mfMTSubtype, guid: &mfAudioFormatAAC},
attr{key: &mfMTAudioBitsPerSample, value: 16}, attr{key: &mfMTAudioSampleRate, value: sampleRate},
attr{key: &mfMTAudioChannels, value: 2}, attr{key: &mfMTAudioBytesPerSec, value: bytes})
if err != nil {
return err
}
defer free(&out)
if hr := call(s.writer, writerAddStream, out, uintptr(unsafe.Pointer(&s.audio))); failed(hr) {
return fmt.Errorf("render: Media Foundation has no AAC encoder: %#x", uint32(hr))
}
in, err := mediaType(
attr{key: &mfMTMajorType, guid: &mfMediaTypeAudio}, attr{key: &mfMTSubtype, guid: &mfAudioFormatPCM},
attr{key: &mfMTAudioBitsPerSample, value: 16}, attr{key: &mfMTAudioSampleRate, value: sampleRate},
attr{key: &mfMTAudioChannels, value: 2}, attr{key: &mfMTAudioBlockAlign, value: 4},
attr{key: &mfMTAudioBytesPerSec, value: 4 * sampleRate})
if err != nil {
return err
}
defer free(&in)
if hr := call(s.writer, writerSetInputMediaType, uintptr(s.audio), in, 0); failed(hr) {
return fmt.Errorf("render: Media Foundation cannot encode the sound: %#x", uint32(hr))
}
}
if hr := call(s.writer, writerBeginWriting); failed(hr) {
return fmt.Errorf("render: Media Foundation cannot start writing: %#x", uint32(hr))
}
return nil
}
// write gives stream a sample of size bytes, which fill writes, at time t
// for duration d, in 100 ns.
func (s *mfSink) write(stream uint32, size int, fill func([]byte), t, d int64) error {
var buf, sample uintptr
if hr, _, _ := procMFCreateMemoryBuffer.Call(uintptr(size), uintptr(unsafe.Pointer(&buf))); failed(hr) {
return fmt.Errorf("render: Media Foundation: no buffer: %#x", uint32(hr))
}
defer free(&buf)
var p uintptr
if hr := call(buf, bufferLock, uintptr(unsafe.Pointer(&p)), 0, 0); failed(hr) {
return fmt.Errorf("render: Media Foundation: cannot lock a buffer: %#x", uint32(hr))
}
fill(unsafe.Slice((*byte)(cptr(p)), size))
call(buf, bufferUnlock)
call(buf, bufferSetCurrentLength, uintptr(size))
if hr, _, _ := procMFCreateSample.Call(uintptr(unsafe.Pointer(&sample))); failed(hr) {
return fmt.Errorf("render: Media Foundation: no sample: %#x", uint32(hr))
}
defer free(&sample)
call(sample, sampleAddBuffer, buf)
call(sample, sampleSetTime, uintptr(t))
call(sample, sampleSetDuration, uintptr(d))
if hr := call(s.writer, writerWriteSample, uintptr(stream), sample); failed(hr) {
return fmt.Errorf("render: Media Foundation cannot write a sample: %#x", uint32(hr))
}
return nil
}
// soundTo writes the sound track up to frame `to` of it, in 0.1 s
// samples: the writer interleaves it with the video.
func (s *mfSink) soundTo(to int64) error {
track := s.spec.sound
to = min(to, int64(len(track)/2))
for s.samples < to {
n := min(to-s.samples, sampleRate/10)
pcm := track[2*s.samples : 2*(s.samples+n)]
t := s.samples * 10_000_000 / sampleRate
fill := func(b []byte) {
for i, v := range pcm {
b[2*i], b[2*i+1] = byte(v), byte(uint16(v)>>8)
}
}
if err := s.write(s.audio, len(pcm)*2, fill, t, n*10_000_000/sampleRate); err != nil {
return err
}
s.samples += n
}
return nil
}
func (s *mfSink) frame(_ int, pix []byte) error {
sp := s.spec
t := s.n * sp.den * 10_000_000 / sp.num
next := (s.n + 1) * sp.den * 10_000_000 / sp.num
s.n++
if s.hasSound {
// The sound up to half a second ahead of the frame.
if err := s.soundTo(next*sampleRate/10_000_000 + sampleRate/2); err != nil {
return err
}
}
return s.write(s.video, sp.w*sp.h*3/2, func(b []byte) { bgraToNV12(b, pix, sp.w, sp.h) }, t, next-t)
}
func (s *mfSink) close() error {
if s.hasSound {
if err := s.soundTo(int64(len(s.spec.sound) / 2)); err != nil {
return err
}
}
hr := call(s.writer, writerFinalize)
free(&s.writer)
if failed(hr) {
return fmt.Errorf("render: Media Foundation cannot finish the file: %#x", uint32(hr))
}
return nil
}
func (s *mfSink) abort() { free(&s.writer) }
+169
View File
@@ -0,0 +1,169 @@
package render
import (
"context"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
// Codec is how Video compresses the frames.
type Codec uint8
const (
// DefaultCodec is H264, or VP9 for WebM.
DefaultCodec Codec = iota
// H264 is H.264 (AVC), which every player plays: in MP4 or QuickTime.
H264
// HEVC is H.265, about as good at two thirds of the bitrate, which
// newer systems play: in MP4 or QuickTime. Windows encodes it with the
// HEVC Video Extensions.
HEVC
// ProRes is Apple ProRes 422 HQ, for editing: in QuickTime, on macOS,
// or with ffmpeg.
ProRes
// ProRes4444 is Apple ProRes 4444, with the alpha of a Transparent
// composition: in QuickTime, on macOS, or with ffmpeg.
ProRes4444
// VP9 is VP9 in WebM, with the alpha of a Transparent composition
// with ffmpeg: on Linux with GStreamer's vpx plugin, or with ffmpeg.
VP9
)
func (c Codec) String() string {
switch c {
case H264:
return "H.264"
case HEVC:
return "HEVC"
case ProRes:
return "ProRes 422 HQ"
case ProRes4444:
return "ProRes 4444"
case VP9:
return "VP9"
}
return "Codec(" + strconv.Itoa(int(c)) + ")"
}
// alpha reports whether the codec keeps alpha.
func (c Codec) alpha() bool { return c == ProRes4444 || c == VP9 }
// Encoder chooses what encodes a Video.
type Encoder uint8
const (
// System encodes with the system's media framework, in hardware
// where it can: AVFoundation (VideoToolbox) on macOS, Media
// Foundation on Windows, GStreamer on Linux.
System Encoder = iota
// FFmpeg pipes the frames to ffmpeg (Options.FFmpeg), for what the
// system has no encoder of, as WebM on macOS and Windows, or a Linux
// without GStreamer's encoders.
FFmpeg
)
// container is the format of a video file.
type container uint8
const (
mp4 container = iota
mov
webm
)
// videoSpec is what a video sink writes.
type videoSpec struct {
path string
container container
codec Codec
// w and h are the size of the frames, num/den their rate.
w, h int
num, den int64
// bitrate and audioBitrate are bits a second; alpha keeps the frames'
// alpha, premultiplied.
bitrate, audioBitrate int
alpha bool
// sound is the sound track, interleaved stereo at 48 kHz, nil for
// none.
sound []int16
ffmpeg string
}
// Video renders the composition into a video file at path: an MP4 (.mp4,
// .m4v), a QuickTime movie (.mov), or a WebM (.webm), with the sound its
// frames play (Frame.Audio) in AAC, or Opus in WebM. The file appears
// when the video is whole: until then the frames go into a file beside
// it, which an error or ctx's end removes.
func Video(ctx context.Context, comp Composition, path string, o Options) error {
if err := comp.validate(); err != nil {
return err
}
spec := videoSpec{w: comp.Width, h: comp.Height, codec: o.Codec, bitrate: o.Bitrate, audioBitrate: o.AudioBitrate, ffmpeg: o.FFmpeg}
spec.num, spec.den = comp.rate()
switch ext := strings.ToLower(filepath.Ext(path)); ext {
case ".mp4", ".m4v":
spec.container = mp4
case ".mov":
spec.container = mov
case ".webm":
spec.container = webm
default:
return fmt.Errorf("render: no video format for %q: name an .mp4, .mov or .webm", ext)
}
if spec.codec == DefaultCodec {
spec.codec = H264
if spec.container == webm {
spec.codec = VP9
}
}
switch {
case spec.container == webm && spec.codec != VP9,
spec.container != webm && spec.codec == VP9:
return fmt.Errorf("render: %v goes into WebM alone", VP9)
case spec.container == mp4 && (spec.codec == ProRes || spec.codec == ProRes4444):
return fmt.Errorf("render: %v goes into QuickTime (.mov)", spec.codec)
case spec.codec > VP9:
return fmt.Errorf("render: unknown codec %v", spec.codec)
}
if spec.codec != ProRes && spec.codec != ProRes4444 && (spec.w%2 != 0 || spec.h%2 != 0) {
// YUV 4:2:0 halves the chroma's size.
return fmt.Errorf("render: %v takes an even Width and Height, not %d×%d", spec.codec, spec.w, spec.h)
}
spec.alpha = comp.Transparent && spec.codec.alpha()
if spec.bitrate <= 0 {
bpp := 0.2 // bits a pixel a frame: H.264 of motion graphics
if spec.codec == HEVC || spec.codec == VP9 {
bpp = 0.12
}
spec.bitrate = max(int(float64(spec.w*spec.h)*float64(spec.num)/float64(spec.den)*bpp), 500_000)
}
if spec.audioBitrate <= 0 {
spec.audioBitrate = 192_000
}
from, to, err := comp.span(o)
if err != nil {
return err
}
if spec.sound, err = soundtrack(ctx, comp, from, to); err != nil {
return err
}
dir, base := filepath.Split(path)
ext := filepath.Ext(base)
tmp := filepath.Join(dir, "."+strings.TrimSuffix(base, ext)+".render-"+strconv.Itoa(os.Getpid())+ext)
os.Remove(tmp)
spec.path = tmp
err = run(ctx, comp, o, func(s *session, d drawer) (sink, error) {
if o.Encoder == FFmpeg {
return newFFmpegSink(ctx, spec)
}
return newVideoSink(spec, d)
})
if err != nil {
os.Remove(tmp)
return err
}
return os.Rename(tmp, path)
}