player

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 24, 2026 License: MIT Imports: 18 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

mygo-player

Standalone community video player plugin for MyGo (v0.10.0), powered by libmpv (LGPL 2.1+) with zero cgo, mygo/ffi, mygo-plugin.json, zero-copy GPU rendering on macOS (IOSurface → Metal *native.Texture), and double-buffered ui.Bitmap compositing on Windows (MPV_RENDER_API_TYPE_SW + hwdec=auto-copy + ao=wasapi, with no child HWND occlusion).

Features

  • Zero cgo: Pure Go bindings via github.com/egoist/mygo/ffi + purego (CGO_ENABLED=0) shared across macOS and Windows.
  • Zero-Copy GPU Rendering (macOS): Renders libmpv frames (MPV_RENDER_API_TYPE_OPENGL) via a pooled CGL + IOSurface (BGRA8Unorm) ring directly into MyGo's *native.Texture (MTLTexture).
  • Scene-Graph Composited Rendering (Windows windows-amd64): Renders libmpv frames (MPV_RENDER_API_TYPE_SW + hwdec=auto-copy / d3d11va-copy + ao=wasapi) at viewport physical size into a double-buffered ui.Bitmap (UpdateYUV NV12 preferred, Update RGBA fallback), keeping danmaku, translucent glass HUDs, rounded corners, and popovers cleanly above video without child HWND occlusion.
  • Hardware Decoding: Apple VideoToolbox (auto-safe / videotoolbox / videotoolbox-copy), Windows D3D11VA (auto-copy / d3d11va-copy), or software (no), dynamically switchable at runtime.
  • Multi-Audio & Subtitles: Inspect AudioTracks() / SubtitleTracks(), switch tracks on the fly, toggle visibility, and attach external subtitles (AddSubtitleFile for .srt, .ass, .ssa, .vtt, .sup).
  • Custom HTTP Headers: Per-open and default HTTP headers (Headers, UserAgent, Referrer) passed via libmpv structured node arrays (http-header-fields) with automatic isolation between Open() calls.
  • MyGo Plugin Manifest (mygo-plugin.json): Compatible with mygo dev, mygo build, MYGO_NATIVE_MPV, and automated GitHub Actions LGPL-2.1+ builds.

Installation

go get github.com/arixbit/mygo-player

Quick Start

package main

import (
	"log"

	"github.com/egoist/mygo"
	"github.com/egoist/mygo/ui"
	player "github.com/arixbit/mygo-player"
)

func main() {
	mygo.App.WhenReady(func() {
		p, err := player.New(player.Options{
			HWDec: player.HWDecAutoSafe, // VideoToolbox on macOS
		})
		if err != nil {
			log.Fatal(err)
		}
		_ = p.Open("/path/to/movie.mkv", player.OpenOptions{
			Subtitles: []string{"/path/to/movie.srt"},
		})

		win := mygo.NewWindow(mygo.WindowOptions{
			Title:  "Player",
			Width:  1024,
			Height: 600,
			Content: ui.View(func(c *ui.Context) {
				player.View(c, p).Fill()
			}),
		})
		win.OnClosed(func() { _ = p.Close() })
	})

	if err := mygo.App.Run(); err != nil {
		log.Fatal(err)
	}
}
Custom HTTP Headers, Audio & Subtitles
// Open a network stream with per-request HTTP headers (isolated per Open call).
err := p.Open("https://media.example.com/episode.mkv", player.OpenOptions{
	Headers: map[string]string{
		"Authorization": "Bearer your-token",
		"Cookie":        "session=abc",
	},
	UserAgent: "MyApp/1.0",
	Referrer:  "https://media.example.com/",
})

// Switch audio tracks & subtitles.
audios := p.AudioTracks()
_ = p.SelectAudioTrack(audios[1].ID)

_ = p.AddSubtitleFile("/path/to/chinese.ass", player.SubtitleSelect)
_ = p.SetSubtitleVisible(true)

// Query or change hardware decoding mode.
_ = p.SetHWDec(player.HWDecVideoToolbox)
log.Println("Active hwdec:", p.CurrentHWDec())

Running the Example Player

# With a published libmpv (via mygo-plugin.json) or Homebrew mpv (`brew install mpv`):
CGO_ENABLED=0 go run ./examples/player /path/to/video.mkv

# Or explicitly specify a libmpv dylib:
MYGO_NATIVE_MPV=/path/to/libmpv.dylib CGO_ENABLED=0 go run ./examples/player \
  -hwdec auto-safe \
  -sub /path/to/subtitle.srt \
  /path/to/video.mkv

Keyboard shortcuts in examples/player:

  • Space: Play / Pause
  • Left / Right: Seek -5s / +5s
  • M: Mute / Unmute
  • Cmd+O: Open local video file

Native Library Lookup & Releases

mygo-player embeds mygo-plugin.json and resolves libmpv via mygo/ffi:

  1. $MYGO_NATIVE_MPV environment variable (or player.SetLibraryPath(...)).
  2. Packaged app resources (Contents/Resources/libmpv.dylib) / Contents/Frameworks/ / executable directory.
  3. Local .mygo/native/<goos>-<goarch>/libmpv.dylib (unpackaged runs).
  4. Published SHA-256 verified binary declared in mygo-plugin.json (downloaded once into user cache in unpackaged runs; bundled by mygo build).
  5. Standard macOS Homebrew paths (/opt/homebrew/lib/libmpv.dylib, /usr/local/lib/libmpv.dylib) as an unpackaged dev fallback.

To build self-contained LGPL-2.1+ libraries locally or in GitHub Actions:

  • macOS local script: ./scripts/build-libmpv-macos.sh arm64 dist/libmpv-darwin-arm64.dylib
  • Windows local script (MSYS2 UCRT64): ./scripts/build-libmpv-windows.sh amd64 dist/mpv-2.dll
  • GitHub Actions workflow: .github/workflows/build-libmpv.yml (builds darwin-arm64, darwin-amd64, and windows-amd64, verifies zero non-system dependencies via otool -L / objdump -p, runs zero-cgo Go integration tests, uploads SHA-256 assets to GitHub Release, and updates mygo-plugin.json).

License

  • Go plugin source code, examples, and scripts: MIT License (LICENSE).
  • Underlying libmpv dynamic library: LGPL 2.1 or later (compiled strictly without GPL/nonfree components). See THIRD_PARTY_LICENSES.md for full details and dynamic relinking instructions.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("player: closed")

ErrClosed is returned when operations are invoked on a closed Player.

Functions

func ClientAPIVersion

func ClientAPIVersion() (major, minor uint32, err error)

ClientAPIVersion returns the loaded libmpv client API major and minor version.

func LibraryPath

func LibraryPath() (string, error)

LibraryPath returns the resolved path of the libmpv dynamic library.

func Load

func Load() error

Load loads libmpv and binds all symbols once. New calls Load automatically; call Load earlier to verify libmpv availability at startup.

func SetLibraryPath

func SetLibraryPath(path string)

SetLibraryPath overrides the libmpv shared library path before Load or New is called. Most applications should rely on mygo-plugin.json or MYGO_NATIVE_MPV instead.

func View

func View(c *ui.Context, p *Player) ui.Element

View renders p's video frame inside MyGo's native UI scene graph (zero-copy Metal native.Texture on macOS; double-buffered ui.Bitmap on Windows). Because frames are composited directly in MyGo rather than a native child window, overlays such as danmaku, HUD controls, rounded corners, and popovers always render cleanly on top.

The returned ui.Element can be styled and laid out like any ui.Image (Fill, Width, Height, Fit, Radius, Opacity, etc.). View automatically binds the window's Invalidate hook to the player and reads the window's live display scale via ui.Painter.Scale() so both video and libass subtitles stay sharp across HiDPI/Retina and multi-monitor setups.

Types

type HWDecMode

type HWDecMode string

HWDecMode controls hardware video decoding in libmpv.

const (
	// HWDecAutoSafe enables safe zero-copy hardware decoding (VideoToolbox on
	// macOS) and falls back to software decoding for unsupported streams.
	HWDecAutoSafe HWDecMode = "auto-safe"
	// HWDecAutoCopy enables safe copy-back hardware decoding (such as D3D11VA on
	// Windows or VideoToolbox copy-back on macOS) and falls back to software
	// decoding for unsupported streams. Default on Windows.
	HWDecAutoCopy HWDecMode = "auto-copy"
	// HWDecVideoToolbox explicitly requests Apple VideoToolbox zero-copy decoding.
	HWDecVideoToolbox HWDecMode = "videotoolbox"
	// HWDecVideoToolboxCopy requests VideoToolbox decoding with copy-back.
	HWDecVideoToolboxCopy HWDecMode = "videotoolbox-copy"
	// HWDecD3D11VACopy explicitly requests Windows D3D11VA hardware decoding with copy-back.
	HWDecD3D11VACopy HWDecMode = "d3d11va-copy"
	// HWDecNone disables hardware decoding (software decoding only).
	HWDecNone HWDecMode = "no"
)

type OpenOptions

type OpenOptions struct {
	// Headers overrides or supplements HTTP headers for this media source.
	// Per-open headers are automatically reset on subsequent Open calls.
	Headers map[string]string
	// UserAgent overrides the HTTP User-Agent for this media source.
	UserAgent string
	// Referrer overrides the HTTP Referer for this media source.
	Referrer string
	// StartTime seeks to the given position when opening the media.
	StartTime time.Duration
	// Paused opens the media paused on its first frame.
	Paused bool
	// Subtitles specifies external subtitle files to attach automatically.
	Subtitles []string
}

OpenOptions configures per-file playback parameters passed to Player.Open.

type Options

type Options struct {
	// HWDec configures hardware decoding. Defaults to HWDecAutoSafe on macOS
	// and HWDecAutoCopy on Windows.
	HWDec HWDecMode
	// KeepOpen keeps the last frame visible when playback reaches EOF.
	// Defaults to true when KeepOpen is nil.
	KeepOpen *bool
	// Volume sets initial volume in [0, 100] (or higher for software boost).
	// Defaults to 100 when <= 0 and StartMuted is false.
	Volume float64
	// StartMuted mutes audio on creation.
	StartMuted bool
	// Loop loops the current file indefinitely when true.
	Loop bool
	// HTTPHeaders sets default HTTP headers sent for network streams.
	HTTPHeaders map[string]string
	// UserAgent sets the default HTTP User-Agent for network streams.
	UserAgent string
	// Referrer sets the default HTTP Referer header for network streams.
	Referrer string
	// AudioOutput overrides mpv's "ao" option (e.g. "null" for headless tests).
	// Defaults to "wasapi" on Windows and mpv's native default on macOS.
	AudioOutput string
	// LogLevel enables libmpv log callbacks ("fatal", "error", "warn", "info", "v", "debug").
	// Empty disables log message delivery.
	LogLevel string
	// ExtraOptions sets arbitrary libmpv options before mpv_initialize.
	ExtraOptions map[string]string
	// OnLog receives libmpv log lines when LogLevel is set.
	// Runs on the player's background event goroutine.
	OnLog func(level, prefix, text string)
	// OnStateChange is invoked when playback state, tracks, or metadata change.
	// Runs on the player's background event goroutine; calls to Player methods are safe.
	OnStateChange func()
	// OnEndFile is invoked when playback of a file ends (EOF, stop, or error).
	// Runs on the player's background event goroutine.
	OnEndFile func(err error)
}

Options configures a new Player created by New.

type Player

type Player struct {
	// contains filtered or unexported fields
}

Player manages a libmpv playback instance rendered into MyGo's native UI scene graph (zero-copy native.Texture on macOS; double-buffered ui.Bitmap on Windows). Its methods are safe to call from any goroutine.

func New

func New(opts ...Options) (*Player, error)

New creates and initializes a libmpv Player integrated with MyGo's UI.

func (*Player) AddSubtitleFile

func (p *Player) AddSubtitleFile(path string, flags ...SubtitleFlag) error

AddSubtitleFile attaches an external subtitle file (SRT, ASS/SSA, WebVTT, SUP, etc.). By default flag is SubtitleSelect so the added subtitle is immediately active.

func (*Player) AudioTracks

func (p *Player) AudioTracks() []Track

AudioTracks returns all audio tracks in the current media.

func (*Player) Close

func (p *Player) Close() error

Close shuts down the render context, event loop, and libmpv instance cleanly.

func (*Player) CurrentHWDec

func (p *Player) CurrentHWDec() string

CurrentHWDec returns the active hardware decoder reported by libmpv (for example "videotoolbox", or "" / "no" when software decoding is active).

func (*Player) DisableAudioTrack

func (p *Player) DisableAudioTrack() error

DisableAudioTrack disables audio playback ("aid=no").

func (*Player) DisableSubtitleTrack

func (p *Player) DisableSubtitleTrack() error

DisableSubtitleTrack turns off subtitle track selection ("sid=no").

func (*Player) FrameSize added in v0.2.0

func (p *Player) FrameSize() (width, height int)

FrameSize returns the pixel dimensions of the most recently rendered video frame on any supported platform.

func (*Player) FramesRendered

func (p *Player) FramesRendered() uint64

FramesRendered returns the total number of video frames rendered since creation.

func (*Player) GetPropertyString

func (p *Player) GetPropertyString(name string) (string, error)

GetPropertyString is an escape hatch for querying an arbitrary libmpv property.

func (*Player) ImageSource added in v0.2.0

func (p *Player) ImageSource() ui.ImageSource

ImageSource returns the ui.ImageSource for the current video frame (*native.Texture on macOS, *ui.Bitmap on Windows). Call it on the UI thread (typically via View(c, p)).

func (*Player) Open

func (p *Player) Open(target string, opts ...OpenOptions) error

Open opens a local file path or network URL for playback.

func (*Player) Pause

func (p *Player) Pause() error

Pause pauses playback.

func (*Player) Play

func (p *Player) Play() error

Play starts or resumes playback. If playback reached EOF, it seeks back to 0 first.

func (*Player) Seek

func (p *Player) Seek(pos time.Duration) error

Seek seeks to an absolute playback timestamp.

func (*Player) SeekRelative

func (p *Player) SeekRelative(delta time.Duration) error

SeekRelative seeks forward (positive) or backward (negative) by delta.

func (*Player) SelectAudioTrack

func (p *Player) SelectAudioTrack(id int64) error

SelectAudioTrack switches to the audio track with the given mpv track ID.

func (*Player) SelectSubtitleTrack

func (p *Player) SelectSubtitleTrack(id int64) error

SelectSubtitleTrack switches to the embedded or external subtitle track with the given mpv track ID and ensures subtitle visibility is enabled.

func (*Player) SetHTTPHeaders

func (p *Player) SetHTTPHeaders(headers map[string]string) error

SetHTTPHeaders sets default HTTP headers applied to subsequent network streams. Special headers "User-Agent" and "Referer"/"Referrer" are automatically mapped to libmpv's dedicated user-agent and referrer properties.

func (*Player) SetHWDec

func (p *Player) SetHWDec(mode HWDecMode) error

SetHWDec dynamically updates the hardware decoding mode (e.g. HWDecAutoSafe, HWDecAutoCopy, HWDecVideoToolbox, HWDecD3D11VACopy, HWDecNone).

func (*Player) SetLoop

func (p *Player) SetLoop(loop bool) error

SetLoop enables or disables infinite looping of the current file.

func (*Player) SetMuted

func (p *Player) SetMuted(muted bool) error

SetMuted mutes or unmutes audio output.

func (*Player) SetPropertyString

func (p *Player) SetPropertyString(name, value string) error

SetPropertyString is an escape hatch for setting an arbitrary libmpv property.

func (*Player) SetReferrer

func (p *Player) SetReferrer(ref string) error

SetReferrer sets the default HTTP Referer header applied to network streams.

func (*Player) SetRenderSize

func (p *Player) SetRenderSize(width, height int)

SetRenderSize sets the target physical pixel dimensions for video rendering. Pass (0, 0) to revert to the video's native resolution.

func (*Player) SetSpeed

func (p *Player) SetSpeed(rate float64) error

SetSpeed sets the playback rate multiplier (e.g. 0.5, 1.0, 1.5, 2.0).

func (*Player) SetSubtitleVisible

func (p *Player) SetSubtitleVisible(visible bool) error

SetSubtitleVisible toggles subtitle rendering without changing the selected track.

func (*Player) SetUserAgent

func (p *Player) SetUserAgent(ua string) error

SetUserAgent sets the default HTTP User-Agent applied to network streams.

func (*Player) SetVolume

func (p *Player) SetVolume(v float64) error

SetVolume sets playback volume (typically 0..100).

func (*Player) Snapshot

func (p *Player) Snapshot() Snapshot

Snapshot returns a consistent copy of the player's current playback state and tracks.

func (*Player) Stop

func (p *Player) Stop() error

Stop stops playback and returns the player to idle.

func (*Player) SubtitleTracks

func (p *Player) SubtitleTracks() []Track

SubtitleTracks returns all embedded and external subtitle tracks in the current media.

func (*Player) Texture

func (p *Player) Texture() *native.Texture

Texture returns the zero-copy GPU native.Texture on macOS, or nil on platforms that present frames through ui.Bitmap (such as Windows). Prefer View(c, p) or ImageSource() for cross-platform UI rendering.

func (*Player) TogglePause

func (p *Player) TogglePause() error

TogglePause switches between playing and paused states.

func (*Player) Tracks

func (p *Player) Tracks() []Track

Tracks returns all tracks reported by libmpv for the current file.

func (*Player) VideoTracks

func (p *Player) VideoTracks() []Track

VideoTracks returns all video tracks in the current media.

type Snapshot

type Snapshot struct {
	State        State
	Position     time.Duration
	Duration     time.Duration
	Volume       float64
	Muted        bool
	Speed        float64
	Paused       bool
	Buffering    bool
	EOF          bool
	VideoWidth   int
	VideoHeight  int
	CurrentHWDec string
	MediaTitle   string
	AudioTrackID int64
	SubTrackID   int64
	SubVisible   bool
	Tracks       []Track
	Err          error
}

Snapshot is an immutable point-in-time summary of player state suitable for reading in UI view functions without taking locks repeatedly.

type State

type State int

State represents the playback lifecycle state of a Player.

const (
	StateIdle State = iota
	StateLoading
	StatePlaying
	StatePaused
	StateBuffering
	StateEnded
	StateError
)

func (State) String

func (s State) String() string

type SubtitleFlag

type SubtitleFlag string

SubtitleFlag controls how AddSubtitleFile treats a newly added subtitle track.

const (
	// SubtitleSelect loads and immediately activates the subtitle track (default).
	SubtitleSelect SubtitleFlag = "select"
	// SubtitleAuto loads the subtitle track without overriding an active track.
	SubtitleAuto SubtitleFlag = "auto"
	// SubtitleCached loads the subtitle track without selecting it.
	SubtitleCached SubtitleFlag = "cached"
)

type Track

type Track struct {
	ID               int64
	Type             TrackType
	SrcID            int64
	Title            string
	Lang             string
	Codec            string
	Selected         bool
	Default          bool
	Forced           bool
	External         bool
	ExternalFilename string
	Width            int
	Height           int
	FPS              float64
	Channels         int
	SampleRate       int
}

Track describes a video, audio, or subtitle stream reported by libmpv.

type TrackType

type TrackType string

TrackType identifies the kind of media stream in a Track.

const (
	TrackVideo TrackType = "video"
	TrackAudio TrackType = "audio"
	TrackSub   TrackType = "sub"
)

Directories

Path Synopsis
examples
player command
Example player demonstrates github.com/arixbit/mygo-player in a MyGo native UI window on macOS with zero-copy GPU rendering (IOSurface -> Metal), MKV playback, multi-audio track switching, embedded & external subtitles, hardware decoding (VideoToolbox), and custom HTTP headers.
Example player demonstrates github.com/arixbit/mygo-player in a MyGo native UI window on macOS with zero-copy GPU rendering (IOSurface -> Metal), MKV playback, multi-audio track switching, embedded & external subtitles, hardware decoding (VideoToolbox), and custom HTTP headers.
internal
mpv
scripts
update-manifest command
Command update-manifest updates mygo-plugin.json with SHA-256 checksums and immutable release asset URLs for built libmpv dynamic libraries, matching MyGo's native library publishing convention.
Command update-manifest updates mygo-plugin.json with SHA-256 checksums and immutable release asset URLs for built libmpv dynamic libraries, matching MyGo's native library publishing convention.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL