0
# Python-MPV
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: mpv
7
- **Language**: Python
8
- **Installation**: `pip install mpv`
9
- **Requirements**: libmpv shared library
10
- **Supported Platforms**: Linux, Windows, macOS
11
12
## Core Imports
13
14
```python
15
import mpv
16
```
17
18
Most commonly used:
19
20
```python
21
from mpv import MPV
22
```
23
24
For specific components:
25
26
```python
27
from mpv import MPV, ErrorCode, MpvFormat, MpvEventID
28
```
29
30
## Basic Usage
31
32
```python
33
import mpv
34
import time
35
36
# Create mpv player instance
37
player = mpv.MPV()
38
39
# Play a video file
40
player.play('/path/to/video.mp4')
41
42
# Wait for playback to start
43
player.wait_until_playing()
44
45
# Control playback
46
player.pause = True
47
time.sleep(2)
48
player.pause = False
49
50
# Seek to 30 seconds
51
player.seek(30, reference='absolute')
52
53
# Access properties
54
print(f"Duration: {player.duration}")
55
print(f"Position: {player.time_pos}")
56
print(f"Volume: {player.volume}")
57
58
# Set properties
59
player.volume = 50
60
player.fullscreen = True
61
62
# Observe property changes
63
@player.property_observer('time-pos')
64
def time_observer(name, value):
65
print(f"Current position: {value}")
66
67
# Register event callback
68
@player.event_callback('end-file')
69
def end_file_handler(event):
70
print("Playback finished")
71
72
# Wait for playback to complete
73
player.wait_for_playback()
74
75
# Clean up
76
player.terminate()
77
```
78
79
## Architecture
80
81
The python-mpv library provides multiple layers of abstraction:
82
83
- **MPV Class**: Main interface providing high-level control over playback
84
- **Property System**: Direct access to mpv properties with observation capabilities
85
- **Event System**: Comprehensive event handling for monitoring player state
86
- **Ctypes Bindings**: Low-level access to libmpv API for advanced use cases
87
- **Data Structures**: Specialized classes for events, nodes, and render contexts
88
89
The library maintains compatibility with mpv's property system and command interface, ensuring feature parity with mpv's native capabilities.
90
91
## Capabilities
92
93
### Core Playback Control
94
95
Essential playback functionality including play, pause, seek, stop operations, and basic player lifecycle management.
96
97
```python { .api }
98
class MPV:
99
def play(self, filename: str): ...
100
def seek(self, amount: float, reference: str = "relative", precision: str = "keyframes"): ...
101
def stop(self, keep_playlist: bool = False): ...
102
def terminate(self): ...
103
104
# Properties
105
pause: bool
106
time_pos: float
107
duration: float
108
```
109
110
[Core Playback](./core-playback.md)
111
112
### Property Management
113
114
Complete access to mpv's property system with observation capabilities, type conversion, and specialized property accessors.
115
116
```python { .api }
117
class MPV:
118
def observe_property(self, name: str, handler): ...
119
def property_observer(self, name: str): ... # decorator
120
def unobserve_property(self, name: str, handler): ...
121
122
# Property access
123
def __getattr__(self, name): ...
124
def __setattr__(self, name, value): ...
125
properties: dict
126
osd: PropertyProxy
127
file_local: PropertyProxy
128
```
129
130
[Property Management](./property-management.md)
131
132
### Event Handling
133
134
Comprehensive event system for monitoring player state, handling errors, and responding to user interactions.
135
136
```python { .api }
137
class MPV:
138
def register_event_callback(self, callback): ...
139
def event_callback(self, *event_types): ... # decorator
140
def wait_for_event(self, *event_types, **kwargs): ...
141
142
# Event classes
143
class MpvEvent: ...
144
class MpvEventProperty: ...
145
class MpvEventLogMessage: ...
146
class MpvEventEndFile: ...
147
```
148
149
[Event Handling](./event-handling.md)
150
151
### Playlist and Media Loading
152
153
Playlist management, file loading with options, and track selection for audio, video, and subtitle tracks.
154
155
```python { .api }
156
class MPV:
157
def loadfile(self, filename: str, mode: str = 'replace', **options): ...
158
def loadlist(self, playlist: str, mode: str = 'replace'): ...
159
def playlist_append(self, filename: str, **options): ...
160
def playlist_next(self, mode: str = 'weak'): ...
161
def playlist_prev(self, mode: str = 'weak'): ...
162
def audio_add(self, url: str, flags: str = 'select', **kwargs): ...
163
def video_add(self, url: str, flags: str = 'select', **kwargs): ...
164
def sub_add(self, url: str, flags: str = 'select', **kwargs): ...
165
```
166
167
[Playlist and Media](./playlist-media.md)
168
169
### Screenshots and Overlays
170
171
Screenshot capture with multiple output formats and overlay system for images and text on top of video content.
172
173
```python { .api }
174
class MPV:
175
def screenshot(self, includes: str = 'subtitles', mode: str = 'single'): ...
176
def screenshot_to_file(self, filename: str, includes: str = 'subtitles'): ...
177
def screenshot_raw(self, includes: str = 'subtitles'): ...
178
def create_image_overlay(self, img=None, pos=(0,0)): ...
179
def create_file_overlay(self, filename=None, **kwargs): ...
180
181
class ImageOverlay: ...
182
class FileOverlay: ...
183
```
184
185
[Screenshots and Overlays](./screenshots-overlays.md)
186
187
### Input and Key Binding
188
189
Input event handling, custom key bindings, mouse interaction, and OSD (On-Screen Display) control.
190
191
```python { .api }
192
class MPV:
193
def keypress(self, name: str): ...
194
def keybind(self, name: str, command: str): ...
195
def register_key_binding(self, keydef: str, callback_or_cmd, mode: str = 'force'): ...
196
def key_binding(self, keydef: str, mode: str = 'force'): ... # decorator
197
def mouse(self, x: int, y: int, button=None, mode: str = 'single'): ...
198
def show_text(self, string: str, duration: str = '-1', level: int = 0): ...
199
```
200
201
[Input and Key Binding](./input-keybinding.md)
202
203
### Streaming and Custom Protocols
204
205
Custom stream protocol registration, Python-based streaming, and generator-based data feeding.
206
207
```python { .api }
208
class MPV:
209
def register_stream_protocol(self, proto: str, open_fn=None): ...
210
def python_stream(self, name=None, size=None): ... # decorator
211
def python_stream_catchall(self, cb): ...
212
def play_bytes(self, data: bytes): ...
213
214
class GeneratorStream: ...
215
```
216
217
[Streaming](./streaming.md)
218
219
### Advanced Rendering
220
221
OpenGL render context management for custom rendering scenarios and integration with graphics frameworks.
222
223
```python { .api }
224
class MpvRenderContext:
225
def __init__(self, mpv: MPV, api_type: str, **kwargs): ...
226
def render(self, **kwargs): ...
227
def update(self): ...
228
def free(self): ...
229
230
class MpvOpenGLInitParams: ...
231
class MpvOpenGLFBO: ...
232
class MpvRenderParam: ...
233
```
234
235
[Advanced Rendering](./advanced-rendering.md)
236
237
## Constants
238
239
```python { .api }
240
__version__: str # Library version ('1.0.8')
241
MPV_VERSION: tuple # MPV API version numbers
242
fs_enc: str # File system encoding
243
```
244
245
## Error Handling
246
247
The library provides structured error handling through custom exception classes:
248
249
```python { .api }
250
class ShutdownError(SystemError): ...
251
class EventOverflowError(SystemError): ...
252
class PropertyUnavailableError(AttributeError): ...
253
254
class ErrorCode:
255
SUCCESS: int
256
EVENT_QUEUE_FULL: int
257
NOMEM: int
258
INVALID_PARAMETER: int
259
# ... additional error codes
260
```
261
262
Most operations can raise these exceptions when the underlying mpv operation fails or when the player has been terminated.
263
264
## Type Definitions
265
266
```python { .api }
267
class MpvFormat:
268
NONE: int
269
STRING: int
270
INT64: int
271
DOUBLE: int
272
FLAG: int
273
NODE: int
274
275
class MpvEventID:
276
SHUTDOWN: int
277
START_FILE: int
278
END_FILE: int
279
PROPERTY_CHANGE: int
280
# ... additional event IDs
281
```