Skip to main content

Engine

Struct Engine 

Source
pub struct Engine { /* private fields */ }
Expand description

One embedded mpv player core.

Toolkit-agnostic by construction: no main-loop integration, no widget, no GL context of its own. A shell attaches a render target with attach_gl_render, forwards the update callback to its own main loop, and drains pump_events on whatever cadence suits it.

Implementations§

Source§

impl Engine

Source

pub fn builder() -> EngineBuilder

Neutral builder with no properties preset — for consumers whose configuration doesn’t start from video or headless. (The presets can also be overridden: properties apply in call order.)

Source

pub fn video() -> EngineBuilder

Builder preset for video playback via the libmpv render API. Frames appear only after attach_gl_render; see that method’s note on load ordering.

Source

pub fn headless() -> EngineBuilder

Builder preset for audio-only / headless use (vo=null): playback starts as soon as load runs, no render target needed. Also what the test suite uses — no display required.

Source

pub fn load(&self, source: &str) -> Result<()>

Load a file path or URL and start playback.

For video engines, prefer load_paused until the shell’s surface is mapped: loadfile before a render context exists leaves mpv with nowhere to send frames (audio plays, video stays black), and demuxing before the window shows wastes work.

Source

pub fn load_paused(&self, source: &str) -> Result<()>

load, but paused: pause is set before loadfile so demuxing/audio don’t start before the shell is ready. Call set_paused(false) on your window-ready signal. (Setting pause at init time instead has a tendency to hang — this runtime-property ordering is the reliable variant.)

Source

pub fn command(&self, name: &str, args: &[&str]) -> Result<()>

Escape hatch: any mpv command, args passed as an array (no quoting needed).

Source

pub fn set_property( &self, name: &str, value: impl Into<PropertyValue>, ) -> Result<()>

Set an mpv property. Accepts bool / i64 / f64 / &str / String (anything Into<PropertyValue>).

Source

pub fn get_property<T: PropertyGet>(&self, name: &str) -> Result<T>

Read an mpv property as bool, i64, f64, or String (PropertyGet is sealed to those).

Source

pub fn set_paused(&self, paused: bool) -> Result<()>

Pause (true) or resume (false) playback.

Source

pub fn is_paused(&self) -> bool

Best-effort pause-state query; false when nothing is loaded yet — use is_idle to tell “playing” apart from “nothing to play”.

Source

pub fn is_idle(&self) -> bool

True when no file is loaded (idle-active) — distinguishes “nothing to pause” from is_paused being false.

Source

pub fn stop(&self) -> Result<()>

Stop playback and unload the current file. Surfaces as PlaybackEvent::Ended with EndReason::Stop.

Source

pub fn set_volume(&self, percent: f64) -> Result<()>

Volume in percent: 0–100 is normal range, above 100 amplifies (up to mpv’s volume-max).

Source

pub fn volume(&self) -> Option<f64>

Best-effort volume query in percent.

Source

pub fn set_muted(&self, muted: bool) -> Result<()>

Mute (true) or unmute (false) audio.

Source

pub fn is_muted(&self) -> bool

Best-effort mute-state query; false when nothing is loaded yet.

Source

pub fn set_speed(&self, speed: f64) -> Result<()>

Playback speed multiplier (1.0 = normal).

Source

pub fn speed(&self) -> Option<f64>

Best-effort speed query.

Source

pub fn position(&self) -> Option<f64>

Current playback position in seconds, if a file is loaded.

Source

pub fn duration(&self) -> Option<f64>

Total duration in seconds. None while mpv is still parsing or for unknown-duration streams.

Source

pub fn seek_absolute(&self, secs: f64) -> Result<()>

Seek to an absolute position in seconds.

Source

pub fn seek_relative(&self, secs: f64) -> Result<()>

Seek by a delta in seconds (negative seeks backward).

Source

pub fn observe(&self, name: &str, format: PropertyFormat) -> Result<ObserveId>

Observe a property for changes: matching PlaybackEvent::PropertyChanged events arrive via pump_events, starting with one carrying the current value (handy for initializing UI state). format picks the delivered PropertyValue variant; mpv coerces where it can.

Typical player set: pause (Flag), time-pos/duration (Double), paused-for-cache (Flag), dwidth/dheight (Int).

Source

pub fn unobserve(&self, id: ObserveId) -> Result<()>

Cancel one observation made with observe.

Source

pub fn set_wakeup_callback(&self, on_wakeup: impl Fn() + Send + Sync + 'static)

Register a callback fired whenever mpv queues new events — the push alternative to polling pump_events on a timer, and the only timely signal when no frames are flowing (audio-only playback, a load failure while paused).

The callback also fires once synchronously during this call (so the construct → share → register ordering documented on the attach methods applies here too), and mpv may additionally fire it spuriously. Treat a wakeup as “check the queue”, never “an event arrived”.

Fires on arbitrary mpv-internal threads — possibly several at once (hence Sync), possibly re-entrantly with other engine calls: do no work and call no engine methods inside — signal your main loop and pump from there (the same bridging pattern as the render-update callback). Replaces any previously registered wakeup callback.

Source

pub fn pump_events(&self) -> Vec<PlaybackEvent>

Drain pending mpv events into typed PlaybackEvents. Call on a timer or after the update callback; never blocks.

Built on rsmpv’s non-blocking poll_event (&self; internally serialized against libmpv’s one-waiter-per-handle rule). The engine adds the pump lock on top so each drain is atomic — concurrent pollers would otherwise split the stream, tearing ordered sequences across callers’ batches.

Source

pub unsafe fn attach_gl_render( &self, get_proc_address: ProcAddressFn, options: GlRenderOptions, on_update: impl Fn() + Send + Sync + 'static, ) -> Result<()>

Create the OpenGL render context. Call with the target GL context current (e.g. GTK: in the GLArea realize handler).

get_proc_address resolves GL symbols (on Linux, EGL 1.5’s eglGetProcAddress covers everything mpv asks for — beware libepoxy on glvnd builds, which doesn’t export core GL symbols as plain dlsym-able functions and makes mpv report MPV_ERROR_UNSUPPORTED). on_update fires on mpv’s render thread — and once synchronously during this call — to signal “a new frame wants drawing”; forward it to your main loop and call render_gl from your draw handler.

The synchronous first call arrives before the context is stored: a render_gl from inside it no-ops (harmlessly — mpv re-signals). It runs on the caller’s thread but outside the engine’s render lock, so calling back into render methods cannot deadlock.

on_update typically captures a Weak handle to your player state — construct the Engine, wrap it in your Arc/shared structure, then attach with the weak-capturing closure, then load.

options fixes the shell’s render-loop discipline at attach: frame pacing (GlRenderOptions::block_for_target_time) and mpv’s advanced control (GlRenderOptions::advanced_control, which obligates render_update after every update callback). GlRenderOptions::default is mpv’s stock behavior.

§Safety

GL-context currency is a dynamic, per-call rule the type system cannot capture (rsmpv’s OpenGL constructor is unsafe for the same reason, and this crate forwards the obligation rather than hiding it): the target GL context must be current on the calling thread now, on every later render_gl or render_update, and when the context is freed — detach_render or the engine’s drop. Violating the rule is undefined behavior.

Source

pub fn attach_sw_render( &self, on_update: impl Fn() + Send + Sync + 'static, ) -> Result<()>

Create the software render context: frames arrive as RGBA bytes via render_sw, no GL anywhere — the backend for shells that upload pixels themselves (or hand them to a non-GL compositor). Unlike the GL backend there are no context-current requirements, for rendering or teardown.

on_update has the same contract as in attach_gl_render: fires on mpv’s render thread plus once synchronously (outside the render lock, before the context is stored), and typically captures a Weak handle — construct, share, attach, then load.

Source

pub fn detach_render(&self)

Drop the render context now. For the OpenGL backend, call with the GL context still current (GTK: from the unrealize handler): freeing without the right context current leaks mpv’s GL objects into whatever context is current — in GTK that painted artifacts over the whole window. The software backend has no such requirement; detach from any thread.

Source

pub fn has_render(&self) -> bool

Whether a render context (of either backend) is currently attached.

Source

pub fn render_update(&self) -> bool

Process pending render work after an update callback fired (never call it from inside the callback itself — that’s forbidden, like any other engine call there). Returns true when a new frame should be drawn. Optional under default options; mandatory promptly after every update callback when the GL backend was attached with GlRenderOptions::advanced_control. false when no backend is attached. For the GL backend, the attach contract’s GL-currency rule covers this call too.

Source

pub fn render_gl(&self, fbo: i32, w: i32, h: i32, flip_y: bool) -> Result<()>

Draw the current frame into fbo (0 = default framebuffer) with the GL context current. No-op before attach_gl_render; errors with Error::RenderBackendMismatch if the software backend is attached instead. flip_y flips the output for flipped-origin targets (GTK’s GLArea wants true). Whether this call blocks until the frame’s target display time was fixed at attach (GlRenderOptions::block_for_target_time; the default blocks).

Source

pub fn render_sw(&self, w: i32, h: i32, buf: &mut Vec<u8>) -> Result<()>

Render the current frame as RGBA8 into buf (resized to w * h * 4; alpha always opaque). Callable from any thread. No-op before attach_sw_renderbuf is left untouched; errors with Error::RenderBackendMismatch if the OpenGL backend is attached instead.

Auto Trait Implementations§

§

impl !Freeze for Engine

§

impl !RefUnwindSafe for Engine

§

impl !UnwindSafe for Engine

§

impl Send for Engine

§

impl Sync for Engine

§

impl Unpin for Engine

§

impl UnsafeUnpin for Engine

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more