or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-rendering.mdcore-playback.mdevent-handling.mdindex.mdinput-keybinding.mdplaylist-media.mdproperty-management.mdscreenshots-overlays.mdstreaming.md
tile.json

tessl/pypi-mpv

A python interface to the mpv media player

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/mpv@1.0.x

To install, run

npx @tessl/cli install tessl/pypi-mpv@1.0.0

index.mddocs/

Python-MPV

A comprehensive Python interface to the mpv media player through ctypes bindings to libmpv. Provides complete control over mpv's features similar to the Lua interface, enabling developers to embed video and audio playback capabilities into Python applications.

Package Information

  • Package Name: mpv
  • Language: Python
  • Installation: pip install mpv
  • Requirements: libmpv shared library
  • Supported Platforms: Linux, Windows, macOS

Core Imports

import mpv

Most commonly used:

from mpv import MPV

For specific components:

from mpv import MPV, ErrorCode, MpvFormat, MpvEventID

Basic Usage

import mpv
import time

# Create mpv player instance
player = mpv.MPV()

# Play a video file
player.play('/path/to/video.mp4')

# Wait for playback to start
player.wait_until_playing()

# Control playback
player.pause = True
time.sleep(2)
player.pause = False

# Seek to 30 seconds
player.seek(30, reference='absolute')

# Access properties
print(f"Duration: {player.duration}")
print(f"Position: {player.time_pos}")
print(f"Volume: {player.volume}")

# Set properties
player.volume = 50
player.fullscreen = True

# Observe property changes
@player.property_observer('time-pos')
def time_observer(name, value):
    print(f"Current position: {value}")

# Register event callback
@player.event_callback('end-file')
def end_file_handler(event):
    print("Playback finished")

# Wait for playback to complete
player.wait_for_playback()

# Clean up
player.terminate()

Architecture

The python-mpv library provides multiple layers of abstraction:

  • MPV Class: Main interface providing high-level control over playback
  • Property System: Direct access to mpv properties with observation capabilities
  • Event System: Comprehensive event handling for monitoring player state
  • Ctypes Bindings: Low-level access to libmpv API for advanced use cases
  • Data Structures: Specialized classes for events, nodes, and render contexts

The library maintains compatibility with mpv's property system and command interface, ensuring feature parity with mpv's native capabilities.

Capabilities

Core Playback Control

Essential playback functionality including play, pause, seek, stop operations, and basic player lifecycle management.

class MPV:
    def play(self, filename: str): ...
    def seek(self, amount: float, reference: str = "relative", precision: str = "keyframes"): ...
    def stop(self, keep_playlist: bool = False): ...
    def terminate(self): ...
    
    # Properties
    pause: bool
    time_pos: float
    duration: float
    ```

[Core Playback](./core-playback.md)

### Property Management

Complete access to mpv's property system with observation capabilities, type conversion, and specialized property accessors.

```python { .api }
class MPV:
    def observe_property(self, name: str, handler): ...
    def property_observer(self, name: str): ...  # decorator
    def unobserve_property(self, name: str, handler): ...
    
    # Property access
    def __getattr__(self, name): ...
    def __setattr__(self, name, value): ...
    properties: dict
    osd: PropertyProxy
    file_local: PropertyProxy

Property Management

Event Handling

Comprehensive event system for monitoring player state, handling errors, and responding to user interactions.

class MPV:
    def register_event_callback(self, callback): ...
    def event_callback(self, *event_types): ...  # decorator
    def wait_for_event(self, *event_types, **kwargs): ...
    
# Event classes
class MpvEvent: ...
class MpvEventProperty: ...
class MpvEventLogMessage: ...
class MpvEventEndFile: ...

Event Handling

Playlist and Media Loading

Playlist management, file loading with options, and track selection for audio, video, and subtitle tracks.

class MPV:
    def loadfile(self, filename: str, mode: str = 'replace', **options): ...
    def loadlist(self, playlist: str, mode: str = 'replace'): ...
    def playlist_append(self, filename: str, **options): ...
    def playlist_next(self, mode: str = 'weak'): ...
    def playlist_prev(self, mode: str = 'weak'): ...
    def audio_add(self, url: str, flags: str = 'select', **kwargs): ...
    def video_add(self, url: str, flags: str = 'select', **kwargs): ...
    def sub_add(self, url: str, flags: str = 'select', **kwargs): ...

Playlist and Media

Screenshots and Overlays

Screenshot capture with multiple output formats and overlay system for images and text on top of video content.

class MPV:
    def screenshot(self, includes: str = 'subtitles', mode: str = 'single'): ...
    def screenshot_to_file(self, filename: str, includes: str = 'subtitles'): ...
    def screenshot_raw(self, includes: str = 'subtitles'): ...
    def create_image_overlay(self, img=None, pos=(0,0)): ...
    def create_file_overlay(self, filename=None, **kwargs): ...

class ImageOverlay: ...
class FileOverlay: ...

Screenshots and Overlays

Input and Key Binding

Input event handling, custom key bindings, mouse interaction, and OSD (On-Screen Display) control.

class MPV:
    def keypress(self, name: str): ...
    def keybind(self, name: str, command: str): ...
    def register_key_binding(self, keydef: str, callback_or_cmd, mode: str = 'force'): ...
    def key_binding(self, keydef: str, mode: str = 'force'): ...  # decorator
    def mouse(self, x: int, y: int, button=None, mode: str = 'single'): ...
    def show_text(self, string: str, duration: str = '-1', level: int = 0): ...

Input and Key Binding

Streaming and Custom Protocols

Custom stream protocol registration, Python-based streaming, and generator-based data feeding.

class MPV:
    def register_stream_protocol(self, proto: str, open_fn=None): ...
    def python_stream(self, name=None, size=None): ...  # decorator
    def python_stream_catchall(self, cb): ...
    def play_bytes(self, data: bytes): ...

class GeneratorStream: ...

Streaming

Advanced Rendering

OpenGL render context management for custom rendering scenarios and integration with graphics frameworks.

class MpvRenderContext:
    def __init__(self, mpv: MPV, api_type: str, **kwargs): ...
    def render(self, **kwargs): ...
    def update(self): ...
    def free(self): ...

class MpvOpenGLInitParams: ...
class MpvOpenGLFBO: ...
class MpvRenderParam: ...

Advanced Rendering

Constants

__version__: str      # Library version ('1.0.8')
MPV_VERSION: tuple    # MPV API version numbers
fs_enc: str          # File system encoding

Error Handling

The library provides structured error handling through custom exception classes:

class ShutdownError(SystemError): ...
class EventOverflowError(SystemError): ...
class PropertyUnavailableError(AttributeError): ...

class ErrorCode:
    SUCCESS: int
    EVENT_QUEUE_FULL: int
    NOMEM: int
    INVALID_PARAMETER: int
    # ... additional error codes

Most operations can raise these exceptions when the underlying mpv operation fails or when the player has been terminated.

Type Definitions

class MpvFormat:
    NONE: int
    STRING: int
    INT64: int
    DOUBLE: int
    FLAG: int
    NODE: int

class MpvEventID:
    SHUTDOWN: int
    START_FILE: int
    END_FILE: int
    PROPERTY_CHANGE: int
    # ... additional event IDs