gompv

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2026 License: MIT Imports: 13 Imported by: ? modules, 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

gompv

Go Reference

A clean, idiomatic, and concurrent-safe Go client for controlling mpv through its JSON-IPC interface over Unix sockets.

Features

  • Concurrent-safe IPC: Send commands and receive correlated responses synchronously or asynchronously.
  • Event Streaming: Listen to mpv property changes and lifecycle events via a type-safe channel (<-chan Event).
  • Convenient Playback API: Play, pause, resume, seek, toggle mute, volume controls, and playlist navigation.
  • Playlist Management: Query entries, switch tracks, remove items, clear, and shuffle playlists.
  • Optional Process Launcher: Built-in helper to spawn and supervise background mpv processes cleanly.
  • Sentinel Errors: Standard errors (ErrClosed, ErrTimeout) for idiomatic errors.Is error handling.
  • Zero External Dependencies: Pure standard library implementation.

Requirements

  • Go 1.22+
  • Linux / Unix environment with mpv installed (uses Unix domain sockets).

Installation

go get github.com/ioksc/gompv

Quick Start

1. Connect to an existing mpv instance

Start mpv with an IPC socket:

mpv --input-ipc-server=/tmp/mpv.sock --idle=yes

Connect using gompv:

package main

import (
    "fmt"
    "log"

    "github.com/ioksc/gompv"
)

func main() {
    client, err := gompv.Connect("/tmp/mpv.sock")
    if err != nil {
        log.Fatalf("connect: %v", err)
    }
    defer client.Close()

    // Play a file
    if err := client.LoadFile("song.flac"); err != nil {
        log.Fatalf("load file: %v", err)
    }

    // Toggle pause
    if err := client.TogglePause(); err != nil {
        log.Fatalf("pause: %v", err)
    }

    fmt.Println("Playing file via mpv!")
}
2. Spawn and supervise mpv automatically

If you want gompv to manage the lifecycle of the background mpv process:

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/ioksc/gompv"
)

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()

    socketPath := "/tmp/mpv-app.sock"
    server, client, err := gompv.StartAndConnect(ctx, socketPath, "song.mp3")
    if err != nil {
        log.Fatal(err)
    }
    defer server.Stop()
    defer client.Close()

    // Observe properties to receive change events
    _ = client.ObserveProperties("volume", "time-pos", "pause")

    go func() {
        for ev := range client.Events() {
            if name, val, ok := ev.PropertyFloat(); ok {
                fmt.Printf("Property %s updated to %v\n", name, val)
            }
        }
    }()

    _ = server.Wait()
}

API Highlights

Low-level IPC Commands
  • client.Command(args ...any) (json.RawMessage, error): Synchronously sends a command and waits for response.
  • client.CommandContext(ctx, args ...any): Context-aware synchronous command with custom deadlines.
  • client.Send(args ...any) error: Asynchronous fire-and-forget command.
High-level Playback Controls
  • client.TogglePause(), client.Pause(), client.Resume(), client.Stop()
  • client.Next(), client.Prev()
  • client.SeekRelative(seconds), client.SeekAbsolute(seconds)
  • client.SetVolume(vol), client.GetVolume(), client.SetMute(bool), client.ToggleMute()
Playlists
  • client.GetPlaylist() ([]PlaylistItem, int, error)
  • client.PlayIndex(index)
  • client.RemoveIndex(index)
  • client.ClearPlaylist()
  • client.Shuffle()
  • client.LoadFile(path, mode...)
Events

Events arrive on client.Events() <-chan Event:

  • ev.PropertyChange() (name string, data any, ok bool)
  • ev.PropertyFloat() (name string, val float64, ok bool)
  • ev.PropertyBool() (name string, val bool, ok bool)
  • ev.PropertyString() (name string, val string, ok bool)

License

MIT License. See LICENSE for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrClosed is returned when an operation is performed on a closed client.
	ErrClosed = errors.New("gompv: connection closed")
	// ErrTimeout is returned when a command response exceeds its deadline.
	ErrTimeout = errors.New("gompv: request timeout")
)
View Source
var DefaultObservedProperties = []string{
	"pause",
	"time-pos",
	"duration",
	"media-title",
	"volume",
	"mute",
	"playlist-pos",
	"playlist-count",
	"eof-reached",
	"idle-active",
}

DefaultObservedProperties contains the common properties observed by media players.

Functions

func StartAndConnect

func StartAndConnect(ctx context.Context, socketPath string, files ...string) (*Server, *Client, error)

StartAndConnect launches mpv and establishes a connection using retry logic.

Types

type Client

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

Client handles concurrent-safe IPC communication over an mpv Unix socket.

func Connect

func Connect(socketPath string) (*Client, error)

Connect dials the given socket path and initializes the background read loop.

func ConnectWithRetry

func ConnectWithRetry(ctx context.Context, socketPath string, interval time.Duration) (*Client, error)

ConnectWithRetry repeatedly attempts to connect until the socket appears or context is canceled.

func (*Client) ClearPlaylist added in v0.3.0

func (c *Client) ClearPlaylist() error

ClearPlaylist removes all entries from the playlist.

func (*Client) Close

func (c *Client) Close() error

Close gracefully shuts down the client connection and cleans up pending requests.

func (*Client) Command

func (c *Client) Command(args ...any) (json.RawMessage, error)

Command sends a synchronous JSON command and blocks until a response is received.

func (*Client) CommandContext

func (c *Client) CommandContext(ctx context.Context, args ...any) (json.RawMessage, error)

CommandContext sends a synchronous JSON command respecting the provided context.

func (*Client) DroppedEvents

func (c *Client) DroppedEvents() int64

DroppedEvents returns the count of events dropped due to a full buffer.

func (*Client) Events

func (c *Client) Events() <-chan Event

Events returns a read-only channel of events received from mpv.

func (*Client) GetPlaylist

func (c *Client) GetPlaylist() ([]PlaylistItem, int, error)

GetPlaylist queries the current playlist and returns the active track index (-1 if none).

func (*Client) GetVolume added in v0.3.0

func (c *Client) GetVolume() (float64, error)

GetVolume retrieves the current volume level.

func (*Client) LoadFile added in v0.3.0

func (c *Client) LoadFile(path string, mode ...string) error

LoadFile appends or replaces a file in the playlist. Mode can be "replace", "append", or "append-play". Defaults to "replace".

func (*Client) Next added in v0.3.0

func (c *Client) Next() error

Next advances to the next entry in the playlist.

func (*Client) ObserveProperties

func (c *Client) ObserveProperties(properties ...string) error

ObserveProperties registers change notifications for the given properties. If no properties are provided, DefaultObservedProperties will be observed.

func (*Client) ObserveProperty added in v0.3.0

func (c *Client) ObserveProperty(id int64, property string) error

ObserveProperty registers an individual property change notification with mpv.

func (*Client) Pause added in v0.3.0

func (c *Client) Pause() error

Pause pauses the current playback.

func (*Client) PlayIndex

func (c *Client) PlayIndex(idx int) error

PlayIndex switches playback to the specified playlist index.

func (*Client) Prev added in v0.3.0

func (c *Client) Prev() error

Prev moves to the previous entry in the playlist.

func (*Client) RemoveIndex

func (c *Client) RemoveIndex(idx int) error

RemoveIndex removes a track from the playlist by its index.

func (*Client) Resume added in v0.3.0

func (c *Client) Resume() error

Resume resumes playback if paused.

func (*Client) SeekAbsolute added in v0.3.0

func (c *Client) SeekAbsolute(seconds float64) error

SeekAbsolute performs an absolute seek to the specified timestamp in seconds.

func (*Client) SeekRelative

func (c *Client) SeekRelative(seconds float64) error

SeekRelative performs a relative seek by the specified number of seconds.

func (*Client) Send added in v0.1.1

func (c *Client) Send(args ...any) error

Send writes an asynchronous JSON command without waiting for a response.

func (*Client) SetMute added in v0.3.0

func (c *Client) SetMute(mute bool) error

SetMute sets the mute state.

func (*Client) SetVolume added in v0.3.0

func (c *Client) SetVolume(volume float64) error

SetVolume sets playback volume (0-100+).

func (*Client) Shuffle

func (c *Client) Shuffle() error

Shuffle randomizes the order of tracks in the playlist.

func (*Client) Stop added in v0.3.0

func (c *Client) Stop() error

Stop terminates the currently playing file.

func (*Client) ToggleMute added in v0.3.0

func (c *Client) ToggleMute() error

ToggleMute toggles mute state.

func (*Client) TogglePause

func (c *Client) TogglePause() error

TogglePause toggles playback state between pause and play.

type Event added in v0.2.0

type Event struct {
	Type EventType
	Raw  map[string]any
}

Event encapsulates an mpv event with helper methods to avoid manual type assertions.

func (Event) PropertyBool added in v0.2.3

func (e Event) PropertyBool() (string, bool, bool)

PropertyBool safely extracts the value of a boolean property.

func (Event) PropertyChange added in v0.2.0

func (e Event) PropertyChange() (string, any, bool)

PropertyChange extracts the property name and its value if the event is a property-change.

func (Event) PropertyFloat added in v0.2.3

func (e Event) PropertyFloat() (string, float64, bool)

PropertyFloat safely extracts the value of a numeric property as a float64.

func (Event) PropertyString added in v0.2.4

func (e Event) PropertyString() (string, string, bool)

PropertyString safely extracts a text property, handling both direct strings and json.RawMessage wrappers.

type EventType added in v0.2.0

type EventType string

EventType represents the type of event received from mpv.

const (
	EventPropertyChange EventType = "property-change"
	EventEndFile        EventType = "end-file"
	EventStartFile      EventType = "start-file"
	EventIdle           EventType = "idle"
)

type PlaylistItem

type PlaylistItem struct {
	Filename string `json:"filename"`
	Title    string `json:"title"`
	Current  bool   `json:"current"`
	Playing  bool   `json:"playing"`
}

PlaylistItem represents an entry within the mpv playlist.

func (PlaylistItem) DisplayName

func (p PlaylistItem) DisplayName() string

DisplayName returns the metadata title or, if unavailable, the base file name.

type Server

type Server struct {
	SocketPath string
	// contains filtered or unexported fields
}

Server manages the background mpv process lifecycle.

func StartServer

func StartServer(socketPath string, files ...string) (*Server, error)

StartServer removes any stale socket if it exists and launches mpv in background IPC mode.

func (*Server) Stop

func (s *Server) Stop()

Stop terminates the mpv process cleanly with timeout fallback and removes the socket file.

func (*Server) Wait

func (s *Server) Wait() error

Wait blocks until the underlying mpv process terminates.

Jump to

Keyboard shortcuts

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