player

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 21 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

English | 中文文档

mygo-player

Standalone native UI video player plugin for MyGo (v0.10.0), powered by libmpv (LGPL 2.1+) with zero cgo (CGO_ENABLED=0).

mygo-player follows the same plugin layout as official MyGo native plugins (mygo-plugin.json, mygo/ffi, Load, LibraryPath, New, View). Frames render directly inside MyGo's native UI scene graph—never as a separate native child window—so HUD controls, danmaku, rounded corners, and popovers always composite cleanly above the video.

Why mygo-player vs Built-in ui/video?

MyGo's built-in ui/video wraps each OS's media framework (AVFoundation, Media Foundation, GStreamer, and browser <video>). It requires no extra native library and is ideal for simple MP4/H.264 clips or web builds. mygo-player complements ui/video when your desktop app needs full media-player features:

Capability Built-in ui/video mygo-player
Media engine OS media frameworks (AVFoundation / Media Foundation / GStreamer / <video>) Embedded libmpv (LGPL 2.1+) via mygo/ffi, zero cgo
Extra native library None libmpv shared library (auto-managed via mygo-plugin.json)
Formats & codecs MP4 / MOV (H.264 / AAC) everywhere; HEVC / VP9 / AV1 depend on OS decoders Full format playback out of the box (MKV, MP4, WebM, TS, FLV; H.264, HEVC, AV1, VP9, etc.)
Multi-audio tracks Not exposed List, switch, and disable audio tracks at runtime
Subtitles Not exposed Embedded subtitles + external subtitle files (SRT, ASS/SSA, VTT, SUP) with libass styling & toggle
Online streams & auth Plain URLs via OpenURL Custom HTTP headers per stream (auth tokens, cookies, anti-hotlink Referer & User-Agent), isolated per Open()
Hardware decoding control Managed automatically by OS Configurable & switchable at runtime (VideoToolbox, D3D11VA, VA-API, or software)
UI overlay compositing Scene-graph composited Scene-graph composited (HUD controls, danmaku, popovers, rounded corners stay above video)
Best fit Trailers, onboarding clips, lightweight embeds, browser/WASM apps Media players, anime/movie apps, NAS/Emby/Jellyfin clients, authenticated stream players

Platform Support

Platform Rendering Path Default HWDec Audio Output Prebuilt mygo-plugin.json / Build
darwin-arm64 Zero-copy GPU (IOSurface -> Metal *native.Texture) auto-safe (VideoToolbox) CoreAudio Published (scripts/build-libmpv-macos.sh)
darwin-amd64 Zero-copy GPU (IOSurface -> Metal *native.Texture) auto-safe (VideoToolbox) CoreAudio Published (scripts/build-libmpv-macos.sh)
windows-amd64 Double-buffered *ui.Bitmap (MPV_RENDER_API_TYPE_SW, no child HWND occlusion) auto-copy (D3D11VA) WASAPI Published (scripts/build-libmpv-windows.sh)
linux-amd64 Double-buffered *ui.Bitmap (MPV_RENDER_API_TYPE_SW) auto-copy (VA-API / SW fallback) PulseAudio (incl. pipewire-pulse) / ALSA Published (scripts/build-libmpv-linux.sh)
linux-arm64 Double-buffered *ui.Bitmap (MPV_RENDER_API_TYPE_SW) auto-copy (copy-back / SW fallback) PulseAudio (incl. pipewire-pulse) / ALSA Published (scripts/build-libmpv-linux.sh)

Unsupported targets (js/wasm, iOS, Android): mygo-player compiles cleanly without desktop purego/renderer dependencies (CGO_ENABLED=0 for js/wasm) and returns errors.ErrUnsupported at runtime, so cross-platform codebases can import it safely.

Installation

go get github.com/arixbit/mygo-player
  • Requires Go and MyGo (v0.10.0) with CGO_ENABLED=0.
  • mygo-plugin.json is embedded in the package, so mygo dev and mygo build automatically discover and bundle libmpv.

Quick Start

Leave HWDec empty to use the recommended platform default automatically (auto-safe on macOS, auto-copy on Windows and Linux):

package main

import (
	"log"

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

func main() {
	mygo.App.WhenReady(func() {
		p, err := player.New(player.Options{})
		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)
	}
}
Running the Example Player
# Uses the published libmpv (via mygo-plugin.json) or a locally installed libmpv:
CGO_ENABLED=0 go run ./examples/player /path/to/video.mkv

# Or point to a specific libmpv shared library (.dylib / .dll / .so):
MYGO_NATIVE_MPV=/path/to/libmpv.dylib CGO_ENABLED=0 go run ./examples/player \
  -sub /path/to/subtitle.srt \
  /path/to/video.mkv

The example is a complete, minimal player: drop a video (or choose one with Cmd+O / Ctrl+O, or "Open With" from Finder/Explorer) and it plays. Matching subtitle files next to the video load automatically, and dropping subtitle files on a playing video adds them. The control bar hides with the cursor after a moment of playback and comes back on any movement; subtitles move up out of its way while it shows. Menus only appear when they offer a choice (the audio menu needs two or more tracks), narrow windows fold what doesn't fit into the More (⋯) menu, tracks are named in plain language ("Japanese · Commentary"), errors show as toasts or as a card with a way forward, and every transition respects the system's Reduce Motion setting.

Keyboard shortcuts in examples/player (shown in each control's tooltip):

  • Space / K: Play / Pause (replays at the end); clicking the picture plays or pauses immediately
  • Left / Right: Back / forward 5 seconds
  • Up / Down: Volume up / down (turning it up unmutes)
  • M: Mute / Unmute
  • C: Subtitles off / back on
  • F, or a double click on the picture: Full screen (Esc leaves it; undoes the first click's pause/play)
  • Cmd+O (macOS) / Ctrl+O (Windows & Linux): Choose a video

Audio Tracks, Subtitles & Online Streams (Custom Headers)

  • Online streams with custom HTTP headers: Pass auth tokens (Authorization), session Cookies, and anti-hotlink Referer / User-Agent headers per stream. Per-open headers are isolated and automatically reset on the next Open() call so credentials never leak between videos.
  • Multi-audio tracks: Inspect all embedded audio streams (AudioTracks()), switch languages/commentary tracks on the fly (SelectAudioTrack), or mute audio decoding (DisableAudioTrack).
  • Readable track names: Track.DisplayName() names a track for menus ("Japanese · Commentary", "English · Forced", or an external subtitle's file name), and LanguageName("jpn") spells out the ISO 639-1/639-2 codes of about fifty common languages (other codes stay as upper-case codes; und, mul, mis and zxx, which name no single language, return ""), so apps don't show raw #2 [jpn] (aac) labels.
  • Embedded & external subtitles: Switch between embedded tracks or attach external subtitle files (.srt, .ass, .ssa, .vtt, .sup) with AddSubtitleFile, and show/hide them anytime (SetSubtitleVisible).
  • Mute toggle: ToggleMute() mutes or unmutes; unmuting at volume 0 restores an audible volume so it is never silent.
  • Runtime hardware decoding: Switch modes dynamically with SetHWDec (HWDecAutoSafe, HWDecAutoCopy, HWDecVideoToolbox, HWDecD3D11VACopy, HWDecVAAPICopy, HWDecNone) and inspect the active decoder with CurrentHWDec().
// Play an online stream with auth token, cookie, and anti-hotlink Referer & User-Agent.
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.
if audios := p.AudioTracks(); len(audios) > 1 {
	_ = p.SelectAudioTrack(audios[1].ID)
}

// Load an external subtitle (SRT/ASS/VTT/SUP) and toggle visibility.
_ = p.AddSubtitleFile("/path/to/subtitle.ass", player.SubtitleSelect)
_ = p.SetSubtitleVisible(true)

// Query or switch hardware decoding at runtime.
_ = p.SetHWDec(player.HWDecAutoCopy)
log.Println("Active hwdec:", p.CurrentHWDec())

Audio/Video & Subtitle Fine-Tuning

All tuning methods return ErrClosed after Close, reject out-of-range values with an error, redraw the current frame when the picture changes, and are mirrored in Snapshot() (also when changed via SetPropertyString):

Method Range Snapshot field
SetSubtitleDelay(d time.Duration) / SetAudioDelay(d time.Duration) any (positive = later) SubDelay / AudioDelay
SetSubtitleScale(f float64) (0, 100], default 1.0 SubScale
SetSubtitlePos(p int) 0..150 (% of height), default 100 SubPos
SetVideoRotate(deg int) 0, 90, 180, 270 VideoRotate
SetPanscan(f float64) 0..1 (1 = crop to fill the View) Panscan
FrameStep() / FrameBackStep() pause and step one frame forward / back Position
_ = p.SetSubtitleDelay(250 * time.Millisecond)
_ = p.SetSubtitleScale(1.2)
_ = p.SetPanscan(1.0) // fill a View whose aspect differs from the video (no black bars)

View always renders at the element's full size (libmpv letterboxes inside it, keeping subtitles sharp), so Fit(ui.Cover) does not remove black bars — use SetPanscan.

Playback notes: TogglePause/Play at EOF replay from the start; with the default KeepOpen, OnEndFile(nil) fires once when EOF is reached; Close may be called from inside OnStateChange/OnEndFile; position-only OnStateChange notifications are throttled to ~100 ms while Snapshot().Position keeps full precision.

Headless UI Testing (ui.NewTester)

Because player.View renders straight into MyGo's scene graph, you can test player layouts, HUD overlays, empty/idle states, and HiDPI viewport sizing deterministically with MyGo's headless ui.NewTester—without opening a window or even installing libmpv:

func TestPlayerOverlay(t *testing.T) {
	tt := ui.NewTester(func(c *ui.Context) {
		ui.Box(c).Fill().Children(func() {
			player.View(c, nil).Fill()
			ui.Text(c, "Paused").Absolute().Left(16).Top(16)
		})
	}, 320, 180)
	tt.Frame()

	if !tt.HasText("Paused") {
		t.Fatal("expected overlay text to render above player.View")
	}
}

Run tests locally:

# Fast headless UI & unit tests (no libmpv required):
CGO_ENABLED=0 go test -v -run 'TestView|TestManifest|TestSplitHTTP|TestParseTrack|TestSWRenderer' ./...

# Full test suite including real MKV playback integration tests (requires libmpv + ffmpeg):
CGO_ENABLED=0 MYGO_REQUIRE_LIBMPV=1 go test -v ./...

Native Library Lookup & LGPL Builds

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

  1. player.SetLibraryPath(...) or the $MYGO_NATIVE_MPV environment variable.
  2. Packaged app resources (Contents/Resources/libmpv.dylib / Contents/Frameworks/ on macOS; mpv-2.dll next to the executable on Windows; libmpv.so next to or bundled with the executable on Linux).
  3. Local .mygo/native/<goos>-<goarch>/ directory (unpackaged runs).
  4. Published SHA-256 verified binary declared in mygo-plugin.json (downloaded once into the user cache in unpackaged runs; bundled automatically by mygo build).
  5. Local development fallbacks when unpackaged (Homebrew /opt/homebrew/lib/libmpv.dylib or /usr/local/lib/libmpv.dylib on macOS; local directory mpv-2.dll on Windows; system libmpv.so / libmpv.so.2 paths on Linux).

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

  • macOS: ./scripts/build-libmpv-macos.sh arm64 dist/libmpv-darwin-arm64.dylib
  • Windows (MSYS2 UCRT64): ./scripts/build-libmpv-windows.sh amd64 dist/mpv-2.dll
  • Linux: ./scripts/build-libmpv-linux.sh amd64 dist/libmpv-linux-amd64.so
  • GitHub Actions: .github/workflows/build-libmpv.yml builds darwin-arm64, darwin-amd64, windows-amd64, linux-amd64, and linux-arm64 LGPL-2.1+ libraries, checks shared-library dependencies, runs zero-cgo Go integration tests, publishes SHA-256 assets to GitHub Releases, and updates mygo-plugin.json.

License

  • Go plugin source code, examples, and build scripts: MIT License (LICENSE).
  • Underlying libmpv shared library: LGPL 2.1 or later (compiled strictly without GPL or nonfree components). See THIRD_PARTY_LICENSES.md for the complete list of third-party licenses and LGPL 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 LanguageName added in v0.5.0

func LanguageName(code string) string

LanguageName returns the English name of an ISO 639-1 ("ja") or ISO 639-2 ("jpn"; both "ger" and "deu") language code as reported in track metadata, ignoring case and region suffixes ("pt-BR" is "Portuguese"). It knows about fifty widely used languages; other codes are returned upper-cased ("BN"), which still reads as a language code. Codes that name no single language ("und", "mul", "mis", "zxx") and empty codes return "", so that callers fall back to the track's title.

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 and Linux). 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, 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.

Aspect ratio and filling: View asks libmpv to render at the element's full physical size, and libmpv itself letterboxes the picture inside that frame (black bars) while drawing subtitles at full viewport resolution. The element's Fit(ui.Contain) therefore only matters before the first sized frame; overriding it with Fit(ui.Cover) does NOT remove libmpv's black bars (the frame already matches the element's size, bars included). To fill the viewport (crop-to-fill), keep the View full-size and call p.SetPanscan(1.0) (any value in 0..1 trades bars for cropping); SetVideoRotate rotates within the same frame.

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, VA-API/NVDEC on Linux, or VideoToolbox copy-back on macOS) and
	// falls back to software decoding for unsupported streams. Default on Windows
	// and Linux.
	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"
	// HWDecVAAPICopy explicitly requests Linux VA-API hardware decoding with copy-back.
	HWDecVAAPICopy HWDecMode = "vaapi-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 and Linux.
	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 (also with StartMuted, so unmuting is audible).
	Volume float64
	// StartMuted mutes audio on creation without changing Volume.
	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
	// (CoreAudio) and Linux (PipeWire/PulseAudio/ALSA).
	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.
	// Position-only updates are throttled to about one call per 100ms (the
	// Snapshot itself keeps full precision); state changes and seeks notify
	// immediately. Usually runs on the player's background event goroutine
	// (or the goroutine calling Open/Stop/track methods, after internal locks
	// are released). Calling any Player method, including Close, is safe.
	OnStateChange func()
	// OnEndFile is invoked when playback of a file ends (EOF, stop, or error).
	// With KeepOpen (default) the file stays loaded at EOF, so OnEndFile(nil)
	// is delivered once when EOF is first reached; replaying (Play/seek back)
	// or opening media re-arms it, and a later Stop/Open of the same ended
	// file does not report it again. Errors carry a readable libmpv message.
	// Runs on the player's background event goroutine; calling Close is safe.
	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.

Close is idempotent and safe to call from any goroutine, including from inside OnStateChange / OnEndFile / OnLog callbacks running on the player's event goroutine. In that case Close returns immediately after stopping the renderer; the libmpv handle is destroyed as soon as the callback returns and the event loop unwinds, so no libmpv call ever touches a freed handle.

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) FrameBackStep added in v0.4.0

func (p *Player) FrameBackStep() error

FrameBackStep pauses playback and steps back exactly one video frame (requires a seekable source; it is slower than FrameStep).

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) FrameStep added in v0.4.0

func (p *Player) FrameStep() error

FrameStep pauses playback and advances exactly one video frame.

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.

Open resets every per-file Snapshot field left over from the previous media (position, duration, EOF, buffering, title, video size, track IDs, tracks, error) and synchronizes Snapshot().Paused with opt.Paused immediately.

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 restarts from the beginning: with KeepOpen (default) it seeks back to 0; with KeepOpen=false (file already unloaded) it reloads the last opened target.

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) SetAudioDelay added in v0.4.0

func (p *Player) SetAudioDelay(d time.Duration) error

SetAudioDelay shifts audio relative to video by d (positive delays audio). Mirrored in Snapshot().AudioDelay.

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) SetPanscan added in v0.4.0

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

SetPanscan crops the video to fill the View's aspect ratio: 0 (default) letterboxes the whole picture, 1 fills the viewport completely (cropping edges). Values must be within [0, 1]. Because View renders at the full viewport size, subtitles stay sharp and inside the visible area. Mirrored in Snapshot().Panscan.

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) SetSubtitleDelay added in v0.4.0

func (p *Player) SetSubtitleDelay(d time.Duration) error

SetSubtitleDelay shifts subtitle timing by d (positive shows subtitles later). Mirrored in Snapshot().SubDelay.

func (*Player) SetSubtitlePos added in v0.4.0

func (p *Player) SetSubtitlePos(pos int) error

SetSubtitlePos sets the vertical subtitle position in percent of the screen height (0 = top, 100 = bottom (default), up to 150 to push below the picture). Mirrored in Snapshot().SubPos.

func (*Player) SetSubtitleScale added in v0.4.0

func (p *Player) SetSubtitleScale(scale float64) error

SetSubtitleScale sets the subtitle font scale factor (must be > 0 and <= 100; default 1.0). Mirrored in Snapshot().SubScale.

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) SetVideoRotate added in v0.4.0

func (p *Player) SetVideoRotate(deg int) error

SetVideoRotate rotates the video clockwise by deg, which must be 0, 90, 180 or 270. Mirrored in Snapshot().VideoRotate. Arbitrary angles are not supported by this API; use SetPropertyString("video-rotate", ...) instead.

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, clearing every per-file Snapshot field (EOF, position, duration, buffering, title, video size, track IDs, tracks and error).

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) ToggleMute added in v0.5.0

func (p *Player) ToggleMute() error

ToggleMute mutes or unmutes audio output based on libmpv's current state (not the asynchronously updated Snapshot), so calls made in quick succession each flip it. When unmuting a player whose volume is 0, it also restores an audible volume (50), so that unmuting is never silent.

func (*Player) TogglePause

func (p *Player) TogglePause() error

TogglePause switches between playing and paused states. When playback is paused or has reached EOF it calls Play (which restarts ended media). It decides from libmpv's current pause state rather than the asynchronously updated Snapshot, so calls made in quick succession each flip it.

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

	// SubDelay is the subtitle delay (see SetSubtitleDelay).
	SubDelay time.Duration
	// AudioDelay is the audio delay (see SetAudioDelay).
	AudioDelay time.Duration
	// SubScale is the subtitle scale factor (default 1.0).
	SubScale float64
	// SubPos is the vertical subtitle position in percent (default 100).
	SubPos int
	// VideoRotate is the clockwise video rotation in degrees.
	VideoRotate int
	// Panscan is the crop-to-fill amount in [0, 1] (see SetPanscan).
	Panscan float64
	// Seekable reports whether libmpv can seek in the current media (false
	// for most live streams, and until the file is loaded).
	Seekable bool
}

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.

func (Track) DisplayName added in v0.5.0

func (t Track) DisplayName() string

DisplayName returns a short human-readable name for the track, suitable for menus: the language spelled out ("Japanese" for "jpn" or "ja"), the track title when it adds something, and "Forced" for forced subtitles, joined with " · ". External subtitle files without a meaningful title fall back to their file name. Tracks with no language, title, or file name are named "Track N" by their libmpv ID. Codec and ID details are left out on purpose; callers that show several tracks with the same name can append them to tell the tracks apart.

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 (zero-copy IOSurface -> Metal), Windows and Linux (software render API -> ui.Bitmap): MKV playback, multi-audio track switching, embedded & external subtitles, and custom HTTP headers, behind a control bar that stays out of the way of the picture.
Example player demonstrates github.com/arixbit/mygo-player in a MyGo native UI window on macOS (zero-copy IOSurface -> Metal), Windows and Linux (software render API -> ui.Bitmap): MKV playback, multi-audio track switching, embedded & external subtitles, and custom HTTP headers, behind a control bar that stays out of the way of the picture.
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