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:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+698
@@ -0,0 +1,698 @@
|
||||
//go:build darwin
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
"github.com/ebitengine/purego/objc"
|
||||
|
||||
"github.com/egoist/mygo/internal/media"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// On macOS, AVFoundation plays the video: an AVPlayer, which decodes in
|
||||
// hardware (VideoToolbox), plays the sound and keeps the clock, and an
|
||||
// AVPlayerItemVideoOutput, from which each frame the window builds takes
|
||||
// the picture due as it shows, a CVPixelBuffer in NV12 backed by an
|
||||
// IOSurface, which the Metal renderer wraps as textures without a copy.
|
||||
// A goroutine of the engine's watches how loading and playing go, and
|
||||
// wakes the window as that changes. Bytes in memory reach the player
|
||||
// through an AVAssetResourceLoader, whose delegate answers on a queue of
|
||||
// its own from the bytes, without a file.
|
||||
|
||||
var (
|
||||
avfOnce sync.Once
|
||||
avfErr error
|
||||
|
||||
msgSend, msgSendStret uintptr
|
||||
|
||||
msgItemTimeForHostTime func(obj objc.ID, s objc.SEL, host float64) cmTime
|
||||
msgCMTime func(obj objc.ID, s objc.SEL) cmTime
|
||||
msgHasNewBuffer func(obj objc.ID, s objc.SEL, t cmTime) bool
|
||||
msgCopyBuffer func(obj objc.ID, s objc.SEL, t cmTime, display uintptr) uintptr
|
||||
msgSeek func(obj objc.ID, s objc.SEL, t, before, after cmTime)
|
||||
msgSetFloat32 func(obj objc.ID, s objc.SEL, v float32)
|
||||
msgFloat32 func(obj objc.ID, s objc.SEL) float32
|
||||
msgSetBool func(obj objc.ID, s objc.SEL, v bool)
|
||||
msgInt func(obj objc.ID, s objc.SEL) int
|
||||
msgBool func(obj objc.ID, s objc.SEL) bool
|
||||
|
||||
caCurrentMediaTime func() float64
|
||||
cvBufferRelease func(buf uintptr)
|
||||
cvBufferRetain func(buf uintptr) uintptr
|
||||
cvBufferGetAttachment func(buf, key, mode uintptr) uintptr
|
||||
cvPixelBufferGetWidth func(buf uintptr) uint
|
||||
cvPixelBufferGetHeight func(buf uintptr) uint
|
||||
cvPixelBufferGetPixelFormat func(buf uintptr) uint32
|
||||
cvPixelBufferLock func(buf uintptr, flags uint64) int32
|
||||
cvPixelBufferUnlock func(buf uintptr, flags uint64) int32
|
||||
cvPixelBufferPlaneBase func(buf uintptr, plane uint) unsafe.Pointer
|
||||
cvPixelBufferPlaneStride func(buf uintptr, plane uint) uint
|
||||
cfEqual func(a, b uintptr) bool
|
||||
dispatchQueueCreate func(label string, attr uintptr) uintptr
|
||||
poolPush func() uintptr
|
||||
poolPop func(pool uintptr)
|
||||
|
||||
// The constants of CoreVideo and AVFoundation the engine compares
|
||||
// and passes.
|
||||
cvMatrixKey, cvMatrix709, cvMatrix601, cvMatrix2020 uintptr
|
||||
cvPixelFormatKey, cvMetalCompatibilityKey uintptr
|
||||
avMediaTypeVideo uintptr
|
||||
|
||||
// loaderClass is the class of the delegates answering for bytes in
|
||||
// memory; loaders their sources, by the number in their URL.
|
||||
loaderClass objc.Class
|
||||
loaderQueue uintptr
|
||||
loaders sync.Map // uint64 → []byte
|
||||
lastLoader atomic.Uint64
|
||||
)
|
||||
|
||||
// cmTime is a CMTime.
|
||||
type cmTime struct {
|
||||
Value int64
|
||||
Timescale int32
|
||||
Flags uint32
|
||||
Epoch int64
|
||||
}
|
||||
|
||||
const (
|
||||
cmTimeValid = 1
|
||||
cmTimeIndefinite = 16
|
||||
cmTimeInfinite = 4 | 8
|
||||
|
||||
pixelFormat420v = 0x34323076 // kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange
|
||||
pixelFormat420f = 0x34323066 // kCVPixelFormatType_420YpCbCr8BiPlanarFullRange
|
||||
|
||||
avStatusReadyToPlay = 1
|
||||
avStatusFailed = 2
|
||||
avWaitingToPlay = 1 // AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate
|
||||
avActionAtEndNone = 2
|
||||
)
|
||||
|
||||
func (t cmTime) duration() (time.Duration, bool) {
|
||||
if t.Flags&cmTimeValid == 0 || t.Flags&(cmTimeIndefinite|cmTimeInfinite) != 0 || t.Timescale <= 0 {
|
||||
return 0, false
|
||||
}
|
||||
return time.Duration(float64(t.Value) / float64(t.Timescale) * float64(time.Second)), true
|
||||
}
|
||||
|
||||
func cmTimeOf(d time.Duration) cmTime {
|
||||
return cmTime{Value: int64(d), Timescale: int32(time.Second), Flags: cmTimeValid}
|
||||
}
|
||||
|
||||
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)) }
|
||||
|
||||
// cptr is the pointer of an address of native memory.
|
||||
func cptr(a uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&a)) }
|
||||
|
||||
func nsString(s string) objc.ID {
|
||||
return send(class("NSString"), "stringWithUTF8String:", s)
|
||||
}
|
||||
|
||||
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))
|
||||
}
|
||||
|
||||
func loadAVFoundation() error {
|
||||
avfOnce.Do(func() {
|
||||
defer func() {
|
||||
if v := recover(); v != nil {
|
||||
avfErr = errors.Join(ErrUnsupported, errors.New("video: AVFoundation: "+toString(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")
|
||||
cf := open("/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation")
|
||||
qc := open("/System/Library/Frameworks/QuartzCore.framework/QuartzCore")
|
||||
sys := open("/usr/lib/libSystem.B.dylib")
|
||||
sym := func(lib uintptr, name string) uintptr {
|
||||
p, err := purego.Dlsym(lib, name)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
constant := func(lib uintptr, name string) uintptr { return *(*uintptr)(cptr(sym(lib, name))) }
|
||||
msgSend = sym(objcLib, "objc_msgSend")
|
||||
msgSendStret = msgSend
|
||||
if runtime.GOARCH == "amd64" {
|
||||
msgSendStret = sym(objcLib, "objc_msgSend_stret")
|
||||
}
|
||||
purego.RegisterFunc(&msgItemTimeForHostTime, msgSendStret)
|
||||
purego.RegisterFunc(&msgCMTime, msgSendStret)
|
||||
purego.RegisterFunc(&msgHasNewBuffer, msgSend)
|
||||
purego.RegisterFunc(&msgCopyBuffer, msgSend)
|
||||
purego.RegisterFunc(&msgSeek, msgSend)
|
||||
purego.RegisterFunc(&msgSetFloat32, msgSend)
|
||||
purego.RegisterFunc(&msgFloat32, msgSend)
|
||||
purego.RegisterFunc(&msgSetBool, msgSend)
|
||||
purego.RegisterFunc(&msgInt, msgSend)
|
||||
purego.RegisterFunc(&msgBool, msgSend)
|
||||
purego.RegisterLibFunc(&caCurrentMediaTime, qc, "CACurrentMediaTime")
|
||||
purego.RegisterLibFunc(&cvBufferRelease, cv, "CVBufferRelease")
|
||||
purego.RegisterLibFunc(&cvBufferRetain, cv, "CVBufferRetain")
|
||||
purego.RegisterLibFunc(&cvBufferGetAttachment, cv, "CVBufferGetAttachment")
|
||||
purego.RegisterLibFunc(&cvPixelBufferGetWidth, cv, "CVPixelBufferGetWidth")
|
||||
purego.RegisterLibFunc(&cvPixelBufferGetHeight, cv, "CVPixelBufferGetHeight")
|
||||
purego.RegisterLibFunc(&cvPixelBufferGetPixelFormat, cv, "CVPixelBufferGetPixelFormatType")
|
||||
purego.RegisterLibFunc(&cvPixelBufferLock, cv, "CVPixelBufferLockBaseAddress")
|
||||
purego.RegisterLibFunc(&cvPixelBufferUnlock, cv, "CVPixelBufferUnlockBaseAddress")
|
||||
purego.RegisterLibFunc(&cvPixelBufferPlaneBase, cv, "CVPixelBufferGetBaseAddressOfPlane")
|
||||
purego.RegisterLibFunc(&cvPixelBufferPlaneStride, cv, "CVPixelBufferGetBytesPerRowOfPlane")
|
||||
purego.RegisterLibFunc(&cfEqual, cf, "CFEqual")
|
||||
purego.RegisterLibFunc(&dispatchQueueCreate, sys, "dispatch_queue_create")
|
||||
purego.RegisterLibFunc(&poolPush, objcLib, "objc_autoreleasePoolPush")
|
||||
purego.RegisterLibFunc(&poolPop, objcLib, "objc_autoreleasePoolPop")
|
||||
cvMatrixKey = constant(cv, "kCVImageBufferYCbCrMatrixKey")
|
||||
cvMatrix709 = constant(cv, "kCVImageBufferYCbCrMatrix_ITU_R_709_2")
|
||||
cvMatrix601 = constant(cv, "kCVImageBufferYCbCrMatrix_ITU_R_601_4")
|
||||
cvMatrix2020 = constant(cv, "kCVImageBufferYCbCrMatrix_ITU_R_2020")
|
||||
cvPixelFormatKey = constant(cv, "kCVPixelBufferPixelFormatTypeKey")
|
||||
cvMetalCompatibilityKey = constant(cv, "kCVPixelBufferMetalCompatibilityKey")
|
||||
avMediaTypeVideo = constant(av, "AVMediaTypeVideo")
|
||||
if class("AVPlayer") == 0 || class("AVPlayerItemVideoOutput") == 0 {
|
||||
panic("no AVPlayer")
|
||||
}
|
||||
})
|
||||
return avfErr
|
||||
}
|
||||
|
||||
// pooled pushes an autorelease pool on the thread, which the goroutine
|
||||
// keeps until the function it returns pops it.
|
||||
func pooled() func() {
|
||||
runtime.LockOSThread()
|
||||
p := poolPush()
|
||||
return func() {
|
||||
poolPop(p)
|
||||
runtime.UnlockOSThread()
|
||||
}
|
||||
}
|
||||
|
||||
func toString(v any) string {
|
||||
if err, ok := v.(error); ok {
|
||||
return err.Error()
|
||||
}
|
||||
if s, ok := v.(string); ok {
|
||||
return s
|
||||
}
|
||||
return "failed to load"
|
||||
}
|
||||
|
||||
// avEngine plays a video with an AVPlayer.
|
||||
type avEngine struct {
|
||||
player, item, output objc.ID
|
||||
loader uint64 // in loaders, for bytes in memory; 0 for none
|
||||
delegate objc.ID
|
||||
quit chan struct{}
|
||||
done chan struct{}
|
||||
|
||||
// buf is the CVPixelBuffer that Frame last returned, retained, and
|
||||
// surface the surface showing it.
|
||||
buf uintptr
|
||||
surface *scene.Surface
|
||||
w, h int
|
||||
// interval is Interval's, which the watching goroutine reads once
|
||||
// the item is ready to play: 0 until it has.
|
||||
interval atomic.Int64
|
||||
|
||||
mu sync.Mutex
|
||||
wake func()
|
||||
state media.State
|
||||
err error
|
||||
// playing is whether the app plays it, loop whether it plays again
|
||||
// at its end, which the watching goroutine sees.
|
||||
playing, loop, closed bool
|
||||
rate float32
|
||||
}
|
||||
|
||||
func newEngine(s source) (media.Engine, error) {
|
||||
if err := loadAVFoundation(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer pooled()()
|
||||
e := &avEngine{quit: make(chan struct{}), done: make(chan struct{}), rate: 1}
|
||||
var asset objc.ID
|
||||
if s.data != nil {
|
||||
if err := loadDelegate(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.loader = lastLoader.Add(1)
|
||||
loaders.Store(e.loader, s.data)
|
||||
url := send(class("NSURL"), "URLWithString:", nsString("mygo-video://data/"+itoa(e.loader)+".mp4"))
|
||||
asset = send(send(class("AVURLAsset"), "alloc"), "initWithURL:options:", url, objc.ID(0))
|
||||
e.delegate = send(send(objc.ID(loaderClass), "alloc"), "init")
|
||||
send(send(asset, "resourceLoader"), "setDelegate:queue:", e.delegate, loaderQueue)
|
||||
} else {
|
||||
url := send(class("NSURL"), "URLWithString:", nsString(s.url))
|
||||
if url == 0 {
|
||||
return nil, errors.New("video: not a URL: " + s.url)
|
||||
}
|
||||
asset = send(send(class("AVURLAsset"), "alloc"), "initWithURL:options:", url, objc.ID(0))
|
||||
}
|
||||
e.item = send(send(class("AVPlayerItem"), "alloc"), "initWithAsset:", asset)
|
||||
send(asset, "release")
|
||||
attrs := send(class("NSDictionary"), "dictionaryWithObjects:forKeys:count:",
|
||||
unsafe.Pointer(&[2]objc.ID{send(class("NSNumber"), "numberWithUnsignedInt:", uint32(pixelFormat420v)), send(class("NSNumber"), "numberWithBool:", true)}),
|
||||
unsafe.Pointer(&[2]uintptr{cvPixelFormatKey, cvMetalCompatibilityKey}), uint(2))
|
||||
e.output = send(send(class("AVPlayerItemVideoOutput"), "alloc"), "initWithPixelBufferAttributes:", attrs)
|
||||
send(e.item, "addOutput:", e.output)
|
||||
e.player = send(send(class("AVPlayer"), "alloc"), "initWithPlayerItem:", e.item)
|
||||
// The player pauses at the end, rather than stand at the end playing,
|
||||
// for the goroutine to see; it loops by a seek.
|
||||
send(e.player, "setActionAtItemEnd:", avActionAtEndNone)
|
||||
msgSetBool(e.player, sel("setPreventsDisplaySleepDuringVideoPlayback:"), true)
|
||||
go e.watch()
|
||||
return e, nil
|
||||
}
|
||||
|
||||
func itoa(n uint64) string {
|
||||
var b [20]byte
|
||||
i := len(b)
|
||||
for {
|
||||
i--
|
||||
b[i] = byte('0' + n%10)
|
||||
n /= 10
|
||||
if n == 0 {
|
||||
return string(b[i:])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// watch follows how loading and playing go, as the player reports it,
|
||||
// and wakes the window when that changes: a loop seeks back at the end.
|
||||
// It wakes the window for the first picture too, which only Frame takes,
|
||||
// on the main thread, as a frame of the window builds: the state stays
|
||||
// Loading until then, and nothing else may build one (#1830).
|
||||
func (e *avEngine) watch() {
|
||||
defer close(e.done)
|
||||
runtime.LockOSThread() // for the autorelease pools
|
||||
defer runtime.UnlockOSThread()
|
||||
tick := time.NewTicker(25 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
// When the window was last woken for a first picture, which it wakes
|
||||
// for again while none was taken: a frame woken may build before the
|
||||
// output has it at the frame's time, or while none of the window shows.
|
||||
var wokeFirst time.Time
|
||||
for {
|
||||
select {
|
||||
case <-e.quit:
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
pool := poolPush()
|
||||
e.mu.Lock()
|
||||
before, beforeErr := e.state, e.err
|
||||
e.poll()
|
||||
changed := e.state != before || e.err != beforeErr
|
||||
loading := e.state == media.Loading
|
||||
wake := e.wake
|
||||
e.mu.Unlock()
|
||||
ready := msgInt(e.item, sel("status")) == avStatusReadyToPlay
|
||||
if ready && e.interval.Load() == 0 {
|
||||
// Out of mu: State, on the main thread, never waits for it.
|
||||
e.interval.Store(int64(e.frameInterval()))
|
||||
}
|
||||
if ready && loading && time.Since(wokeFirst) >= 250*time.Millisecond {
|
||||
// The output has the first picture once it has one for now,
|
||||
// which the frame woken, due a little later, takes.
|
||||
at := msgItemTimeForHostTime(e.output, sel("itemTimeForHostTime:"), caCurrentMediaTime())
|
||||
if msgHasNewBuffer(e.output, sel("hasNewPixelBufferForItemTime:"), at) {
|
||||
wokeFirst, changed = time.Now(), true
|
||||
}
|
||||
}
|
||||
poolPop(pool)
|
||||
if changed && wake != nil {
|
||||
wake()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// poll reads the item's state, under mu.
|
||||
func (e *avEngine) poll() {
|
||||
if e.closed {
|
||||
return
|
||||
}
|
||||
switch msgInt(e.item, sel("status")) {
|
||||
case avStatusFailed:
|
||||
e.state = media.Failed
|
||||
msg := "AVFoundation could not play the video"
|
||||
if err := send(e.item, "error"); err != 0 {
|
||||
msg = goString(send(err, "localizedDescription"))
|
||||
}
|
||||
e.err = errors.New("video: " + msg)
|
||||
return
|
||||
case avStatusReadyToPlay:
|
||||
default:
|
||||
return // loading
|
||||
}
|
||||
if e.state == media.Loading && e.buf == 0 {
|
||||
// Ready once its first picture shows (Frame).
|
||||
return
|
||||
}
|
||||
cur, _ := msgCMTime(e.item, sel("currentTime")).duration()
|
||||
dur, known := msgCMTime(e.item, sel("duration")).duration()
|
||||
if known && cur >= dur-time.Millisecond && e.playing {
|
||||
if e.loop {
|
||||
e.seek(0)
|
||||
msgSetFloat32(e.player, sel("setRate:"), e.rate)
|
||||
return
|
||||
}
|
||||
if e.state != media.Ended {
|
||||
e.state = media.Ended
|
||||
send(e.player, "pause")
|
||||
}
|
||||
return
|
||||
}
|
||||
if e.state == media.Ended {
|
||||
return
|
||||
}
|
||||
if e.playing && msgInt(e.player, sel("timeControlStatus")) == avWaitingToPlay {
|
||||
e.state = media.Buffering
|
||||
} else {
|
||||
e.state = media.Ready
|
||||
}
|
||||
}
|
||||
|
||||
func (e *avEngine) SetWake(wake func()) {
|
||||
e.mu.Lock()
|
||||
e.wake = wake
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *avEngine) Frame(t time.Time) (media.Picture, bool, bool) {
|
||||
defer pooled()()
|
||||
// The picture due as the frame shows, and never one from before now:
|
||||
// a Tester's clock stands still, and the player's runs on.
|
||||
host := caCurrentMediaTime() + max(time.Until(t), 0).Seconds()
|
||||
at := msgItemTimeForHostTime(e.output, sel("itemTimeForHostTime:"), host)
|
||||
changed := false
|
||||
if e.buf == 0 && msgInt(e.item, sel("status")) != avStatusReadyToPlay {
|
||||
// The output may have a picture before the item knows its
|
||||
// duration: ready is both.
|
||||
return media.Picture{}, false, false
|
||||
}
|
||||
if msgHasNewBuffer(e.output, sel("hasNewPixelBufferForItemTime:"), at) {
|
||||
if buf := msgCopyBuffer(e.output, sel("copyPixelBufferForItemTime:itemTimeForDisplay:"), at, 0); buf != 0 {
|
||||
// What drew the last one holds it still (the renderer's
|
||||
// textures): the surface no longer shows it.
|
||||
if e.buf != 0 {
|
||||
cvBufferRelease(e.buf)
|
||||
}
|
||||
e.buf, changed = buf, true
|
||||
e.w, e.h = int(cvPixelBufferGetWidth(buf)), int(cvPixelBufferGetHeight(buf))
|
||||
m := matrixOf(buf)
|
||||
if cvPixelBufferGetPixelFormat(buf) == pixelFormat420f {
|
||||
m += scene.FullRange
|
||||
}
|
||||
e.surface = &scene.Surface{Format: scene.SurfaceNV12, Matrix: m, Native: buf}
|
||||
e.mu.Lock()
|
||||
if e.state == media.Loading {
|
||||
e.state = media.Ready
|
||||
}
|
||||
e.mu.Unlock()
|
||||
}
|
||||
}
|
||||
if e.buf == 0 {
|
||||
return media.Picture{}, false, false
|
||||
}
|
||||
s, w, h := e.surface, e.w, e.h
|
||||
return media.Picture{Surface: s, W: w, H: h, RGBA: func(dst []byte) []byte { return pixelBufferRGBA(s, dst, w, h) }}, changed, true
|
||||
}
|
||||
|
||||
// matrixOf is the YUV matrix a pixel buffer's attachment says, or for
|
||||
// none that of its size.
|
||||
func matrixOf(buf uintptr) scene.YUVMatrix {
|
||||
if m := cvBufferGetAttachment(buf, cvMatrixKey, 0); m != 0 {
|
||||
switch {
|
||||
case cfEqual(m, cvMatrix709):
|
||||
return scene.BT709
|
||||
case cfEqual(m, cvMatrix601):
|
||||
return scene.BT601
|
||||
case cfEqual(m, cvMatrix2020):
|
||||
return scene.BT2020
|
||||
}
|
||||
}
|
||||
if cvPixelBufferGetHeight(buf) >= 720 {
|
||||
return scene.BT709
|
||||
}
|
||||
return scene.BT601
|
||||
}
|
||||
|
||||
// pixelBufferRGBA converts the frame of a surface's pixel buffer, for
|
||||
// the CPU renderer, reading its planes in memory.
|
||||
func pixelBufferRGBA(s *scene.Surface, dst []byte, w, h int) []byte {
|
||||
buf := s.Native
|
||||
if buf == 0 || cvPixelBufferLock(buf, 1) != 0 { // kCVPixelBufferLock_ReadOnly
|
||||
return nil
|
||||
}
|
||||
defer cvPixelBufferUnlock(buf, 1)
|
||||
rows := [2]int{h, (h + 1) / 2}
|
||||
var planes scene.Surface
|
||||
planes.Format, planes.Matrix = s.Format, s.Matrix
|
||||
for p := range 2 {
|
||||
base, stride := cvPixelBufferPlaneBase(buf, uint(p)), int(cvPixelBufferPlaneStride(buf, uint(p)))
|
||||
if base == nil {
|
||||
return nil
|
||||
}
|
||||
planes.Planes[p] = scene.Plane{Pix: unsafe.Slice((*byte)(base), stride*rows[p]), Stride: stride}
|
||||
}
|
||||
return planes.RGBA(dst, w, h)
|
||||
}
|
||||
|
||||
// frameInterval is half the time a picture shows at the video's
|
||||
// nominal rate, or 1/60 s for none. It reads the asset's tracks, which
|
||||
// for an AVURLAsset loads them, over the network for a URL, until the
|
||||
// item is ready to play: only the watching goroutine calls it, once the
|
||||
// item is.
|
||||
func (e *avEngine) frameInterval() time.Duration {
|
||||
tracks := send(send(e.item, "asset"), "tracksWithMediaType:", avMediaTypeVideo)
|
||||
if tracks != 0 && msgInt(tracks, sel("count")) > 0 {
|
||||
if fps := msgFloat32(send(tracks, "firstObject"), sel("nominalFrameRate")); fps > 1 {
|
||||
// Asked for twice as often, so that a frame shows at the
|
||||
// refresh after it came due, not up to one later.
|
||||
return time.Duration(float64(time.Second) / float64(fps) / 2)
|
||||
}
|
||||
}
|
||||
return time.Second / 60
|
||||
}
|
||||
|
||||
// Interval is 1/60 s until the watching goroutine read the video's rate,
|
||||
// never touching the asset's tracks on the main thread (#1743).
|
||||
func (e *avEngine) Interval() time.Duration {
|
||||
if d := e.interval.Load(); d > 0 {
|
||||
return time.Duration(d)
|
||||
}
|
||||
return time.Second / 60
|
||||
}
|
||||
|
||||
func (e *avEngine) State() (media.State, error) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return e.state, e.err
|
||||
}
|
||||
|
||||
func (e *avEngine) Size() (int, int) { return e.w, e.h }
|
||||
|
||||
func (e *avEngine) Duration() time.Duration {
|
||||
d, _ := msgCMTime(e.item, sel("duration")).duration()
|
||||
return d
|
||||
}
|
||||
|
||||
func (e *avEngine) Position() time.Duration {
|
||||
d, _ := msgCMTime(e.item, sel("currentTime")).duration()
|
||||
return d
|
||||
}
|
||||
|
||||
func (e *avEngine) Play() {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.playing = true
|
||||
if e.state == media.Ended {
|
||||
e.state = media.Ready
|
||||
e.seek(0)
|
||||
}
|
||||
msgSetFloat32(e.player, sel("setRate:"), e.rate)
|
||||
}
|
||||
|
||||
func (e *avEngine) Pause() {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.playing = false
|
||||
send(e.player, "pause")
|
||||
}
|
||||
|
||||
func (e *avEngine) Seek(d time.Duration) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.state == media.Ended {
|
||||
e.state = media.Ready
|
||||
}
|
||||
e.seek(d)
|
||||
}
|
||||
|
||||
// seek seeks to d exactly, under mu.
|
||||
func (e *avEngine) seek(d time.Duration) {
|
||||
zero := cmTime{Flags: cmTimeValid, Timescale: 1}
|
||||
msgSeek(e.player, sel("seekToTime:toleranceBefore:toleranceAfter:"), cmTimeOf(d), zero, zero)
|
||||
}
|
||||
|
||||
func (e *avEngine) SetLoop(loop bool) {
|
||||
e.mu.Lock()
|
||||
e.loop = loop
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *avEngine) SetRate(r float64) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.rate = float32(r)
|
||||
if e.playing && e.state != media.Ended {
|
||||
msgSetFloat32(e.player, sel("setRate:"), e.rate)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *avEngine) SetVolume(v float64) { msgSetFloat32(e.player, sel("setVolume:"), float32(v)) }
|
||||
|
||||
func (e *avEngine) SetMuted(m bool) { msgSetBool(e.player, sel("setMuted:"), m) }
|
||||
|
||||
// Close stops the player and frees it. The pixel buffer showing goes
|
||||
// once nothing shows its surface any more.
|
||||
func (e *avEngine) Close() error {
|
||||
e.mu.Lock()
|
||||
if e.closed {
|
||||
e.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
e.closed = true
|
||||
e.wake = nil
|
||||
e.mu.Unlock()
|
||||
close(e.quit)
|
||||
<-e.done
|
||||
pop := pooled()
|
||||
send(e.player, "pause")
|
||||
send(e.player, "replaceCurrentItemWithPlayerItem:", objc.ID(0))
|
||||
send(e.item, "removeOutput:", e.output)
|
||||
send(e.output, "release")
|
||||
send(e.item, "release")
|
||||
send(e.player, "release")
|
||||
if e.delegate != 0 {
|
||||
send(e.delegate, "release")
|
||||
loaders.Delete(e.loader)
|
||||
}
|
||||
pop()
|
||||
if e.buf != 0 {
|
||||
buf := e.buf
|
||||
e.buf = 0
|
||||
runtime.AddCleanup(e.surface, func(b uintptr) { cvBufferRelease(b) }, buf)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// loadDelegate registers the class of the delegates that answer an
|
||||
// AVAssetResourceLoader from bytes in memory, on a queue of their own.
|
||||
func loadDelegate() error {
|
||||
if loaderClass != 0 {
|
||||
return nil
|
||||
}
|
||||
// The protocol is in the runtime only if something compiled against
|
||||
// it loaded: a nil one in the class's list would crash the runtime
|
||||
// when AVFoundation asks the class for a method's signature.
|
||||
var protocols []*objc.Protocol
|
||||
if p := objc.GetProtocol("AVAssetResourceLoaderDelegate"); p != nil {
|
||||
protocols = append(protocols, p)
|
||||
}
|
||||
var err error
|
||||
loaderClass, err = objc.RegisterClass("MyGoVideoDataLoader", objc.GetClass("NSObject"),
|
||||
protocols, nil,
|
||||
[]objc.MethodDef{{
|
||||
Cmd: sel("resourceLoader:shouldWaitForLoadingOfRequestedResource:"),
|
||||
Fn: answerLoading,
|
||||
}})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
loaderQueue = dispatchQueueCreate("mygo.video.data", 0)
|
||||
return nil
|
||||
}
|
||||
|
||||
// answerLoading answers a request for bytes of a video in memory: what
|
||||
// they are, and those asked for.
|
||||
func answerLoading(self objc.ID, _ objc.SEL, loader, req objc.ID) bool {
|
||||
url := goString(send(send(send(req, "request"), "URL"), "absoluteString"))
|
||||
var n uint64
|
||||
for i := len("mygo-video://data/"); i < len(url) && '0' <= url[i] && url[i] <= '9'; i++ {
|
||||
n = n*10 + uint64(url[i]-'0')
|
||||
}
|
||||
v, ok := loaders.Load(n)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
data := v.([]byte)
|
||||
if info := send(req, "contentInformationRequest"); info != 0 {
|
||||
send(info, "setContentType:", nsString(contentType(data)))
|
||||
send(info, "setContentLength:", int64(len(data)))
|
||||
msgSetBool(info, sel("setByteRangeAccessSupported:"), true)
|
||||
}
|
||||
if dr := send(req, "dataRequest"); dr != 0 {
|
||||
off := int64(send(dr, "currentOffset"))
|
||||
end := int64(send(dr, "requestedOffset")) + int64(send(dr, "requestedLength"))
|
||||
if msgBool(dr, sel("requestsAllDataToEndOfResource")) {
|
||||
end = int64(len(data))
|
||||
}
|
||||
off, end = min(max(off, 0), int64(len(data))), min(end, int64(len(data)))
|
||||
if end > off {
|
||||
chunk := send(class("NSData"), "dataWithBytes:length:", unsafe.Pointer(&data[off]), uint(end-off))
|
||||
send(dr, "respondWithData:", chunk)
|
||||
}
|
||||
}
|
||||
send(req, "finishLoading")
|
||||
return true
|
||||
}
|
||||
|
||||
// contentType is the UTI of a video's bytes, as their container says.
|
||||
func contentType(b []byte) string {
|
||||
if len(b) >= 12 && string(b[4:8]) == "ftyp" && string(b[8:12]) == "qt " {
|
||||
return "com.apple.quicktime-movie"
|
||||
}
|
||||
return "public.mpeg-4"
|
||||
}
|
||||
+269
@@ -0,0 +1,269 @@
|
||||
//go:build js
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"syscall/js"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/media"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// In browsers, a video element plays the video, not in the page: it
|
||||
// decodes, plays the sound and keeps the clock, and WebGL uploads each
|
||||
// picture from it, GPU to GPU (texSubImage2D of the element). Where the
|
||||
// browser has requestVideoFrameCallback, each picture the element
|
||||
// presents wakes the window; elsewhere the window asks for frames at the
|
||||
// display's rate while it plays. Bytes in memory play from a Blob's URL.
|
||||
|
||||
type elementEngine struct {
|
||||
el js.Value
|
||||
native uintptr
|
||||
blob string // the object URL of bytes in memory, revoked on Close
|
||||
funcs []js.Func
|
||||
names []string
|
||||
frameF js.Func
|
||||
rvfc bool
|
||||
// frameReq is the pending requestVideoFrameCallback's handle.
|
||||
frameReq js.Value
|
||||
|
||||
wake func()
|
||||
state media.State
|
||||
err error
|
||||
fresh bool // a picture presented since the last Frame
|
||||
lastT float64
|
||||
shown bool
|
||||
surface *scene.Surface
|
||||
canvas js.Value // for reading pictures back (RGBA)
|
||||
closed bool
|
||||
}
|
||||
|
||||
func newEngine(s source) (media.Engine, error) {
|
||||
doc := js.Global().Get("document")
|
||||
if doc.IsUndefined() {
|
||||
return nil, ErrUnsupported
|
||||
}
|
||||
e := &elementEngine{el: doc.Call("createElement", "video")}
|
||||
el := e.el
|
||||
el.Set("playsInline", true)
|
||||
el.Set("preload", "auto")
|
||||
el.Set("crossOrigin", "anonymous") // for WebGL to read a picture of another origin that allows it
|
||||
url := s.url
|
||||
if s.data != nil {
|
||||
arr := js.Global().Get("Uint8Array").New(len(s.data))
|
||||
js.CopyBytesToJS(arr, s.data)
|
||||
blob := js.Global().Get("Blob").New([]any{arr}, map[string]any{"type": mimeOf(s.data)})
|
||||
e.blob = js.Global().Get("URL").Call("createObjectURL", blob).String()
|
||||
url = e.blob
|
||||
}
|
||||
e.native = media.AddElement(el)
|
||||
e.surface = &scene.Surface{Format: scene.SurfaceBGRA, Native: e.native}
|
||||
on := func(name string, fn func()) {
|
||||
f := js.FuncOf(func(js.Value, []js.Value) any {
|
||||
if !e.closed {
|
||||
fn()
|
||||
e.wakeWindow()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
e.funcs, e.names = append(e.funcs, f), append(e.names, name)
|
||||
el.Call("addEventListener", name, f)
|
||||
}
|
||||
on("loadeddata", func() { e.fresh = true })
|
||||
on("seeked", func() { e.fresh = true })
|
||||
on("waiting", func() {
|
||||
if e.state == media.Ready {
|
||||
e.state = media.Buffering
|
||||
}
|
||||
})
|
||||
on("playing", func() {
|
||||
if e.state == media.Buffering {
|
||||
e.state = media.Ready
|
||||
}
|
||||
})
|
||||
on("ended", func() {
|
||||
if !el.Get("loop").Bool() {
|
||||
e.state = media.Ended
|
||||
}
|
||||
})
|
||||
on("error", func() {
|
||||
e.state = media.Failed
|
||||
msg := "the browser could not play the video"
|
||||
if me := el.Get("error"); !me.IsNull() && !me.IsUndefined() {
|
||||
if m := me.Get("message").String(); m != "" {
|
||||
msg = m
|
||||
}
|
||||
}
|
||||
e.err = errors.New("video: " + msg)
|
||||
})
|
||||
on("durationchange", func() {})
|
||||
if !el.Get("requestVideoFrameCallback").IsUndefined() {
|
||||
e.rvfc = true
|
||||
e.frameF = js.FuncOf(func(js.Value, []js.Value) any {
|
||||
if e.closed {
|
||||
return nil
|
||||
}
|
||||
e.fresh = true
|
||||
e.frameReq = el.Call("requestVideoFrameCallback", e.frameF)
|
||||
e.wakeWindow()
|
||||
return nil
|
||||
})
|
||||
e.frameReq = el.Call("requestVideoFrameCallback", e.frameF)
|
||||
}
|
||||
el.Set("src", url)
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// mimeOf is the MIME type of a video's bytes, as their container says.
|
||||
func mimeOf(b []byte) string {
|
||||
switch {
|
||||
case len(b) >= 4 && string(b[:4]) == "\x1a\x45\xdf\xa3":
|
||||
return "video/webm"
|
||||
case len(b) >= 12 && string(b[4:8]) == "ftyp" && string(b[8:12]) == "qt ":
|
||||
return "video/quicktime"
|
||||
}
|
||||
return "video/mp4"
|
||||
}
|
||||
|
||||
func (e *elementEngine) wakeWindow() {
|
||||
if e.wake != nil {
|
||||
e.wake()
|
||||
}
|
||||
}
|
||||
|
||||
func (e *elementEngine) SetWake(wake func()) { e.wake = wake }
|
||||
|
||||
func (e *elementEngine) Frame(time.Time) (media.Picture, bool, bool) {
|
||||
if e.closed || e.el.Get("readyState").Int() < 2 { // HAVE_CURRENT_DATA
|
||||
return media.Picture{}, false, false
|
||||
}
|
||||
t := e.el.Get("currentTime").Float()
|
||||
changed := e.fresh || !e.shown || (!e.rvfc && t != e.lastT)
|
||||
e.fresh, e.shown, e.lastT = false, true, t
|
||||
if e.state == media.Loading {
|
||||
e.state = media.Ready
|
||||
}
|
||||
w, h := e.Size()
|
||||
return media.Picture{Surface: e.surface, W: w, H: h, RGBA: func(dst []byte) []byte { return e.readBack(dst, w, h) }}, changed, true
|
||||
}
|
||||
|
||||
// readBack draws the picture into a canvas of its own, for the CPU
|
||||
// renderer, and copies its pixels, premultiplied as they are opaque.
|
||||
func (e *elementEngine) readBack(dst []byte, w, h int) []byte {
|
||||
if e.closed || w <= 0 || h <= 0 {
|
||||
return nil
|
||||
}
|
||||
if e.canvas.IsUndefined() || e.canvas.IsNull() {
|
||||
e.canvas = js.Global().Get("document").Call("createElement", "canvas")
|
||||
}
|
||||
e.canvas.Set("width", w)
|
||||
e.canvas.Set("height", h)
|
||||
ctx := e.canvas.Call("getContext", "2d", map[string]any{"willReadFrequently": true})
|
||||
if ctx.IsNull() {
|
||||
return nil
|
||||
}
|
||||
ctx.Call("drawImage", e.el, 0, 0, w, h)
|
||||
data := ctx.Call("getImageData", 0, 0, w, h).Get("data")
|
||||
n := 4 * w * h
|
||||
if cap(dst) < n {
|
||||
dst = make([]byte, n)
|
||||
}
|
||||
dst = dst[:n]
|
||||
js.CopyBytesToGo(dst, js.Global().Get("Uint8Array").New(data.Get("buffer"), data.Get("byteOffset"), n))
|
||||
return dst
|
||||
}
|
||||
|
||||
// Interval is 0 where each picture the element presents wakes the
|
||||
// window, else the display's rate.
|
||||
func (e *elementEngine) Interval() time.Duration {
|
||||
if e.rvfc {
|
||||
return 0
|
||||
}
|
||||
return time.Second / 60
|
||||
}
|
||||
|
||||
func (e *elementEngine) State() (media.State, error) { return e.state, e.err }
|
||||
|
||||
func (e *elementEngine) Size() (int, int) {
|
||||
return e.el.Get("videoWidth").Int(), e.el.Get("videoHeight").Int()
|
||||
}
|
||||
|
||||
func (e *elementEngine) Duration() time.Duration {
|
||||
d := e.el.Get("duration").Float()
|
||||
if d != d || d <= 0 || d > 1e12 { // NaN, or Infinity for a live stream
|
||||
return 0
|
||||
}
|
||||
return time.Duration(d * float64(time.Second))
|
||||
}
|
||||
|
||||
func (e *elementEngine) Position() time.Duration {
|
||||
return time.Duration(e.el.Get("currentTime").Float() * float64(time.Second))
|
||||
}
|
||||
|
||||
func (e *elementEngine) Play() {
|
||||
if e.state == media.Ended {
|
||||
e.state = media.Ready
|
||||
e.el.Set("currentTime", 0)
|
||||
}
|
||||
// A browser that does not let a page play sound before the user
|
||||
// interacted with it rejects the promise: the video plays muted.
|
||||
p := e.el.Call("play")
|
||||
if p.Truthy() && !p.Get("catch").IsUndefined() {
|
||||
var f js.Func
|
||||
f = js.FuncOf(func(js.Value, []js.Value) any {
|
||||
f.Release()
|
||||
if !e.closed && !e.el.Get("muted").Bool() {
|
||||
e.el.Set("muted", true)
|
||||
e.el.Call("play")
|
||||
}
|
||||
return nil
|
||||
})
|
||||
p.Call("catch", f)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *elementEngine) Pause() { e.el.Call("pause") }
|
||||
|
||||
func (e *elementEngine) Seek(d time.Duration) {
|
||||
if e.state == media.Ended {
|
||||
e.state = media.Ready
|
||||
}
|
||||
e.el.Set("currentTime", d.Seconds())
|
||||
}
|
||||
|
||||
func (e *elementEngine) SetLoop(loop bool) { e.el.Set("loop", loop) }
|
||||
|
||||
func (e *elementEngine) SetRate(r float64) {
|
||||
e.el.Set("defaultPlaybackRate", r)
|
||||
e.el.Set("playbackRate", r)
|
||||
}
|
||||
|
||||
func (e *elementEngine) SetVolume(v float64) { e.el.Set("volume", v) }
|
||||
|
||||
func (e *elementEngine) SetMuted(m bool) { e.el.Set("muted", m) }
|
||||
|
||||
func (e *elementEngine) Close() error {
|
||||
if e.closed {
|
||||
return nil
|
||||
}
|
||||
e.closed = true
|
||||
e.wake = nil
|
||||
for i, f := range e.funcs {
|
||||
e.el.Call("removeEventListener", e.names[i], f)
|
||||
f.Release()
|
||||
}
|
||||
if e.rvfc {
|
||||
e.el.Call("cancelVideoFrameCallback", e.frameReq)
|
||||
e.frameF.Release()
|
||||
}
|
||||
e.el.Call("pause")
|
||||
e.el.Call("removeAttribute", "src")
|
||||
e.el.Call("load")
|
||||
if e.blob != "" {
|
||||
js.Global().Get("URL").Call("revokeObjectURL", e.blob)
|
||||
}
|
||||
media.RemoveElement(e.native)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//go:build windows
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"math"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// On amd64, syscall passes each of the first four arguments in the
|
||||
// floating point register of its place too, and returns the first one
|
||||
// (XMM0), as Windows passes and returns doubles.
|
||||
|
||||
func loadFloatCalls() error { return nil }
|
||||
|
||||
// callSetDouble calls method i of a COM object taking a double.
|
||||
func callSetDouble(obj uintptr, i int, v float64) uintptr {
|
||||
r, _, _ := syscall.SyscallN(method(obj, i), obj, uintptr(math.Float64bits(v)))
|
||||
return r
|
||||
}
|
||||
|
||||
// callGetDouble calls method i of a COM object returning a double.
|
||||
func callGetDouble(obj uintptr, i int) float64 {
|
||||
_, r2, _ := syscall.SyscallN(method(obj, i), obj)
|
||||
return math.Float64frombits(uint64(r2))
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//go:build windows
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
// On arm64, Windows passes and returns doubles in the floating point
|
||||
// registers, which syscall neither sets nor reads. Two thunks of machine
|
||||
// code, made once in memory of their own, move them between those and the
|
||||
// integer registers syscall has:
|
||||
//
|
||||
// setDouble(obj X0, bits X1, fn X2): FMOV D0, X1; BR X2
|
||||
// getDouble(obj X0, fn X1): STP X29, X30, [SP, #-16]!; MOV X29, SP;
|
||||
// BLR X1; FMOV X0, D0; LDP X29, X30, [SP], #16; RET
|
||||
|
||||
var setDoubleThunk, getDoubleThunk uintptr
|
||||
|
||||
func loadFloatCalls() error {
|
||||
code := []uint32{
|
||||
0x9e670020, 0xd61f0040, // setDouble
|
||||
0xa9bf7bfd, 0x910003fd, 0xd63f0020, 0x9e660000, 0xa8c17bfd, 0xd65f03c0, // getDouble
|
||||
}
|
||||
k := syscall.NewLazyDLL("kernel32.dll")
|
||||
const memCommitReserve, pageReadWrite, pageExecuteRead = 0x3000, 0x04, 0x20
|
||||
mem, _, err := k.NewProc("VirtualAlloc").Call(0, uintptr(4*len(code)), memCommitReserve, pageReadWrite)
|
||||
if mem == 0 {
|
||||
return fmt.Errorf("video: VirtualAlloc: %v", err)
|
||||
}
|
||||
copy(unsafe.Slice((*uint32)(cptr(mem)), len(code)), code)
|
||||
var old uint32
|
||||
if r, _, err := k.NewProc("VirtualProtect").Call(mem, uintptr(4*len(code)), pageExecuteRead, uintptr(unsafe.Pointer(&old))); r == 0 {
|
||||
return fmt.Errorf("video: VirtualProtect: %v", err)
|
||||
}
|
||||
proc, _, _ := k.NewProc("GetCurrentProcess").Call()
|
||||
k.NewProc("FlushInstructionCache").Call(proc, mem, uintptr(4*len(code)))
|
||||
setDoubleThunk, getDoubleThunk = mem, mem+8
|
||||
return nil
|
||||
}
|
||||
|
||||
// callSetDouble calls method i of a COM object taking a double.
|
||||
func callSetDouble(obj uintptr, i int, v float64) uintptr {
|
||||
r, _, _ := syscall.SyscallN(setDoubleThunk, obj, uintptr(math.Float64bits(v)), method(obj, i))
|
||||
return r
|
||||
}
|
||||
|
||||
// callGetDouble calls method i of a COM object returning a double.
|
||||
func callGetDouble(obj uintptr, i int) float64 {
|
||||
r, _, _ := syscall.SyscallN(getDoubleThunk, obj, method(obj, i))
|
||||
return math.Float64frombits(uint64(r))
|
||||
}
|
||||
+721
@@ -0,0 +1,721 @@
|
||||
//go:build linux && !android && (amd64 || arm64)
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"sync"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/ebitengine/purego"
|
||||
|
||||
"github.com/egoist/mygo/internal/media"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// On Linux, GStreamer plays the video: a playbin, which demuxes, decodes
|
||||
// (in hardware through VA-API where its plugins are installed), plays the
|
||||
// sound and keeps the clock, with an appsink as its video sink taking
|
||||
// NV12. The appsink hands each frame over as its time comes, on the clock
|
||||
// the sound plays by; a goroutine of the engine's takes it, copies its
|
||||
// planes into memory of its own, 1.5 bytes a pixel, and wakes the window,
|
||||
// whose renderer uploads them as they are and converts them in its
|
||||
// shader. Another goroutine reads the pipeline's messages. No GLib
|
||||
// callback is made, so nothing of Go runs on GStreamer's threads.
|
||||
//
|
||||
// libgstreamer, libgstapp and libgstvideo are loaded with the first video
|
||||
// opened.
|
||||
|
||||
var (
|
||||
gstOnce sync.Once
|
||||
gstErr error
|
||||
|
||||
gstInit func(argc, argv uintptr)
|
||||
gstElementFactoryMake func(factory, 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, err, debug *uintptr)
|
||||
gstMessageParseBuffering func(msg uintptr, percent *int32)
|
||||
gstMiniObjectUnref func(obj uintptr)
|
||||
gstObjectUnref func(obj uintptr)
|
||||
gstElementSeek func(el uintptr, rate float64, format, flags, startType int32, start int64, stopType int32, stop int64) bool
|
||||
gstElementQueryPosition func(el uintptr, format int32, cur *int64) bool
|
||||
gstElementQueryDuration func(el uintptr, format int32, dur *int64) bool
|
||||
gstCapsFromString func(s string) uintptr
|
||||
gstSampleGetBuffer func(sample uintptr) uintptr
|
||||
gstSampleGetCaps func(sample uintptr) uintptr
|
||||
gstBufferMap func(buf uintptr, info *gstMapInfo, flags int32) bool
|
||||
gstBufferUnmap func(buf uintptr, info *gstMapInfo)
|
||||
gstAppSinkSetCaps func(sink, caps uintptr)
|
||||
gstAppSinkSetMaxBuffers func(sink uintptr, n uint32)
|
||||
gstAppSinkSetDrop func(sink uintptr, drop bool)
|
||||
gstAppSinkTryPullSample func(sink uintptr, timeout uint64) uintptr
|
||||
gstSampleGetType func() uintptr
|
||||
gstAppSinkIsEOS func(sink uintptr) bool
|
||||
gObjectGetProperty func(obj uintptr, name string, v *gValue)
|
||||
gValueDupBoxed func(v *gValue) uintptr
|
||||
gstBufferGetVideoMeta func(buf uintptr) uintptr
|
||||
gstVideoInfoNew func() uintptr
|
||||
gstVideoInfoFromCaps func(info, caps uintptr) bool
|
||||
gstVideoInfoFree func(info uintptr)
|
||||
gObjectSetProperty func(obj uintptr, name string, v *gValue)
|
||||
gValueInit func(v *gValue, t uintptr) *gValue
|
||||
gValueUnset func(v *gValue)
|
||||
gValueSetString func(v *gValue, s string)
|
||||
gValueSetObject func(v *gValue, obj uintptr)
|
||||
gValueSetDouble func(v *gValue, d float64)
|
||||
gValueSetBoolean func(v *gValue, b bool)
|
||||
gErrorFree func(err uintptr)
|
||||
gFree func(p uintptr)
|
||||
)
|
||||
|
||||
const (
|
||||
gstStateNull = 1
|
||||
gstStatePaused = 3
|
||||
gstStatePlaying = 4
|
||||
|
||||
gstFormatTime = 3
|
||||
|
||||
gstSeekFlagFlush = 1
|
||||
gstSeekFlagAccurate = 2
|
||||
gstSeekTypeNone = 0
|
||||
gstSeekTypeSet = 1
|
||||
|
||||
gstMessageEOS = 1 << 0
|
||||
gstMessageError = 1 << 1
|
||||
gstMessageBuffering = 1 << 5
|
||||
gstMessageDurationChanged = 1 << 18
|
||||
gstMessageAsyncDone = 1 << 21
|
||||
|
||||
gTypeBoolean = 5 << 2
|
||||
gTypeDouble = 15 << 2
|
||||
gTypeString = 16 << 2
|
||||
gTypeObject = 20 << 2
|
||||
|
||||
gstMapRead = 1
|
||||
|
||||
// gstMessageTypeOffset is where a GstMessage keeps its type, after
|
||||
// its GstMiniObject (GST_MESSAGE_TYPE).
|
||||
gstMessageTypeOffset = 64
|
||||
// gstBufferPTSOffset is where a GstBuffer keeps its PTS, after its
|
||||
// GstMiniObject and pool (GST_BUFFER_PTS).
|
||||
gstBufferPTSOffset = 72
|
||||
)
|
||||
|
||||
// gValue is a GValue: its type, and two words of value.
|
||||
type gValue struct {
|
||||
typ uintptr
|
||||
data [2]uint64
|
||||
}
|
||||
|
||||
// gstMapInfo is a GstMapInfo.
|
||||
type gstMapInfo struct {
|
||||
memory uintptr
|
||||
flags int32
|
||||
_ int32
|
||||
data unsafe.Pointer
|
||||
size uintptr
|
||||
maxsize uintptr
|
||||
user [4]uintptr
|
||||
reserved [4]uintptr
|
||||
}
|
||||
|
||||
func loadGStreamer() error {
|
||||
gstOnce.Do(func() {
|
||||
var libs [5]uintptr
|
||||
for i, name := range []string{"libgstreamer-1.0.so.0", "libgstapp-1.0.so.0", "libgstvideo-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("%w: %v", ErrUnsupported, err)
|
||||
return
|
||||
}
|
||||
libs[i] = h
|
||||
}
|
||||
defer func() {
|
||||
if v := recover(); v != nil {
|
||||
gstErr = fmt.Errorf("%w: %v", ErrUnsupported, v)
|
||||
}
|
||||
}()
|
||||
gst, app, video, gobject, glib := libs[0], libs[1], libs[2], libs[3], libs[4]
|
||||
purego.RegisterLibFunc(&gstInit, gst, "gst_init")
|
||||
purego.RegisterLibFunc(&gstElementFactoryMake, gst, "gst_element_factory_make")
|
||||
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(&gstMessageParseBuffering, gst, "gst_message_parse_buffering")
|
||||
purego.RegisterLibFunc(&gstMiniObjectUnref, gst, "gst_mini_object_unref")
|
||||
purego.RegisterLibFunc(&gstObjectUnref, gst, "gst_object_unref")
|
||||
purego.RegisterLibFunc(&gstElementSeek, gst, "gst_element_seek")
|
||||
purego.RegisterLibFunc(&gstElementQueryPosition, gst, "gst_element_query_position")
|
||||
purego.RegisterLibFunc(&gstElementQueryDuration, gst, "gst_element_query_duration")
|
||||
purego.RegisterLibFunc(&gstCapsFromString, gst, "gst_caps_from_string")
|
||||
purego.RegisterLibFunc(&gstSampleGetBuffer, gst, "gst_sample_get_buffer")
|
||||
purego.RegisterLibFunc(&gstSampleGetCaps, gst, "gst_sample_get_caps")
|
||||
purego.RegisterLibFunc(&gstBufferMap, gst, "gst_buffer_map")
|
||||
purego.RegisterLibFunc(&gstBufferUnmap, gst, "gst_buffer_unmap")
|
||||
purego.RegisterLibFunc(&gstAppSinkSetCaps, app, "gst_app_sink_set_caps")
|
||||
purego.RegisterLibFunc(&gstAppSinkSetMaxBuffers, app, "gst_app_sink_set_max_buffers")
|
||||
purego.RegisterLibFunc(&gstAppSinkSetDrop, app, "gst_app_sink_set_drop")
|
||||
purego.RegisterLibFunc(&gstAppSinkTryPullSample, app, "gst_app_sink_try_pull_sample")
|
||||
purego.RegisterLibFunc(&gstSampleGetType, gst, "gst_sample_get_type")
|
||||
purego.RegisterLibFunc(&gstAppSinkIsEOS, app, "gst_app_sink_is_eos")
|
||||
purego.RegisterLibFunc(&gObjectGetProperty, gobject, "g_object_get_property")
|
||||
purego.RegisterLibFunc(&gValueDupBoxed, gobject, "g_value_dup_boxed")
|
||||
purego.RegisterLibFunc(&gstBufferGetVideoMeta, video, "gst_buffer_get_video_meta")
|
||||
purego.RegisterLibFunc(&gstVideoInfoNew, video, "gst_video_info_new")
|
||||
purego.RegisterLibFunc(&gstVideoInfoFromCaps, video, "gst_video_info_from_caps")
|
||||
purego.RegisterLibFunc(&gstVideoInfoFree, video, "gst_video_info_free")
|
||||
purego.RegisterLibFunc(&gObjectSetProperty, gobject, "g_object_set_property")
|
||||
purego.RegisterLibFunc(&gValueInit, gobject, "g_value_init")
|
||||
purego.RegisterLibFunc(&gValueUnset, gobject, "g_value_unset")
|
||||
purego.RegisterLibFunc(&gValueSetString, gobject, "g_value_set_string")
|
||||
purego.RegisterLibFunc(&gValueSetObject, gobject, "g_value_set_object")
|
||||
purego.RegisterLibFunc(&gValueSetDouble, gobject, "g_value_set_double")
|
||||
purego.RegisterLibFunc(&gValueSetBoolean, gobject, "g_value_set_boolean")
|
||||
purego.RegisterLibFunc(&gErrorFree, glib, "g_error_free")
|
||||
purego.RegisterLibFunc(&gFree, glib, "g_free")
|
||||
gstInit(0, 0)
|
||||
})
|
||||
return gstErr
|
||||
}
|
||||
|
||||
// setProperty sets a property of a GObject from a GValue of type t that
|
||||
// set fills.
|
||||
func setProperty(obj uintptr, name string, t uintptr, set func(*gValue)) {
|
||||
var v gValue
|
||||
gValueInit(&v, t)
|
||||
set(&v)
|
||||
gObjectSetProperty(obj, name, &v)
|
||||
gValueUnset(&v)
|
||||
}
|
||||
|
||||
// gstEngine plays a video with a playbin.
|
||||
type gstEngine struct {
|
||||
pipe, sink, bus uintptr
|
||||
// memfd holds the bytes of OpenData, which the playbin reads as a
|
||||
// file of /proc/self/fd; -1 for none.
|
||||
memfd int
|
||||
quit chan struct{}
|
||||
done sync.WaitGroup
|
||||
|
||||
mu sync.Mutex
|
||||
// ring are the frames copied out of the samples: shown is the one
|
||||
// Frame last returned, latest the newest, which the next Frame
|
||||
// returns; the goroutine copies into neither. changed tells latest
|
||||
// is not shown yet.
|
||||
ring [3]gstFrame
|
||||
shown, latest int
|
||||
changed bool
|
||||
w, h int
|
||||
interval time.Duration
|
||||
state media.State
|
||||
err error
|
||||
wake func()
|
||||
wantPlay, loop bool
|
||||
// percent is how full a stream's buffer is, below 100 while it
|
||||
// waits for data.
|
||||
buffering bool
|
||||
// pending are a seek, and a rate, asked for before the pipeline
|
||||
// could take them, once it prerolled (prerolled).
|
||||
prerolled bool
|
||||
seekTo time.Duration
|
||||
seekSet bool
|
||||
rate float64
|
||||
closed bool
|
||||
lastPosNs int64
|
||||
durationNs int64
|
||||
}
|
||||
|
||||
// gstFrame is a frame of the ring: NV12 planes in Go memory.
|
||||
type gstFrame struct {
|
||||
surface scene.Surface
|
||||
w, h int
|
||||
}
|
||||
|
||||
func newEngine(s source) (media.Engine, error) {
|
||||
if err := loadGStreamer(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e := &gstEngine{memfd: -1, shown: -1, latest: -1, quit: make(chan struct{}), rate: 1}
|
||||
uri := s.url
|
||||
if s.data != nil {
|
||||
fd, err := memfd(s.data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
e.memfd = fd
|
||||
uri = fmt.Sprintf("file:///proc/%d/fd/%d", os.Getpid(), fd)
|
||||
}
|
||||
e.pipe = gstElementFactoryMake("playbin", "")
|
||||
e.sink = gstElementFactoryMake("appsink", "")
|
||||
if e.pipe == 0 || e.sink == 0 {
|
||||
e.free()
|
||||
return nil, fmt.Errorf("%w: GStreamer has no playbin or appsink (gst-plugins-base)", ErrUnsupported)
|
||||
}
|
||||
caps := gstCapsFromString("video/x-raw,format=NV12")
|
||||
gstAppSinkSetCaps(e.sink, caps)
|
||||
gstMiniObjectUnref(caps)
|
||||
gstAppSinkSetMaxBuffers(e.sink, 1)
|
||||
gstAppSinkSetDrop(e.sink, true)
|
||||
setProperty(e.pipe, "video-sink", gTypeObject, func(v *gValue) { gValueSetObject(v, e.sink) })
|
||||
if st := gstElementFactoryMake("scaletempo", ""); st != 0 {
|
||||
// The sound at another rate keeps its pitch.
|
||||
setProperty(e.pipe, "audio-filter", gTypeObject, func(v *gValue) { gValueSetObject(v, st) })
|
||||
}
|
||||
setProperty(e.pipe, "uri", gTypeString, func(v *gValue) { gValueSetString(v, uri) })
|
||||
e.bus = gstElementGetBus(e.pipe)
|
||||
gstElementSetState(e.pipe, gstStatePaused)
|
||||
e.done.Add(2)
|
||||
go e.pull()
|
||||
go e.messages()
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// memfd returns a file in memory holding data.
|
||||
func memfd(data []byte) (int, error) {
|
||||
name := []byte("mygo-video\x00")
|
||||
fd, _, errno := syscall.Syscall(sysMemfdCreate, uintptr(unsafe.Pointer(&name[0])), 1 /* MFD_CLOEXEC */, 0)
|
||||
runtime.KeepAlive(name)
|
||||
if errno != 0 {
|
||||
return -1, fmt.Errorf("video: memfd_create: %w", errno)
|
||||
}
|
||||
f := os.NewFile(fd, "mygo-video")
|
||||
if _, err := f.Write(data); err != nil {
|
||||
f.Close()
|
||||
return -1, err
|
||||
}
|
||||
// The file stays open, as its descriptor; f must not close it when
|
||||
// collected.
|
||||
nfd, err := syscall.Dup(int(fd))
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
return nfd, nil
|
||||
}
|
||||
|
||||
// pull takes the frames the appsink hands over as their times come and,
|
||||
// while none comes, the frame the sink holds last, which is the one a
|
||||
// paused pipeline prerolled after loading or a seek: taken once each.
|
||||
func (e *gstEngine) pull() {
|
||||
defer e.done.Done()
|
||||
var lastBuf uintptr
|
||||
lastPTS := ^uint64(0)
|
||||
for {
|
||||
select {
|
||||
case <-e.quit:
|
||||
return
|
||||
default:
|
||||
}
|
||||
s := gstAppSinkTryPullSample(e.sink, uint64(20*time.Millisecond))
|
||||
if s == 0 && gstAppSinkIsEOS(e.sink) {
|
||||
// Which returns at once: nothing comes until a seek.
|
||||
select {
|
||||
case <-e.quit:
|
||||
return
|
||||
case <-time.After(20 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
if s == 0 {
|
||||
s = lastSample(e.sink)
|
||||
}
|
||||
if s == 0 {
|
||||
continue
|
||||
}
|
||||
if buf := gstSampleGetBuffer(s); buf != 0 {
|
||||
pts := *(*uint64)(unsafe.Add(cptr(buf), gstBufferPTSOffset))
|
||||
if buf != lastBuf || pts != lastPTS {
|
||||
lastBuf, lastPTS = buf, pts
|
||||
e.take(s)
|
||||
}
|
||||
}
|
||||
gstMiniObjectUnref(s)
|
||||
}
|
||||
}
|
||||
|
||||
// lastSample returns a reference to the sample a sink holds last, or 0.
|
||||
func lastSample(sink uintptr) uintptr {
|
||||
var v gValue
|
||||
gValueInit(&v, gstSampleGetType())
|
||||
gObjectGetProperty(sink, "last-sample", &v)
|
||||
s := gValueDupBoxed(&v)
|
||||
gValueUnset(&v)
|
||||
return s
|
||||
}
|
||||
|
||||
// take copies a sample's planes into a frame of the ring, which becomes
|
||||
// the latest, and wakes the window.
|
||||
func (e *gstEngine) take(sample uintptr) {
|
||||
buf, caps := gstSampleGetBuffer(sample), gstSampleGetCaps(sample)
|
||||
if buf == 0 || caps == 0 {
|
||||
return
|
||||
}
|
||||
info := gstVideoInfoNew()
|
||||
defer gstVideoInfoFree(info)
|
||||
if !gstVideoInfoFromCaps(info, caps) {
|
||||
return
|
||||
}
|
||||
vi := unsafe.Slice((*byte)(cptr(info)), 152)
|
||||
w, h := int(int32(le32(vi[16:]))), int(int32(le32(vi[20:])))
|
||||
rng, matrix := le32(vi[40:]), le32(vi[44:])
|
||||
fpsN, fpsD := int32(le32(vi[64:])), int32(le32(vi[68:]))
|
||||
offset := [2]uintptr{uintptr(le64(vi[72:])), uintptr(le64(vi[80:]))}
|
||||
stride := [2]int{int(int32(le32(vi[104:]))), int(int32(le32(vi[108:])))}
|
||||
if meta := gstBufferGetVideoMeta(buf); meta != 0 {
|
||||
m := unsafe.Slice((*byte)(cptr(meta)), 96)
|
||||
offset = [2]uintptr{uintptr(le64(m[48:])), uintptr(le64(m[56:]))}
|
||||
stride = [2]int{int(int32(le32(m[80:]))), int(int32(le32(m[84:])))}
|
||||
}
|
||||
if w <= 0 || h <= 0 {
|
||||
return
|
||||
}
|
||||
var mi gstMapInfo
|
||||
if !gstBufferMap(buf, &mi, gstMapRead) {
|
||||
return
|
||||
}
|
||||
defer gstBufferUnmap(buf, &mi)
|
||||
cw, ch := (w+1)/2, (h+1)/2
|
||||
if offset[0]+uintptr(stride[0]*(h-1)+w) > mi.size || offset[1]+uintptr(stride[1]*(ch-1)+2*cw) > mi.size {
|
||||
return
|
||||
}
|
||||
data := unsafe.Slice((*byte)(mi.data), mi.size)
|
||||
|
||||
e.mu.Lock()
|
||||
i := 0
|
||||
for i == e.shown || i == e.latest {
|
||||
i++
|
||||
}
|
||||
e.mu.Unlock()
|
||||
f := &e.ring[i]
|
||||
f.w, f.h = w, h
|
||||
s := &f.surface
|
||||
s.Format = scene.SurfaceNV12
|
||||
s.Matrix = gstMatrix(matrix, h)
|
||||
if rng == 1 { // GST_VIDEO_COLOR_RANGE_0_255
|
||||
s.Matrix += scene.FullRange
|
||||
}
|
||||
planes := [2]struct{ rowBytes, rows int }{{w, h}, {2 * cw, ch}}
|
||||
for p, pl := range planes {
|
||||
n := pl.rowBytes * pl.rows
|
||||
if cap(s.Planes[p].Pix) < n {
|
||||
s.Planes[p].Pix = make([]byte, n)
|
||||
}
|
||||
dst := s.Planes[p].Pix[:n]
|
||||
for y := range pl.rows {
|
||||
copy(dst[y*pl.rowBytes:][:pl.rowBytes], data[offset[p]+uintptr(y*stride[p]):][:pl.rowBytes])
|
||||
}
|
||||
s.Planes[p] = scene.Plane{Pix: dst, Stride: pl.rowBytes}
|
||||
}
|
||||
|
||||
e.mu.Lock()
|
||||
e.latest, e.changed = i, true
|
||||
e.w, e.h = w, h
|
||||
if fpsN > 0 && fpsD > 0 {
|
||||
e.interval = time.Duration(int64(time.Second) * int64(fpsD) / int64(fpsN))
|
||||
}
|
||||
if e.state == media.Loading {
|
||||
e.state = media.Ready
|
||||
}
|
||||
wake := e.wake
|
||||
e.mu.Unlock()
|
||||
if wake != nil {
|
||||
wake()
|
||||
}
|
||||
}
|
||||
|
||||
// gstMatrix is the YUV matrix of a GstVideoColorMatrix, or for an unknown
|
||||
// one that of the video's size, as players guess it.
|
||||
func gstMatrix(m uint32, h int) scene.YUVMatrix {
|
||||
switch m {
|
||||
case 3:
|
||||
return scene.BT709
|
||||
case 4:
|
||||
return scene.BT601
|
||||
case 6:
|
||||
return scene.BT2020
|
||||
}
|
||||
if h >= 720 {
|
||||
return scene.BT709
|
||||
}
|
||||
return scene.BT601
|
||||
}
|
||||
|
||||
func le32(b []byte) uint32 {
|
||||
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
|
||||
}
|
||||
func le64(b []byte) uint64 { return uint64(le32(b)) | uint64(le32(b[4:]))<<32 }
|
||||
|
||||
// messages reads what the pipeline reports: that it prerolled, its end,
|
||||
// an error, a stream's buffering.
|
||||
func (e *gstEngine) messages() {
|
||||
defer e.done.Done()
|
||||
const types = gstMessageEOS | gstMessageError | gstMessageBuffering | gstMessageDurationChanged | gstMessageAsyncDone
|
||||
for {
|
||||
select {
|
||||
case <-e.quit:
|
||||
return
|
||||
default:
|
||||
}
|
||||
msg := gstBusTimedPopFiltered(e.bus, uint64(50*time.Millisecond), types)
|
||||
if msg == 0 {
|
||||
continue
|
||||
}
|
||||
kind := *(*uint32)(unsafe.Add(cptr(msg), gstMessageTypeOffset))
|
||||
e.handle(msg, kind)
|
||||
gstMiniObjectUnref(msg)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *gstEngine) handle(msg uintptr, kind uint32) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
switch kind {
|
||||
case gstMessageAsyncDone:
|
||||
// Prerolled, after loading or a seek: a seek the pipeline did
|
||||
// not take yet goes now.
|
||||
first := !e.prerolled
|
||||
e.prerolled = true
|
||||
if e.seekSet || first && e.rate != 1 {
|
||||
e.seekLocked(e.seekTo)
|
||||
}
|
||||
case gstMessageEOS:
|
||||
if e.loop {
|
||||
e.seekLocked(0)
|
||||
} else {
|
||||
e.state = media.Ended
|
||||
}
|
||||
case gstMessageError:
|
||||
var gerr, debug uintptr
|
||||
gstMessageParseError(msg, &gerr, &debug)
|
||||
text := "GStreamer could not play the video"
|
||||
if gerr != 0 {
|
||||
if p := *(**byte)(unsafe.Add(cptr(gerr), 8)); p != nil {
|
||||
text = goString(p)
|
||||
}
|
||||
gErrorFree(gerr)
|
||||
}
|
||||
if debug != 0 {
|
||||
gFree(debug)
|
||||
}
|
||||
e.state, e.err = media.Failed, errors.New("video: "+text)
|
||||
case gstMessageBuffering:
|
||||
var percent int32
|
||||
gstMessageParseBuffering(msg, &percent)
|
||||
e.buffering = percent < 100
|
||||
switch {
|
||||
case e.buffering && e.state == media.Ready:
|
||||
e.state = media.Buffering
|
||||
case !e.buffering && e.state == media.Buffering:
|
||||
e.state = media.Ready
|
||||
}
|
||||
e.applyState()
|
||||
case gstMessageDurationChanged:
|
||||
e.durationNs = 0
|
||||
}
|
||||
if e.wake != nil {
|
||||
go e.wake()
|
||||
}
|
||||
}
|
||||
|
||||
// cptr is the pointer of an address of C memory, which Go's collector
|
||||
// does not move.
|
||||
func cptr(a uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&a)) }
|
||||
|
||||
func goString(p *byte) string {
|
||||
n := 0
|
||||
for *(*byte)(unsafe.Add(unsafe.Pointer(p), n)) != 0 {
|
||||
n++
|
||||
}
|
||||
return string(unsafe.Slice(p, n))
|
||||
}
|
||||
|
||||
// applyState plays the pipeline when the player plays it, unless a
|
||||
// stream fills its buffer.
|
||||
func (e *gstEngine) applyState() {
|
||||
if e.closed {
|
||||
return
|
||||
}
|
||||
|
||||
if e.wantPlay && !e.buffering && e.state != media.Ended {
|
||||
gstElementSetState(e.pipe, gstStatePlaying)
|
||||
} else {
|
||||
gstElementSetState(e.pipe, gstStatePaused)
|
||||
}
|
||||
}
|
||||
|
||||
func (e *gstEngine) SetWake(wake func()) {
|
||||
e.mu.Lock()
|
||||
e.wake = wake
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *gstEngine) Frame(time.Time) (media.Picture, bool, bool) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.latest < 0 {
|
||||
return media.Picture{}, false, false
|
||||
}
|
||||
changed := e.changed
|
||||
e.shown, e.changed = e.latest, false
|
||||
f := &e.ring[e.shown]
|
||||
s := &f.surface
|
||||
w, h := f.w, f.h
|
||||
return media.Picture{Surface: s, W: w, H: h, RGBA: func(dst []byte) []byte { return s.RGBA(dst, w, h) }}, changed, true
|
||||
}
|
||||
|
||||
func (e *gstEngine) Interval() time.Duration { return 0 } // the appsink wakes the window
|
||||
|
||||
func (e *gstEngine) State() (media.State, error) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return e.state, e.err
|
||||
}
|
||||
|
||||
func (e *gstEngine) Size() (int, int) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return e.w, e.h
|
||||
}
|
||||
|
||||
func (e *gstEngine) Duration() time.Duration {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.durationNs <= 0 && !e.closed {
|
||||
var d int64
|
||||
if gstElementQueryDuration(e.pipe, gstFormatTime, &d) && d > 0 {
|
||||
e.durationNs = d
|
||||
}
|
||||
}
|
||||
return time.Duration(max(e.durationNs, 0))
|
||||
}
|
||||
|
||||
func (e *gstEngine) Position() time.Duration {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.closed {
|
||||
return time.Duration(e.lastPosNs)
|
||||
}
|
||||
if !e.prerolled && e.seekSet {
|
||||
return e.seekTo
|
||||
}
|
||||
var p int64
|
||||
if gstElementQueryPosition(e.pipe, gstFormatTime, &p) && p >= 0 {
|
||||
e.lastPosNs = p
|
||||
}
|
||||
return time.Duration(e.lastPosNs)
|
||||
}
|
||||
|
||||
func (e *gstEngine) Play() {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.wantPlay = true
|
||||
if e.state == media.Ended {
|
||||
e.state = media.Ready
|
||||
e.seekLocked(0)
|
||||
}
|
||||
e.applyState()
|
||||
}
|
||||
|
||||
func (e *gstEngine) Pause() {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
e.wantPlay = false
|
||||
e.applyState()
|
||||
}
|
||||
|
||||
func (e *gstEngine) Seek(d time.Duration) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if e.state == media.Ended {
|
||||
e.state = media.Ready
|
||||
}
|
||||
e.seekLocked(d)
|
||||
e.applyState()
|
||||
}
|
||||
|
||||
// seekLocked seeks the pipeline to d at the rate, or keeps d for once it
|
||||
// prerolled.
|
||||
func (e *gstEngine) seekLocked(d time.Duration) {
|
||||
|
||||
if e.closed {
|
||||
return
|
||||
}
|
||||
e.seekTo, e.seekSet = d, true
|
||||
e.lastPosNs = int64(d)
|
||||
if !e.prerolled {
|
||||
return
|
||||
}
|
||||
if gstElementSeek(e.pipe, e.rate, gstFormatTime, gstSeekFlagFlush|gstSeekFlagAccurate, gstSeekTypeSet, int64(d), gstSeekTypeNone, -1) {
|
||||
e.seekSet = false
|
||||
}
|
||||
}
|
||||
|
||||
func (e *gstEngine) SetLoop(loop bool) {
|
||||
e.mu.Lock()
|
||||
e.loop = loop
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *gstEngine) SetRate(r float64) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
if r == e.rate {
|
||||
return
|
||||
}
|
||||
e.rate = r
|
||||
if e.prerolled {
|
||||
var p int64
|
||||
gstElementQueryPosition(e.pipe, gstFormatTime, &p)
|
||||
e.seekLocked(time.Duration(max(p, 0)))
|
||||
}
|
||||
}
|
||||
|
||||
func (e *gstEngine) SetVolume(v float64) {
|
||||
setProperty(e.pipe, "volume", gTypeDouble, func(g *gValue) { gValueSetDouble(g, v) })
|
||||
}
|
||||
|
||||
func (e *gstEngine) SetMuted(m bool) {
|
||||
setProperty(e.pipe, "mute", gTypeBoolean, func(g *gValue) { gValueSetBoolean(g, m) })
|
||||
}
|
||||
|
||||
// Close stops the goroutines, then the pipeline, which may take a moment.
|
||||
func (e *gstEngine) Close() error {
|
||||
e.mu.Lock()
|
||||
if e.closed {
|
||||
e.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
e.closed = true
|
||||
e.wake = nil
|
||||
e.mu.Unlock()
|
||||
close(e.quit)
|
||||
e.done.Wait()
|
||||
gstElementSetState(e.pipe, gstStateNull)
|
||||
e.free()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *gstEngine) free() {
|
||||
if e.bus != 0 {
|
||||
gstObjectUnref(e.bus)
|
||||
e.bus = 0
|
||||
}
|
||||
if e.pipe != 0 {
|
||||
gstObjectUnref(e.pipe) // and the sink it took
|
||||
e.pipe, e.sink = 0, 0
|
||||
} else if e.sink != 0 {
|
||||
gstObjectUnref(e.sink)
|
||||
e.sink = 0
|
||||
}
|
||||
if e.memfd >= 0 {
|
||||
syscall.Close(e.memfd)
|
||||
e.memfd = -1
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/media/mediatest"
|
||||
)
|
||||
|
||||
func TestMain(m *testing.M) { mediatest.Main(m) }
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build linux && amd64
|
||||
|
||||
package video
|
||||
|
||||
const sysMemfdCreate = 319
|
||||
@@ -0,0 +1,5 @@
|
||||
//go:build linux && !android && arm64
|
||||
|
||||
package video
|
||||
|
||||
const sysMemfdCreate = 279
|
||||
+704
@@ -0,0 +1,704 @@
|
||||
//go:build windows && (amd64 || arm64)
|
||||
|
||||
package video
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"math"
|
||||
"runtime"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"syscall"
|
||||
"time"
|
||||
"unsafe"
|
||||
|
||||
"github.com/egoist/mygo/internal/gpu/d3d11/device"
|
||||
"github.com/egoist/mygo/internal/media"
|
||||
"github.com/egoist/mygo/internal/scene"
|
||||
)
|
||||
|
||||
// On Windows, Media Foundation plays the video: an IMFMediaEngine in
|
||||
// frame-server mode, which decodes on a Direct3D 11 device of the
|
||||
// engine's own (in hardware, through DXVA, where the GPU has it), plays
|
||||
// the sound and keeps the clock. As each frame of the window builds, the
|
||||
// engine converts the picture due into a texture in BGRA of a ring of
|
||||
// three (TransferVideoFrame, a copy on the GPU), each shared with the
|
||||
// window's device by an NT handle and ordered by a keyed mutex (key 0),
|
||||
// which the renderer opens once and reads where it is. The engine's
|
||||
// events reach Go through one COM object, made once, that wakes the
|
||||
// window.
|
||||
|
||||
const ringSize = 3
|
||||
|
||||
var (
|
||||
mfOnce sync.Once
|
||||
mfErr error
|
||||
|
||||
mfplat = syscall.NewLazyDLL(device.SystemDir() + `\mfplat.dll`)
|
||||
ole32 = syscall.NewLazyDLL(device.SystemDir() + `\ole32.dll`)
|
||||
oleaut32 = syscall.NewLazyDLL(device.SystemDir() + `\oleaut32.dll`)
|
||||
shlwapi = syscall.NewLazyDLL(device.SystemDir() + `\shlwapi.dll`)
|
||||
|
||||
procMFStartup = mfplat.NewProc("MFStartup")
|
||||
procMFCreateDXGIDeviceManager = mfplat.NewProc("MFCreateDXGIDeviceManager")
|
||||
procMFCreateAttributes = mfplat.NewProc("MFCreateAttributes")
|
||||
procMFCreateMFByteStreamOnStream = mfplat.NewProc("MFCreateMFByteStreamOnStream")
|
||||
procCoInitializeEx = ole32.NewProc("CoInitializeEx")
|
||||
procCoCreateInstance = ole32.NewProc("CoCreateInstance")
|
||||
procCoTaskMemAlloc = ole32.NewProc("CoTaskMemAlloc")
|
||||
procCoTaskMemFree = ole32.NewProc("CoTaskMemFree")
|
||||
procSysAllocString = oleaut32.NewProc("SysAllocString")
|
||||
procSysFreeString = oleaut32.NewProc("SysFreeString")
|
||||
procSHCreateMemStream = shlwapi.NewProc("SHCreateMemStream")
|
||||
|
||||
// notifyVtbl is the vtable of the engines' IMFMediaEngineNotify
|
||||
// objects, and engines the engines by the number each object holds.
|
||||
notifyVtbl [4]uintptr
|
||||
engines sync.Map // uint64 → *mfEngine
|
||||
lastEngine atomic.Uint64
|
||||
lastShared atomic.Uint64
|
||||
)
|
||||
|
||||
type guid struct {
|
||||
Data1 uint32
|
||||
Data2 uint16
|
||||
Data3 uint16
|
||||
Data4 [8]byte
|
||||
}
|
||||
|
||||
var (
|
||||
clsidMFMediaEngineClassFactory = guid{0xb44392da, 0x499b, 0x446b, [8]byte{0xa4, 0xcb, 0x00, 0x5f, 0xea, 0xd0, 0xe6, 0xd5}}
|
||||
iidIMFMediaEngineClassFactory = guid{0x4d645ace, 0x26aa, 0x4688, [8]byte{0x9b, 0xe1, 0xdf, 0x35, 0x16, 0x99, 0x0b, 0x93}}
|
||||
iidIMFMediaEngineNotify = guid{0xfee7c112, 0xe776, 0x42b5, [8]byte{0x9b, 0xbf, 0x00, 0x48, 0x52, 0x4e, 0x2b, 0xd5}}
|
||||
iidIMFMediaEngineEx = guid{0x83015ead, 0xb1e6, 0x40d0, [8]byte{0xa9, 0x8a, 0x37, 0x14, 0x5f, 0xfe, 0x1a, 0xd1}}
|
||||
iidIUnknown = guid{0, 0, 0, [8]byte{0xc0, 0, 0, 0, 0, 0, 0, 0x46}}
|
||||
iidID3D10Multithread = guid{0x9b7e4e00, 0x342c, 0x4106, [8]byte{0xa1, 0x9f, 0x4f, 0x27, 0x04, 0xf6, 0x89, 0xf0}}
|
||||
iidIDXGIKeyedMutex = guid{0x9d8e1289, 0xd7b3, 0x465f, [8]byte{0x81, 0x26, 0x25, 0x0e, 0x34, 0x9a, 0xf8, 0x5d}}
|
||||
iidIDXGIResource1 = guid{0x30961379, 0x4609, 0x4a41, [8]byte{0x99, 0x8e, 0x54, 0xfe, 0x56, 0x7e, 0xe0, 0xc1}}
|
||||
mfMediaEngineCallback = guid{0xc60381b8, 0x83a4, 0x41f8, [8]byte{0xa3, 0xd0, 0xde, 0x05, 0x07, 0x68, 0x49, 0xa9}}
|
||||
mfMediaEngineDXGIManager = guid{0x065702da, 0x1094, 0x486d, [8]byte{0x86, 0x17, 0xee, 0x7c, 0xc4, 0xee, 0x46, 0x48}}
|
||||
mfMediaEngineVideoOutputFormat = guid{0x5066893c, 0x8cf9, 0x42bc, [8]byte{0x8b, 0x8a, 0x47, 0x22, 0x12, 0xe5, 0x27, 0x26}}
|
||||
)
|
||||
|
||||
// The methods of the interfaces, by their places in the vtables.
|
||||
const (
|
||||
comQueryInterface = 0
|
||||
comRelease = 2
|
||||
|
||||
attrSetUINT32 = 21
|
||||
attrSetUnknown = 27
|
||||
|
||||
managerResetDevice = 7
|
||||
|
||||
factoryCreateInstance = 3
|
||||
|
||||
engineGetError = 3
|
||||
engineSetSource = 6
|
||||
engineIsSeeking = 15
|
||||
engineGetCurrentTime = 16
|
||||
engineSetCurrentTime = 17
|
||||
engineGetDuration = 19
|
||||
engineIsPaused = 20
|
||||
engineSetDefaultRate = 22
|
||||
engineSetPlaybackRate = 24
|
||||
engineIsEnded = 27
|
||||
engineSetLoop = 31
|
||||
enginePlay = 32
|
||||
enginePause = 33
|
||||
engineSetMuted = 35
|
||||
engineSetVolume = 37
|
||||
engineGetNativeVideoSize = 40
|
||||
engineShutdown = 42
|
||||
engineTransferVideoFrame = 43
|
||||
engineOnVideoStreamTick = 44
|
||||
engineExSetSourceFromByte = 45
|
||||
engineExFrameStep = 51
|
||||
|
||||
errorGetErrorCode = 3
|
||||
errorGetExtendedCode = 4
|
||||
|
||||
multithreadSetProtected = 5
|
||||
|
||||
devCreateTexture2D = 5
|
||||
devGetImmediateContext = 40
|
||||
ctxMap = 14
|
||||
ctxUnmap = 15
|
||||
ctxCopyResource = 47
|
||||
|
||||
keyedAcquireSync = 8
|
||||
keyedReleaseSync = 9
|
||||
|
||||
resourceCreateSharedHandle = 13
|
||||
)
|
||||
|
||||
// Media engine events (MF_MEDIA_ENGINE_EVENT).
|
||||
const (
|
||||
eventError = 5
|
||||
eventLoadedMetadata = 10
|
||||
eventLoadedData = 11
|
||||
eventWaiting = 12
|
||||
eventPlaying = 13
|
||||
eventCanPlay = 14
|
||||
eventSeeked = 17
|
||||
eventEnded = 19
|
||||
eventDurationChange = 21
|
||||
|
||||
eventFrameStepCompleted = 1007
|
||||
)
|
||||
|
||||
type texture2DDesc struct {
|
||||
Width, Height, MipLevels, ArraySize, Format, SampleCount, SampleQuality, Usage, BindFlags, CPUAccessFlags, MiscFlags uint32
|
||||
}
|
||||
|
||||
func failed(hr uintptr) bool { return int32(uint32(hr)) < 0 }
|
||||
|
||||
// cptr is the pointer of an address of native memory.
|
||||
func cptr(a uintptr) unsafe.Pointer { return *(*unsafe.Pointer)(unsafe.Pointer(&a)) }
|
||||
|
||||
// call calls method i of a COM object, returning its HRESULT, and what
|
||||
// the call left in the first floating point register on amd64. 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 {
|
||||
r, _ := callRaw(obj, i, args...)
|
||||
return r
|
||||
}
|
||||
|
||||
func callRaw(obj uintptr, i int, args ...uintptr) (uintptr, uintptr) {
|
||||
fn := method(obj, i)
|
||||
a := make([]uintptr, 0, len(args)+1)
|
||||
a = append(a, obj)
|
||||
a = append(a, args...)
|
||||
r1, r2, _ := syscall.SyscallN(fn, a...)
|
||||
return r1, r2
|
||||
}
|
||||
|
||||
func method(obj uintptr, i int) uintptr {
|
||||
vtbl := *(*uintptr)(cptr(obj))
|
||||
return *(*uintptr)(cptr(vtbl + uintptr(i)*unsafe.Sizeof(uintptr(0))))
|
||||
}
|
||||
|
||||
func free(p *uintptr) {
|
||||
if *p != 0 {
|
||||
call(*p, comRelease)
|
||||
*p = 0
|
||||
}
|
||||
}
|
||||
|
||||
func loadMediaFoundation() error {
|
||||
mfOnce.Do(func() {
|
||||
for _, p := range []*syscall.LazyProc{procMFStartup, procMFCreateDXGIDeviceManager, procMFCreateAttributes, procMFCreateMFByteStreamOnStream, procCoCreateInstance, procSysAllocString, procSHCreateMemStream} {
|
||||
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("%w: %v", ErrUnsupported, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
const mfVersion, mfStartupFull = 0x00020070, 0
|
||||
if hr, _, _ := procMFStartup.Call(mfVersion, mfStartupFull); failed(hr) {
|
||||
mfErr = fmt.Errorf("%w: MFStartup: %#x", ErrUnsupported, uint32(hr))
|
||||
return
|
||||
}
|
||||
if err := loadFloatCalls(); err != nil {
|
||||
mfErr = err
|
||||
return
|
||||
}
|
||||
notifyVtbl = [4]uintptr{
|
||||
syscall.NewCallback(notifyQueryInterface),
|
||||
syscall.NewCallback(notifyAddRef),
|
||||
syscall.NewCallback(notifyAddRef), // Release: the engine frees it
|
||||
syscall.NewCallback(notifyEvent),
|
||||
}
|
||||
})
|
||||
return mfErr
|
||||
}
|
||||
|
||||
func notifyQueryInterface(this, riid, out uintptr) uintptr {
|
||||
g := *(*guid)(cptr(riid))
|
||||
if g == iidIUnknown || g == iidIMFMediaEngineNotify {
|
||||
*(*uintptr)(cptr(out)) = this
|
||||
return 0
|
||||
}
|
||||
*(*uintptr)(cptr(out)) = 0
|
||||
return 0x80004002 // E_NOINTERFACE
|
||||
}
|
||||
|
||||
func notifyAddRef(this uintptr) uintptr { return 1 }
|
||||
|
||||
func notifyEvent(this, event, param1, param2 uintptr) uintptr {
|
||||
id := *(*uint64)(cptr(this + unsafe.Sizeof(uintptr(0))))
|
||||
if v, ok := engines.Load(id); ok {
|
||||
v.(*mfEngine).event(uint32(event), param1, uint32(param2))
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// mfEngine plays a video with an IMFMediaEngine.
|
||||
type mfEngine struct {
|
||||
id uint64
|
||||
engine, ex uintptr // IMFMediaEngine, IMFMediaEngineEx
|
||||
notify uintptr // the IMFMediaEngineNotify, CoTaskMemAlloc'd
|
||||
dev, ctx, manager, mt uintptr
|
||||
staging uintptr // for reading a picture back (RGBA)
|
||||
stagingW, stagingH int
|
||||
|
||||
// ring are the shared textures the engine converts pictures into:
|
||||
// shown the one Frame last returned, -1 for none.
|
||||
ring [ringSize]sharedFrame
|
||||
shown int
|
||||
w, h int
|
||||
|
||||
mu sync.Mutex
|
||||
wake func()
|
||||
state media.State
|
||||
err error
|
||||
loop bool
|
||||
seekTo time.Duration
|
||||
seekSince time.Time // a seek not landed yet, until eventSeeked
|
||||
// landed tells a seek landed (eventSeeked) with no picture since
|
||||
// it, for Frame to step to the picture there if the engine has none.
|
||||
landed bool
|
||||
closed bool
|
||||
}
|
||||
|
||||
// sharedFrame is a texture of the ring, and its surface.
|
||||
type sharedFrame struct {
|
||||
tex, mutex uintptr
|
||||
surface *scene.Surface
|
||||
w, h int
|
||||
}
|
||||
|
||||
func newEngine(s source) (media.Engine, error) {
|
||||
if err := loadMediaFoundation(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
// COM, for CoCreateInstance on this thread: the app's thread may
|
||||
// have it already, in its own mode, which serves.
|
||||
procCoInitializeEx.Call(0, 2) // COINIT_APARTMENTTHREADED
|
||||
|
||||
e := &mfEngine{id: lastEngine.Add(1), shown: -1}
|
||||
ok := false
|
||||
defer func() {
|
||||
if !ok {
|
||||
e.release()
|
||||
}
|
||||
}()
|
||||
var err error
|
||||
if e.dev, e.ctx, _, err = device.NewForVideo(); err != nil {
|
||||
return nil, fmt.Errorf("%w: %v", ErrUnsupported, err)
|
||||
}
|
||||
// The engine decodes on the device from threads of its own.
|
||||
if !failed(call(e.dev, comQueryInterface, uintptr(unsafe.Pointer(&iidID3D10Multithread)), uintptr(unsafe.Pointer(&e.mt)))) {
|
||||
call(e.mt, multithreadSetProtected, 1)
|
||||
}
|
||||
var token uint32
|
||||
if hr, _, _ := procMFCreateDXGIDeviceManager.Call(uintptr(unsafe.Pointer(&token)), uintptr(unsafe.Pointer(&e.manager))); failed(hr) {
|
||||
return nil, fmt.Errorf("video: MFCreateDXGIDeviceManager: %#x", uint32(hr))
|
||||
}
|
||||
if hr := call(e.manager, managerResetDevice, e.dev, uintptr(token)); failed(hr) {
|
||||
return nil, fmt.Errorf("video: IMFDXGIDeviceManager.ResetDevice: %#x", uint32(hr))
|
||||
}
|
||||
n, _, _ := procCoTaskMemAlloc.Call(2 * unsafe.Sizeof(uintptr(0)))
|
||||
if n == 0 {
|
||||
return nil, errors.New("video: out of memory")
|
||||
}
|
||||
e.notify = n
|
||||
*(*uintptr)(cptr(n)) = uintptr(unsafe.Pointer(¬ifyVtbl))
|
||||
*(*uint64)(cptr(n + unsafe.Sizeof(uintptr(0)))) = e.id
|
||||
engines.Store(e.id, e)
|
||||
|
||||
var attrs, factory uintptr
|
||||
if hr, _, _ := procMFCreateAttributes.Call(uintptr(unsafe.Pointer(&attrs)), 3); failed(hr) {
|
||||
return nil, fmt.Errorf("video: MFCreateAttributes: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&attrs)
|
||||
call(attrs, attrSetUnknown, uintptr(unsafe.Pointer(&mfMediaEngineCallback)), e.notify)
|
||||
call(attrs, attrSetUnknown, uintptr(unsafe.Pointer(&mfMediaEngineDXGIManager)), e.manager)
|
||||
const formatB8G8R8A8Unorm = 87
|
||||
call(attrs, attrSetUINT32, uintptr(unsafe.Pointer(&mfMediaEngineVideoOutputFormat)), formatB8G8R8A8Unorm)
|
||||
const clsctxInprocServer = 1
|
||||
if hr, _, _ := procCoCreateInstance.Call(uintptr(unsafe.Pointer(&clsidMFMediaEngineClassFactory)), 0, clsctxInprocServer,
|
||||
uintptr(unsafe.Pointer(&iidIMFMediaEngineClassFactory)), uintptr(unsafe.Pointer(&factory))); failed(hr) {
|
||||
return nil, fmt.Errorf("%w: no media engine: %#x", ErrUnsupported, uint32(hr))
|
||||
}
|
||||
defer free(&factory)
|
||||
if hr := call(factory, factoryCreateInstance, 0, attrs, uintptr(unsafe.Pointer(&e.engine))); failed(hr) {
|
||||
return nil, fmt.Errorf("video: IMFMediaEngineClassFactory.CreateInstance: %#x", uint32(hr))
|
||||
}
|
||||
call(e.engine, comQueryInterface, uintptr(unsafe.Pointer(&iidIMFMediaEngineEx)), uintptr(unsafe.Pointer(&e.ex)))
|
||||
|
||||
if s.data != nil {
|
||||
if err := e.setData(s.data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
} else {
|
||||
// Media Foundation reads the percent-escapes of a file: URL as
|
||||
// bytes of the system's code page, not UTF-8, so a file whose path
|
||||
// is not ASCII goes by its path, which SetSource takes as well.
|
||||
src := s.url
|
||||
if s.path != "" {
|
||||
src = s.path
|
||||
}
|
||||
url := bstr(src)
|
||||
hr := call(e.engine, engineSetSource, url)
|
||||
procSysFreeString.Call(url)
|
||||
if failed(hr) {
|
||||
return nil, fmt.Errorf("video: cannot open %s: %#x", s.url, uint32(hr))
|
||||
}
|
||||
}
|
||||
ok = true
|
||||
return e, nil
|
||||
}
|
||||
|
||||
// setData has the engine read the video from bytes in memory, through a
|
||||
// stream in memory: no file.
|
||||
func (e *mfEngine) setData(data []byte) error {
|
||||
if e.ex == 0 {
|
||||
return fmt.Errorf("%w: no IMFMediaEngineEx", ErrUnsupported)
|
||||
}
|
||||
stream, _, _ := procSHCreateMemStream.Call(uintptr(unsafe.Pointer(&data[0])), uintptr(len(data)))
|
||||
if stream == 0 {
|
||||
return errors.New("video: out of memory")
|
||||
}
|
||||
defer free(&stream)
|
||||
var bs uintptr
|
||||
if hr, _, _ := procMFCreateMFByteStreamOnStream.Call(stream, uintptr(unsafe.Pointer(&bs))); failed(hr) {
|
||||
return fmt.Errorf("video: MFCreateMFByteStreamOnStream: %#x", uint32(hr))
|
||||
}
|
||||
defer free(&bs)
|
||||
// The URL names only the type, for the engine to choose its source.
|
||||
name := "data.mp4"
|
||||
if len(data) >= 12 && string(data[4:8]) == "ftyp" && string(data[8:12]) == "qt " {
|
||||
name = "data.mov"
|
||||
} else if len(data) >= 4 && string(data[:4]) == "\x1a\x45\xdf\xa3" {
|
||||
name = "data.webm"
|
||||
}
|
||||
url := bstr(name)
|
||||
defer procSysFreeString.Call(url)
|
||||
if hr := call(e.ex, engineExSetSourceFromByte, bs, url); failed(hr) {
|
||||
return fmt.Errorf("video: cannot open the video: %#x", uint32(hr))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func bstr(s string) uintptr {
|
||||
p, _ := syscall.UTF16PtrFromString(s)
|
||||
b, _, _ := procSysAllocString.Call(uintptr(unsafe.Pointer(p)))
|
||||
return b
|
||||
}
|
||||
|
||||
// event takes an event of the engine, on a thread of Media Foundation's.
|
||||
func (e *mfEngine) event(event uint32, param1 uintptr, param2 uint32) {
|
||||
e.mu.Lock()
|
||||
switch event {
|
||||
case eventError:
|
||||
e.state = media.Failed
|
||||
e.err = fmt.Errorf("video: Media Foundation could not play the video (error %d, %#x)", param1, param2)
|
||||
case eventEnded:
|
||||
if !e.loop {
|
||||
e.state = media.Ended
|
||||
}
|
||||
case eventWaiting:
|
||||
if e.state == media.Ready {
|
||||
e.state = media.Buffering
|
||||
}
|
||||
case eventPlaying, eventCanPlay:
|
||||
if e.state == media.Buffering {
|
||||
e.state = media.Ready
|
||||
}
|
||||
case eventSeeked:
|
||||
e.seekSince = time.Time{}
|
||||
e.landed = true
|
||||
case eventLoadedMetadata, eventLoadedData, eventDurationChange, eventFrameStepCompleted:
|
||||
default:
|
||||
e.mu.Unlock()
|
||||
return
|
||||
}
|
||||
wake := e.wake
|
||||
e.mu.Unlock()
|
||||
if wake != nil {
|
||||
wake()
|
||||
}
|
||||
}
|
||||
|
||||
func (e *mfEngine) SetWake(wake func()) {
|
||||
e.mu.Lock()
|
||||
e.wake = wake
|
||||
e.mu.Unlock()
|
||||
}
|
||||
|
||||
func (e *mfEngine) Frame(time.Time) (media.Picture, bool, bool) {
|
||||
changed := false
|
||||
var pts int64
|
||||
fresh := call(e.engine, engineOnVideoStreamTick, uintptr(unsafe.Pointer(&pts))) == 0 // S_OK: a new picture
|
||||
e.mu.Lock()
|
||||
landed := e.landed
|
||||
e.mu.Unlock()
|
||||
if landed && (fresh || call(e.engine, engineIsSeeking) == 0) {
|
||||
e.mu.Lock()
|
||||
e.landed = false
|
||||
e.mu.Unlock()
|
||||
if !fresh && pts == math.MinInt64 && e.ex != 0 && call(e.engine, engineIsPaused) != 0 {
|
||||
// A seek of a paused video landed with no picture, which then
|
||||
// never comes (Media Foundation on Windows on Arm, about one
|
||||
// seek in three): a step forward shows the one there, and
|
||||
// keeps the position.
|
||||
call(e.ex, engineExFrameStep, 1)
|
||||
}
|
||||
}
|
||||
if fresh {
|
||||
var w, h uint32
|
||||
call(e.engine, engineGetNativeVideoSize, uintptr(unsafe.Pointer(&w)), uintptr(unsafe.Pointer(&h)))
|
||||
if w > 0 && h > 0 {
|
||||
i := (e.shown + 1) % ringSize
|
||||
if e.transfer(i, int(w), int(h)) {
|
||||
e.shown, changed = i, true
|
||||
e.w, e.h = int(w), int(h)
|
||||
e.mu.Lock()
|
||||
if e.state == media.Loading {
|
||||
e.state = media.Ready
|
||||
}
|
||||
e.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
if e.shown < 0 {
|
||||
return media.Picture{}, false, false
|
||||
}
|
||||
f := &e.ring[e.shown]
|
||||
i := e.shown
|
||||
return media.Picture{Surface: f.surface, W: f.w, H: f.h, RGBA: func(dst []byte) []byte { return e.readBack(i, dst) }}, changed, true
|
||||
}
|
||||
|
||||
// transfer converts the picture due into texture i of the ring, which it
|
||||
// makes, or makes again at another size, under its keyed mutex.
|
||||
func (e *mfEngine) transfer(i, w, h int) bool {
|
||||
f := &e.ring[i]
|
||||
if f.tex == 0 || f.w != w || f.h != h {
|
||||
e.freeFrame(f)
|
||||
if !e.newShared(f, w, h) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
const acquireTimeout = 100 // ms: the renderer reads the texture meanwhile
|
||||
if hr := call(f.mutex, keyedAcquireSync, 0, acquireTimeout); failed(hr) || hr == 0x102 {
|
||||
return false
|
||||
}
|
||||
rect := [4]int32{0, 0, int32(w), int32(h)}
|
||||
border := uint32(0xff000000) // opaque black, MFARGB
|
||||
hr := call(e.engine, engineTransferVideoFrame, f.tex, 0, uintptr(unsafe.Pointer(&rect)), uintptr(unsafe.Pointer(&border)))
|
||||
call(f.mutex, keyedReleaseSync, 0)
|
||||
return !failed(hr)
|
||||
}
|
||||
|
||||
// newShared makes f a w×h texture in BGRA that the engine converts into
|
||||
// and the window's device opens, by an NT handle, with a keyed mutex.
|
||||
func (e *mfEngine) newShared(f *sharedFrame, w, h int) bool {
|
||||
const (
|
||||
formatB8G8R8A8Unorm = 87
|
||||
usageDefault = 0
|
||||
bindShaderResource = 0x8
|
||||
bindRenderTarget = 0x20
|
||||
miscSharedKeyedMutex = 0x100
|
||||
miscSharedNTHandle = 0x800
|
||||
sharedRead = 0x80000000
|
||||
sharedWrite = 1
|
||||
)
|
||||
desc := texture2DDesc{Width: uint32(w), Height: uint32(h), MipLevels: 1, ArraySize: 1, Format: formatB8G8R8A8Unorm, SampleCount: 1,
|
||||
Usage: usageDefault, BindFlags: bindShaderResource | bindRenderTarget, MiscFlags: miscSharedKeyedMutex | miscSharedNTHandle}
|
||||
if failed(call(e.dev, devCreateTexture2D, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&f.tex)))) {
|
||||
f.tex = 0
|
||||
return false
|
||||
}
|
||||
var res, handle uintptr
|
||||
if failed(call(f.tex, comQueryInterface, uintptr(unsafe.Pointer(&iidIDXGIKeyedMutex)), uintptr(unsafe.Pointer(&f.mutex)))) ||
|
||||
failed(call(f.tex, comQueryInterface, uintptr(unsafe.Pointer(&iidIDXGIResource1)), uintptr(unsafe.Pointer(&res)))) {
|
||||
e.freeFrame(f)
|
||||
return false
|
||||
}
|
||||
hr := call(res, resourceCreateSharedHandle, 0, sharedRead|sharedWrite, 0, uintptr(unsafe.Pointer(&handle)))
|
||||
free(&res)
|
||||
if failed(hr) {
|
||||
e.freeFrame(f)
|
||||
return false
|
||||
}
|
||||
f.w, f.h = w, h
|
||||
f.surface = &scene.Surface{Format: scene.SurfaceBGRA, Native: handle, NativeID: lastShared.Add(1)}
|
||||
// The handle stays open while anything shows the surface: a renderer
|
||||
// opens it as it first draws it.
|
||||
runtime.AddCleanup(f.surface, func(h uintptr) { syscall.CloseHandle(syscall.Handle(h)) }, handle)
|
||||
return true
|
||||
}
|
||||
|
||||
func (e *mfEngine) freeFrame(f *sharedFrame) {
|
||||
free(&f.mutex)
|
||||
free(&f.tex)
|
||||
f.surface = nil
|
||||
}
|
||||
|
||||
// readBack copies texture i of the ring into premultiplied RGBA, for the
|
||||
// CPU renderer, through a staging texture.
|
||||
func (e *mfEngine) readBack(i int, dst []byte) []byte {
|
||||
f := &e.ring[i]
|
||||
if e.closed || f.tex == 0 {
|
||||
return nil
|
||||
}
|
||||
w, h := f.w, f.h
|
||||
if e.staging == 0 || e.stagingW != w || e.stagingH != h {
|
||||
free(&e.staging)
|
||||
const usageStaging, cpuAccessRead = 3, 0x20000
|
||||
desc := texture2DDesc{Width: uint32(w), Height: uint32(h), MipLevels: 1, ArraySize: 1, Format: 87, SampleCount: 1,
|
||||
Usage: usageStaging, CPUAccessFlags: cpuAccessRead}
|
||||
if failed(call(e.dev, devCreateTexture2D, uintptr(unsafe.Pointer(&desc)), 0, uintptr(unsafe.Pointer(&e.staging)))) {
|
||||
e.staging = 0
|
||||
return nil
|
||||
}
|
||||
e.stagingW, e.stagingH = w, h
|
||||
}
|
||||
if hr := call(f.mutex, keyedAcquireSync, 0, 1000); failed(hr) || hr == 0x102 {
|
||||
return nil
|
||||
}
|
||||
call(e.ctx, ctxCopyResource, e.staging, f.tex)
|
||||
call(f.mutex, keyedReleaseSync, 0)
|
||||
var mapped struct {
|
||||
data uintptr
|
||||
rowPitch, depthPit uint32
|
||||
}
|
||||
const mapRead = 1
|
||||
if failed(call(e.ctx, ctxMap, e.staging, 0, mapRead, 0, uintptr(unsafe.Pointer(&mapped)))) {
|
||||
return nil
|
||||
}
|
||||
defer call(e.ctx, ctxUnmap, e.staging, 0)
|
||||
n := 4 * w * h
|
||||
if cap(dst) < n {
|
||||
dst = make([]byte, n)
|
||||
}
|
||||
dst = dst[:n]
|
||||
src := unsafe.Slice((*byte)(cptr(mapped.data)), int(mapped.rowPitch)*h)
|
||||
for y := range h {
|
||||
row, out := src[y*int(mapped.rowPitch):][:4*w], dst[4*w*y:][:4*w]
|
||||
for x := 0; x < 4*w; x += 4 {
|
||||
out[x], out[x+1], out[x+2], out[x+3] = row[x+2], row[x+1], row[x], 255
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
func (e *mfEngine) Interval() time.Duration { return time.Second / 60 }
|
||||
|
||||
func (e *mfEngine) State() (media.State, error) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
return e.state, e.err
|
||||
}
|
||||
|
||||
func (e *mfEngine) Size() (int, int) { return e.w, e.h }
|
||||
|
||||
func (e *mfEngine) Duration() time.Duration {
|
||||
d := callGetDouble(e.engine, engineGetDuration)
|
||||
if math.IsNaN(d) || math.IsInf(d, 0) || d <= 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(d * float64(time.Second))
|
||||
}
|
||||
|
||||
func (e *mfEngine) Position() time.Duration {
|
||||
e.mu.Lock()
|
||||
if !e.seekSince.IsZero() {
|
||||
d := e.seekTo
|
||||
e.mu.Unlock()
|
||||
return d
|
||||
}
|
||||
e.mu.Unlock()
|
||||
d := callGetDouble(e.engine, engineGetCurrentTime)
|
||||
if math.IsNaN(d) || d < 0 {
|
||||
return 0
|
||||
}
|
||||
return time.Duration(d * float64(time.Second))
|
||||
}
|
||||
|
||||
func (e *mfEngine) Play() {
|
||||
e.mu.Lock()
|
||||
if e.state == media.Ended {
|
||||
e.state = media.Ready
|
||||
}
|
||||
e.mu.Unlock()
|
||||
call(e.engine, enginePlay)
|
||||
}
|
||||
|
||||
func (e *mfEngine) Pause() { call(e.engine, enginePause) }
|
||||
|
||||
func (e *mfEngine) Seek(d time.Duration) {
|
||||
e.mu.Lock()
|
||||
if e.state == media.Ended {
|
||||
e.state = media.Ready
|
||||
}
|
||||
e.seekTo, e.seekSince, e.landed = d, time.Now(), false
|
||||
e.mu.Unlock()
|
||||
callSetDouble(e.engine, engineSetCurrentTime, d.Seconds())
|
||||
}
|
||||
|
||||
func (e *mfEngine) SetLoop(loop bool) {
|
||||
e.mu.Lock()
|
||||
e.loop = loop
|
||||
e.mu.Unlock()
|
||||
call(e.engine, engineSetLoop, boolArg(loop))
|
||||
}
|
||||
|
||||
func (e *mfEngine) SetRate(r float64) {
|
||||
callSetDouble(e.engine, engineSetDefaultRate, r)
|
||||
callSetDouble(e.engine, engineSetPlaybackRate, r)
|
||||
}
|
||||
|
||||
func (e *mfEngine) SetVolume(v float64) { callSetDouble(e.engine, engineSetVolume, v) }
|
||||
|
||||
func (e *mfEngine) SetMuted(m bool) { call(e.engine, engineSetMuted, boolArg(m)) }
|
||||
|
||||
func boolArg(b bool) uintptr {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Close shuts the engine down and frees what it made. The handles of the
|
||||
// shared textures close once nothing shows their surfaces.
|
||||
func (e *mfEngine) Close() error {
|
||||
e.mu.Lock()
|
||||
if e.closed {
|
||||
e.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
e.closed = true
|
||||
e.wake = nil
|
||||
e.mu.Unlock()
|
||||
if e.engine != 0 {
|
||||
call(e.engine, engineShutdown)
|
||||
}
|
||||
e.release()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (e *mfEngine) release() {
|
||||
free(&e.ex)
|
||||
free(&e.engine)
|
||||
engines.Delete(e.id)
|
||||
if e.notify != 0 {
|
||||
procCoTaskMemFree.Call(e.notify)
|
||||
e.notify = 0
|
||||
}
|
||||
for i := range e.ring {
|
||||
e.freeFrame(&e.ring[i])
|
||||
}
|
||||
free(&e.staging)
|
||||
free(&e.manager)
|
||||
free(&e.mt)
|
||||
free(&e.ctx)
|
||||
free(&e.dev)
|
||||
}
|
||||
Vendored
+7
@@ -0,0 +1,7 @@
|
||||
//go:build !(linux && !android && (amd64 || arm64)) && !darwin && !(windows && (amd64 || arm64)) && !js
|
||||
|
||||
package video
|
||||
|
||||
import "github.com/egoist/mygo/internal/media"
|
||||
|
||||
func newEngine(source) (media.Engine, error) { return nil, ErrUnsupported }
|
||||
BIN
Binary file not shown.
Vendored
+99
@@ -0,0 +1,99 @@
|
||||
// Package video plays video files and streams with the system's own media
|
||||
// framework, for ui.Video to show: AVFoundation on macOS, Media
|
||||
// Foundation on Windows, GStreamer on Linux and the video element in
|
||||
// browsers. The system decodes the video, in hardware where it can, and
|
||||
// plays its sound in sync with the picture; its frames reach the window's
|
||||
// renderer where the decoder left them, on the GPU, without a copy
|
||||
// through memory where the system allows it.
|
||||
//
|
||||
// //go:embed trailer.mp4
|
||||
// var trailer []byte
|
||||
//
|
||||
// app.trailer, err = video.OpenData(trailer)
|
||||
// ...
|
||||
// ui.Video(c, app.trailer).Fill().Fit(ui.Contain)
|
||||
//
|
||||
// A video opens at once and loads in the background: the player is not
|
||||
// Ready, and its Size is 0×0, until its first picture came, which builds
|
||||
// a frame of the window that shows it, as a change of its state does.
|
||||
// What formats play is the system's: H.264 and AAC in MP4 or MOV play on
|
||||
// all of them; HEVC, VP9 and AV1 where the system has their decoders, and
|
||||
// HLS streams on macOS, Windows and browsers.
|
||||
//
|
||||
// Apps that do not import the package link none of it. GIFs and animated
|
||||
// PNGs play without it, decoded in Go (ui.NewGIFDecoder,
|
||||
// ui.NewAPNGDecoder), on every system.
|
||||
package video
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// ErrUnsupported reports a system without a media framework that plays
|
||||
// video: a Linux without GStreamer 1.x and its base plugins, or an OS of
|
||||
// none. An app may show a GIF in its place.
|
||||
var ErrUnsupported = errors.New("video: the system has no media framework that plays video")
|
||||
|
||||
// source is what a player opens: a URL, or bytes in memory.
|
||||
type source struct {
|
||||
url string
|
||||
path string // the file Open opened, which url is the file: URL of
|
||||
data []byte
|
||||
}
|
||||
|
||||
// Open opens a video file, playing once a Video shows it.
|
||||
func Open(path string) (*ui.VideoPlayer, error) {
|
||||
abs, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return open(source{url: fileURL(abs), path: abs})
|
||||
}
|
||||
|
||||
// OpenURL opens a video at a URL: a file:, http: or https: URL, or an HLS
|
||||
// playlist (.m3u8) where the system streams them. It plays once a Video
|
||||
// shows it.
|
||||
func OpenURL(url string) (*ui.VideoPlayer, error) {
|
||||
return open(source{url: url})
|
||||
}
|
||||
|
||||
// OpenData opens a video in memory, as one embedded in the app, without
|
||||
// writing it to a file: the system reads it from data, which must stay as
|
||||
// it is while the player is open. It plays once a Video shows it.
|
||||
func OpenData(data []byte) (*ui.VideoPlayer, error) {
|
||||
if len(data) == 0 {
|
||||
return nil, errors.New("video: no data")
|
||||
}
|
||||
return open(source{data: data})
|
||||
}
|
||||
|
||||
func open(s source) (*ui.VideoPlayer, error) {
|
||||
e, err := newEngine(s)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ui.NewEngineVideoPlayer(e), nil
|
||||
}
|
||||
|
||||
// fileURL is the file: URL of an absolute path.
|
||||
func fileURL(abs string) string {
|
||||
p := filepath.ToSlash(abs)
|
||||
if len(p) > 0 && p[0] != '/' {
|
||||
p = "/" + p // C:/… on Windows
|
||||
}
|
||||
const hex = "0123456789ABCDEF"
|
||||
b := []byte("file://")
|
||||
for i := 0; i < len(p); i++ {
|
||||
c := p[i]
|
||||
switch {
|
||||
case 'a' <= c && c <= 'z', 'A' <= c && c <= 'Z', '0' <= c && c <= '9', c == '/', c == '-', c == '_', c == '.', c == '~', c == ':':
|
||||
b = append(b, c)
|
||||
default:
|
||||
b = append(b, '%', hex[c>>4], hex[c&15])
|
||||
}
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
package video
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"errors"
|
||||
"image/color"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/wait"
|
||||
"github.com/egoist/mygo/ui"
|
||||
)
|
||||
|
||||
// rgb.mp4 is 1.2 s of H.264 at 10 fps, 64×48, and silent AAC: 0.4 s red,
|
||||
// then green, then blue. It has no B-frames, so no edit list shifts its
|
||||
// pictures' times: the MPEG-4 source of Windows on Arm ignores one, and
|
||||
// would show each picture two frames late.
|
||||
//
|
||||
//go:embed testdata/rgb.mp4
|
||||
var rgbMP4 []byte
|
||||
|
||||
// played opens rgb.mp4 as open does and shows it in a Tester, skipping
|
||||
// the test on a system that has no engine or no H.264 decoder.
|
||||
func played(t *testing.T, open func() (*ui.VideoPlayer, error)) (*ui.VideoPlayer, *ui.Tester, func() color.RGBA) {
|
||||
t.Helper()
|
||||
p, err := open()
|
||||
if errors.Is(err, ErrUnsupported) {
|
||||
t.Skip(err)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(p.Close)
|
||||
p.SetMuted(true)
|
||||
tt := ui.NewTester(func(c *ui.Context) { ui.Video(c, p).Size(64, 48) }, 64, 48)
|
||||
shows := func() color.RGBA { return tt.Image().RGBAAt(32, 24) }
|
||||
wait.Until(t, "the first picture", func() bool {
|
||||
tt.Frame()
|
||||
checkErr(t, p)
|
||||
return p.Ready()
|
||||
})
|
||||
return p, tt, shows
|
||||
}
|
||||
|
||||
// checkErr fails the test on the error that stopped p, or skips it on a
|
||||
// system that has no H.264 decoder.
|
||||
func checkErr(t *testing.T, p *ui.VideoPlayer) {
|
||||
t.Helper()
|
||||
if err := p.Err(); err != nil {
|
||||
if strings.Contains(err.Error(), "missing") || strings.Contains(err.Error(), "decoder") {
|
||||
t.Skip("no H.264 decoder:", err)
|
||||
}
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestWakesForFirstPicture checks that the engine wakes the window for
|
||||
// the video's first picture: a window that built the video once, before
|
||||
// it had one, and that builds no frame unless woken, as one showing only
|
||||
// the video, shows it (#1830).
|
||||
func TestWakesForFirstPicture(t *testing.T) {
|
||||
p, err := OpenData(rgbMP4)
|
||||
if errors.Is(err, ErrUnsupported) {
|
||||
t.Skip(err)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(p.Close)
|
||||
p.SetMuted(true)
|
||||
tt := ui.NewTester(func(c *ui.Context) { ui.Video(c, p).Size(64, 48) }, 64, 48)
|
||||
for !p.Ready() {
|
||||
// Only the frames the window is woken for build: the engine's
|
||||
// changes of state, and its first picture.
|
||||
wait.Until(t, "a wake, the video not ready", tt.FramePending)
|
||||
tt.Frame()
|
||||
checkErr(t, p)
|
||||
}
|
||||
if w, h := p.Size(); w != 64 || h != 48 {
|
||||
t.Fatalf("size %d×%d, want 64×48", w, h)
|
||||
}
|
||||
}
|
||||
|
||||
// near reports whether c is the color want, give or take what H.264 and
|
||||
// the conversion to RGB change.
|
||||
func near(c, want color.RGBA) bool {
|
||||
d := func(a, b uint8) bool { return max(a, b)-min(a, b) <= 24 }
|
||||
return d(c.R, want.R) && d(c.G, want.G) && d(c.B, want.B) && c.A == 255
|
||||
}
|
||||
|
||||
var (
|
||||
red = color.RGBA{255, 0, 0, 255}
|
||||
green = color.RGBA{0, 255, 0, 255}
|
||||
blue = color.RGBA{0, 0, 255, 255}
|
||||
)
|
||||
|
||||
// TestPlays checks that a video in memory plays its frames, as the system
|
||||
// decodes them, in order and to its end, reporting its length.
|
||||
func TestPlays(t *testing.T) {
|
||||
p, tt, shows := played(t, func() (*ui.VideoPlayer, error) { return OpenData(rgbMP4) })
|
||||
if w, h := p.Size(); w != 64 || h != 48 {
|
||||
t.Fatalf("size %d×%d, want 64×48", w, h)
|
||||
}
|
||||
if d := p.Duration(); d < 1100*time.Millisecond || d > 1300*time.Millisecond {
|
||||
t.Errorf("duration %v, want 1.2s", d)
|
||||
}
|
||||
for _, want := range []color.RGBA{red, green, blue} {
|
||||
wait.Until(t, "the picture "+colorName(want), func() bool {
|
||||
tt.Frame()
|
||||
return near(shows(), want)
|
||||
})
|
||||
}
|
||||
wait.Until(t, "the end", func() bool { tt.Frame(); return p.Ended() })
|
||||
if p.Playing() || !near(shows(), blue) {
|
||||
t.Fatalf("at the end: playing %v, showing %v", p.Playing(), shows())
|
||||
}
|
||||
}
|
||||
|
||||
// TestSeek checks that a paused video shows the picture a seek asks for,
|
||||
// and reports the position, and that one played again after its end
|
||||
// starts over.
|
||||
func TestSeek(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "a video.mp4")
|
||||
if err := os.WriteFile(path, rgbMP4, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, tt, shows := played(t, func() (*ui.VideoPlayer, error) { return Open(path) })
|
||||
p.Pause()
|
||||
for _, s := range []struct {
|
||||
at time.Duration
|
||||
want color.RGBA
|
||||
}{{900 * time.Millisecond, blue}, {500 * time.Millisecond, green}, {100 * time.Millisecond, red}} {
|
||||
p.Seek(s.at)
|
||||
wait.Until(t, "the picture at "+s.at.String(), func() bool {
|
||||
tt.Frame()
|
||||
return near(shows(), s.want)
|
||||
})
|
||||
if pos := p.Position(); pos < s.at-100*time.Millisecond || pos > s.at+100*time.Millisecond {
|
||||
t.Errorf("sought to %v: position %v", s.at, pos)
|
||||
}
|
||||
if p.Playing() {
|
||||
t.Fatal("a seek played a paused video")
|
||||
}
|
||||
}
|
||||
p.Seek(time.Second)
|
||||
p.Play()
|
||||
wait.Until(t, "the end", func() bool { tt.Frame(); return p.Ended() })
|
||||
p.Play()
|
||||
wait.Until(t, "the start, played again", func() bool { tt.Frame(); return near(shows(), red) })
|
||||
}
|
||||
|
||||
// TestOpenNonASCIIPath checks that Open plays a file whose folder and name
|
||||
// are not ASCII, which Media Foundation could not find by its file: URL
|
||||
// (#1752).
|
||||
func TestOpenNonASCIIPath(t *testing.T) {
|
||||
dir := filepath.Join(t.TempDir(), "中文")
|
||||
if err := os.Mkdir(dir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(dir, "測試 é.mp4")
|
||||
if err := os.WriteFile(path, rgbMP4, 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, _, _ := played(t, func() (*ui.VideoPlayer, error) { return Open(path) })
|
||||
if w, h := p.Size(); w != 64 || h != 48 {
|
||||
t.Fatalf("size %d×%d, want 64×48", w, h)
|
||||
}
|
||||
}
|
||||
|
||||
func colorName(c color.RGBA) string {
|
||||
switch c {
|
||||
case red:
|
||||
return "red"
|
||||
case green:
|
||||
return "green"
|
||||
}
|
||||
return "blue"
|
||||
}
|
||||
Reference in new issue
Block a user