knowledge/technology/applications/media/MPV.md
2024-03-19 09:25:42 +01:00

75 KiB

obj website flatpak-id
application https://mpv.io io.mpv.Mpv

MPV

mpv is a based media player. It supports a wide variety of video file formats, audio and video codecs, and subtitle types. Special input URL types are available to read input from a variety of sources other than disk files. Depending on platform, a variety of different video and audio output methods are supported.

Usage

Usage: mpv [options] [file|URL|PLAYLIST|-]

Default Input

Input Action
LEFT and RIGHT Seek backward/forward 5 seconds. Shift+arrow does a 1 second exact seek.
UP and DOWN Seek forward/backward 1 minute. Shift+arrow does a 5 second exact seek.
Ctrl+LEFT and Ctrl+RIGHT Seek to the previous/next subtitle. Subject to some restrictions and might not always work
Ctrl+Shift+LEFT and Ctrl+Shift+RIGHT Adjust subtitle delay so that the next or previous subtitle is displayed now. This is especially useful to sync subtitles to audio.
[ and ] Decrease/increase current playback speed by 10%.
{ and } Halve/double current playback speed.
BACKSPACE Reset playback speed to normal.
Shift+BACKSPACE Undo the last seek. This works only if the playlist entry was not changed. Hitting it a second time will go back to the original position.
Shift+Ctrl+BACKSPACE Mark the current position. This will then be used by Shift+BACKSPACE as revert position (once you seek back, the marker will be reset). You can use this to seek around in the file and then return to the exact position where you left off.
< and > Go backward/forward in the playlist.
ENTER Go forward in the playlist.
p and SPACE Pause (pressing again unpauses).
. Step forward. Pressing once will pause, every consecutive press will play one frame and then go into pause mode again.
, Step backward. Pressing once will pause, every consecutive press will play one frame in reverse and then go into pause mode again.
q Stop playing and quit.
Q Like q, but store the current playback position. Playing the same file later will resume at the old playback position if possible.
/ and * Decrease/increase volume.
9 and 0 Decrease/increase volume.
m Mute sound.
_ Cycle through the available video tracks.
# Cycle through the available audio tracks.
E Cycle through the available Editions.
f Toggle fullscreen
ESC Exit fullscreen mode.
T Toggle stay-on-top (see also --ontop).
o and P Show progression bar, elapsed time and total duration on the OSD.
O Toggle OSD states between normal and playback time/duration.
v Toggle subtitle visibility.
j and J Cycle through the available subtitles.
z and Z Adjust subtitle delay by +/- 0.1 seconds.
l Set/clear A-B loop points. See ab-loop command for details.
L Toggle infinite looping.
Ctrl++ and Ctrl+- Adjust audio delay (A/V sync) by +/- 0.1 seconds.
Shift+g and Shift+f Adjust subtitle font size by +/- 10%.
r and R Move subtitles up/down.
s Take a screenshot.
S Take a screenshot, without subtitles.
Ctrl+s Take a screenshot, as the window shows it (with subtitles, OSD, and scaled video).
PGUP and PGDWN Seek to the beginning of the previous/next chapter. In most cases, "previous" will actually go to the beginning of the current chapter.
Alt+LEFT, Alt+RIGHT, Alt+UP, Alt+DOWN Move the video rectangle (panning).
Alt++ and Alt+- Combining Alt with the + or - keys changes video zoom.
Alt+BACKSPACE Reset the pan/zoom settings.
F8 Show the playlist and the current position in it (useful only if a UI window is used, broken on the terminal).
F9 Show the list of audio and subtitle streams (useful only if a UI window is used, broken on the terminal).
i and I Show/toggle an overlay displaying statistics about the currently playing file such as codec, framerate, number of dropped frames and so on.
DEL Cycle OSC visibility between never / auto (mouse-move) / always
` Show the console. (ESC closes it again)
1 and 2 Adjust contrast.
3 and 4 Adjust brightness.
5 and 6 Adjust gamma.
7 and 8 Adjust saturation.

Options

Track Selection

  • --alang=<languagecode[,languagecode,...]>
    Specify a priority list of audio languages to use, as IETF language tags. Equivalent ISO 639-1 two-letter and ISO 639-2 three-letter codes are treated the same. The first tag in the list whose language matches a track in the file will be used.
  • --slang=<languagecode[,languagecode,...]>
    Equivalent to --alang, for subtitle tracks.
  • --vlang=<...>
    Equivalent to --alang and --slang, for video tracks.
  • --aid=<ID|auto|no>
    Select audio track. auto selects the default, no disables audio. See also --alang. mpv normally prints available audio tracks on the terminal when starting playback of a file.
    --audio is an alias for --aid.
  • --sid=<ID|auto|no>
    Display the subtitle stream specified by <ID>. auto selects the default, no disables subtitles.
    --sub is an alias for --sid.
  • --vid=<ID|auto|no>
    Select video channel. auto selects the default, no disables video.
    --video is an alias for --vid.

Playback Control

  • --start=<relative time>
    Seek to given time position.

    The general format for times is [+|-][[hh:]mm:]ss[.ms]. If the time is prefixed with -, the time is considered relative from the end of the file (as signaled by the demuxer/the file). A + is usually ignored.

    The following alternative time specifications are recognized:

    • pp% seeks to percent position pp (0-100).
    • #c seeks to chapter number c. (Chapters start from 1.)
    • none resets any previously set option (useful for libmpv).
  • --end=<relative time>
    Stop at given time. Use --length if the time should be relative to --start. See --start for valid option values and examples.

  • --length=<relative time>
    Stop after a given time relative to the start time. See --start for valid option values and examples.
    If both --end and --length are provided, playback will stop when it reaches either of the two endpoints.

  • --speed=<0.01-100>
    Slow down or speed up playback by the factor given as parameter.
    If --audio-pitch-correction (on by default) is used, playing with a speed higher than normal automatically inserts the scaletempo2 audio filter.

  • --pause
    Start the player in paused state.

  • --shuffle
    Play files in random order.

  • --playlist-start=<auto|index>
    Set which file on the internal playlist to start playback with. The index is an integer, with 0 meaning the first file. The value auto means that the selection of the entry to play is left to the playback resume mechanism (default).

  • --loop-playlist=<N|inf|force|no>, --loop-playlist
    Loops playback N times. A value of 1 plays it one time (default), 2 two times, etc. inf means forever. no is the same as 1 and disables looping. If several files are specified on command line, the entire playlist is looped. --loop-playlist is the same as --loop-playlist=inf.

  • --loop-file=<N|inf|no>, --loop=<N|inf|no>
    Loop a single file N times. inf means forever, no means normal playback. For compatibility, --loop-file and --loop-file=yes are also accepted, and are the same as --loop-file=inf.

    The difference to --loop-playlist is that this doesn't loop the playlist, just the file itself. If the playlist contains only a single file, the difference between the two option is that this option performs a seek on loop, instead of reloading the file.

  • --ab-loop-a=<time>, --ab-loop-b=<time>
    Set loop points. If playback passes the b timestamp, it will seek to the a timestamp. Seeking past the b point doesn't loop (this is intentional).

    If a is after b, the behavior is as if the points were given in the right order, and the player will seek to b after crossing through a. This is different from old behavior, where looping was disabled (and as a bug, looped back to a on the end of the file).

  • --ab-loop-count=<N|inf>
    Run A-B loops only N times, then ignore the A-B loop points (default: inf). Every finished loop iteration will decrement this option by 1 (unless it is set to inf or 0). inf means that looping goes on forever. If this option is set to 0, A-B looping is ignored, and even the ab-loop command will not enable looping again

  • --play-direction=<forward|+|backward|->
    Control the playback direction (default: forward). Setting backward will attempt to play the file in reverse direction, with decreasing playback time. If this is set on playback starts, playback will start from the end of the file. If this is changed at during playback, a hr-seek will be issued to change the direction.

    + and - are aliases for forward and backward.

Program Behaviour

  • --no-config
    Do not load default configuration or any user files. This prevents loading of both the user-level and system-wide mpv.conf and input.conf files.
  • --list-options
    Prints all available options.
  • --list-properties
    Print a list of the available properties.
  • --list-protocols
    Print a list of the supported protocols.
  • --idle=<no|yes|once>
    Makes mpv wait idly instead of quitting when there is no file to play. Mostly useful in input mode, where mpv can be controlled through input commands. (Default: no)
  • --include=<configuration-file>
    Specify configuration file to be parsed after the default ones.
  • --load-scripts=<yes|no>
    If set to no, don't auto-load scripts from the scripts configuration subdirectory
  • --script=<filename>, --scripts=file1.lua:file2.lua:...
    Load a Lua script. The second option allows you to load multiple scripts by separating them with the path separator (: on Unix, ; on Windows).
  • --profile=<profile1,profile2,...>
    Use the given profile(s), --profile=help displays a list of the defined profiles.
  • --show-profile=<profile>
    Show the description and content of a profile. Lists all profiles if no parameter is provided.
  • --ytdl-format=<ytdl|best|worst|mp4|webm|...>
    Video format/quality that is directly passed to youtube-dl.
  • --ytdl-raw-options=<key>=<value>[,<key>=<value>[,...]]
    Pass arbitrary options to youtube-dl.

Video

  • --vf=<filter1[=parameter1:parameter2:...],filter2,...>
    Specify a list of video filters to apply to the video stream. See VIDEO FILTERS for details and descriptions of the available filters. The option variants --vf-add, --vf-pre, and --vf-clr exist to modify a previously specified list, but you should not need these for typical use.

  • --video-aspect-override=<ratio|no>
    Override video aspect ratio, in case aspect information is incorrect or missing in the file being played.

  • --video-pan-x=<value>, --video-pan-y=<value>
    Moves the displayed video rectangle by the given value in the X or Y direction. The unit is in fractions of the size of the scaled video (the full size, even if parts of the video are not visible due to panscan or other options).

  • --video-rotate=<0-359|no>
    Rotate the video clockwise, in degrees. If no is given, the video is never rotated, even if the file has rotation metadata. (The rotation value is added to the rotation metadata, which means the value 0 would rotate the video according to the rotation metadata.)

  • --video-crop=<[W[xH]][+x+y]>, --video-crop=<x:y>
    Crop the video by starting at the x, y offset for w, h pixels. The crop is applied to the source video rectangle (before anamorphic stretch) by the VO. A crop rectangle that is not within the video rectangle will be ignored.

  • --video-zoom=<value>
    Adjust the video display scale factor by the given value. The parameter is given log 2. For example, --video-zoom=0 is unscaled, --video-zoom=1 is twice the size, --video-zoom=-2 is one fourth of the size, and so on.

  • --video-scale-x=<value>, --video-scale-y=<value>
    Multiply the video display size with the given value (default: 1.0). If a non-default value is used, this will be different from the window size, so video will be either cut off, or black bars are added.

  • --video-align-x=<-1-1>, --video-align-y=<-1-1>
    Moves the video rectangle within the black borders, which are usually added to pad the video to screen if video and screen aspect ratios are different. --video-align-y=-1 would move the video to the top of the screen (leaving a border only on the bottom), a value of 0 centers it (default), and a value of 1 would put the video at the bottom of the screen.

  • --video-margin-ratio-left=<val>, --video-margin-ratio-right=<val>, --video-margin-ratio-top=<val>, --video-margin-ratio-bottom=<val>
    Set extra video margins on each border (default: 0). Each value is a ratio of the window size, using a range 0.0-1.0. For example, setting the option --video-margin-ratio-right=0.2 at a window size of 1000 pixels will add a 200 pixels border on the right side of the window.

    The video is "boxed" by these margins. The window size is not changed. In particular it does not enlarge the window, and the margins will cause the video to be downscaled by default. This may or may not change in the future.

  • --frames=<number>
    Play/convert only first <number> video frames, then quit.

Audio

  • --audio-pitch-correction=<yes|no>
    If this is enabled (default), playing with a speed different from normal automatically inserts the scaletempo2 audio filter.

  • --audio-device=<name>
    Use the given audio device. This consists of the audio output name, e.g. alsa, followed by /, followed by the audio output specific device name. The default value for this option is auto, which tries every audio output in preference order with the default device.

    You can list audio devices with --audio-device=help. This outputs the device name in quotes, followed by a description. The device name is what you have to pass to the --audio-device option.

  • --af=<filter1[=parameter1:parameter2:...],filter2,...>
    Specify a list of audio filters to apply to the audio stream.

  • --volume=<value>
    Set the startup volume. 0 means silence, 100 means no volume reduction or amplification. Negative values can be passed for compatibility, but are treated as 0.

  • --audio-delay=<sec>
    Audio delay in seconds (positive or negative float value). Positive values delay the audio, and negative values delay the video.

  • --mute=<yes|no|auto>
    Set startup audio mute status (default: no).

  • --audio-files=<files>
    Play audio from an external file while viewing a video.

  • --audio-file=<file>
    CLI/config file only alias for --audio-files-append. Each use of this option will add a new audio track. The details are similar to how --sub-file works.

Subtitles

  • --sub-delay=<sec>
    Delays subtitles by <sec> seconds. Can be negative.

  • --sub-files=<file-list>, --sub-file=<filename>
    Add a subtitle file to the list of external subtitles.

    If you use --sub-file only once, this subtitle file is displayed by default.

    If --sub-file is used multiple times, the subtitle to use can be switched at runtime by cycling subtitle tracks. It's possible to show two subtitles at once: use --sid to select the first subtitle index, and --secondary-sid to select the second index. (The index is printed on the terminal output after the --sid= in the list of streams.)

  • --secondary-sid=<ID|auto|no>
    Select a secondary subtitle stream. This is similar to --sid. If a secondary subtitle is selected, it will be rendered as toptitle (i.e. on the top of the screen) alongside the normal subtitle, and provides a way to render two subtitles at once.

  • --sub-scale=<0-100>
    Factor for the text subtitle font size (default: 1).
    This affects ASS subtitles as well, and may lead to incorrect subtitle rendering. Use with care, or use --sub-font-size instead.

  • --sub-pos=<0-150>
    Specify the position of subtitles on the screen. The value is the vertical position of the subtitle in % of the screen height. 100 is the original position, which is often not the absolute bottom of the screen, but with some margin between the bottom and the subtitle. Values above 100 move the subtitle further down.

  • --sub-speed=<0.1-10.0>
    Multiply the subtitle event timestamps with the given value. Can be used to fix the playback speed for frame-based subtitle formats. Affects text subtitles only.

  • --sub-fix-timing=<yes|no>
    Adjust subtitle timing is to remove minor gaps or overlaps between subtitles (if the difference is smaller than 210 ms, the gap or overlap is removed).

  • --sub-font-size=<size>
    Specify the sub font size. The unit is the size in scaled pixels at a window height of 720. The actual pixel size is scaled with the window height: if the window height is larger or smaller than 720, the actual size of the text increases or decreases as well.

  • --sub-shadow-offset=<size>
    Displacement of the sub text shadow in scaled pixels (see --sub-font-size for details). A value of 0 disables shadows.

Window

  • --title=<string>
    Set the window title. This is used for the video window, and if possible, also sets the audio stream title. Properties are expanded.
  • --screen=<default|0-32>
    In multi-monitor configurations (i.e. a single desktop that spans across multiple displays), this option tells mpv which screen to display the video on.
  • --fullscreen, --fs
    Fullscreen playback.
  • --keep-open=<yes|no|always>
    Do not terminate when playing or seeking beyond the end of the file, and there is no next file to be played (and --loop is not used). Instead, pause the player. When trying to seek beyond end of the file, the player will attempt to seek to the last frame.
  • --image-display-duration=<seconds|inf>
    If the current file is an image, play the image for the given amount of seconds (default: 1). inf means the file is kept open forever (until the user stops playback manually).
  • --ontop
    Makes the player window stay on top of other windows.
    On Windows, if combined with fullscreen mode, this causes mpv to be treated as exclusive fullscreen window that bypasses the Desktop Window Manager.
  • --geometry=<[W[xH]][+-x+-y][/WS]>, --geometry=<x:y>
    Adjust the initial window position or size. W and H set the window size in pixels. x and y set the window position, measured in pixels from the top-left corner of the screen to the top-left corner of the image being displayed. If a percentage sign (%) is given after the argument, it turns the value into a percentage of the screen size in that direction.
  • --autofit=<[W[xH]]>
    Set the initial window size to a maximum size specified by WxH, without changing the window's aspect ratio. The size is measured in pixels, or if a number is followed by a percentage sign (%) in percents of the screen size.
  • --window-scale=<factor>
    Resize the video window to a multiple (or fraction) of the video size. This option is applied before --autofit and other options are applied (so they override this option).
  • --auto-window-resize=<yes|no>
    By default, mpv will automatically resize itself if the video's size changes (i.e. advancing forward in a playlist). Setting this to no disables this behavior so the window size never changes automatically.

Equalizer

  • --brightness=<-100-100>
    Adjust the brightness of the video signal (default: 0). Not supported by all video output drivers.
  • --contrast=<-100-100>
    Adjust the contrast of the video signal (default: 0). Not supported by all video output drivers.
  • --saturation=<-100-100>
    Adjust the saturation of the video signal (default: 0). You can get grayscale output with this option. Not supported by all video output drivers.
  • --gamma=<-100-100>
    Adjust the gamma of the video signal (default: 0). Not supported by all video output drivers.
  • --hue=<-100-100>
    Adjust the hue of the video signal (default: 0). You can get a colored negative of the image with this option. Not supported by all video output drivers.

Demuxer

  • --directory-mode=<auto|lazy|recursive|ignore>
    When opening a directory, open subdirectories lazily, recursively or not at all. The default is auto, which behaves like recursive with --shuffle, and like lazy otherwise.

Input

  • --input-conf=<filename>
    Specify input configuration file other than the default location in the mpv configuration directory (usually ~/.config/mpv/input.conf).
  • --input-keylist
    Prints all keys that can be bound to commands.
  • --input-gamepad=<yes|no>
    Enable/disable SDL2 Gamepad support. Disabled by default.

On Screen Controller

  • --osc, --no-osc
    Whether to load the on-screen-controller (default: yes).
  • --no-osd-bar, --osd-bar
    Disable display of the OSD bar.
  • --osd-font-size=<size>
    Specify the OSD font size. See --sub-font-size for details.

Screenshot

  • --screenshot-format=<type>
    Set the image file type used for saving screenshots.

    Available choices:

    • png: PNG
    • jpg: JPEG (default)
    • jpeg: JPEG (alias for jpg)
    • webp: WebP
    • jxl: JPEG XL
    • avif: AVIF
  • --screenshot-template=<template>
    Specify the filename template used to save screenshots. The template specifies the filename without file extension, and can contain format specifiers, which will be substituted when taking a screenshot. By default, the template is mpv-shot%n, which results in filenames like mpv-shot0012.png for example.

    The template can start with a relative or absolute path, in order to specify a directory location where screenshots should be saved.

    Allowed format specifiers:

Format Description
%[#][0X]n A sequence number, padded with zeros to length X (default: 04). E.g. passing the format %04n will yield 0012 on the 12th screenshot. The number is incremented every time a screenshot is taken or if the file already exists. The length X must be in the range 0-9. With the optional # sign, mpv will use the lowest available number. For example, if you take three screenshots--0001, 0002, 0003--and delete the first two, the next two screenshots will not be 0004 and 0005, but 0001 and 0002 again.
%f Filename of the currently played video.
%F Same as %f, but strip the file extension, including the dot.
%x Directory path of the currently played video. If the video is not on the filesystem (but e.g. http://), this expand to an empty string.
%X{fallback} Same as %x, but if the video file is not on the filesystem, return the fallback string inside the {...}.
%p Current playback time, in the same format as used in the OSD. The result is a string of the form HH:MM:SS. For example, if the video is at the time position 5 minutes and 34 seconds, %p will be replaced with 00:05:34.
%P Similar to %p, but extended with the playback time in milliseconds. It is formatted as HH:MM:SS.mmm, with mmm being the millisecond part of the playback time.
%wX Specify the current playback time using the format string X. %p is like %wH:%wM:%wS, and %P is like %wH:%wM:%wS.%wT.
Valid format specifiers:
- %wH: hour (padded with 0 to two digits)
- %wh: hour (not padded)
- %wM: minutes (00-59)
- %wm: total minutes (includes hours, unlike %wM)
- %wS: seconds (00-59)
- %ws: total seconds (includes hours and minutes)
- %wf: like %ws, but as float
- %wT: milliseconds (000-999)
%tX Specify the current local date/time using the format X. This format specifier uses the UNIX strftime() function internally, and inserts the result of passing %X to strftime. For example, %tm will insert the number of the current month as number. You have to use multiple %tX specifiers to build a full date/time string.
%% Replaced with the % character itself.
  • --screenshot-dir=<path>
    Store screenshots in this directory. This path is joined with the filename generated by --screenshot-template. If the template filename is already absolute, the directory is ignored.
    If the directory does not exist, it is created on the first screenshot. If it is not a directory, an error is generated when trying to write a screenshot.

Cache

  • --cache=<yes|no|auto>
    Decide whether to use network cache settings (default: auto).
  • --cache-secs=<seconds>
    How many seconds of audio/video to prefetch if the cache is active.

Network

  • --user-agent=<string>
    Use <string> as user agent for HTTP streaming.
  • --cookies, --no-cookies
    Support cookies when making HTTP requests. Disabled by default.
  • --cookies-file=<filename>
    Read HTTP cookies from <filename>. The file is assumed to be in Netscape format.
  • --http-header-fields=<field1,field2>
    Set custom HTTP fields when accessing HTTP stream.
  • --http-proxy=<proxy>
    URL of the HTTP/HTTPS proxy. If this is set, the http_proxy environment is ignored. The no_proxy environment variable is still respected. This option is silently ignored if it does not start with http://. Proxies are not used for https URLs. Setting this option does not try to make the ytdl script use the proxy.

Video Filters

To see a list of all available video filters: mpv -vf=help

crop

Crop the video
Usage: mpv -vf=crop=<out_w>:<out_h>:<x>:<y>:<keep_aspect>:<exact>

Options

Option Description
out_w set the width crop area expression
out_h set the height crop area expression
x set the x crop area expression
y set the y crop area expression
keep_aspect keep aspect ratio
exact do exact cropping

drawbox

Draw a colored box on the input video.
Usage: mpv -vf=drawbox=<x>:<w>:<width>:<height>:<color>:<thickness>:<replace>:<box_source>

Options

Option Description
x set horizontal position of the left box edge
y set vertical position of the top box edge
width set width of the box
height set height of the box
color set color of the box
thickness set the box thickness
replace replace color & alpha
box_source use datas from bounding box in side data

eq

Adjust brightness, contrast, gamma, and saturation.
Usage: mpv -vf=eq=<contrast>:<brightness>:<saturation>:<gamma>:<gamma_r>:<gamma_g>:<gamma_b>:<gamma_weight>

Options

Option Description
contrast set the contrast adjustment, negative values give a negative image
brightness set the brightness adjustment
saturation set the saturation adjustment
gamma set the initial gamma value
gamma_r gamma value for red
gamma_g gamma value for green
gamma_b gamma value for blue
gamma_weight set the gamma weight which reduces the effect of gamma on bright areas

framerate

Upsamples or downsamples progressive source between specified frame rates.
Usage: mpv -vf=framerate=<fps>

framestep

Select one frame every N frames.
Usage: mpv -vf=framestep=<step>

gblur

Apply Gaussian Blur filter.
Usage: mpv -vf=gblur=<sigma>:<steps>:<planes>:<sigmaV>

Options

Option Description
sigma set sigma
steps set number of steps
planes set planes to filter
sigmaV set vertical sigma

hflip

Horizontally flip the input video.
Usage: mpv -vf=hflip

vflip

Flip the input video vertically.
Usage: mpv -vf=vflip

pixelize

Pixelize video.
Usage: mpv -vf=pixelize=<width>:<height>

rotate

Rotate the input image.
Usage: mpv -vf=rotate=<angle>:<out_w>:<out_h>:<fillcolor>:<bilinear>

Options

Option Description
angle set angle (in radians)
out_w set output width expression
out_h set output height expression
fillcolor set background fill color
bilinear use bilinear interpolation

scale

Scale the input video size and/or convert the image format.
Usage: mpv -vf=scale=<w>:<h>

swaprect

Swap 2 rectangular objects in video.
Usage: mpv -vf=swaprect=<w>:<h>:<x1>:<y1>:<x2>:<y2>

Options

Option Description
w set rect width
h set rect height
x1 set 1st rect x top left coordinate
y1 set 1st rect y top left coordinate
x2 set 2nd rect x top left coordinate
y2 set 2nd rect y top left coordinate

Audio Filters

To see a list of all available audio filters: mpv -af=help

volume

Change input volume.
Usage: mpv -af=volume=<volume>

Encoding

You can encode files from one format/codec to another using this facility. This is useful if you want to apply filters to a file.

  • --o=<filename>
    Enables encoding mode and specifies the output file name.
  • --of=<format>
    Specifies the output format (overrides autodetection by the file name extension of the file specified by -o). See --of=help for a full list of supported formats.
  • --oac=<codec>
    Specifies the output audio codec. See --oac=help for a full list of supported codecs.
  • --oacopts=<options>
    Specifies the output audio codec options for libavcodec. See --oacopts=help for a full list of supported options.
    Example:
    # selects 128 kbps MP3 encoding.
    --oac=libmp3lame --oacopts=b=128000
    
  • --ovc=<codec>
    Specifies the output video codec. See --ovc=help for a full list of supported codecs.
  • --ovcopts=<options>
    Specifies the output video codec options for libavcodec. See --ovcopts=help for a full list of supported options.

Command Interface & Input Mapping

The keymap file is located in the mpv configuration directory (normally at ~/.config/mpv/input.conf depending on platform). The default bindings are defined here.
The input.conf file consists of a list of key bindings, for example:

s screenshot      # take a screenshot with the s key
LEFT seek 15      # map the left-arrow key to seeking forward by 15 seconds

Each line maps a key to an input command. Keys are specified with their literal value (upper case if combined with Shift), or a name for special keys. For example, a maps to the a key without shift, and A maps to a with shift.
Syntax: [Shift+][Ctrl+][Alt+][Meta+]<key> [{<section>}] <command> ( ; <command> )*

List of Input Commands

Commands with parameters have the parameter name enclosed in < / >. Don't add those to the actual command. Optional arguments are enclosed in [ / ]. If you don't pass them, they will be set to a default value.

  • ignore
    Use this to "block" keys that should be unbound, and do nothing. Useful for disabling default bindings, without disabling all bindings with --no-input-default-bindings.
  • seek <target> [<flags>]
    Change the playback position. By default, seeks by a relative amount of seconds.

The second argument consists of flags controlling the seek mode:

Mode Description
relative (default) Seek relative to current position (a negative value seeks backwards).
absolute Seek to a given time (a negative value starts from the end of the file).
absolute-percent Seek to a given percent position.
relative-percent Seek relative to current position in percent.
keyframes Always restart playback at keyframe boundaries (fast).
exact Always do exact/hr/precise seeks (slow).
  • set <name> <value>
    Set the given property or option to the given value.
  • del <name>
    Delete the given property. Most properties cannot be deleted.
  • add <name> [<value>]
    Add the given value to the property or option. On overflow or underflow, clamp the property to the maximum. If <value> is omitted, assume 1.
  • screenshot <flags>
    Take a screenshot.

Multiple flags are available (some can be combined with +):

Flag Description
<subtitles> (default) Save the video image, in its original resolution, and with subtitles. Some video outputs may still include the OSD in the output under certain circumstances.
<video> Like subtitles, but typically without OSD or subtitles. The exact behavior depends on the selected video output.
<window> Save the contents of the mpv window. Typically scaled, with OSD and subtitles. The exact behavior depends on the selected video output.
<each-frame> Take a screenshot each frame. Issue this command again to stop taking screenshots. Note that you should disable frame-dropping when using this mode - or you might receive duplicate images in cases when a frame was dropped. This flag can be combined with the other flags, e.g. video+each-frame.
  • playlist-next
    Go to the next entry on the playlist.
  • playlist-prev
    Go to the previous entry on the playlist.
  • playlist-play-index <integer|current|none>
    Start (or restart) playback of the given playlist index.
  • loadfile <url> [<flags> [<options>]]
    Load the given file or URL and play it. Technically, this is just a playlist manipulation command (which either replaces the playlist or appends an entry to it). Actual file loading happens independently. For example, a loadfile command that replaces the current file with a new one returns before the current file is stopped, and the new file even begins loading.
  • loadlist <url> [<flags>]
    Load the given playlist file or URL (like --playlist).
  • playlist-clear
    Clear the playlist, except the currently played file.
  • playlist-remove <index>
    Remove the playlist entry at the given index. Index values start counting with 0. The special value current removes the current entry. Note that removing the current entry also stops playback and starts playing the next entry.
  • playlist-move <index1> <index2>
    Move the playlist entry at index1, so that it takes the place of the entry index2. (Paradoxically, the moved playlist entry will not have the index value index2 after moving if index1 was lower than index2, because index2 refers to the target entry, not the index the entry will have after moving.)
  • playlist-shuffle
    Shuffle the playlist. This is similar to what is done on start if the --shuffle option is used.
  • run <command> [<arg1> [<arg2> [...]]]
    Run the given command. Unlike in MPlayer/mplayer2 and earlier versions of mpv (0.2.x and older), this doesn't call the shell. Instead, the command is run directly, with each argument passed separately. Each argument is expanded like in Property Expansion.
    This command has a variable number of arguments, and cannot be used with named arguments.
    The program is run in a detached way. mpv doesn't wait until the command is completed, but continues playback right after spawning it.
  • quit [<code>]
    Exit the player. If an argument is given, it's used as process exit code.
  • sub-add <url> [<flags> [<title> [<lang>]]]
    Load the given subtitle file or stream. By default, it is selected as current subtitle after loading.
  • sub-remove [<id>]
    Remove the given subtitle track. If the id argument is missing, remove the current track. (Works on external subtitle files only.)
  • show-text <text> [<duration>|-1 [<level>]]
    Show text on the OSD. The string can contain properties, which are expanded as described in Property Expansion. This can be used to show playback time, filename, and so on. no-osd has no effect on this command.
  • expand-text <string>
    Property-expand the argument and return the expanded string. This can be used only through the client API or from a script using mp.command_native.
  • audio-add <url> [<flags> [<title> [<lang>]]]
    Load the given audio file.
  • audio-remove [<id>]
    Remove the given audio track.
  • audio-reload [<id>]
    Reload the given audio tracks.
  • video-add <url> [<flags> [<title> [<lang> [<albumart>]]]]
    Load the given video file.
  • video-remove [<id>]
    Remove the given video track.
  • video-reload [<id>]
    Reload the given video tracks.

List of Properties

  • filename
    Currently played file, with path stripped. If this is an URL, try to undo percent encoding as well. (The result is not necessarily correct, but looks better for display purposes. Use the path property to get an unmodified filename.)
  • filename/no-ext
    Like the filename property, but if the text contains a ., strip all text after the last .. Usually this removes the file extension.
  • file-size
    Length in bytes of the source file/stream.
  • estimated-frame-count
    Total number of frames in current file.
  • pid
    Process-id of mpv.
  • media-title
    If the currently played file has a title tag, use that. Otherwise, return the filename property.
  • file-format
    Symbolic name of the file format. In some cases, this is a comma-separated list of format names, e.g. mp4 is mov,mp4,m4a,3gp,3g2,mj2 (the list may grow in the future for any format).
  • duration
    Duration of the current file in seconds. If the duration is unknown, the property is unavailable. Note that the file duration is not always exactly known, so this is an estimate.
  • duration/full
    duration with milliseconds.
  • percent-pos (RW)
    Position in current file (0-100). The advantage over using this instead of calculating it out of other properties is that it properly falls back to estimating the playback position from the byte position, if the file duration is not known.
  • time-pos (RW)
    Position in current file in seconds.
  • time-pos/full
    time-pos with milliseconds.
  • time-remaining
    Remaining length of the file in seconds. Note that the file duration is not always exactly known, so this is an estimate.
  • time-remaining/full
    time-remaining with milliseconds.
  • playtime-remaining
    time-remaining scaled by the current speed.
  • playtime-remaining/full
    playtime-remaining with milliseconds.
  • chapter (RW)
    Current chapter number. The number of the first chapter is 0.
  • chapters
    Number of chapters.
  • metadata
    Metadata key/value pairs.
  • metadata/by-key/<key>
    Value of metadata entry <key>.
  • metadata/list/count
    Number of metadata entries.
  • metadata/list/N/key
    Key name of the Nth metadata entry. (The first entry is 0).
  • metadata/list/N/value
    Value of the Nth metadata entry.
  • width, height
    Video size. This uses the size of the video as decoded, or if no video frame has been decoded yet, the (possibly incorrect) container indicated size.
  • playlist-pos (RW)
    Current position on playlist. The first entry is on position 0. Writing to this property may start playback at the new position.
  • playlist-count
    Number of total playlist entries.
  • working-directory
    The working directory of the mpv process. Can be useful for JSON IPC users, because the command line player usually works with relative paths.

Configuration

You can put all of the options in configuration files which will be read every time mpv is run. The system-wide configuration file 'mpv.conf' is in your configuration directory (e.g. /etc/mpv or /usr/local/etc/mpv), the user-specific one is ~/.config/mpv/mpv.conf.

Almost all command line options can be put into the configuration file. Here is a small guide:

Option Configuration file entry
--flag flag
-opt val opt=val
--opt=val opt=val
-opt "has spaces" opt=has spaces

Profiles

To ease working with different configurations, profiles can be defined in the configuration files. A profile starts with its name in square brackets, e.g. [my-profile]. All following options will be part of the profile. A description (shown by --profile=help) can be defined with the profile-desc option. To end the profile, start another one or use the profile name default to continue with normal options.

You can list profiles with --profile=help, and show the contents of a profile with --show-profile=<name> (replace <name> with the profile name). You can apply profiles on start with the --profile=<name> option, or at runtime with the apply-profile <name> command.

Conditional Profiles

Profiles which have the profile-cond option set are applied automatically if the associated condition matches (unless auto profiles are disabled). The option takes a string, which is interpreted as Lua expression. If the expression evaluates as truthy, the profile is applied. If the expression errors or evaluates as falsy, the profile is not applied. This Lua code execution is not sandboxed.

Make only HD video look funny:

[something]
profile-desc=HD video
profile-cond=width >= 1280
hue=-50

Make only videos containing "youtube" or "youtu.be" in their path brighter:

[youtube]
profile-cond=path:find('youtu%.?be')
gamma=20

If you want the profile to be reverted if the condition goes to false again, you can set profile-restore:

[something]
profile-desc=Mess up video when entering fullscreen
profile-cond=fullscreen
profile-restore=copy
vf-add=rotate=PI/2  # rotate by 90 degrees

This appends the rotate filter to the video filter chain when entering fullscreen. When leaving fullscreen, the vf option is set to the value it had before entering fullscreen. Note that this would also remove any other filters that were added during fullscreen mode by the user. Avoiding this is trickier, and could for example be solved by adding a second profile with an inverse condition and operation:

[something]
profile-cond=fullscreen
vf-add=@rot:rotate=PI/2

[something-inv]
profile-cond=not fullscreen
vf-remove=@rot

Lua Scripting

MPV can load Lua scripts.
mpv provides the built-in module mp, which contains functions to send commands to the mpv core and to retrieve information about playback state, user settings, file information, and so on.
Scripts can be passed to the --script option, and are automatically loaded from the scripts subdirectory of the mpv configuration directory (usually ~/.config/mpv/scripts/).

Example - A script which leaves fullscreen mode when the player is paused:

function on_pause_change(name, value)
    if value == true then
        mp.set_property("fullscreen", "no")
    end
end
mp.observe_property("pause", "bool", on_pause_change)

mp functions

The mp module is preloaded, although it can be loaded manually with require 'mp'. It provides the core client API.

  • mp.command(string)
    Run the given command. This is similar to the commands used in input.conf.
    Returns true on success, or nil, error on error.

  • mp.commandv(arg1, arg2, ...)
    Similar to mp.command, but pass each command argument as separate parameter. This has the advantage that you don't have to care about quoting and escaping in some cases.

    Example:

    mp.command("loadfile " .. filename .. " append")
    mp.commandv("loadfile", filename, "append")
    

    These two commands are equivalent, except that the first version breaks if the filename contains spaces or certain special characters.

    Note that properties are not expanded. You can use either mp.command, the expand-properties prefix, or the mp.get_property family of functions.

    Unlike mp.command, this will not use OSD by default either (except for some OSD-specific commands).

  • mp.del_property(name)
    Delete the given property. See mp.get_property and Properties for more information about properties. Most properties cannot be deleted.

    Returns true on success, or nil, error on error.

  • mp.get_property(name [,def])
    Return the value of the given property as string. These are the same properties as used in input.conf. See Properties for a list of properties. The returned string is formatted similar to ${=name}.

    Returns the string on success, or def, error on error. def is the second parameter provided to the function, and is nil if it's missing.

  • mp.get_property_osd(name [,def])
    Similar to mp.get_property, but return the property value formatted for OSD. This is the same string as printed with ${name} when used in input.conf.

    Returns the string on success, or def, error on error. def is the second parameter provided to the function, and is an empty string if it's missing. Unlike get_property(), assigning the return value to a variable will always result in a string.

  • mp.get_property_bool(name [,def])
    Similar to mp.get_property, but return the property value as Boolean.

    Returns a Boolean on success, or def, error on error.

  • mp.get_property_number(name [,def])
    Similar to mp.get_property, but return the property value as number.

    Note that while Lua does not distinguish between integers and floats, mpv internals do. This function simply request a double float from mpv, and mpv will usually convert integer property values to float.

    Returns a number on success, or def, error on error.

  • mp.get_property_native(name [,def])
    Similar to mp.get_property, but return the property value using the best Lua type for the property. Most time, this will return a string, Boolean, or number. Some properties (for example chapter-list) are returned as tables.

    Returns a value on success, or def, error on error. Note that nil might be a possible, valid value too in some corner cases.

  • mp.set_property(name, value)
    Set the given property to the given string value.

    Returns true on success, or nil, error on error.

  • mp.set_property_bool(name, value)
    Similar to mp.set_property, but set the given property to the given Boolean value.

  • mp.set_property_number(name, value)
    Similar to mp.set_property, but set the given property to the given numeric value.

    Note that while Lua does not distinguish between integers and floats, mpv internals do. This function will test whether the number can be represented as integer, and if so, it will pass an integer value to mpv, otherwise a double float.

  • mp.set_property_native(name, value)
    Similar to mp.set_property, but set the given property using its native type.

    Since there are several data types which cannot represented natively in Lua, this might not always work as expected. For example, while the Lua wrapper can do some guesswork to decide whether a Lua table is an array or a map, this would fail with empty tables. Also, there are not many properties for which it makes sense to use this, instead of set_property, set_property_bool, set_property_number. For these reasons, this function should probably be avoided for now, except for properties that use tables natively.

  • mp.get_time()
    Return the current mpv internal time in seconds as a number. This is basically the system time, with an arbitrary offset.

  • mp.add_key_binding(key, name|fn [,fn [,flags]])
    Register callback to be run on a key binding. The binding will be mapped to the given key, which is a string describing the physical key. This uses the same key names as in input.conf, and also allows combinations (e.g. ctrl+a). If the key is empty or nil, no physical key is registered, but the user still can create own bindings (see below).

    After calling this function, key presses will cause the function fn to be called (unless the user remapped the key with another binding).

    The name argument should be a short symbolic string. It allows the user to remap the key binding via input.conf using the script-message command, and the name of the key binding (see below for an example). The name should be unique across other bindings in the same script - if not, the previous binding with the same name will be overwritten. You can omit the name, in which case a random name is generated internally. (Omitting works as follows: either pass nil for name, or pass the fn argument in place of the name. The latter is not recommended and is handled for compatibility only.)

    The last argument is used for optional flags. This is a table, which can have the following entries:

    • repeatable
      If set to true, enables key repeat for this specific binding.
    • complex
      If set to true, then fn is called on both key up and down events (as well as key repeat, if enabled), with the first argument being a table. This table has the following entries (and may contain undocumented ones):
      • event
        Set to one of the strings down, repeat, up or press (the latter if key up/down can't be tracked).
      • is_mouse
        Boolean Whether the event was caused by a mouse button.
      • key_name
        The name of they key that triggered this, or nil if invoked artificially. If the key name is unknown, it's an empty string.
      • key_text
        Text if triggered by a text key, otherwise nil. See description of script-binding command for details (this field is equivalent to the 5th argument).

    Internally, key bindings are dispatched via the script-message-to or script-binding input commands and mp.register_script_message.

    Example:

    function something_handler()
        print("the key was pressed")
    end
    mp.add_key_binding("x", "something", something_handler)
    

    This will print the message the key was pressed when x was pressed.

    The user can remap these key bindings. Then the user has to put the following into their input.conf to remap the command to the y key:

    y script-binding something
    

    This will print the message when the key y is pressed. (x will still work, unless the user remaps it.)

    You can also explicitly send a message to a named script only. Assume the above script was using the filename fooscript.lua:

    y script-binding fooscript/something
    
  • mp.remove_key_binding(name)
    Remove a key binding added with mp.add_key_binding. Use the same name as you used when adding the bindings. It's not possible to remove bindings for which you omitted the name.

  • mp.observe_property(name, type, fn)
    Watch a property for changes. If the property name is changed, then the function fn(name) will be called. type can be nil, or be set to one of none, native, bool, string, or number. none is the same as nil. For all other values, the new value of the property will be passed as second argument to fn, using mp.get_property_<type> to retrieve it. This means if type is for example string, fn is roughly called as in fn(name, mp.get_property_string(name)).

    If possible, change events are coalesced. If a property is changed a bunch of times in a row, only the last change triggers the change function. (The exact behavior depends on timing and other things.)

    If a property is unavailable, or on error, the value argument to fn is nil. (The observe_property() call always succeeds, even if a property does not exist.)

    In some cases the function is not called even if the property changes. This depends on the property, and it's a valid feature request to ask for better update handling of a specific property.

    If the type is none or nil, sporadic property change events are possible. This means the change function fn can be called even if the property doesn't actually change.

    You always get an initial change notification. This is meant to initialize the user's state to the current value of the property.

  • mp.unobserve_property(fn)
    Undo mp.observe_property(..., fn). This removes all property handlers that are equal to the fn parameter. This uses normal Lua == comparison, so be careful when dealing with closures.

  • mp.add_timeout(seconds, fn [, disabled])
    Call the given function fn when the given number of seconds has elapsed. Note that the number of seconds can be fractional. For now, the timer's resolution may be as low as 50 ms, although this will be improved in the future.

    If the disabled argument is set to true or a truthy value, the timer will wait to be manually started with a call to its resume() method.

    This is a one-shot timer: it will be removed when it's fired.

    Returns a timer object. See mp.add_periodic_timer for details.

  • mp.add_periodic_timer(seconds, fn [, disabled])
    Call the given function periodically. This is like mp.add_timeout, but the timer is re-added after the function fn is run.

    Returns a timer object. The timer object provides the following methods:

    • stop()
      Disable the timer. Does nothing if the timer is already disabled. This will remember the current elapsed time when stopping, so that resume() essentially unpauses the timer.

    • kill()
      Disable the timer. Resets the elapsed time. resume() will restart the timer.

    • resume()
      Restart the timer. If the timer was disabled with stop(), this will resume at the time it was stopped. If the timer was disabled with kill(), or if it's a previously fired one-shot timer (added with add_timeout()), this starts the timer from the beginning, using the initially configured timeout.

    • is_enabled()
      Whether the timer is currently enabled or was previously disabled (e.g. by stop() or kill()).

    • timeout (RW)
      This field contains the current timeout period. This value is not updated as time progresses. It's only used to calculate when the timer should fire next when the timer expires.

      If you write this, you can call t:kill() ; t:resume() to reset the current timeout to the new one. (t:stop() won't use the new timeout.)

    • oneshot (RW)
      Whether the timer is periodic (false) or fires just once (true). This value is used when the timer expires (but before the timer callback function fn is run).

    Note that these are methods, and you have to call them using : instead of . (Refer to https://www.lua.org/manual/5.2/manual.html#3.4.9 .)

    Example:

    seconds = 0
    timer = mp.add_periodic_timer(1, function()
        print("called every second")
        # stop it after 10 seconds
        seconds = seconds + 1
        if seconds >= 10 then
            timer:kill()
        end
    end)
    
  • mp.osd_message(text [,duration])
    Show an OSD message on the screen. duration is in seconds, and is optional.

mp.utils

This built-in module provides generic helper functions for Lua, and have strictly speaking nothing to do with mpv or video/audio playback. They are provided for convenience. Most compensate for Lua's scarce standard library.

Be warned that any of these functions might disappear any time. They are not strictly part of the guaranteed API.

  • utils.getcwd()
    Returns the directory that mpv was launched from. On error, nil, error is returned.

  • utils.readdir(path [, filter])
    Enumerate all entries at the given path on the filesystem, and return them as array. Each entry is a directory entry (without the path). The list is unsorted (in whatever order the operating system returns it).

    If the filter argument is given, it must be one of the following strings:

    • files
      List regular files only. This excludes directories, special files (like UNIX device files or FIFOs), and dead symlinks. It includes UNIX symlinks to regular files.
    • dirs
      List directories only, or symlinks to directories. . and .. are not included.
    • normal
      Include the results of both files and dirs. (This is the default.)
    • all
      List all entries, even device files, dead symlinks, FIFOs, and the . and .. entries.

    On error, nil, error is returned.

  • utils.file_info(path)
    Stats the given path for information and returns a table with the following entries:

    • mode
      protection bits
    • size
      size in bytes
    • atime
      time of last access
    • mtime
      time of last modification
    • ctime
      time of last metadata change
    • is_file
      Whether path is a regular file (boolean)
    • is_dir
      Whether path is a directory (boolean)

    mode and size are integers. Timestamps (atime, mtime and ctime) are integer seconds since the Unix epoch (Unix time). The booleans is_file and is_dir are provided as a convenience; they can be and are derived from mode.

    On error (e.g. path does not exist), nil, error is returned.

  • utils.split_path(path)
    Split a path into directory component and filename component, and return them. The first return value is always the directory. The second return value is the trailing part of the path, the directory entry.

  • utils.join_path(p1, p2)
    Return the concatenation of the 2 paths. Tries to be clever. For example, if p2 is an absolute path, p2 is returned without change.

  • utils.get_env_list()
    Returns the C environment as a list of strings.

  • utils.parse_json(str [, trail])
    Parses the given string argument as JSON, and returns it as a Lua table. On error, returns nil, error. (Currently, error is just a string reading error, because there is no fine-grained error reporting of any kind.)

    The returned value uses similar conventions as mp.get_property_native() to distinguish empty objects and arrays.

    If the trail parameter is true (or any value equal to true), then trailing non-whitespace text is tolerated by the function, and the trailing text is returned as 3rd return value. (The 3rd return value is always there, but with trail set, no error is raised.)

  • utils.format_json(v)
    Format the given Lua table (or value) as a JSON string and return it. On error, returns nil, error. (Errors usually only happen on value types incompatible with JSON.)

    The argument value uses similar conventions as mp.set_property_native() to distinguish empty objects and arrays.

  • utils.to_string(v)
    Turn the given value into a string. Formats tables and their contents. This doesn't do anything special; it is only needed because Lua is terrible.

User Scripts

  • autoloop: Automatically loops files that are under a given duration (default 5 seconds).
  • copyTime: Get the current time of the video and copy it to the clipboard with the format HH:MM:SS.MS.