Compare commits

..
54 Commits
Author SHA1 Message Date
wm4 78adec6c9c Release 0.2.3 2013-11-08 00:01:29 +01:00
wm4 0fed032ca0 audio: fix bogus audio format comparison 2013-11-07 23:59:38 +01:00
wm4 96532916fe osdep: handle SIGTERM
There's no reason why we should e.g. handle SIGQUIT, but not SIGTERM.

Note that sending SIGTERM twice still kills the player.
2013-11-07 23:58:56 +01:00
wm4 c265855d44 input.conf: clarify the magic how default key bindings are added
This is a confusing mechanism, so the explanation should bit more clear.
2013-11-07 23:58:47 +01:00
wm4 7816fa9745 manpage: fix incorrect default for --osc 2013-11-07 23:58:12 +01:00
wm4 e76076da3d stream_lavf: support more libavformat protocols 2013-11-07 23:57:56 +01:00
wm4 90015a8b8b vo_opengl: reserve 4 texture units for video instead of 3
Video has up to 4 textures, if you include obscure formats with alpha.
This means alpha formats could always overwrite the first scaler
texture, leading to corrupted video display. This problem was recently
brought to light, when commit 571e697 started to explicitly unbind all 4
video textures, which broke rendering for non-alpha formats as well.

Fix this by reserving the correct number of texture units.
2013-11-07 23:57:43 +01:00
ChrisK2 d1a8dfb8c4 tools: add --no-cache --no-config to mpv_identify.sh 2013-11-07 23:57:16 +01:00
wm4 e68fcbfa39 player: fix quvi 0.9 playlist loading
The code made no sense at all.

Conflicts:
	mpvcore/player/loadfile.c
2013-11-07 23:57:05 +01:00
wm4 391c087d75 stream: reconnecting doesn't make sense if stream is not seekable
This stops mpv from being stuck in reconnecting at the end of the file
with some unseekable streams.

Test URL: http://playerservices.streamtheworld.com/pls/CBC_R1_VCR_H.pls
2013-11-07 23:55:45 +01:00
wm4 b4f6e57d2c Release 0.2.2 2013-11-02 20:11:57 +01:00
wm4 854cdb796e ta: re-add MinGW cargo culting
Not really cargo cult, but an unexplainable, needless difference that
just exists to annoy us.

Fixes that gcc on MinGW treats format specifiers in MSVC mode. Just why?
Why?
2013-11-02 19:06:59 +01:00
wm4 504c452568 sd_lavc: display DVD subs with unknown duration
DVD subs (rarely) have subtitle events without end timestamp. The
duration is unknown, and they should be displayed until they're
replaced by the next event.

FFmpeg fails hard to make us aware whether duration is unknown or
actually 0, so we can't distinguish between these two cases. It fails
at this twice: AVPacket.duration is set to 0 if duration is unknown,
and AVSubtitle.end_display_time has the same issue.

Add a hack that considers all bitmap subtitles with duration==0 as
events with uknown length. I'd rather accidentally display a hidden
subtitle (if they exist at all), instead of not displaying random
subtitles at all.

See github issue #325.
2013-11-02 19:06:16 +01:00
wm4 ee54711ceb ao_pulse: fix channel layouts
The code was selecting PA_CHANNEL_POSITION_MONO for MP_SPEAKER_ID_FC,
which is correct only with the "mono" channel layout, but not anything
else. Remove the mono entry, and handle mono separately.

See github issue #326.
2013-11-02 19:06:13 +01:00
wm4 3ac568714c vd_lavc: add more ifdeffery and ffmpeg cargo culting for correctness
We mixed the "old" AVFrame management functions (avcodec_alloc_frame,
avcodec_free_frame) with reference counting. This doesn't work
correctly; you must use av_frame_alloc and av_frame_free. Of course
ffmpeg doesn't warn us about the bad usage, but will just mess up
things silently. (Thanks a lot...)

While the alloc function seems to be 100% compatible, the free function
will do bad things, such as freeing memory that might still be
referenced by another frame. I didn't experience any actual bugs, but
maybe that was pure luck.
2013-11-02 19:06:10 +01:00
Rudolf Polzer d64b165b2a encoding-example-configs: add more comments regarding the scaling method 2013-11-02 19:06:02 +01:00
Stefano Pigozzi 78a57135f9 gl_common: osx: fix compilation with latest XQuartz RC
Looks the gl.h header in XQuartz is incompatible with the one in OS X 10.9.
2013-11-02 19:05:58 +01:00
wm4 09f00db142 x11: restore support for --wid=0
This stopped working when the code was changed to create a window even
if --wid is used.

It appears we can't create our own window in this case, because in X11
there is no difference between a window with the root window as parent,
and a window that is managed by the WM. So make this (kind of worthless)
special case use the root window itself.
2013-11-02 19:05:43 +01:00
Rudolf Polzer 673919df7d Fix style of the HP Slate 7 vf-add line. 2013-11-02 19:05:24 +01:00
Rudolf Polzer d2fc1534c8 encoding-example-profiles: support HP Slate 7's weird aspect.
Also, replace broken noup= by lavfi expressions.
2013-11-02 19:05:21 +01:00
wm4 10c3b71720 gl_x11: change error message when GL3 context creation fails
On systems that provide legacy OpenGL (up to 2.1), but not GL3 and
later, creating a GL3 context will fail. We then revert to legacy GL.

Apparently the error message printed when the GL3 context creation
fails is confusing. We could just silence it, but there's still a X
error ("X11 error: GLXBadFBConfig"), which would be quite hard to
filter out. For one, it would require messing with the X11 error
handler, which doesn't even carry a context pointer (for application
private data), so we don't even want to touch it. Instead, change
the error message to inform the user what's actually happening: a
fallback to an older version of OpenGL.
2013-11-02 19:05:10 +01:00
wm4 0ba3760745 getch2: assume EOF when input file descriptor is invalid
When starting mpv with nohup, file descriptor 0 seems to be invalid for
some reason. (I'm not quite sure why it should be... /proc/pid/fd/0
seems to indicate it's just /dev/null, and using /dev/null explicitly
shows that it works just fine.)

select() will always immediately return, and this causes mpv to burn CPU
without reason. Fix this by treating it as EOF when read() returns
EBADF.

Also add EINVAL to this condition, because it seems like a good idea.

Conflicts:
	osdep/getch2.c
2013-11-02 19:05:04 +01:00
Stefano Pigozzi 1dbbd845a4 cocoa: apply the more invasive constraining only with cmd+1/2/3
Regression from bc49957
Fixes #321
2013-11-02 19:03:50 +01:00
wm4 131fad8bc9 x11: fix border toggling
Trying to toggle the border during fullscreen (with "cycle border")
would leave the window stuck without border, and it couldn't be
restored. This was because vo_x11_decoration() always excepted to be
called when toggling the state, and thus confusing the contents of the
olddecor variable. Add got_motif_hints to hopefully prevent this.

Also, when changing the border, don't take fs in account. May break on
older/broken WMs, but all in all is in fact more robust and simpler,
because you do not need to update the border state manually when
returning from fullscreen.
2013-11-02 19:03:40 +01:00
wm4 6af87017d1 vo_xv: check whether image allocation succeeds 2013-11-02 19:03:37 +01:00
wm4 bd70c32504 gl_common: suggest --vo=opengl-old if OpenGL 2.1 missing
If the caller requests at least OpenGL 2.1 (which --vo=opengl does),
but we get OpenGL 1.x, suggest using opengl-old.

Based on a patch by pfor on IRC.
2013-11-02 19:03:28 +01:00
Ben Boeckel 4c88ac3434 mpvcore: add a note about desync on track switches 2013-11-02 19:03:21 +01:00
ChrisK2 4cd36b999f osc: make sure the OSC actually fits into the video 2013-11-02 19:03:03 +01:00
wm4 1b3155cf51 ao_alsa: don't include alloca.h
It's true that ALSA uses alloca() in some of its API functions, but
since this is hidden behind macros in the ALSA headers, we have no
reason to include alloca.h ourselves.

Might help with portability (FreeBSD).
2013-11-02 19:02:42 +01:00
wm4 ace9a4b6c6 README: add a link to the wiki about the FFmpeg vs. Libav issue 2013-11-02 19:02:36 +01:00
wm4 84cd043f85 manpage: clarify --heartbeat-interval operation 2013-11-02 19:02:33 +01:00
wm4 6cdc5627f0 x11_common: reduce screensaver heartbeat from 30 to 10 seconds
Apparently this fixes issues with Gnome, which has a smaller timeout.
See github issue #315.
2013-11-02 19:02:29 +01:00
Stefano Pigozzi cb355443dc cocoa: constraint the window position a little more
The intention of this is to not make the window go outside the screen when
changing dimensions from 2x to .5x.
2013-11-02 19:02:26 +01:00
wm4 cc2b5c16fa mplayer: make --length relative to actual start of file, instead of 0
We always use the file's timestamps, so the start time can be easily
something different from 0. Make the --length option respect this.
2013-11-02 19:02:21 +01:00
Alexander Preisinger bf345136b9 wayland: fix fullscreen transparent border regions
The default behavior of weston changed some time ago to not fill the surface
black for fullscreen windows.

Now let mpv draw the whole screen in fullscreen mode.
2013-11-02 19:02:07 +01:00
Stefano Pigozzi 6b525b84bb cocoa: fix opening quarantined files on 10.9 with the bundle [2]
Fixup commit for bbc146927
2013-11-02 19:02:03 +01:00
Stefano Pigozzi ea17adcd66 cocoa: fix opening quarantined files on 10.9 with the bundle
It looks like on Mavericks the Finder is passing different arguments to mpv
depending on whether the opened file is quarantined or not.

Fixes #285
2013-11-02 19:01:42 +01:00
Stefano Pigozzi 31cdb96474 cocoa: fix race condition with input context creation
This seems to be a problem only in OS X 10.9. I guess they improved the
general speed of the Cocoa startup and suddenly mpv core takes more time
than the Cocoa thread to initialize.

Fixes #285

(hopefully!)
2013-11-02 19:01:39 +01:00
wm4 b3233fa3ff gl_video: add RGB10_A2 FBO format
Maybe this can be the default in the future, but I'm not sure yet.
2013-11-02 19:01:13 +01:00
wm4 132528ff67 ao_pcm: big endian AC3 in wav doesn't work
At least not with ffmpeg.

Honestly, I have no idea how little endian AC3 works at all, since
ao_pcm doesn't do anything special about it, and treats it like s16le.
Maybe it's broken and ffmpeg has special logic to detect it.
2013-11-02 19:01:04 +01:00
wm4 efc32ac0df mplayer: don't call libquvi for local files
This is obviously not needed, and just creates potential for bad
breakages (e.g. what happens if libquvi tries to open a normal filename
as http URL?).

Note that for simplicity, we still pass file:// URIs to quvi, and we
don't exclude other protocol prefixes either. In general, we don't know
what protocols quvi might support, so we don't try to second-guess it.
(Even though in practice, it's probably only "http" and "https".)
2013-11-02 19:00:53 +01:00
Stefano Pigozzi 042302fa65 cocoa: set and clear gl context inside of sync sections
The code did not set and unset the current context inside sync sections. I am
not sure if this was an actual problem but this is better since the context is
linked to a single thread. In my brief tests this seems to avoid garbage to
show up in fullscreen.
2013-11-02 19:00:36 +01:00
wm4 93ce083bd8 Release 0.2.1 2013-10-20 14:12:33 +02:00
wm4 97c93918fe input: fix --input-ar-rate=0
Crashed, instead of disabling auto-repeat.
2013-10-20 14:11:28 +02:00
Alexander Preisinger 7078df4f5e wayland: use mp_input_test_dragging
Instead of removing dragging we now test if it we should drag the window or
not. Because if the OSC shows up we can not drag the window because that would
cause mouse events that makes the OSC disappear.
2013-10-20 14:11:25 +02:00
Alexander Preisinger 8e642809bf Revert "wayland: remove moving window by grabbing"
This reverts commit 3308bc2bc9.
2013-10-20 14:11:21 +02:00
Alexander Preisinger 8c4cf5ce84 Revert "wayland: remove outdated comment"
This reverts commit d75cfef49c.
2013-10-20 14:11:18 +02:00
wm4 16cbc4a014 vdpau_old: restore hardware decoding with old API
--hwdec=vdpau did nothing with older ffmpeg/libav versions. Oops.
2013-10-20 14:11:11 +02:00
wm4 2aff8b7523 af_lavrresample: actually free resampler
Fixes #304.
2013-10-20 14:11:04 +02:00
Nikoli 5d9353f0d5 mpv.desktop: add russian translation, sort 2013-10-20 14:11:00 +02:00
wm4 6f139ad981 sws_utils: work around libswscale crash with --contrast=-100 2013-10-20 14:10:49 +02:00
wm4 0052445e86 vf_scale: fix get/set confusion
This caused the equalizer controls to appear stuck.
2013-10-20 14:10:46 +02:00
Alessandro Ghedini 2cf8d4ffdb spelling fixes 2013-10-20 14:10:43 +02:00
wm4 e6236e22db Release 0.2.0 2013-10-16 00:11:28 +02:00
1020 changed files with 129317 additions and 209261 deletions

No files matched your search

-16
View File
@@ -1,16 +0,0 @@
---
name: 'README: DO NOT IGNORE OR DELETE THE ISSUE TEMPLATE'
about: 'Chose and fill out one of the following templates!'
title: ''
labels: priority:ignored-issue-template
assignees: ''
---
We ask you to not ignore the issue template. Fill it out as good and correct as
possible. Issues that don't adhere to our request will be closed for ignoring
the issue template. This is because analyzing a bug without a log file is harder
than necessary. Low quality bug reports are noise.
Please go back and chose the proper issue template. Opening issues with this
template will be closed immediately.
@@ -1,49 +0,0 @@
---
name: 'Report a Linux Issue'
about: 'Create a report for a runtime related Linux Issue'
title: ''
labels: 'os:linux'
assignees: ''
---
### Important Information
Provide following Information:
- mpv version
- Linux Distribution and Version
- Source of the mpv binary
- If known which version of mpv introduced the problem
- Window Manager and version
- GPU driver and version
- Possible screenshot or video of visual glitches
If you're not using git master or the latest release, update.
Releases are listed here: https://github.com/mpv-player/mpv/releases
### Reproduction steps
Try to reproduce your issue with --no-config first. If it isn't reproducible
with --no-config try to first find out which option or script causes your issue.
Describe the reproduction steps as precise as possible. It's very likely that
the bug you experience wasn't reproduced by the developer because the workflow
differes from your own.
### Expected behavior
### Actual behavior
### Log file
Make a log file made with -v -v or --log-file=output.txt, paste it to
https://0x0.st/ or attach it to the github issue, and replace this text with a
link to it.
The issue will be closed for ignoring the issue template.
### Sample files
Sample files needed to reproduce this issue can be uploaded to https://0x0.st/
or similar sites. (Only needed if the issue cannot be reproduced without it.)
Do not use garbage like "cloud storage", especially not Google Drive.
@@ -1,51 +0,0 @@
---
name: 'Report a macOS Issue'
about: 'Create a report for a runtime related macOS Issue'
title: ''
labels: 'os:mac'
assignees: ''
---
### Important Information
Provide following Information:
- mpv version
- macOS Version
- Source of the mpv binary or bundle
- If known which version of mpv introduced the problem
- Possible screenshot or video of visual glitches
If you're not using git master or the latest release, update.
Releases are listed here: https://github.com/mpv-player/mpv/releases
### Reproduction steps
Try to reproduce your issue with --no-config first. If it isn't reproducible
with --no-config try to first find out which option or script causes your issue.
Describe the reproduction steps as precise as possible. It's very likely that
the bug you experience wasn't reproduced by the developer because the workflow
differes from your own.
### Expected behavior
### Actual behavior
### Log file
Make a log file made with -v -v or --log-file=output.txt. If you use the Bundle
from a version later than 0.32 a default log is created for your last run at
~/Library/Logs/mpv.log. You can jump to that file via the Help > Show log File…
menu. Paste the log to https://0x0.st/ or attach it to the github issue, and
replace this text with a link to it.
In the case of a crash please provide the macOS Crash Report (Backtrace).
The issue will be closed for ignoring the issue template.
### Sample files
Sample files needed to reproduce this issue can be uploaded to https://0x0.st/
or similar sites. (Only needed if the issue cannot be reproduced without it.)
Do not use garbage like "cloud storage", especially not Google Drive.
@@ -1,47 +0,0 @@
---
name: 'Report a Windows Issue'
about: 'Create a report for a runtime related Windows Issue'
title: ''
labels: 'os:win'
assignees: ''
---
### Important Information
Provide following Information:
- mpv version
- Windows Version
- Source of the mpv binary
- If known which version of mpv introduced the problem
- Possible screenshot or video of visual glitches
If you're not using git master or the latest release, update.
Releases are listed here: https://github.com/mpv-player/mpv/releases
### Reproduction steps
Try to reproduce your issue with --no-config first. If it isn't reproducible
with --no-config try to first find out which option or script causes your issue.
Describe the reproduction steps as precise as possible. It's very likely that
the bug you experience wasn't reproduced by the developer because the workflow
differes from your own.
### Expected behavior
### Actual behavior
### Log file
Make a log file made with -v -v or --log-file=output.txt, paste it to
https://0x0.st/ or attach it to the github issue, and replace this text with a
link to it.
The issue will be closed for ignoring the issue template.
### Sample files
Sample files needed to reproduce this issue can be uploaded to https://0x0.st/
or similar sites. (Only needed if the issue cannot be reproduced without it.)
Do not use garbage like "cloud storage", especially not Google Drive.
-43
View File
@@ -1,43 +0,0 @@
---
name: 'Report a different Issue'
about: 'Create a report for a runtime related Issue'
title: ''
labels: ''
assignees: ''
---
### Important Information
Provide following Information:
- mpv version
- Platform and Version
- Source of the mpv binary
If you're not using git master or the latest release, update.
Releases are listed here: https://github.com/mpv-player/mpv/releases
### Reproduction steps
Try to reproduce your issue with --no-config first. If it isn't reproducible
with --no-config try to first find out which option or script causes your issue.
Describe the reproduction steps as precise as possible. It's very likely that
the bug you experience wasn't reproduced by the developer because the workflow
differes from your own.
### Expected behavior
### Actual behavior
### Log file
Make a log file made with -v -v or --log-file=output.txt, paste it to
https://0x0.st/ or attach it to the github issue, and replace this text with a
link to it.
### Sample files
Sample files needed to reproduce this issue can be uploaded to https://0x0.st/
or similar sites. (Only needed if the issue cannot be reproduced without it.)
Do not use garbage like "cloud storage", especially not Google Drive.
@@ -1,30 +0,0 @@
---
name: 'Report a build Problem'
about: 'Create a report for a build related Issue'
title: ''
labels: 'core:waf'
assignees: ''
---
### mpv version and platform versions
If you're not using git master or the latest release, update.
Releases are listed here: https://github.com/mpv-player/mpv/releases
### Reproduction steps
Describe the reproduction steps as precise as possible. It's very likely that
the bug you experience wasn't reproduced by the developer because the workflow
differes from your own.
### Expected behavior
### Actual behavior
### Log file
Upload build/config.log or ./waf configure output to https://0x0.st/ or attach
it to the github issue, and replace this text with a link to it.
The issue will be closed for ignoring the issue template.
@@ -1,22 +0,0 @@
---
name: 'Request a new Feature'
about: 'Create a request for a new feature'
title: ''
labels: 'meta:feature-request'
assignees: ''
---
Before requesting a new feature make sure it hasn't been requested yet.
https://github.com/mpv-player/mpv/labels/meta%3Afeature-request
### Expected behavior of the wanted feature
### Alternative behavior of the wanted feature
### Log file
Even if you think it's not necessary at first, it might help us later to find
possible issues. Make a log file made with -v -v or --log-file=output.txt, paste
it to https://0x0.st/ or attach it to the github issue, and replace this text
with a link to it.
-25
View File
@@ -1,25 +0,0 @@
---
name: 'Ask a Question'
about: 'Ask a question about mpv'
title: ''
labels: 'meta:question'
assignees: ''
---
Don't ask questions about issues, errors or problems you have and instead open
a proper issue with the right template from the previous selection.
This template is meant for questions about the workings of mpv, to clarify about
unspecified behaviour of options or command, or anything else that is not well
described and needs clarification.
Before asking a question make sure it hasn't been asked or answered yet.
https://github.com/mpv-player/mpv/labels/meta%3Aquestion
### Log file
Even if you think it's not necessary at first, it might help us later to find
possible issues. Make a log file made with -v -v or --log-file=output.txt, paste
it to https://0x0.st/ or attach it to the github issue, and replace this text
with a link to it.
-9
View File
@@ -1,9 +0,0 @@
blank_issues_enabled: false
contact_links:
- name: mpv irc channel
url: https://mpv.io/community/
about: Feel free to ask questions here irc://irc.freenode.net/mpv
- name: mpv irc developer channel
url: https://mpv.io/community/
about: Ask questions related to the development of mpv here
irc://irc.freenode.net/mpv-devel
-5
View File
@@ -1,5 +0,0 @@
Read this before you submit this pull request:
https://github.com/mpv-player/mpv/blob/master/DOCS/contribute.md
Reading this link and following the rules will get your pull request reviewed
and merged faster. Nobody wants lazy pull requests.
+9 -20
View File
@@ -2,7 +2,6 @@
*.a
*.d
*.exe
*.pyc
.depend
/config.h
@@ -11,28 +10,18 @@
/mpv
/mpv.app
/version.h
/input/input_conf.h
/mpvcore/input/input_conf.h
/tags
/TAGS
/video/out/gl_video_shaders.h
/video/out/x11_icon.inc
/demux/ebml_defs.c
/demux/ebml_types.h
/sub/osd_font.h
/player/lua/*.inc
/player/builtin_conf.inc
/DOCS/man/mpv.1
/DOCS/man/mpv.aux
/DOCS/man/mpv.log
/DOCS/man/mpv.out
/DOCS/man/mpv.pdf
/DOCS/man/mpv.toc
/waf
/waf-*
/waf3-*
/build
/.waf*
/.lock-waf_*
/old_build
/Makefile
/mpvcore/lua/*.inc
/DOCS/man/*/mpv.1
/DOCS/man/*/mpv.aux
/DOCS/man/*/mpv.log
/DOCS/man/*/mpv.out
/DOCS/man/*/mpv.pdf
/DOCS/man/*/mpv.toc
+17 -164
View File
@@ -1,177 +1,30 @@
language: c
_macbase:
- &mac
os: osx
compiler: clang
env:
- HOMEBREW_NO_AUTO_UPDATE=1
- HOMEBREW_NO_INSTALL_CLEANUP=1
before_cache:
- brew cleanup -s
cache:
directories:
- $HOME/Library/Caches/Homebrew
- /usr/local/Homebrew
_mingwbase:
- &mingw
os: linux
addons:
apt:
packages:
- 'autoconf'
- 'automake'
- 'pkg-config'
- 'gcc-mingw-w64'
- 'gcc-multilib'
- 'nasm'
- 'yasm'
cache:
directories:
- mingw_prefix/
matrix:
include:
- <<: *mac
osx_image: xcode11.6
- <<: *mac
osx_image: xcode10.1
- <<: *mac
osx_image: xcode9.2
env:
- HOMEBREW_NO_AUTO_UPDATE=1
- HOMEBREW_NO_INSTALL_CLEANUP=1
- CI_SWIFT_FLAGS="\-target x86_64-apple-macosx10.12"
- os: freebsd
compiler: clang
- os: linux
compiler: gcc
env: CONTAINER=registry.cirno.systems/kiwi/containers/mpv-ci:stable-deps CI_SCRIPT=ci/build-tumbleweed.sh
- os: linux
compiler: clang
env: CONTAINER=registry.cirno.systems/kiwi/containers/mpv-ci:stable-deps CI_SCRIPT=ci/build-tumbleweed.sh
- <<: *mingw
env: CI_SCRIPT=ci/build-mingw64.sh TARGET=i686-w64-mingw32
- <<: *mingw
env: CI_SCRIPT=ci/build-mingw64.sh TARGET=x86_64-w64-mingw32
allow_failures:
- os: osx
osx_image: xcode9.2
fast_finish: true
dist: focal
services:
- docker
env:
global:
# Coverity token
- secure: "H21mSRlMhk4BKS0xHZvCFGJxteCP0hRVUxTuNfM2Z9HBsyutuLEYMtViLO86VtM+Tqla3xXPzUdS4ozLwI72Ax/5ZUDXACROj73yW6QhFB5D6rLut12+FjqC7M33Qv2hl0xwgNBmR5dsm1ToP37+Wn+ecJQNvN8fkTXF+HVzOEw="
# Travis token for mpv.io
- secure: "nlTVLJK6kRhtXvhKCoJ3YdFGHuKaq/eHowfPw25hqRWuBOZd+HjHY5KIYjV7SxuKFDpJE4GpNcvA3Q31nsqomxpkLYgrwjg6TSazN7ZP+x85ZgV1QGFebrPfGm2n5UR5CAPAwFoeF3pZheLi4bajVzwq1fWW+x3grS188P9OZso="
- LIBAV=libav-stable
- LIBAV=libav-git
- LIBAV=ffmpeg-stable
- LIBAV=ffmpeg-git
compiler:
- clang
branches:
only:
- master
- ci
- coverity_scan
- /release\/.*$/
before_install:
- if [ "$TRAVIS_COMPILER" = "clang" ]; then export CXX="clang++"; fi
- if [ "$TRAVIS_COMPILER" = "gcc" ]; then export CXX="g++"; fi
- if [ -n "$CONTAINER" ]; then docker pull $CONTAINER; fi
- |
if [ "$TRAVIS_OS_NAME" = "freebsd" ]; then
# Requested in ci/build-freebsd.sh
sudo pkg install -y \
evdev-proto \
ffmpeg \
libplacebo \
libxkbcommon \
luajit \
openal-soft \
pkgconf \
python3 \
sdl2 \
vulkan-headers \
wayland-protocols \
$NULL
# Optionally auto-enabled
sudo pkg install -y \
alsa-lib \
jackit \
libXv \
libarchive \
libbluray \
libcaca \
libcdio-paranoia \
libdvdnav \
mujs \
pulseaudio \
rubberband \
sekrit-twc-zimg \
uchardet \
v4l_compat \
$NULL
fi
- |
if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then
remove=$(brew list)
keep="gettext pcre2 git"
install="autoconf automake pkg-config libtool python freetype fribidi little-cms2 luajit libass ffmpeg"
for formula in ${keep[@]}; do remove=("${remove[@]/$formula}"); done
for formula in ${install[@]}; do remove=("${remove[@]/$formula}"); done
brew remove --force $remove --ignore-dependencies
if [[ "$TRAVIS_OSX_IMAGE" == "xcode9.2" ]]; then
brew untap caskroom/cask
fi
brew update
if [[ "$TRAVIS_OSX_IMAGE" == "xcode9.2" ]]; then
pushd "/usr/local/Homebrew/Library/Taps/homebrew/homebrew-core"
git checkout --force 55e02323812604add9a69bab8730319b9255a697
fi
brew install $install
brew link --overwrite python
if [[ "$TRAVIS_OSX_IMAGE" == "xcode9.2" ]]; then
git checkout master
popd
fi
fi
before_install: ./travis-deps libass-stable $LIBAV
script: ./configure && make
script:
- ./bootstrap.py
- |
if [ "$TRAVIS_OS_NAME" = "linux" ]; then
if [ -n "$CONTAINER" ]; then
docker run --env CC --env TARGET -v $TRAVIS_BUILD_DIR:/build $CONTAINER /bin/sh -c "cd /build && $CI_SCRIPT"
else
$CI_SCRIPT
fi
fi
- if [ "$TRAVIS_OS_NAME" = "osx" ]; then ./ci/build-macos.sh; fi
- if [ "$TRAVIS_OS_NAME" = "freebsd" ]; then ./ci/build-freebsd.sh; fi
after_failure: cat ./build/config.log
after_script: TOOLS/travis-rebuild-website
notifications-policy: &notifications-policy
on_success: change
on_failure: always
notifications:
email: false
email:
recipients:
- mpv-team@googlegroups.com
<<: *notifications-policy
irc:
if: fork = false
channels:
- "irc.freenode.org#mpv-devel"
on_success: change
on_failure: always
addons:
coverity_scan:
project:
name: "mpv-player/mpv"
description: "Build submitted via Travis CI"
notification_email: mpv-team@googlegroups.com
build_command_prepend: "./bootstrap.py && ./waf configure"
build_command: "./waf build"
branch_pattern: coverity_scan
- "irc.freenode.org#mpv-player-dev"
<<: *notifications-policy
+12 -67
View File
@@ -1,74 +1,19 @@
mpv is a fork of mplayer2, which is a fork of MPlayer.
mpv as a whole is licensed under the GNU General Public License GPL version 2
or later (called GPLv2+ in this document, see LICENSE.GPL for full license
text) by default, or the GNU Lesser General Public License LGPL version 2 or
later (LGPLv2.1+ in this document, see LICENSE.LGPL for full license text) if
built with the --enable-lgpl configure switch.
Most source files are LGPLv2.1+ or GPLv2+, but some files are available under
more liberal licenses, such as BSD, MIT, ISC, and possibly others. Look at the
copyright header of each source file, and grep the sources for "Copyright" if
you need to know details. C source files without Copyright notice are usually
licensed as LGPLv2.1+. Also see the list of files with specific licenses below
(not all files can have a standard license header).
All new contributions must be LGPLv2.1+ licensed. Using a more liberal license
compatible to LGPLv2.1+ is also ok.
Changes done to GPL code must come with the implicit/explicit agreement that the
project can relicense the changes to LGPLv2.1+ at a later point without asking
the contributor. This is a safeguard for making potential relicensing of
remaining GPL code to LGPLv2.1+ easier.
See DOCS/contribute.md for binding rules wrt. licensing for contributions.
mpv as a whole is licensed as GPL version 2 or later (see LICENSE). Most source
files are GPLv2+, but some files are available under a more liberal license,
such as LGPLv2+, BSD, MIT, ISC, and possibly others. Look at the copyright
header of each source file, and grep the sources for "Copyright" if you need
to know details. Files without Copyright notice are licensed as LGPLv2+.
For information about authors and contributors, consult the git log, which
contains the complete SVN and CVS history as well.
"v2.1+" in this context means "version 2.1 or later".
Note that mplayer2 as a whole is licensed under GPLv3+. This is because it uses
a copy of talloc (part of Samba), which is LGPLv3+, and the next compatible
license for this mix is GPLv3+.
Some libraries are GPLv2+ or GPLv3+ only. Building mpv with Samba support makes
it GPLv3+.
mpv can be built as LGPLv2.1+ with the --enable-lgpl configure option. To add
a LGPL mode to mpv, MPlayer code had to be relicensed from GPLv2+ to LGPLv2.1+
by asking the MPlayer authors for permission. Since permission could not be
obtained from everyone, LGPL mode disables the following features, some of
them quite central:
- Linux X11 video output
- BSD audio output via OSS
- NVIDIA/Linux hardware decoding (vdpau, although nvdec usually works)
- Linux TV input
- minor features: jack, DVD, CDDA, SMB, CACA, legacy direct3d VO
Some of these will be fixed in the future. The intended use for LGPL mode is
with libmpv, and currently it's not recommended to build mpv CLI in LGPL mode
at all.
The following files are still GPL only (--enable-lgpl disables them):
audio/out/ao_jack.c will stay GPL
audio/out/ao_oss.c will stay GPL
stream/dvb* must stay GPL
stream/stream_cdda.c unknown
stream/stream_dvb.* must stay GPL
stream/stream_dvdnav.c unknown
video/out/vo_caca.c unknown
video/out/vo_direct3d.c unknown
video/out/vo_vaapi.c probably impossible (some company's code)
video/out/vo_vdpau.c probably impossible (nVidia's code)
video/out/vo_x11.c probably impossible
video/out/vo_xv.c probably impossible
video/out/x11_common.* probably impossible
video/vdpau.c hard (GPL-only parts must be ifdefed)
video/vdpau.h unknown
video/vdpau_mixer.* actual code must be rewritten
DOCS/man/ GPLv2+
bootstrap.py unknown license, probably GPLv2+ or LGPLv2+
etc/mplayer-input.conf unknown license, probably GPLv2+
mpv.desktop unknown license, probably GPLv2+
etc/restore-old-bindings.conf unknown license, probably GPLv2+
None of the cases listed above affect the final binary if it's built as
LGPL. Linked libraries still can affect the final license (for example if
FFmpeg was built as GPL).
MPlayer as a whole is licensed under GPLv2 (incompatible to GPLv3!), because
some files are licensed to GPLv2 (and _not_ any later version of the license).
In particular, this affects the file libmpdemux/demux_ty_osd.c. It is disabled
under mplayer2, and has been removed from mpv.
+160
View File
@@ -0,0 +1,160 @@
1. Input layer, supported devices, methods:
- plain file, with seeking
- STDIN, without seeking backward
- network streaming (currently plain wget-like HTTP and MMS (.asx))
- VCD (Video CD) track, by direct CDROM device access (not requires mounting disc)
- DVD titles using .IFO structure, by direct DVD device access (not requires mounting disc)
- DVD titles using menu navigation (experimental/alpha, not yet finished!!!)
- CDDA - raw audio from audio CD-ROM discs (using cdparanoia libs)
- RTP streaming (mpeg-ps over multicast only)
- LIVE555 streaming - support SDP/RTSP (using the LIVE555 libs)
- SMB - file access over samba (experimental)
2. Demuxer/parser layer, supported file/media formats:
- MPEG streams (ES,PES,PS. no TS support yet)
note: mpeg demuxer silently ignore non-mpeg content, and find mpeg packets
in arbitrary streams. it means you can play directly VCD images (for example
CDRwin's .BIN files) without extracting mpeg files first (with tools like vcdgear)
It accepts all PES variants, including files created by VDR.
Note: VOB (video object) is simple mpeg stream, but it usually has 01BD
packets which may contain subtitles and non-mpeg audio. Usually found on DVD discs.
Headers: mpeg streams has no global header. each frame sequence (also called GOP,
group of pictures) contains an sequence header, it describes that block.
In normal mpeg 1/2 content there are groups of 12-15 frames (24/30 fps).
It means you can freely seek in mpeg streams, and even can cut it to
small parts with standard file tools (dd, cut) without destroying it.
Codecs: video is always mpeg video (mpeg1, mpeg2 or mpeg4).
audio is usually mpeg audio (any layer allowed, but it's layer 2 in most files)
but 01BD packets may contain AC3, DTS or LPCM too.
FPS: mpeg2 content allows variable framerate, in form of delayed frames.
It's mostly used for playback 24fps content at 29.97/30 fps (NTSC) rate.
(so called Telecine or 3:2 pulldown effect)
It means you see 30 frames per second, but there are only 24 different
pictures and some of them are shown longer to fill 30 frame time.
If you encode such files with mencoder, using -ofps 24 or -ofps 23.976
is recommended.
- AVI streams.
Two kind of RIFF AVI files exists:
1. interleaved: audio and video content is interleaved. it's faster and
requires only 1 reading thread, so it's recommended (and mostly used).
2. non-interleaved: audio and video aren't interleaved, i mean first come
whole video followed by whole audio. it requires 2 reading process or
1 reading with lots of seeking. very bad for network or cdrom.
3. badly interleaved streams: mplayer detects interleaving at startup and
enables -ni option if it finds non-interleaved content. but sometimes
the stream seems to be interleaved, but with bad sync so it should be
played as non-interleaved otherwise you get a-v desync or buffer overflow.
MPlayer supports 2 kind of timing for AVI files:
- bps-based: it is based on bitrate/samplerate of video/audio stream.
this method is used by most players, including avifile and wmp.
files with broken headers, and files created with VBR audio but not
vbr-compliant encoder will result a-v desync with this method.
(mostly at seeking).
- interleaving-based: note: it can't be used togethwer with -ni
it doesn't use bitrate stuff of header, it uses the relative position
of interleaved audio and video chunks. makes some badly encoded file
with vbr audio playable.
Headers: AVI files has a mandatory header at the begin of the file,
describing video parameters (resolution, fps) and codecs. Optionally
they have an INDEX block at the end of the file. It's optional, but
most files has such block, because it's REQUIRED for seeking.
Btw usually it can be rebuilt from file content, mplayer does it with
the -idx switch. MPlayer can recreate broken index blocks using -forceidx.
As AVI files needs index for random access, broken files with no index
are usually unplayable.
Of course, cutting/joining AVI files needs special programs.
Codecs: any audio and video codecs allowed, but I note that VBR audio is
not well supported by most players. The file format makes it possible to
use VBR audio, but most players expect CBR audio and fails with VBR,
as VBR is unusual, and Microsoft's AVI specs only describe CBR audio.
I also note, that most AVI encoders/multiplexers create bad files if
using VBR audio. only 2 exception (known by me): NaNDub and MEncoder.
FPS: only constant framerate allowed, but it's possible to skip frames.
- ASF streams:
ASF (active streaming format) comes from Microsoft. they developed two
variant of ASF, v1.0 and v2.0. v1.0 is used by their media tools (wmp and
wme) and v2.0 is published and patented :). of course, they differ,
no compatibility at all. (it's just a legality game)
MPlayer supports only v1.0, as nobody ever seen v2.0 files :)
Note, that .ASF files are nowdays come with extension .WMA or .WMV.
UPDATE: MS recently released the ASF v1.0 specs too, but it has some
restrictions making it illegal to read by us :)
Headers: Stream headers (codecs parameters) can be everywhere (in theory),
but all files i've seen had it at the beginning of the file.
Asf uses fixed packet size, so it is seekable without any INDEX block,
and broken files are playable well.
Codecs: video is mostly microsoft's mpeg4 variants: MP42, MP43 (aka DivX),
WMV1 and WMV2. but any codecs allowed.
audio is usually wma or voxware, sometimes mp3, but any codecs allowed.
FPS: no fixed fps, every video frame has an exact timestamp instead.
I've got stream with up to 3 sec frame display times.
- QuickTime / MOV files:
They come from Mac users, usually with .mov or .qt extension, but as
MPEG Group chose quicktime as recommended file format for MPEG4,
sometimes you meet quicktime files with .mpg or .mp4 extension.
At first look, it's a mixture of ASF and AVI.
It requires INDEX block for random access and seeking, and even for
playback, like AVI, but uses timestamps instead of constant framerate
and has more flexible stream options (including network stuff) like ASF.
Headers: header can be placed at the beginning or at the end of file.
About half of my files have it at the beginning, others have it at the end.
Broken files are only playable if they have header at the beginning!
Codecs: any codecs allowed, both CBR and VBR.
Note: most new mov files use Sorenson video and QDesign Music audio,
they are patented, closed, secret, (TM)-ed etc formats, only Apple's
quicktime player is able to playback these files (on win/mac only).
- VIVO files:
They are funny streams. They have a human-readable ascii header at
the beginning, followed by interleaved audio and video chunks.
It has no index block, has no fixed packetsize or sync bytes, and most
files even has no keyframes, so forget seeking!
Video is standard h.263 (in vivo/2.0 files it's modified, non-standard
h.263), audio is either standard g.723 or Vivo Siren codec.
Note, that microsoft licensed vivo stuff, and included in their netshow
v2.0 program, so there are VfW/ACM codecs for vivo video and audio.
- RealMedia files:
A mixture of AVI and ASF features. It has mandatory headers at the
beginning and an optional INDEX (missing in most files).
The file is constructed of variable size chunks, with small header
telling the stream ID, timestamp, flags (keyframe...) and size.
But it has some features found in ASF files:
The video is actually double-muxed, the video chunks are really
appended fragments of the video frame. RV30+ supports B frames, so
you have to parse some bits of the first fragment to get the real PTS.
The audio frames are fixed size (CBR) but using the same scrambling
(out-of-order interleaving) as in the ASF files.
Codecs: Audio is either COOK(er), SIPR(o), ATRAC3 or DNET.
The DNET is actually a byte-swapped low-bitrate Dolby AC3 variant :)
Video is RV10 (h263 variant), RV20 (rp G2), RV30 (rp v8) or RV40 (rp v9).
FPS: variable, just like in ASF.
Note, that similarity of real and asf has some background - they worked
together on the (never finished/used) ASF v2 spec for some time.
- GIF files:
The GIF format is a common format for web graphics that supports
animation. These are read through libungif or compatible library.
Variable frame delays are supported, but seeking is not supported.
Seeking will be supported once an index of gif frames can be built.
+228
View File
@@ -0,0 +1,228 @@
So, I'll describe how this stuff works.
The main modules:
1. stream.c: this is the input layer, this reads the input media (file, stdin,
vcd, dvd, network etc). what it has to know: appropriate buffering by
sector, seek, skip functions, reading by bytes, or blocks with any size.
The stream_t (stream.h) structure describes the input stream, file/device.
There is a stream cache layer (cache2.c), it's a wrapper for the stream
API. It does fork(), then emulates stream driver in the parent process,
and stream user in the child process, while proxying between them using
preallocated big memory chunk for FIFO buffer.
2. demuxer.c: this does the demultiplexing (separating) of the input to
audio, video or dvdsub channels, and their reading by buffered packages.
The demuxer.c is basically a framework, which is the same for all the
input formats, and there are parsers for each of them (mpeg-es,
mpeg-ps, avi, avi-ni, asf), these are in the demux_*.c files.
The structure is the demuxer_t. There is only one demuxer.
2.a. demux_packet_t, that is DP.
Contains one chunk (avi) or packet (asf,mpg). They are stored in memory as
in linked list, cause of their different size.
2.b. demuxer stream, that is DS.
Struct: demux_stream_t
Every channel (a/v/s) has one. This contains the packets for the stream
(see 2.a). For now, there can be 3 for each demuxer :
- audio (d_audio)
- video (d_video)
- DVD subtitle (d_dvdsub)
2.c. stream header. There are 2 types (for now): sh_audio_t and sh_video_t
This contains every parameter essential for decoding, such as input/output
buffers, chosen codec, fps, etc. There are each for every stream in
the file. At least one for video, if sound is present then another,
but if there are more, then there'll be one structure for each.
These are filled according to the header (avi/asf), or demux_mpg.c
does it (mpg) if it founds a new stream. If a new stream is found,
the ====> Found audio/video stream: <id> messages is displayed.
The chosen stream header and its demuxer are connected together
(ds->sh and sh->ds) to simplify the usage. So it's enough to pass the
ds or the sh, depending on the function.
For example: we have an asf file, 6 streams inside it, 1 audio, 5
video. During the reading of the header, 6 sh structs are created, 1
audio and 5 video. When it starts reading the packet, it chooses the
stream for the first found audio & video packet, and sets the sh
pointers of d_audio and d_video according to them. So later it reads
only these streams. Of course the user can force choosing a specific
stream with
-vid and -aid switches.
A good example for this is the DVD, where the english stream is not
always the first, so every VOB has different language :)
That's when we have to use for example the -aid 128 switch.
Now, how this reading works?
- demuxer.c/demux_read_data() is called, it gets how many bytes,
and where (memory address), would we like to read, and from which
DS. The codecs call this.
- this checks if the given DS's buffer contains something, if so, it
reads from there as much as needed. If there isn't enough, it calls
ds_fill_buffer(), which:
- checks if the given DS has buffered packages (DP's), if so, it moves
the oldest to the buffer, and reads on. If the list is empty, it
calls demux_fill_buffer() :
- this calls the parser for the input format, which reads the file
onward, and moves the found packages to their buffers.
Well it we'd like an audio package, but only a bunch of video
packages are available, then sooner or later the:
DEMUXER: Too many (%d in %d bytes) audio packets in the buffer
error shows up.
2.d. video.c: this file/function handle the reading and assembling of the
video frames. each call to video_read_frame() should read and return a
single video frame, and it's duration in seconds (float).
The implementation is splitted to 2 big parts - reading from mpeg-like
streams and reading from one-frame-per-chunk files (avi, asf, mov).
Then it calculates duration, either from fixed FPS value, or from the
PTS difference between and after reading the frame.
2.e. other utility functions: there are some useful code there, like
AVI muxer, or mp3 header parser, but leave them for now.
So everything is ok 'till now. It can be found in libmpdemux/ library.
It should compile outside of mplayer tree, you just have to implement few
simple functions, like mp_msg() to print messages, etc.
See libmpdemux/test.c for example.
See also formats.txt, for description of common media file formats and their
implementation details in libmpdemux.
Now, go on:
3. mplayer.c - ooh, he's the boss :)
Its main purpose is connecting the other modules, and maintaining A/V
sync.
The given stream's actual position is in the 'timer' field of the
corresponding stream header (sh_audio / sh_video).
The structure of the playing loop :
while(not EOF) {
fill audio buffer (read & decode audio) + increase a_frame
read & decode a single video frame + increase v_frame
sleep (wait until a_frame>=v_frame)
display the frame
apply A-V PTS correction to a_frame
handle events (keys,lirc etc) -> pause,seek,...
}
When playing (a/v), it increases the variables by the duration of the
played a/v.
- with audio this is played bytes / sh_audio->o_bps
Note: i_bps = number of compressed bytes for one second of audio
o_bps = number of uncompressed bytes for one second of audio
(this is = bps*samplerate*channels)
- with video this is usually == 1.0/fps, but I have to note that
fps doesn't really matters at video, for example asf doesn't have that,
instead there is "duration" and it can change per frame.
MPEG2 has "repeat_count" which delays the frame by 1-2.5 ...
Maybe only AVI and MPEG1 has fixed fps.
So everything works right until the audio and video are in perfect
synchronity, since the audio goes, it gives the timing, and if the
time of a frame passed, the next frame is displayed.
But what if these two aren't synchronized in the input file?
PTS correction kicks in. The input demuxers read the PTS (presentation
timestamp) of the packages, and with it we can see if the streams
are synchronized. Then MPlayer can correct the a_frame, within
a given maximal bounder (see -mc option). The summary of the
corrections can be found in c_total .
Of course this is not everything, several things suck.
For example the soundcards delay, which has to be corrected by
MPlayer! The audio delay is the sum of all these:
- bytes read since the last timestamp:
t1 = d_audio->pts_bytes/sh_audio->i_bps
- if Win32/ACM then the bytes stored in audio input buffer
t2 = a_in_buffer_len/sh_audio->i_bps
- uncompressed bytes in audio out buffer
t3 = a_buffer_len/sh_audio->o_bps
- not yet played bytes stored in the soundcard's (or DMA's) buffer
t4 = get_audio_delay()/sh_audio->o_bps
From this we can calculate what PTS we need for the just played
audio, then after we compare this with the video's PTS, we have
the difference!
Life didn't get simpler with AVI. There's the "official" timing
method, the BPS-based, so the header contains how many compressed
audio bytes or chunks belong to one second of frames.
In the AVI stream header there are 2 important fields, the
dwSampleSize, and dwRate/dwScale pairs:
- If the dwSampleSize is 0, then it's VBR stream, so its bitrate
isn't constant. It means that 1 chunk stores 1 sample, and
dwRate/dwScale gives the chunks/sec value.
- If the dwSampleSize is >0, then it's constant bitrate, and the
time can be measured this way: time = (bytepos/dwSampleSize) /
(dwRate/dwScale) (so the sample's number is divided with the
samplerate). Now the audio can be handled as a stream, which can
be cut to chunks, but can be one chunk also.
The other method can be used only for interleaved files: from
the order of the chunks, a timestamp (PTS) value can be calculated.
The PTS of the video chunks are simple: chunk number * fps
The audio is the same as the previous video chunk was.
We have to pay attention to the so called "audio preload", that is,
there is a delay between the audio and video streams. This is
usually 0.5-1.0 sec, but can be totally different.
The exact value was measured until now, but now the demux_avi.c
handles it: at the audio chunk after the first video, it calculates
the A/V difference, and take this as a measure for audio preload.
3.a. audio playback:
Some words on audio playback:
Not the playing is hard, but:
1. knowing when to write into the buffer, without blocking
2. knowing how much was played of what we wrote into
The first is needed for audio decoding, and to keep the buffer
full (so the audio will never skip). And the second is needed for
correct timing, because some soundcards delay even 3-7 seconds,
which can't be forgotten about.
To solve this, the OSS gives several possibilities:
- ioctl(SNDCTL_DSP_GETODELAY): tells how many unplayed bytes are in
the soundcard's buffer -> perfect for timing, but not all drivers
support it :(
- ioctl(SNDCTL_DSP_GETOSPACE): tells how much can we write into the
soundcard's buffer, without blocking. If the driver doesn't
support GETODELAY, we can use this to know how much the delay is.
- select(): should tell if we can write into the buffer without
blocking. Unfortunately it doesn't say how much we could :((
Also, doesn't/badly works with some drivers.
Only used if none of the above works.
4. Codecs. Consists of libmpcodecs/* and separate files or libs,
for example libmpeg2, loader, mp3lib.
mplayer.c doesn't call them directly, but through the dec_audio.c and
dec_video.c files, so the mplayer.c doesn't have to know anything about
the codecs.
libmpcodecs contains wrapper for every codecs, some of them include the
codec function implementation, some calls functions from other files
included with mplayer, some calls optional external libraries.
file naming convention in libmpcodecs:
ad_*.c - audio decoder (called through dec_audio.c)
vd_*.c - video decoder (called through dec_video.c)
ve_*.c - video encoder (used by mencoder)
vf_*.c - video filter (see option -vf)
On this topic, see also:
libmpcodecs.txt - The structure of the codec-filter path, with explanation
dr-methods.txt - Direct rendering, MPI buffer management for video codecs
codecs.conf.txt - How to write/edit codec configuration file (codecs.conf)
codec-devel.txt - Mike's hints about codec development - a bit OUTDATED
hwac3.txt - about SP/DIF audio passthrough
5. libvo: this displays the frame.
for details on this, read libvo.txt
6. libao2: this control audio playing
6.a audio plugins
for details on this, read libao2.txt
+145
View File
@@ -0,0 +1,145 @@
mails by A'rpi and Marcus Blomenkamp <Marcus.Blomenkamp@epost.de>
describing how this ac3-passtrough hack work under linux and mplayer...
-----------------------------------------------------------------------
Hi,
> I received the following patch from Steven Brookes <stevenjb@mda.co.uk>.
> He is working on fixing the digital audio output of the dxr3 driver and
> told me he fixed some bugs in mplayer along the way. I don't know shit
> about hwac3 output so all I did was to make sure the patch applied
> against latest cvs.
> This is from his e-mail to me:
>
> "Secondly there is a patch to dec_audio.c and
> ac3-iec958 to fix the -ac hwac3 codec stuff and to use liba52 to sync it.
> Seems to work for everything I've thrown at and maintains sync for all audio
> types through the DXR3."
patch applied (with some comments added and an unwanted change (in software
a52 decoder) removed)
now i understand how this whole hwac3 mess work.
it's very very tricky. it virtually decodes ac3 to LPCM packets, but really
it keeps the original compressed data padded by zeros. this way it's
constant bitrate, and sync is calculated just like for stereo PCM.
(so it bypass LPCM-capable media converters...)
so, every ac3 frame is translated to 6144 byte long tricky LPCM packet.
6144 = 4*(6*256) = 4 * samples_per_ac3_frame = LPCM size of uncompressed ac3
frame.
i wanna know if it works for sblive and other ac3-capable cards too?
(i can't test it, lack of ac3 decoder)
A'rpi / Astral & ESP-team
-----------------------------------------------------------------------
Hi folks.
I spend some time fiddling with ac3 passthrough in mplayer. The
traditional way of setting the output format to AFMT_AC3 was no ideal
solution since not all digital io cards/drivers supported this format or
honoured it to set the spdif non-audio bit. To make it short, it only
worked with oss sblive driver IIRC.
Inspired by alsa's ac3dec program I found an alternative way by
inspecting to which format the alsa device had been set. Suprise: it was
simple 16bit_le 2_channel pcm. So setting the non-audio bit doesn't
necessarily mean the point. The only important thing seems to be
bit-identical output at the correct samplerate. Modern AV-Receivers seem
to be quite tolerant/compatible.
So I changed the output format of hwac3 from
AFMT_AC3 channels=1
to
AFMT_S16_LE channels=2
and corrected the absolute time calculation. That was all to get it
running for me.
-----------------------------------------------------------------------
Hi there.
Perhaps I can clear up some mystification about AC3 passthrough in
general and mplayer in special:
To get the external decoder solution working, it must be fed with data
which is bitidentical to the chunks in the source ac3 file (compressed
data is very picky about bit errors). Additionally - or better to say
'historically' - the non-audio bit should be set in the spdif status
fields to prevent old spdif hardware from reproducing ugly scratchy
noise. Note: for current decoders (probably those with DTS capability)
this safety bit isn't needed anymore. At least I can state that for my
Sherwood RVD-6095RDS. I think it is due to DTS because DTS sound can
reside on a ordinary AudioCD and an ordinary AudioCD-Player will always
have it's audio-bit set.
The sample format of the data must be 2channel 16bit (little endian
IIRC). Samplerates are 48kHz - although my receiver also accepts
44100Hz. I do not know if this is due to an over-compatability of my
receiver or if 44100 is also possible in the ac3 specs. For safety's
sake lets keep this at 48000Hz. AC3 data chunks are inserted into the
stream every 0x1600 bytes (don't bite me on that, look into
'ac3-iec958.c': 'ac3_iec958_build_burst').
To come back to the problem: data must be played bit-identically through
the soundcard at the correct samplerate and should optionally have it's
non-audio bit set. There are two ways to accomplish this:
1) Some OSS guy invented the format AFMT_AC3. Soundcard drivers
implementing this format should therefore adjust it's mixers and
switches to produce the desired output. Unfortunately some soundcard
drivers do not support this format correctly and most do not even
support it at all (including ALSA).
2) The alternative approach currently in mplayer CVS is to simply set
the output format to 48kHz16bitLE and rely on the user to have the
soundcard mixers adjusted properly.
I do have two soundcards with digital IO facilities (CMI8738 and
Trident4DWaveNX based) plus the mentioned decoder. I'm currently running
Linux-2.4.17. Following configurations are happily running here:
1. Trident with ALSA drivers (OSS does not support Hoontech's dig. IO)
2. CMI with ALSA drivers
3. CMI with OSS drivers
For Linux I'd suggest using ALSA because of it's cleaner architecture
and more consitent user interface. Not to mention that it'll be the
standard sound support in Linux soon.
For those who want to stick to OSS drivers: The CMI8738 drivers works
out-of-the-box, if the PCM/Wave mixer is set to 100%.
For ALSA I'd suggest using its OSS emulation. More on that later.
ALSA-0.9 invented the idea of cards, devices and dubdevices. You can
reach the digital interface of all supported cards consitently by using
the device 'hw:x,2' (x counting from 0 is the number of your soundcard).
So most people would end up at 'hw:0,2'. This device can only be opened
in sample formats and rates which are directly supported in hardware
hence no samplerate conversion is done keeping the stream as-is. However
most consumer soundcards do not support 44kHz so it would definitively
be a bad idea to use this as your standard device if you wanted to
listen to some mp3s (most of them are 44kHz due to CD source). Here the
OSS comes to play again. You can configure which OSS device (/dev/dsp
and /dev/adsp) uses which ALSA device. So I'd suggest pointing the
standard '/dev/dsp' to standard 'hw:0,0' which suports mixing and
samplerate conversion. No further reconfiguration would be needed for
your sound apps. For movies I'd point '/dev/adsp' to 'hw:0,2' and
configure mplayer to use adsp instead of dsp. The samplerate constrain
is no big deal here since movies usually are in 48Khz anyway. The
configuration in '/etc/modules.conf' is no big deal also:
alias snd-card-0 snd-card-cmipci # insert your card here
alias snd-card-1 snd-pcm-oss # load OSS emulation
options snd-pcm-oss snd_dsp_map=0 snd_adsp_map=2 # do the mapping
This works flawlessly in combination with alsa's native
SysVrc-init-script 'alsasound'. Be sure to disable any distribution
dependent script (e.g. Mandrake-8.1 has an 'alsa' script which depends
on ALSA-0.5).
Sorry for you *BSD'lers out there. I have no grasp on sound support there.
HTH Marcus
+56
View File
@@ -0,0 +1,56 @@
6. libao2: this control audio playing
As in libvo (see 5.) also here are some drivers, based on the same API:
static int control(int cmd, int arg);
This is for reading/setting driver-specific and other special parameters.
Not really used for now.
static int init(int rate,int channels,int format,int flags);
The init of driver, opens device, sets sample rate, channels, sample format
parameters.
Sample format: usually AFMT_S16_LE or AFMT_U8, for more definitions see
dec_audio.c and linux/soundcards.h files!
static void uninit(void);
Guess what.
Ok I help: closes the device, not (yet) called when exit.
static void reset(void);
Resets device. To be exact, it's for deleting buffers' contents,
so after reset() the previously received stuff won't be output.
(called if pause or seek)
static int get_space(void);
Returns how many bytes can be written into the audio buffer without
blocking (making caller process wait). MPlayer occasionally checks the
remaining space and tries to fill the buffer with play() if there's free
space. The buffer size used should be sane; a buffer that is too small
could run empty before MPlayer tries filling it again (normally once per
video frame), a buffer that is too big would force MPlayer decode the file
far ahead trying to find enough audio data to fill it.
static int play(void* data,int len,int flags);
Plays a bit of audio, which is received throught the "data" memory area, with
a size of "len". It has to copy the data, because they can be overwritten
after the call is made. Doesn't have to use all the bytes; it has to
return the number of bytes used used (copied to buffer). If
flags|AOPLAY_FINAL_CHUNK is true then this is the last audio in the file.
The purpose of this flag is to tell aos that round down the audio played
from "len" to a multiple of some chunksize that this "len" should not be
rounded down to 0 or the data will never be played (as MPlayer will never
call play() with a larger len).
static float get_delay(void);
Returns how long time it will take to play the data currently in the
output buffer. Be exact, if possible, since the whole timing depends
on this! In the worst case, return the maximum delay.
!!! Because the video is synchronized to the audio (card), it's very important
!!! that the get_delay function is correctly implemented!
static void audio_pause(void);
Pause playing but do not delete buffered data if possible.
static void audio_resume(void);
Continue playing after audio_pause().
+173
View File
@@ -0,0 +1,173 @@
libvo --- the library to handle video output by A'rpi, 2002.04
============================================
Note: before start on this, read colorspaces.txt !
The constants for different pixelformats are defined in img_format.h,
their usage is mandatory.
WARNING: Please keep in mind that some of this information may be out-dated,
so if you are working on a new vo, consider submitting preliminary patches
very early on. Currently vo_gl is one of the more up-to-date VOs to use
as reference if you are unsure about something and do not want to ask on the
list.
vo_vdpau and vo_direct3d may be a good choice, too, they use different
approaches closer to the sometimes convoluted way DirectX works.
Each vo driver _has_ to implement these:
preinit():
init the video system (to support querying for supported formats)
uninit():
Uninit the whole system, this is on the same "level" as preinit.
control():
Current controls (VOCTRL_QUERY_FORMAT must be implemented,
VOCTRL_DRAW_IMAGE, VOCTRL_FULLSCREEN, VOCTRL_UPDATE_SCREENINFO
should be implemented):
VOCTRL_QUERY_FORMAT - queries if a given pixelformat is supported.
It also returns various flags decsirbing the capabilities
of the driver with teh given mode. for the flags, see
file vfcaps.h !
the most important flags, every driver must properly report
these:
0x1 - supported (with or without conversion)
0x2 - supported without conversion (define 0x1 too!)
0x100 - driver/hardware handles timing (blocking)
also SET sw/hw scaling and osd support flags, and flip,
and accept_stride if you implement VOCTRL_DRAW_IMAGE (see bellow)
NOTE: VOCTRL_QUERY_FORMAT may be called _before_ first config()
but is always called between preinit() and uninit()
VOCTRL_GET_IMAGE
libmpcodecs Direct Rendering interface
You need to update mpi (mp_image.h) structure, for example,
look at vo_x11, vo_sdl, vo_xv or mga_common.
VOCTRL_DRAW_IMAGE
replacement for the current draw_slice/draw_frame way of
passing video frames. by implementing SET_IMAGE, you'll get
image in mp_image struct instead of by calling draw_*.
unless you return VO_TRUE for VOCTRL_DRAW_IMAGE call, the
old-style draw_* functils will be called!
Note: draw_slice is still mandatory, for per-slice rendering!
VOCTRL_RESET - reset the video device
This is sent on seeking and similar and is useful if you are
using a device which prebuffers frames that need to flush them
before refilling audio/video buffers.
VOCTRL_PAUSE
VOCTRL_RESUME
VOCTRL_GUISUPPORT
return true only if driver supports co-operation with
MPlayer's GUI (not yet used by GUI)
VOCTRL_SET_EQUALIZER
set the video equalizer to the given values
two arguments are provided: item and value
item is a string, the possible values are (currently):
brightness, contrast, saturation, hue
VOCTRL_GET_EQUALIZER
get the current video equalizer values
two arguments are provided: item and value
item is a string, the possible values are (currently):
brightness, contrast, saturation, hue
VOCTRL_ONTOP
Makes the player window stay-on-top. Only supported (currently)
by drivers which use X11, except SDL, as well as directx and
gl2 under Windows.
VOCTRL_BORDER
Makes the player window borderless.
VOCTRL_FULLSCREEN
Switch from and to fullscreen mode
VOCTRL_GET_PANSCAN
VOCTRL_SET_PANSCAN
Needed to implement pan-scan support ('w' and 'e' keys during
playback in fullscreen mode)
VOCTRL_START_SLICE
Called before the first draw_slice of each frame, useful if
you need to do some set-up work.
VOCTRL_DRAW_EOSD
Required for EOSD (ASS subtitle) support. Provides all
information necessary to draw the EOSD for the current video
frame.
VOCTRL_GET_EOSD_RES
Required for EOSD (ASS subtitle) support. Informs the ASS
renderer about the properties of the drawing area (size,
borders).
VOCTRL_SET_DEINTERLACE
VOCTRL_GET_DEINTERLACE
Get or set deinterlacing status for VOs that support some kind
of deinterlacing.
VOCTRL_UPDATE_SCREENINFO
Should set the xinerama_x, xinerama_y, vo_screenwidth and
vo_screenheight appropriately for the currently used
monitor and -xineramascreen option.
Usually should simply call the w32_update_xinerama_info or
update_xinerama_info function.
By supporting this, the VO also requests the newer API
that sets vo_dx, vo_dy etc. appropriately before config()
is called.
config():
Set up the video system. You get the dimensions and flags.
width, height: size of the source image
d_width, d_height: wanted scaled/display size (it's a hint)
Flags:
0x01 - force fullscreen (-fs)
0x02 - allow mode switching (-vm)
0x04 - allow software scaling (-zoom)
0x08 - flipping (-flip)
They're defined as VOFLAG_* (see libvo/video_out.h)
IMPORTANT NOTE: config() may be called 0 (zero), 1 or more (2,3...)
times between preinit() and uninit() calls. You MUST handle it, and
you shouldn't crash at second config() call or at uninit() without
any config() call! To make your life easier, vo_config_count is
set to the number of previous config() call, counted from preinit().
It's set by the caller (vf_vo.c), you don't have to increase it!
So, you can check for vo_config_count>0 in uninit() when freeing
resources allocated in config() to avoid crash!
You should implement VOCTRL_UPDATE_SCREENINFO so that vo_dx, vo_dy,
vo_dwidth and vo_dheight are already pre-set to values that take
aspect and -geometry into account. It is also necessary to properly
support multi-monitor setups (if based on x11_common, w32_common).
draw_slice(): this displays YV12 pictures (3 planes, one full sized that
contains brightness (Y), and 2 quarter-sized which the colour-info
(U,V). MPEG codecs (libmpeg2, opendivx) use this. This doesn't have
to display the whole frame, only update small parts of it.
If this is not supported, it must be signaled in QUERY_FORMAT with
VOCAP_NOSLICES.
draw_frame(): this is the older interface, this displays only complete
frames, and can do only packed format (YUY2, RGB/BGR).
Win32 codecs use this (DivX, Indeo, etc).
If you implement VOCTRL_DRAW_IMAGE, you do not need to implement draw_frame.
draw_osd(): this displays subtitles and OSD.
It's a bit tricky to use it, since it's a callback-style stuff.
It should call vo_draw_text() with screen dimension and your
draw_alpha implementation for the pixelformat (function pointer).
The vo_draw_text() checks the characters to draw, and calls
draw_alpha() for each. As a help, osd.c contains draw_alpha for
each pixelformats, use this if possible!
Note that if you do not draw directly onto the video you should
use vo_draw_text_ext() which allows you to specify the border
values etc. needed to draw DVD menu highlights at the correct place.
If you do not want to implement this, you can still use -vf
expand=osd=1 to draw the OSD, or even implement code to insert
this filter automatically.
Make sure you set VFCAP_OSD depending on whether you implemented it
or not.
NOTE: This one will be obsolete soon! But it's still useful when
you want to do tricks, like rendering osd _after_ hardware scaling
(tdfxfb) or render subtitles under of the image (vo_mpegpes, sdl)
NOTE2: above NOTE is probably wrong, there are currently no plans to
obsolete draw_osd, though there is the more advanced EOSD support for
ASS subtitles.
flip_page(): this is called after each frame, this displays the buffer for
real. This is 'swapbuffers' when doublebuffering.
Try to do as little work here as possible, since that affect jitter/
A-V sync.
+100
View File
@@ -0,0 +1,100 @@
TITLE=Weird Al Yankovic - The Saga Begins (clip)
# just to be informative (maybe future
# use?)
FILE=14233792,7972c637f619e01854ecb453b7339e3f # size,md5
AUTHOR=Gabucino
TYPE=VIDEO # maybe AUDIO in future (for displaying
# mp3 lyrics while playing or whatever)
FORMAT=TIME # this file contains measures based on
# TIME, not frames.
# if FORMAT is a number, then it's frame based, i.e.:
# FORMAT=25
NOTE=MPlayerSub test file v0.1
# first number : wait this much after previous subtitle disappeared
# second number : display the current subtitle for this many seconds
15 3
A long, long time ago...
0 3
in a galaxy far away...
0 3
Naboo was under an attack.
1 2.5
And I thought me and
Qui-Gon Jinn could
0 2.5
talk the Federation into
0 4
...maybe cutting them a
little slack.
2 3
But their response, it
didn't thrill us,
0 3
They locked the doors,
and tried to kill us.
0 2.5
We escaped from that gas,
0 3.5
then met Jar-jar and
Boss-Nass.
1 6
We took a bongo from the
scene and we went to
Theed to see the Queen.
0 5
We all wound' up on
Tatooine.
0 6
That's where, we've found
this boy.
0 4
Oh my, my this here
Anakin guy,
0 5
maybe Vader someday
later now he's just
a small fry.
0 4
And he left his home and
kissed his mommy goodbye,
0 5
singing "Soon I'm gonna be
a Jedi!"
6 6
Did you know this junkyard
slave isn't even old enough
to shave,
0 3
but he can use the Force,
they say.
1 6
Ahh, do you see him hitting
on the queen though he's
just nine and she's fourteen
0 6
yeah, he's probably gonna
marry her, someday!
+19
View File
@@ -0,0 +1,19 @@
software scaler filter docs
-ssf cgb=<float> chrominance gaussian blur
useful for videos with some chroma (color) noise (TV captures, VHS, ...)
-ssf lgb=<float> -> luminance gaussian blur
hmm, mostly special effect, could be used as lame noise reducer though
-ssf chs=<int> -> shift chrominance horizontally
-ssf cvs=<int> -> shift chrominance vertically
useful if the luma & chroma are not aligned exactly
-ssf cs=<float> -> chrominance sharpen
-ssf ls=<float> -> luminance sharpen
simple sharpening filter
note: these will only work if the swscaler is used at all (use -vf scale)
example: mplayer foobar.avi -vf scale -ssf lgb=3.0
+68
View File
@@ -0,0 +1,68 @@
artifact types:
---------------------------------------------------------------------
ringing
wave or noise like patterns around sharp edges
bad: sinc, lanczos (with high filter length)
acceptable: lanczos (with low filter length), cubic, spline
ok: area, (fast)blinear, gauss, point
blur
loss of detail / high frequency
bad: gauss with high variance
acceptable: (fast)bilinear, area
ok: others
aliasing (only downscale)
straight lines look like staircases
areas of high detail look worse
regular patterns turn into a funny looking mess (moire patterns)
bad: fast bilinear, point, gauss with low variance
acceptable: area
ok: others
blocky (upscale only)
looks like the image is made of rectangular blocks like a mosaic
bad: point
ok: others
recommendations: (based upon my personal opinion many ppl might disagree ...)
---------------------------------------------------------------------
the recommended scalers for upscaling:
fast_bilinear, point if speed is important
cubic, spline, lanczos if quality is important
the recommended scalers for downscaling:
fast_bilinear, point if speed is important
gauss, bilinear if quality is important
cubic, spline, lanczos if a sharper picture is important
note: when encoding at a limited amount of bits (not constant quantizer)
then a slightly blurred input might look better after decoding than a slightly
sharpened one, especially for lower bitrates
sws numbers / names / artifact types
-------------------------------------------------------------------------
r ringing
b blurry
a aliasing (downscale only)
m mosaic (blocky) (upscale only)
-sws 0 fast bilinear bA
-sws 1 bilinear b
-sws 2 bicubic high sharpness r
low sharpness b
-sws 3 experimental ????
-sws 4 nearest neighbour AM
-sws 5 area ba
-sws 6 luma bicubic / chroma bilinear r
-sws 7 gauss low sharpness B
high sharpness AM
-sws 8 sinc R
-sws 9 lanczos long filter R
short filter b
-sws 10 bicubic spline r
Notes:
area upscale is identical to bilinear
-270
View File
@@ -1,270 +0,0 @@
Introduction
============
This file lists all changes that can cause compatibility issues when using
mpv through the client API (libmpv and ``client.h``). Since the client API
interfaces to input handling (commands, properties) as well as command line
options, you should also look at ``interface-changes.rst``.
Normally, changes to the C API that are incompatible to previous iterations
receive a major version bump (i.e. the first version number is increased),
while C API additions bump the minor version (i.e. the second number is
increased). Changes to properties/commands/options may also lead to a minor
version bump, in particular if they are incompatible.
The version number is the same as used for MPV_CLIENT_API_VERSION (see
``client.h`` how to convert between major/minor version numbers and the flat
32 bit integer).
Also, read the section ``Compatibility`` in ``client.h``, and compatibility.rst.
Options, commands, properties
=============================
Changes to these are not listed here, but in ``interface-changes.rst``. (Before
client API version 1.17, they were listed here partially.)
This listing includes changes to the bare C API and behavior only, not what
you can access with them.
API changes
===========
::
--- mpv 0.33.0 ---
1.109 - add MPV_RENDER_API_TYPE_SW and related (software rendering API)
- inactivate the opengl_cb API (always fails to initialize now)
The opengl_cb API was deprecated over 2 years ago. Use the render API
instead.
1.108 - Deprecate MPV_EVENT_IDLE
- add mpv_event_start_file
- add the following fields to mpv_event_end_file: playlist_entry_id,
playlist_insert_id, playlist_insert_num_entries
- add mpv_event_to_node()
- add mpv_client_id()
1.107 - Remove the deprecated qthelper.hpp. This was obviously not part of the
libmpv API, only an "additionally" provided helper, thus this is not
considered an API change. If you are maintaining a project that relies
on this header, you can simply download this file and adjust the
include statement to use it instead:
https://raw.githubusercontent.com/mpv-player/mpv/v0.32.0/libmpv/qthelper.hpp
It is a good idea to write better wrappers for your use, though.
--- mpv 0.31.0 ---
1.107 - Deprecate MPV_EVENT_TICK
--- mpv 0.30.0 ---
1.106 - Add cancel_fn to mpv_stream_cb_info
1.105 - Fix deadlock problems with MPV_RENDER_PARAM_ADVANCED_CONTROL and if
the "vd-lavc-dr" option is enabled (which it is by default).
There were no actual API changes.
API users on older API versions and mpv releases should set
"vd-lavc-dr" to "no" to avoid these issues.
API users must still adhere to the tricky rules documented in render.h
to avoid other deadlocks.
1.104 - Deprecate struct mpv_opengl_drm_params. Replaced by mpv_opengl_drm_params_v2
- Deprecate MPV_RENDER_PARAM_DRM_DISPLAY. Replaced by MPV_RENDER_PARAM_DRM_DISPLAY_V2.
1.103 - redo handling of async commands
- add mpv_event_command and make it possible to return values from
commands issued with mpv_command_async() or mpv_command_node_async()
- add mpv_abort_async_command()
1.102 - rename struct mpv_opengl_drm_osd_size to mpv_opengl_drm_draw_surface_size
- rename MPV_RENDER_PARAM_DRM_OSD_SIZE to MPV_RENDER_PARAM_DRM_DRAW_SURFACE_SIZE
--- mpv 0.29.0 ---
1.101 - add MPV_RENDER_PARAM_ADVANCED_CONTROL and related API
- add MPV_RENDER_PARAM_NEXT_FRAME_INFO and related symbols
- add MPV_RENDER_PARAM_BLOCK_FOR_TARGET_TIME
- add MPV_RENDER_PARAM_SKIP_RENDERING
- add mpv_render_context_get_info()
1.100 - bump API number to avoid confusion with mpv release versions
- actually apply the GL_MP_MPGetNativeDisplay change for the new render
API. This also means compatibility for anything but x11 and wayland
through the old opengl-cb GL_MP_MPGetNativeDisplay method is now
unsupported.
- deprecate mpv_get_wakeup_pipe(). It's complex, but easy to replace
using normal API (just set a wakeup callback to a function which
writes to a pipe).
- add a 1st class hook API, which replaces the hacky mpv_command()
based one. The old API is deprecated and will be removed soon. The
old API was never meant to be stable, while the new API is.
1.29 - the behavior of mpv_terminate_destroy() and mpv_detach_destroy()
changes subtly (see documentation in the header file). In particular,
mpv_detach_destroy() will not leave the player running in all
situations anymore (it gets closer to refcounting).
- rename mpv_detach_destroy() to mpv_destroy() (the old function will
remain valid as deprecated alias)
- add mpv_create_weak_client(), which makes use of above changes
- MPV_EVENT_SHUTDOWN is now returned exactly once if a mpv_handle
should terminate, instead of spamming the event queue with this event
1.28 - deprecate the render opengl_cb API, and replace it with render.h
and render_gl.h. The goal is allowing support for APIs other than
OpenGL. The old API is emulated with the new API.
Likewise, the "opengl-cb" VO is renamed to "libmpv".
mpv_get_sub_api() is deprecated along the opengl_cb API.
The new API is relatively similar, but not the same. The rough
equivalents are:
mpv_opengl_cb_init_gl => mpv_render_context_create
mpv_opengl_cb_set_update_callback => mpv_render_context_set_update_callback
mpv_opengl_cb_draw => mpv_render_context_render
mpv_opengl_cb_report_flip => mpv_render_context_report_swap
mpv_opengl_cb_uninit_gl => mpv_render_context_free
The VO opengl-cb is also renamed to "libmpv".
Also, the GL_MP_MPGetNativeDisplay pseudo extension is not used by the
render API anymore, and the old opengl-cb API only handles the "x11"
and "wl" names anymore. Support for everything else has been removed.
The new render API uses proper API parameters, e.g. for X11 you pass
MPV_RENDER_PARAM_X11_DISPLAY directly.
- deprecate the qthelper.hpp header file. This provided some C++ helper
utility functions for Qt with use of libmpv. There is no reason to
keep this in the mpv git repository, nor to make it part of the libmpv
API. If you're using this header, you can safely copy it into your
project - it uses only libmpv public API. Alternatively, it could be
maintained in a separate repository by interested parties.
1.27 - make opengl-cb the default VO. This causes a subtle behavior change
if the API user called mpv_opengl_cb_init_gl(), but does not set
the "vo" option. Before, it would still have used another VO (like
on the CLI, e.g. vo=gpu). Now it'll behave as if vo=opengl-cb was
used.
--- mpv 0.28.0 ---
1.26 - remove glMPGetNativeDisplay("drm") support
- add mpv_opengl_cb_window_pos and mpv_opengl_cb_drm_params and
support via glMPGetNativeDisplay() for using it
- make --stop-playback-on-init-failure=no the default in libmpv (just
like in mpv CLI)
--- mpv 0.27.0 ---
1.25 - remove setting "no-" options via mpv_set_option*(). (See corresponding
deprecation in 0.23.0.)
--- mpv 0.25.0 ---
1.24 - add a MPV_ENABLE_DEPRECATED preprocessor symbol, which can be defined
by the user to exclude deprecated API symbols from the C headers
--- mpv 0.23.0 ---
1.24 - the deprecated mpv_suspend() and mpv_resume() APIs now do nothing.
--- mpv 0.22.0 ---
1.23 - deprecate setting "no-" options via mpv_set_option*(). For example,
instead of "no-video=" you should set "video=no".
- do not override the SIGPIPE signal handler anymore. This was done as
workaround for the FFmpeg TLS code, which has been fixed long ago.
- deprecate mpv_suspend() and mpv_resume(). They will be stubbed out
in mpv 0.23.0.
- make mpv_set_property() work to some degree before mpv_initialize().
It can now be used instead of mpv_set_option().
- semi-deprecate mpv_set_option()/mpv_set_option_string(). You should
use mpv_set_property() instead. There are some deprecated properties
which conflict with some options (see client.h remarks on
mpv_set_option()), for which mpv_set_option() might still be required.
In future mpv releases, the conflicting deprecated options/properties
will be removed, and mpv_set_option() will internally translate API
calls to mpv_set_property().
- qthelper.hpp: deprecate get_property_variant, set_property_variant,
set_option_variant, command_variant, and replace them with
get_property, set_property, command.
--- mpv 0.19.0 ---
1.22 - add stream_cb API for custom protocols
--- mpv 0.18.1 ---
---- - remove "status" log level from mpv_request_log_messages() docs. This
is 100% equivalent to "v". The behavior is still the same, thus no
actual API change.
--- mpv 0.18.0 ---
1.21 - mpv_set_property() changes behavior with MPV_FORMAT_NODE. Before this
change it rejected mpv_nodes with format==MPV_FORMAT_STRING if the
property was not a string or did not have special mechanisms in place
the function failed. Now it always invokes the option string parser,
and mpv_node with a basic data type works exactly as if the function
is invoked with that type directly. This new behavior is equivalent
to mpv_set_option().
This also affects the mp.set_property_native() Lua function.
- generally, setting choice options/properties with "yes"/"no" options
can now be set as MPV_FORMAT_FLAG
- reading a choice property as MPV_FORMAT_NODE will now return a
MPV_FORMAT_FLAG value if the choice is "yes" (true) or "no" (false)
This implicitly affects Lua and JSON IPC interfaces as well.
- big changes to vo-cmdline on vo_opengl and vo_opengl_hq (but not
vo_opengl_cb): options are now normally not reset, but applied on top
of the current options. The special undocumented value "-" still
works, but now resets all options to before any vo-cmdline command
has been called.
--- mpv 0.12.0 ---
1.20 - deprecate "GL_MP_D3D_interfaces"/"glMPGetD3DInterface", and introduce
"GL_MP_MPGetNativeDisplay"/"glMPGetNativeDisplay" (this is a
backwards-compatible rename)
--- mpv 0.11.0 ---
--- mpv 0.10.0 ---
1.19 - add "GL_MP_D3D_interfaces" pseudo extension to make it possible to
use DXVA2 in OpenGL fullscreen mode in some situations
- mpv_request_log_messages() now accepts "terminal-default" as parameter
1.18 - add MPV_END_FILE_REASON_REDIRECT, and change behavior of
MPV_EVENT_END_FILE accordingly
- a bunch of interface-changes.rst changes
1.17 - mpv_initialize() now blocks SIGPIPE (details see client.h)
--- mpv 0.9.0 ---
1.16 - add mpv_opengl_cb_report_flip()
- introduce mpv_opengl_cb_draw() and deprecate mpv_opengl_cb_render()
- add MPV_FORMAT_BYTE_ARRAY
1.15 - mpv_initialize() will now load config files. This requires setting
the "config" and "config-dir" options. In particular, it will load
mpv.conf.
- minor backwards-compatible change to the "seek" and "screenshot"
commands (new flag syntax, old additional args deprecated)
--- mpv 0.8.0 ---
1.14 - add mpv_wait_async_requests()
- the --msg-level option changes its native type from a flat string to
a key-value list (setting/reading the option as string still works)
1.13 - add MPV_EVENT_QUEUE_OVERFLOW
1.12 - add class Handle to qthelper.hpp
- improve opengl_cb.h API uninitialization behavior, and fix the qml
example
- add mpv_create_client() function
1.11 - add OpenGL rendering interop API - allows an application to combine
its own and mpv's OpenGL rendering
Warning: this API is not stable yet - anything in opengl_cb.h might
be changed in completely incompatible ways in minor API bumps
--- mpv 0.7.0 ---
1.10 - deprecate/disable everything directly related to script_dispatch
(most likely affects nobody)
1.9 - add enum mpv_end_file_reason for mpv_event_end_file.reason
- add MPV_END_FILE_REASON_ERROR and the mpv_event_end_file.error field
for slightly better error reporting on playback failure
- add --stop-playback-on-init-failure option, and make it the default
behavior for libmpv only
- add qthelper.hpp set_option_variant()
- mark the following events as deprecated:
MPV_EVENT_TRACKS_CHANGED
MPV_EVENT_TRACK_SWITCHED
MPV_EVENT_PAUSE
MPV_EVENT_UNPAUSE
MPV_EVENT_METADATA_UPDATE
MPV_EVENT_CHAPTER_CHANGE
They are handled better with mpv_observe_property() as mentioned in
the documentation comments. They are not removed and still work.
1.8 - add qthelper.hpp
1.7 - add mpv_command_node(), mpv_command_node_async()
1.6 - modify "core-idle" property behavior
- MPV_EVENT_LOG_MESSAGE now always sends complete lines
- introduce numeric log levels (mpv_log_level)
--- mpv 0.6.0 ---
1.5 - change in X11 and "--wid" behavior again. The previous change didn't
work as expected, and now the behavior can be explicitly controlled
with the "input-x11-keyboard" option. This is only a temporary
measure until XEmbed is implemented and confirmed working.
Note: in 1.6, "input-x11-keyboard" was renamed to "input-vo-keyboard",
although the old option name still works.
1.4 - subtle change in X11 and "--wid" behavior
(this change was added to 0.5.2, and broke some things, see #1090)
--- mpv 0.5.0 ---
1.3 - add MPV_MAKE_VERSION()
1.2 - remove "stream-time-pos" property (no replacement)
1.1 - remap dvdnav:// to dvd://
- add "--cache-file", "--cache-file-size"
- add "--colormatrix-primaries" (and property)
- add "primaries" sub-field to image format properties
- add "playback-time" property
- extend the "--start" option; a leading "+", which was previously
insignificant is now significant
- add "cache-free" and "cache-used" properties
- OSX: the "coreaudio" AO spdif code is split into a separate AO
--- mpv 0.4.0 ---
1.0 - the API is declared stable
-177
View File
@@ -1,177 +0,0 @@
CLI and API compatibility policy
================================
Human users and API users rely on the mpv/libmpv/scripting/IPC interface not
breaking their use case. On the other hand, active development occasionally
requires breaking things, such as removing old options or changing options in
a way that may break.
This document lists rules when, what, and how incompatible changes can be made.
It's interesting both for mpv developers, who want to change user-visible parts,
and mpv users, who want to know what is guaranteed to remain stable.
Any of the rules below may be overridden by statements in more specific
documentation (for example, if the manpage says that a particular option may be
removed any time, it means that, and the option probably won't even go through
deprecation).
Additions
---------
Additions are basically always allowed. API users etc. are supposed to deal with
the possibility that for example new API functions are added. Some parts of the
API may document how they are extended.
Options, commands, properties, events, hooks (command interface)
----------------------------------------------------------------
All of these are important for interfacing both with end users and API users
(which include Lua scripts, libmpv, and the JSON IPC). As such, they constitute
a large part of the user interface and APIs.
All incompatible changes to this must be declared in interface-changes.rst.
(This may also list compatible additions, but it's not a requirement.)
Degrees of importance and compatibility preservation
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Critical and central parts of the command interface have the strictest
requirements. It may not be reasonable to break them, and other means to achieve
some change have to be found. For example, the "seek" command is a bit of a
mess, but since changing it would likely affect almost every user, it may be
impossible to break at least the commonly used syntax. If changed anyway, there
should be a deprecation period of at least 1 year, during which the command
still works, and possibly a warning should remain even after this.
Important/often used parts must be deprecated for at least 2 releases before
they can be broken. There must be at least 1 release where the deprecated
functionality still works, and a replacement is available (if technically
reasonable). For example, a feature deprecated in mpv 0.30.0 may be removed in
mpv 0.32.0. Minor releases do not count towards this.
Less useful parts can be broken immediately, but must come with some sort of
removal warning-
Parts for debugging and testing may be removed any time, potentially even
without any sort of documentation.
Currently, the importance of a part is not documented and not even well-defined,
which is probably a mistake.
Renaming or removing options
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Typically, renaming an option can be done in a compatible way with OPT_REPLACED.
You may need to check whether the corresponding properties still work (including
messy details like observing properties for changes).
OPT_REMOVED can be used to inform the user of alternatives or reasons for the
removal, which is better than an option not found error. Likewise,
m_option.deprecation_message should be set to something helpful.
Both OPT_REPLACED and OPT_REMOVED can remain in the code for a long time, since
they're unintrusive and hopefully make incompatible changes less painful for
users.
Scripting APIs
--------------
This affects internal scripting APIs (currently Lua and JavaScript).
Vaguely the same rules as with the command interface apply. Since there is a
large number of scripts, an effort should be made to provide compatibility
for old scripts, but it does not need to be stronger than that of the command
interface.
Undocumented parts of the scripting APIs are _not_ guaranteed for compatibility.
This applies especially for internals. Languages like Lua do not have strict
access control (nor does the mpv code try to emulate any), so if a script
accesses private parts, and breaks on the next mpv release, it's not mpv's
problem.
JSON IPC
--------
The JSON IPC is a thin protocol wrapping the libmpv API and the command
interface. Compatibility-wise, it's about the same as the scripting APIs.
The JSON protocol commands should remain as compatible as possible, and it
should probably accept the current way commands are delimited (line breaks)
forever.
The protocol may accept non-standard JSON extensions, but only standard JSON
(possibly with restrictions) is guaranteed for compatibility. Clients which want
to remain compatible should not use any extensions.
CLI
---
Things such as default key bindings do not necessarily require compatibility.
However, the release notes should be extremely clear on changes to "important"
key bindings. Bindings which restore the old behavior should be added to
restore-old-bindings.conf.
Some option parsing is CLI-only and not available from libmpv or scripting. No
compatibility guarantees come with them. However, the rules which mpv uses to
distinguish between options and filenames must remain consistent (if the
non-deprecated options syntax is used).
Terminal and log output
-----------------------
There are no compatibility guarantees for the terminal output, or the text
logged via ``MPV_EVENT_LOG_MESSAGE`` and similar APIs. In particular, scripts
invoking mpv CLI are extremely discouraged from trying to parse text output,
and should use other mechanisms such as the JSON IPC.
Protocols, filters, demuxers, etc.
----------------------------------
Which of these are present is generally not guaranteed, and can even depend
on compile time settings.
The filter list and their sub-options are considered part of the
command-interface.
libmpv C API
------------
The libmpv client API (such as ``<libmpv/client.h>``) mostly gives access to
the command interface. The API itself (if looked at as a component separate
from the command interface) is intended to be extremely stable.
All API changes are documented in client-api-changes.rst.
API compatibility
^^^^^^^^^^^^^^^^^
The API is *always* compatible. Incompatible changes are only allowed on major
API version changes (see ``MPV_CLIENT_API_VERSION``). A major version change is
an extremely rare event, which means usually no API symbols are ever removed.
Essentially removing API functions by making them always return an error, or
making it do nothing is allowed in cases where it is unlikely to break most
clients, but requires a deprecation period of 2 releases. (This has happened to
``mpv_suspend()`` for example.)
API symbols can be deprecated. This should be clearly marked in the doxygen
with ``@deprecated``, and if possible, the affected API symbols should not be
visible if the API user defines ``MPV_ENABLE_DEPRECATED`` to 0.
ABI compatibility
^^^^^^^^^^^^^^^^^
The ABI must never be broken, except on major API version changes. For example,
constants don't change their values.
Structs are tricky. If a struct can be allocated by a user (such as ``mpv_node``),
no fields can be added. (Unless it's an union, and the addition does not change
the offset or alignment of any of the fields or the struct itself. This has
happened to ``mpv_node`` in the past.) If a struct is allocated by libmpv only,
new fields can be appended to the end (for example ``mpv_event``).
The ABI is only backward compatible. This means if a host application is linked
to an older libmpv, and libmpv is updated to a newer version, it will still
work (as in not causing any undefined behavior).
Forward compatibility (an application would work with an older libmpv than it
was linked to) is not required.
-213
View File
@@ -1,213 +0,0 @@
Compiling for Windows
=====================
Compiling for Windows is supported with MinGW-w64. This can be used to produce
both 32-bit and 64-bit executables, and it works for building on Windows and
cross-compiling from Linux and Cygwin. MinGW-w64 is available from:
http://mingw-w64.sourceforge.net.
While building a complete MinGW-w64 toolchain yourself is possible, there are a
few build environments and scripts to help ease the process, such as MSYS2 and
MXE. Note that MinGW environments included in Linux distributions are often
broken, outdated and useless, and usually don't use MinGW-w64.
**Warning**: the original MinGW (http://www.mingw.org) is unsupported.
Cross-compilation
=================
When cross-compiling, you have to run mpv's configure with these arguments:
```bash
DEST_OS=win32 TARGET=i686-w64-mingw32 ./waf configure
```
[MXE](http://mxe.cc) makes it very easy to bootstrap a complete MingGW-w64
environment from a Linux machine. See a working example below.
Alternatively, you can try [mingw-w64-cmake](https://github.com/lachs0r/mingw-w64-cmake),
which bootstraps a MinGW-w64 environment and builds mpv and dependencies.
Example with MXE
----------------
```bash
# Before starting, make sure you install MXE prerequisites. MXE will download
# and build all target dependencies, but no host dependencies. For example,
# you need a working compiler, or MXE can't build the crosscompiler.
#
# Refer to
#
# http://mxe.cc/#requirements
#
# Scroll down for disto/OS-specific instructions to install them.
# Download MXE. Note that compiling the required packages requires about 1.4 GB
# or more!
cd /opt
git clone https://github.com/mxe/mxe mxe
cd mxe
# Set build options.
# The JOBS environment variable controls threads to use when building. DO NOT
# use the regular `make -j4` option with MXE as it will slow down the build.
# Alternatively, you can set this in the make command by appending "JOBS=4"
# to the end of command:
echo "JOBS := 4" >> settings.mk
# The MXE_TARGET environment variable builds MinGW-w64 for 32 bit targets.
# Alternatively, you can specify this in the make command by appending
# "MXE_TARGETS=i686-w64-mingw32" to the end of command:
echo "MXE_TARGETS := i686-w64-mingw32.static" >> settings.mk
# If you want to build 64 bit version, use this:
# echo "MXE_TARGETS := x86_64-w64-mingw32.static" >> settings.mk
# Build required packages. The following provide a minimum required to build
# a reasonable mpv binary (though not an absolute minimum).
make gcc ffmpeg libass jpeg lua luajit
# Add MXE binaries to $PATH
export PATH=/opt/mxe/usr/bin/:$PATH
# Build mpv. The target will be used to automatically select the name of the
# build tools involved (e.g. it will use i686-w64-mingw32.static-gcc).
cd ..
git clone https://github.com/mpv-player/mpv.git
cd mpv
python ./bootstrap.py
DEST_OS=win32 TARGET=i686-w64-mingw32.static ./waf configure
# Or, if 64 bit version,
# DEST_OS=win32 TARGET=x86_64-w64-mingw32.static ./waf configure
./waf build
```
Native compilation with MSYS2
=============================
For Windows developers looking to get started quickly, MSYS2 can be used to
compile mpv natively on a Windows machine. The MSYS2 repositories have binary
packages for most of mpv's dependencies, so the process should only involve
building mpv itself.
To build 64-bit mpv on Windows:
Installing MSYS2
----------------
1. Download an installer from https://msys2.github.io/
Both the i686 and the x86_64 version of MSYS2 can build 32-bit and 64-bit
mpv binaries when running on a 64-bit version of Windows, but the x86_64
version is preferred since the larger address space makes it less prone to
fork() errors.
2. Start a MinGW-w64 shell (``mingw64.exe``). **Note:** This is different from
the MSYS2 shell that is started from the final installation dialog. You must
close that shell and open a new one.
For a 32-bit build, use ``mingw32.exe``.
Updating MSYS2
--------------
To prevent errors during post-install, the MSYS2 core runtime must be updated
separately.
```bash
# Check for core updates. If instructed, close the shell window and reopen it
# before continuing.
pacman -Syu
# Update everything else
pacman -Su
```
Installing mpv dependencies
---------------------------
```bash
# Install MSYS2 build dependencies and a MinGW-w64 compiler
pacman -S git python $MINGW_PACKAGE_PREFIX-{pkg-config,gcc}
# Install the most important MinGW-w64 dependencies. libass and lcms2 are also
# pulled in as dependencies of ffmpeg.
pacman -S $MINGW_PACKAGE_PREFIX-{ffmpeg,libjpeg-turbo,lua51}
```
Building mpv
------------
Clone the latest mpv from git and install waf. **Note:** ``/usr/bin/python3``
is invoked directly here, since an MSYS2 version of Python is required.
```bash
git clone https://github.com/mpv-player/mpv.git && cd mpv
/usr/bin/python3 bootstrap.py
```
Finally, compile and install mpv. Binaries will be installed to
``/mingw64/bin`` or ``/mingw32/bin``.
```bash
/usr/bin/python3 waf configure CC=gcc.exe --check-c-compiler=gcc --prefix=$MSYSTEM_PREFIX
/usr/bin/python3 waf install
```
Or, compile and install both libmpv and mpv:
```bash
/usr/bin/python3 waf configure CC=gcc.exe --check-c-compiler=gcc --enable-libmpv-shared --prefix=$MSYSTEM_PREFIX
/usr/bin/python3 waf install
```
Linking libmpv with MSVC programs
---------------------------------
mpv/libmpv cannot be built with Visual Studio (Microsoft is too incompetent to
support C99/C11 properly and/or hates open source and Linux too much to
seriously do it). But you can build C++ programs in Visual Studio and link them
with a libmpv built with MinGW.
To do this, you need a Visual Studio which supports ``stdint.h`` (recent ones do),
and you need to create a import library for the mpv DLL:
```bash
lib /def:mpv.def /name:mpv-1.dll /out:mpv.lib /MACHINE:X64
```
The string in the ``/name:`` parameter must match the filename of the DLL (this
is simply the filename the MSVC linker will use). The ``mpv.def`` can be
retrieved from the mpv build directory, or can be produced by MingGW's
gendef.exe helper from the mpv DLL.
Static linking is not possible.
Running mpv
-----------
If you want to run mpv from the MinGW-w64 shell, you will find the experience
much more pleasant if you use the ``winpty`` utility
```bash
pacman -S winpty
winpty mpv.com ToS-4k-1920.mov
```
If you want to move / copy ``mpv.exe`` and ``mpv.com`` to somewhere other than
``/mingw64/bin/`` for use outside the MinGW-w64 shell, they will still depend on
DLLs in that folder. The simplest solution is to add ``C:\msys64\mingw64\bin``
to the windows system ``%PATH%``. Beware though that this can cause problems or
confusion in Cygwin if that is also installed on the machine.
Use of the ANGLE OpenGL backend requires a copy of the D3D compiler DLL that
matches the version of the D3D SDK that ANGLE was built with
(``d3dcompiler_43.dll`` in case of MinGW-built ANGLE) in the path or in the
same folder as mpv. It must be of the same architecture (x86_64 / i686) as the
mpv you compiled. You can find copies here:
https://mpv.srsfckn.biz/d3dcompiler.7z
-275
View File
@@ -1,275 +0,0 @@
How to contribute
=================
General
-------
The main contact for mpv development is IRC, specifically #mpv
and #mpv-devel on Freenode. Github is used for code review and
long term discussions.
Sending patches
---------------
- Make a github pull request, or send a link to a plaintext patch created with
``git format-patch``.
- Plain diffs posted as pastebins are not acceptable! (Especially if the http
link returns HTML.) They only cause extra work for everyone, because they lack
commit message and authorship information.
- Never send patches to any of the developers email addresses.
- If your changes are not supposed to be merged immediately, mark them as
"[RFC]" in the commit message or the pull request title.
- Be sure to test your changes. If you didn't, please say so in the commit
message and the pull request text.
Copyright of contributions
--------------------------
- The copyright belongs to contributors. The project is a collaborative work. By
sending your changes, you agree to license your contributions according to the
requirements of this project.
- All new code must be LGPLv2.1+ licensed, or come with the implicit agreement
that it will be relicensed to LGPLv2.1+ later (see ``Copyright`` in the
repository root directory).
- 100% compatible licenses are allowed too.
- Changes in files with more liberal licenses (such as BSD, MIT, or ISC) are
assumed to be dual-licensed under LGPLv2.1+ and the license indicated in the
file header.
- You must be either the exclusive author of the patch, or acknowledge all
authors involved in the commit message. If you take 3rd party code, authorship
and copyright must be properly acknowledged. If you're making changes on
behalf of your employer, and the employer owns the copyright, you must mention
this. If the license of the code is not LGPLv2.1+, you must mention this.
- These license statements are legally binding.
- Don't use fake names (something that looks like an actual name, and may be
someone else's name, but is not your legal name). Using a pseudonyms is
allowed if it can be used to identify or contact you, even if whatever
account you used to submit the patch dies.
- Do not add your name to the license header. This convention is not used by
this project, and neither copyright law nor any of the used licenses require
it.
Write good commit messages
--------------------------
- Write informative commit messages. Use present tense to describe the
situation with the patch applied, and past tense for the situation before
the change.
- The subject line (the first line in a commit message) must contain a
prefix identifying the sub system, followed by a short description what
impact this commit has. This subject line and the commit message body
must not be longer than 72 characters per line, because it messes up the
output of many git tools otherwise.
For example, you fixed a crash in af_volume.c:
- Bad: ``fixed the bug (wtf?)``
- Good: ``af_volume: fix crash due to null pointer access``
Having a prefix gives context, and is especially useful when trying to find
a specific change by looking at the history, or when running ``git blame``.
- The first word after the ``:`` is lower case.
- Don't end the subject line with a ``.``.
- Put an empty line between the subject line and the commit message.
If this is missing, it will break display in common git tools.
- The body of the commit message (everything else after the subject line) must
be as informative as possible and contain everything that isn't obvious. Don't
hesitate to dump as much information as you can - it doesn't cost you
anything. Put some effort into it. If someone finds a bug months or years
later, and finds that it's caused by your commit (even though your commit was
supposed to fix another bug), it would be bad if there wasn't enough
information to test the original bug. The old bug might be reintroduced while
fixing the new bug.
The commit message must be wrapped on 72 characters per line, because git
tools usually do not break text automatically. On the other hand, you do not
need to break text that would be unnatural to break (like data for test cases,
or long URLs).
- Another summary of good conventions: https://chris.beams.io/posts/git-commit/
Split changes into multiple commits
-----------------------------------
- Follow git good practices, and split independent changes into several commits.
It's usually OK to put them into a single pull request.
- Try to separate cosmetic and functional changes. It's ok to make a few
additional cosmetic changes in the same file you're working on. But don't do
something like reformatting a whole file, and hiding an actual functional
change in the same commit.
- Splitting changes does _not_ mean that you should make them as fine-grained
as possible. Commits should form logical steps in development. The way you
split changes is important for code review and analyzing bugs.
Always squash fixup commits when making changes to pull requests
----------------------------------------------------------------
- If you make fixup commits to your pull request, you should generally squash
them with "git rebase -i". We prefer to have pull requests in a merge
ready state.
- We don't squash-merge (nor do we use github's feature that does this) because
pull requests with multiple commits are perfectly legitimate, and the only
thing that makes sense in non-trivial cases.
- With complex pull requests, it *may* make sense to keep them separate, but
they should be clearly marked as such. Reviewing commits is generally easier
with fixups squashed.
- Reviewers are encouraged to look at individual commits instead of github's
"changes from all commits" view (which just encourages bad git and review
practices).
Touching user-visible parts may require updating the mpv docs
-------------------------------------------------------------
- Most user-visible things are normally documented in DOCS/man/. If your commit
touches documented behavior, list of sub-options, etc., you need to adjust the
documentation.
- These changes usually go into the same commit that changes the code.
- Changes to command line options (addition/modification/removal) must be
documented in options.rst.
- Changes to input properties or input commands must be documented in input.rst.
- All incompatible changes to the user interface (options, properties, commands)
must be documented with a small note in interface-changes.rst. (Additions may
be documented there as well, but this isn't required.)
- Changes to the libmpv API must be reflected in the libmpv's headers doxygen,
and in client-api-changes.rst.
Code formatting
---------------
mpv uses C99 with K&R formatting, with some exceptions.
- Use the K&R indent style.
- Use 4 spaces of indentation, never use tabs (except in Makefiles).
- Add a single space between keywords and binary operators. There are some other
cases where spaces must be added. Example:
```C
if ((a * b) > c) {
// code
some_function(a, b, c);
}
```
- Break lines on 80 columns. There is a hard limit of 85 columns. You may ignore
this limit if there's a strong case that not breaking the line will increase
readability. Going over 85 columns might provoke endless discussions about
whether such a limit is needed or not, so avoid it.
- If the body of an if/for/while statement has more than 1 physical lines, then
always add braces, even if they're technically redundant.
Bad:
```C
if (a)
// do something if b
if (b)
do_something();
```
Good:
```C
if (a) {
// do something if b
if (b)
do_something();
}
```
- If the if has an else branch, both branches must use braces, even if they're
technically redundant.
Example:
```C
if (a) {
one_line();
} else {
one_other_line();
}
```
- If an if condition spans multiple physical lines, then put the opening brace
for the if body on the next physical line. (Also, preferably always add a
brace, even if technically none is needed.)
Example:
```C
if (very_long_condition_a &&
very_long_condition_b)
{
code();
} else {
...
}
```
(If the if body is simple enough, this rule can be skipped.)
- Remove any trailing whitespace.
- Do not make stray whitespaces changes.
Header #include statement order
-------------------------------
The order of ``#include`` statements in the source code is not very consistent.
New code must follow the following conventions:
- Put standard includes (``#include <stdlib.h>`` etc.) on the top,
- then after a blank line, add library includes (``#include <zlib.h>`` etc.)
- then after a blank line, add internal includes (``#include "player/core.h"``)
- sort them alphabetically within these sections
General coding
--------------
- Use C99. Also freely make use of C99 features if it's appropriate, such as
stdbool.h. (Except VLA and complex number types.)
- Don't use non-standard language (such as GNU C-only features). In some cases
they may be warranted, if they are optional (such as attributes enabling
printf-like format string checks). "#pragma once" is allowed as an exception.
But in general, standard C99 must be used.
- The same applies to libc functions. We have to be Windows-compatible too. Use
functions guaranteed by C99 or POSIX only, unless your use is guarded by a
configure check. There is some restricted use of C11 (ask on IRC for details).
- Prefer fusing declaration and initialization, rather than putting declarations
on the top of a block. Obvious data flow is more important than avoiding
mixing declarations and statements, which is just a C90 artifact.
- If you add features that require intrusive changes, discuss them on the dev
channel first. There might be a better way to add a feature and it can avoid
wasted work.
Code of Conduct
---------------
Please note that this project is released with a Contributor Code of Conduct.
By participating in this project you agree to abide by its terms.
The Contributor Code of Conduct can be found here:
https://www.contributor-covenant.org/version/2/0/code_of_conduct/
Rules for git push access
-------------------------
Push access to the main git repository is handed out on an arbitrary basis. If
you got access, the following rules must be followed:
- You are expected to follow the general development rules as outlined in this
whole document.
- You must be present on the IRC dev channel when you push something.
- Anyone can push small fixes: typo corrections, small/obvious/uncontroversial
bug fixes, edits to the user documentation or code comments, and so on.
- You can freely make changes to parts of the code which you maintain. For
larger changes, it's recommended to let others review the changes first.
- You automatically maintain code if you wrote or modified most of it before
(e.g. you made larger changes to it before, did partial or full rewrites, did
major bug fixes, or you're the original author of the code). If there is more
than one maintainer, you may need to come to an agreement with the others how
to handle this to avoid conflict.
- If you make a pull requests (especially if it's to code you maintain), and you
want reviews, explicitly ping the people from which you expect reviews.
- As a maintainer, you can approve pull requests by others to "your" code.
- If you approve or merge 3rd party changes, make sure they follow the general
development rules.
- Changes to user interface and public API must always be approved by the
project leader.
- Seasoned project members are allowed to revert commits that broke the build,
or broke basic functionality in a catastrophic way, and the developer who
broke it is unavailable. (Depending on severity.)
- Adhere to the CoC.
- The project leader is not bound by these rules.
+52
View File
@@ -0,0 +1,52 @@
Cross compiling mpv to Windows is supported with MinGW-w64. This can be used to
produce both 32 bit and 64 bit executables. MinGW-w64 is available from
http://mingw-w64.sourceforge.net.
You have to run mpv's configure with these arguments:
./configure --enable-cross-compile --target=i686-w64-mingw32
Using mingw-w64-cmake to setup a MinGW-w64 environment is recommended (this will
also build mpv and its dependencies): https://github.com/lachs0r/mingw-w64-cmake
Alternatively, use MXE: http://mxe.cc
Warning: the original MinGW (http://www.mingw.org) is unsupported.
Note that MinGW environments included in Linux distributions are often broken,
outdated and useless, and usually don't use MinGW-w64.
Example with MXE
================
# Download MXE. Note that compiling the required packages requires about 1 GB
# or more!
cd /opt
git clone https://github.com/mxe/mxe
cd mingw
# Edit the MXE target, so that MinGW-w64 for 32 bit targets is built.
echo "MXE_TARGETS := i686-w64-mingw32" > settings.mk
# Build required packages. The following provide a minimum required to build
# mpv. (Not all of the following packages are strictly required.)
make gcc
make ffmpeg
make libass
make jpeg
make pthreads
# Build mpv. The target will be used to automatically select the name of the
# build tools involved (e.g. it will use i686-w64-mingw32-gcc).
git clone https://github.com/mpv-player/mpv.git
cd mpv
export PATH=/opt/mingw/usr/bin/:$PATH
./configure --enable-cross-compile --target=i686-w64-mingw32
make
# This should work. Note however that MXE’s ffmpeg package might be very old
# in order to avoid breaking e.g. xine-lib, so you might want to update that
# or build it manually as well.
-376
View File
@@ -1,376 +0,0 @@
EDL files
=========
EDL files basically concatenate ranges of video/audio from multiple source
files into a single continuous virtual file. Each such range is called a
segment, and consists of source file, source offset, and segment length.
For example::
# mpv EDL v0
f1.mkv,10,20
f2.mkv
f1.mkv,40,10
This would skip the first 10 seconds of the file f1.mkv, then play the next
20 seconds, then switch to the file f2.mkv and play all of it, then switch
back to f1.mkv, skip to the 40 second mark, and play 10 seconds, and then
stop playback. The difference to specifying the files directly on command
line (and using ``--{ --start=10 --length=20 f1.mkv --}`` etc.) is that the
virtual EDL file appears as a virtual timeline (like a single file), instead
as a playlist.
The general simplified syntax is::
# mpv EDL v0
<filename>
<filename>,<start in seconds>,<length in seconds>
If the start time is omitted, 0 is used. If the length is omitted, the
estimated remaining duration of the source file is used.
Note::
Usage of relative or absolute paths as well as any protocol prefixes may be
prevented for security reasons.
Syntax of mpv EDL files
=======================
Generally, the format is relatively strict. No superfluous whitespace (except
empty lines and commented lines) are allowed. You must use UNIX line breaks.
The first line in the file must be ``# mpv EDL v0``. This designates that the
file uses format version 0, which is not frozen yet and may change any time.
(If you need a stable EDL file format, make a feature request. Likewise, if
you have suggestions for improvements, it's not too late yet.)
The rest of the lines belong to one of these classes:
1) An empty or commented line. A comment starts with ``#``, which must be the
first character in the line. The rest of the line (up until the next line
break) is ignored. An empty line has 0 bytes between two line feed bytes.
2) A header entry if the line starts with ``!``.
3) A segment entry in all other cases.
Each segment entry consists of a list of named or unnamed parameters.
Parameters are separated with ``,``. Named parameters consist of a name,
followed by ``=``, followed by the value. Unnamed parameters have only a
value, and the name is implicit from the parameter position.
Syntax::
segment_entry ::= <param> ( <param> ',' )*
param ::= [ <name> '=' ] ( <value> | '%' <number> '%' <valuebytes> )
The ``name`` string can consist of any characters, except ``=%,;\n!``. The
``value`` string can consist of any characters except of ``,;\n!``.
The construct starting with ``%`` allows defining any value with arbitrary
contents inline, where ``number`` is an integer giving the number of bytes in
``valuebytes``. If a parameter value contains disallowed characters, it has to
be guarded by a length specifier using this syntax.
The parameter name defines the meaning of the parameter:
1) ``file``, the source file to use for this segment.
2) ``start``, a time value that specifies the start offset into the source file.
3) ``length``, a time value that specifies the length of the segment.
See the section below for the format of timestamps.
Unnamed parameters carry implicit names. The parameter position determines
which of the parameters listed above is set. For example, the second parameter
implicitly uses the name ``start``.
Example::
# mpv EDL v0
%18%filename,with,.mkv,10,length=20,param3=%13%value,escaped,param4=value2
this sets ``file`` to ``filename,with,.mkv``, ``start`` to ``10``, ``length``
to ``20``, ``param3`` to ``value,escaped``, ``param4`` to ``value2``.
Instead of line breaks, the character ``;`` can be used. Line feed bytes and
``;`` are treated equally.
Header entries start with ``!`` as first character after a line break. Header
entries affect all other file entries in the EDL file. Their format is highly
implementation specific. They should generally follow the file header, and come
before any file entries.
Disabling chapter generation and copying
========================================
By default, chapters from the source ranges are copied to the virtual file's
chapters. Also, a chapter is inserted after each range. This can be disabled
with the ``no_chapters`` header.
Example::
!no_chapters
MP4 DASH
========
This is a header that helps implementing DASH, although it only provides a low
level mechanism.
If this header is set, the given url designates an mp4 init fragment. It's
downloaded, and every URL in the EDL is prefixed with the init fragment on the
byte stream level. This is mostly for use by mpv's internal ytdl support. The
ytdl script will call youtube-dl, which in turn actually processes DASH
manifests. It may work only for this very specific purpose and fail to be
useful in other scenarios. It can be removed or changed in incompatible ways
at any times.
Example::
!mp4_dash,init=url
The ``url`` is encoded as parameter value as defined in the general EDL syntax.
It's expected to point to an "initialization fragment", which will be prefixed
to every entry in the EDL on the byte stream level.
The current implementation will
- ignore stream start times
- use durations as hint for seeking only
- not adjust source timestamps
- open and close segments (i.e. fragments) as needed
- not add segment boundaries as chapter points
- require full compatibility between all segments (same codec etc.)
Another header part of this mechanism is ``no_clip``. This header is similar
to ``mp4_dash``, but does not include on-demand opening/closing of segments,
and does not support init segments. It also exists solely to support internal
ytdl requirements. Using ``no_clip`` with segments is not recommended and
probably breaks. ``mp4_dash`` already implicitly does a variant of ``no_clip``.
The ``mp4_dash`` and ``no_clip`` headers are not part of the core EDL format.
They may be changed or removed at any time, depending on mpv's internal
requirements.
Separate files for tracks
=========================
The special ``new_stream`` header lets you specify separate parts and time
offsets for separate tracks. This can for example be used to source audio and
video track from separate files.
Example::
# mpv EDL v0
video.mkv
!new_stream
audio.mkv
This adds all tracks from both files to the virtual track list. Upon playback,
the tracks will be played at the same time, instead of appending them. The files
can contain more than 1 stream; the apparent effect is the same as if the second
part after the ``!new_stream`` part were in a separate ``.edl`` file and added
with ``--external-file``.
Note that all metadata between the stream sets created by ``new_stream`` is
disjoint. Global metadata is taken from the first part only.
In context of mpv, this is redundant to the ``--audio-file`` and
``--external-file`` options, but (as of this writing) has the advantage that
this will use a unified cache for all streams.
The ``new_stream`` header is not part of the core EDL format. It may be changed
or removed at any time, depending on mpv's internal requirements.
If the first ``!new_stream`` is redundant, it is ignored. This is the same
example as above::
# mpv EDL v0
!new_stream
video.mkv
!new_stream
audio.mkv
Note that ``!new_stream`` must be the first header. Whether the parser accepts
(i.e. ignores) or rejects other headers before that is implementation specific.
Track metadata
==============
The special ``track_meta`` header can set some specific metadata fields of the
current ``!new_stream`` partition. The tags are applied to all tracks within
the partition. It is not possible to set the metadata for individual tracks (the
feature was needed only for single-track media).
It provides following parameters change track metadata:
``lang``
Set the language tag.
``title``
Set the title tag.
``byterate``
Number of bytes per second this stream uses. (Purely informational.)
``index``
The numeric index of the track this should map to (default: -1). This is
the 0-based index of the virtual stream as seen by the player, enumerating
all audio/video/subtitle streams. If nothing matches, this is silently
discarded. The special index -1 (the default) has two meanings: if there
was a previous meta data entry (either ``!track_meta`` or ``!delay_open``
element since the last ``!new_stream``), then this element manipulates
the previous meta data entry. If there was no previous entry, a new meta
data entry that matches all streams is created.
Example::
# mpv EDL v0
!track_meta,lang=bla,title=blabla
file.mkv
!new_stream
!track_meta,title=ducks
sub.srt
If ``file.mkv`` has an audio and a video stream, both will use ``blabla`` as
title. The subtitle stream will use ``ducks`` as title.
The ``track_meta`` header is not part of the core EDL format. It may be changed
or removed at any time, depending on mpv's internal requirements.
Delayed media opening
=====================
The special ``delay_open`` header can be used to open the media URL of the
stream only when the track is selected for the first time. This is supposed to
be an optimization to speed up opening of a remote stream if there are many
tracks for whatever reasons.
This has various tricky restrictions, and also will defer failure to open a
stream to "later". By design, it's supposed to be used for single-track streams.
Using multiple segments requires you to specify all offsets and durations (also
it was never tested whether it works at all). Interaction with ``mp4_dash`` may
be strange.
You can describe multiple sub-tracks by using multiple ``delay_open`` headers
before the same source URL. (If there are multiple sub-tracks of the same media
type, then the mapping to the real stream is probably rather arbitrary.) If the
source contains tracks not described, a warning is logged when the delayed
opening happens, and the track is hidden.
This has the following parameters:
``media_type``
Required. Must be set to ``video``, ``audio``, or ``sub``. (Other tracks in
the opened URL are ignored.)
``codec``
The mpv codec name that is expected. Although mpv tries to initialize a
decoder with it currently (and will fail track selection if it does not
initialize successfully), it is not used for decoding - decoding still uses
the information retrieved from opening the actual media information, and may
be a different codec (you should try to avoid this, of course). Defaults to
``null``.
Above also applies for similar fields such as ``w``. These fields are
mostly to help with user track pre-selection.
``flags``
A ``+`` separated list of boolean flags. Currently defined flags:
``default``
Set the default track flag.
``forced``
Set the forced track flag.
Other values are ignored after triggering a warning.
``w``, ``h``
For video codecs: expected video size. See ``codec`` for details.
``fps``
For video codecs: expected video framerate, as integer. (The rate is usually
only crudely reported, and it makes no sense to expect exact values.)
``samplerate``
For audio codecs: expected sample rate, as integer.
The ``delay_open`` header is not part of the core EDL format. It may be changed
or removed at any time, depending on mpv's internal requirements.
Timestamp format
================
Currently, time values are floating point values in seconds.
As an extension, you can set the ``timestamps=chapters`` option. If this option
is set, timestamps have to be integers, and refer to chapter numbers, starting
with 0. The default value for this parameter is ``seconds``, which means the
time is as described in the previous paragraph.
Example::
# mpv EDL v0
file.mkv,2,4,timestamps=chapters
Plays chapter 3 and ends with the start of chapter 7 (4 chapters later).
Implicit chapters
=================
mpv will add one chapter per segment entry to the virtual timeline.
By default, the chapter's titles will match the entries' filenames.
You can override set the ``title`` option to override the chapter title for
that segment.
Example::
# mpv EDL v0
cap.ts,5,240
OP.mkv,0,90,title=Show Opening
The virtual timeline will have two chapters, one called "cap.ts" from 0-240s
and a second one called "Show Opening" from 240-330s.
Entry which defines the track layout
====================================
Normally, you're supposed to put only files with compatible layouts into an EDL
file. However, at least the mpv implementation accepts entries that use
different codecs, or even have a different number of audio/video/subtitle
tracks. In this case, it's not obvious, which virtual tracks the EDL show should
expose when being played.
Currently, mpv will apply an arbitrary heuristic which tracks the EDL file
should expose. (Before mpv 0.30.0, it always used the first source file in the
segment list.)
You can set the ``layout`` option to ``this`` to make a specific entry define
the track layout.
Example::
# mpv EDL v0
file_with_2_streams.ts,5,240
file_with_5_streams.mkv,0,90,layout=this
The way the different virtual EDL tracks are associated with the per-segment
ones is highly implementation-defined, and uses a heuristic. If a segment is
missing a track, there will be a "hole", and bad behavior may result. Improving
this is subject to further development (due to being fringe cases, they don't
have a high priority).
If future versions of mpv change this again, this option may be ignored.
Syntax of EDL URIs
==================
mpv accepts inline EDL data in form of ``edl://`` URIs. Other than the
header, the syntax is exactly the same. It's far more convenient to use ``;``
instead of line breaks, but that is orthogonal.
Example: ``edl://f1.mkv,length=5,start=10;f2.mkv,30,20;f3.mkv``
+139
View File
@@ -0,0 +1,139 @@
Format of mplayer2 EDL files
============================
The first line in the file must be ``mplayer EDL file, version 2``.
The rest of the lines belong to one of these classes:
1) lines specifying source files
2) empty lines
3) lines specifying timeline segments.
Lines beginning with ``<`` specify source files. These lines first
contain an identifier used to refer to the source file later, then the
filename separated by whitespace. The identifier must start with a
letter. Filenames that start or end with whitespace or contain
newlines are not supported.
On other lines ``#`` characters delimit comments. Lines that contain
only whitespace after comments have been removed are ignored.
Timeline segments must appear in the file in chronological order. Each
segment has the following information associated with it:
- duration
- output start time
- output end time (= output start time + duration)
- source id (specifies the file the content of the segment comes from)
- source start time (timestamp in the source file)
- source end time (= source start time + duration)
The output timestamps must form a continuous timeline from 0 to the
end of the last segment, such that each new segment starts from the
time the previous one ends at. Source files and times may change
arbitrarily between segments.
The general format for lines specifying timeline segments is
[output time info] source_id [source time info]
source_id must be an identifier defined on a ``<`` line. Both the time
info parts consists of zero or more of the following elements:
1) ``timestamp``
2) ``-timestamp``
3) ``+duration``
4) ``*``
5) ``-*``
, where ``timestamp`` and ``duration`` are decimal numbers (computations
are done with nanosecond precision). Whitespace around ``+`` and ``-`` is
optional. 1) and 2) specify start and end time of the segment on
output or source side. 3) specifies duration; the semantics are the
same whether this appears on output or source side. 4) and 5) are
ignored on the output side (they're always implicitly assumed). On the
source side 4) specifies that the segment starts where the previous
segment *using this source* ended; if there was no previous segment
time 0 is used. 5) specifies that the segment ends where the next
segment using this source starts.
Redundant information may be omitted. It will be filled in using the
following rules:
- output start for first segment is 0
- two of [output start, output end, duration] imply third
- two of [source start, source end, duration] imply third
- output start = output end of previous segment
- output end = output start of next segment
- if ``*``, source start = source end of earlier segment
- if ``-*``, source end = source start of a later segment
As a special rule, a last zero-duration segment without a source
specification may appear. This will produce no corresponding segment
in the resulting timeline, but can be used as syntax to specify the
end time of the timeline (with effect equal to adding -time on the
previous line).
Examples::
mplayer EDL file, version 2
< id1 filename
0 id1 123
100 id1 456
200 id1 789
300
All segments come from the source file ``filename``. First segment
(output time 0-100) comes from time 123-223, second 456-556, third
789-889.
::
mplayer EDL file, version 2
< f filename
f 60-120
f 600-660
f 30- 90
Play first seconds 60-120 from the file, then 600-660, then 30-90.
::
mplayer EDL file, version 2
< id1 filename1
< id2 filename2
+10 id1 *
+10 id2 *
+10 id1 *
+10 id2 *
+10 id1 *
+10 id2 *
This plays time 0-10 from filename1, then 0-10 from filename1, then
10-20 from filename1, then 10-20 from filename2, then 20-30 from
filename1, then 20-30 from filename2.
::
mplayer EDL file, version 2
< t1 filename1
< t2 filename2
t1 * +2 # segment 1
+2 t2 100 # segment 2
t1 * # segment 3
t2 *-* # segment 4
t1 3 -* # segment 5
+0.111111 t2 102.5 # segment 6
7.37 t1 5 +1 # segment 7
This rather pathological example illustrates the rules for filling in
implied data. All the values can be determined by recursively applying
the rules given above, and the full end result is this::
+2 0-2 t1 0-2 # segment 1
+2 2-4 t2 100-102 # segment 2
+0.758889 4-4.758889 t1 2-2.758889 # segment 3
+0.5 4.4758889-5.258889 t2 102-102.5 # segment 4
+2 5.258889-7.258889 t1 3-5 # segment 5
+0.111111 7.258889-7.37 t2 102.5-102.611111 # segment 6
+1 7.37-8.37 t1 5-6 # segment 7
+17 -28
View File
@@ -3,7 +3,8 @@ General usage
::
mpv infile -o outfile [-of outfileformat] [-ofopts formatoptions] [-orawts] \
mpv infile -o outfile [-of outfileformat] [-ofopts formatoptions] \
[-ofps outfps | -oautofps] [-oharddup] [-ocopyts | -orawts] [-oneverdrop] \
[(any other mpv options)] \
-ovc outvideocodec [-ovcopts outvideocodecoptions] \
-oac outaudiocodec [-oacopts outaudiocodecoptions]
@@ -24,34 +25,25 @@ from the input video. Note that not all codecs and not all formats support VFR
encoding, and some which do have bugs when a target bitrate is specified - use
-ofps or -oautofps to force CFR encoding in these cases.
Of course, the options can be stored in a profile, like this .config/mpv/mpv.conf
Of course, the options can be stored in a profile, like this .mpv/config
section::
[myencprofile]
vf-add = scale=480:-2
ovc = libx264
ovcopts-add = preset=medium
ovcopts-add = tune=fastdecode
ovcopts-add = preset=medium,tune=fastdecode
ovcopts-add = crf=23
ovcopts-add = maxrate=1500k
ovcopts-add = bufsize=1000k
ovcopts-add = rc_init_occupancy=900k
ovcopts-add = refs=2
ovcopts-add = maxrate=1500k,bufsize=1000k,rc_init_occupancy=900k,refs=2
ovcopts-add = profile=baseline
oac = aac
oacopts-add = b=96k
It's also possible to define default encoding options by putting them into
the section named ``[encoding]``. (This behavior changed after mpv 0.3.x. In
mpv 0.3.x, config options in the default section / no section were applied
to encoding. This is not the case anymore.)
One can then encode using this profile using the command::
mpv infile -o outfile.mp4 -profile myencprofile
Some example profiles are provided in a file
etc/encoding-profiles.conf; as for this, see below.
etc/encoding-example-profiles.conf; as for this, see below.
Encoding examples
@@ -63,13 +55,13 @@ for.
Typical MPEG-4 Part 2 ("ASP", "DivX") encoding, AVI container::
mpv infile -o outfile.avi \
--vf=fps=25 \
-ofps 25 \
-ovc mpeg4 -ovcopts qscale=4 \
-oac libmp3lame -oacopts ab=128k
Note: AVI does not support variable frame rate, so the fps filter must be used.
The frame rate should ideally match the input (25 for PAL, 24000/1001 or
30000/1001 for NTSC)
Note: AVI does not support variable frame rate, so -ofps must be used. The
frame rate should ideally match the input (25 for PAL, 24000/1001 or 30000/1001
for NTSC)
Typical MPEG-4 Part 10 ("AVC", "H.264") encoding, Matroska (MKV) container::
@@ -97,16 +89,13 @@ Device targets
As the options for various devices can get complex, profiles can be used.
An example profile file for encoding is provided in
etc/encoding-profiles.conf in the source tree. This file is installed and loaded
by default. If you want to modify it, you can replace and it with your own copy
by doing::
etc/encoding-example-profiles.conf in the source tree. You can include it into
your configuration by doing::
mkdir -p ~/.mpv
cp /etc/mpv/encoding-profiles.conf ~/.mpv/encoding-profiles.conf
Keep in mind that the default profile is the playback one. If you want to add
options that apply only in encoding mode, put them into a ``[encoding]``
section.
curl https://raw.github.com/mpv-player/mpv/master/etc/encoding-example-profiles.conf \
> ~/.mpv/encoding-profiles.conf
echo "include = $HOME/.mpv/encoding-profiles.conf" >> ~/.mpv/config
Refer to the top of that file for more comments - in a nutshell, the following
options are added by it::
@@ -132,7 +121,7 @@ What works
==========
* Encoding at variable frame rate (default)
* Encoding at constant frame rate using --vf=fps=RATE
* Encoding at constant frame rate using -ofps framerate -oharddup
* 2-pass encoding (specify flags=+pass1 in the first pass's -ovcopts, specify
flags=+pass2 in the second pass)
* Hardcoding subtitles using vobsub, ass or srt subtitle rendering (just
@@ -146,9 +135,9 @@ What works
* Deinterlacing/Inverse Telecine with any of mpv's filters for that
* Audio file converting: mpv -o outfile.mp3 infile.flac -no-video -oac
libmp3lame -oacopts ab=320k
* inverse telecine filters (confirmed working: detc, pullup, filmdint)
What does not work yet
======================
* 3-pass encoding (ensuring constant total size and bitrate constraints while
having VBR audio; mencoder calls this "frameno")
-777
View File
@@ -1,777 +0,0 @@
Introduction
============
mpv provides access to its internals via the following means:
- options
- commands
- properties
- events
- hooks
The sum of these mechanisms is sometimes called command interface.
All of these are important for interfacing both with end users and API users
(which include Lua scripts, libmpv, and the JSON IPC). As such, they constitute
a large part of the user interface and APIs.
Also see compatibility.rst.
This document lists changes to them. New changes are added to the top. Usually,
only incompatible or important changes are mentioned. New options/commands/etc.
are not always listed.
Interface changes
=================
::
--- mpv 0.33.0 ---
- add `--d3d11-exclusive-fs` flag to enable D3D11 exclusive fullscreen mode
when the player enters fullscreen.
- directories in ~/.mpv/scripts/ (or equivalent) now have special semantics
(see mpv Lua scripting docs)
- names starting with "." in ~/.mpv/scripts/ (or equivalent) are now ignored
- js modules: ~~/scripts/modules.js/ is no longer used, global paths can be
set with custom init (see docs), dir-scripts first look at <dir>/modules/
- the OSX bundle now logs to "~/Library/Logs/mpv.log" by default
- deprecate the --cache-secs option (once removed, the cache cannot be
limited by time anymore)
- remove deprecated legacy hook API ("hook-add", "hook-ack"). Use either the
libmpv API (mpv_hook_add(), mpv_hook_continue()), or the Lua scripting
wrappers (mp.add_hook()).
- improve how property change notifications are delivered on events and on
hooks. In particular, a hook event is only returned to a client after all
changes initiated before the hook point were delivered to the same client.
In addition, it should no longer happen that events and property change
notifications were interleaved in bad ways (it could happen that a
property notification delivered after an event contained a value that was
valid only before the event happened).
- the playlist-pos and playlist-pos-1 properties now can return and accept
-1, and are never unavailable. Out of range indexes are now accepted, but
behave like writing -1.
- the playlist-pos and playlist-pos-1 properties deprecate the current
behavior when writing back the current value to the property: currently,
this restarts playback, but in the future, it will do nothing.
Using the "playlist-play-index" command is recommended instead.
- add "playlist-play-index" command
- add playlist-current-pos, playlist-playing-pos properties
- Lua end-file events set the "error" field; this is deprecated; use the
"file_error" instead for this specific event. Scripts relying on the
"error" field for end-file will silently break at some point in the
future.
- remove deprecated --input-file option, add --input-ipc-client, which is
vaguely a replacement of the removed option, but not the same
- change another detail for track selection options (see --aid manpage
entry)
- reading loop-file property as native property or mpv_node will now return
"inf" instead of boolean true (also affects loop option)
- remove some --vo-direct3d-... options (it got dumbed down; use --vo=gpu)
- remove video-params/plane-depth property (was too vaguely defined)
- remove --video-sync-adrop-size option (implementation was changed, no
replacement for what this option did)
- undeprecate --video-sync=display-adrop
- deprecate legacy auto profiles (profiles starting with "extension." and
"protocol."). Use conditional auto profiles instead.
- the "subprocess" command does not connect spawned processes' stdin to
mpv's stdin anymore. Instead, stdin is connected to /dev/null by default.
To get the old behavior, set the "passthrough_stdin" argument to true.
- key/value list options do not accept ":" as item separator anymore,
only ",". This means ":" is always considered part of the value.
- remove deprecated --vo-vdpau-deint option
- add `delete-watch-later-config` command to complement
`write-watch-later-config`
--- mpv 0.32.0 ---
- change behavior when using legacy option syntax with options that start
with two dashes (``--`` instead of a ``-``). Now, using the recommended
syntax is required for options starting with ``--``, which means an option
value must be strictly passed after a ``=``, instead of as separate
argument. For example, ``--log-file f.txt`` was previously accepted and
behaved like ``--log-file=f.txt``, but now causes an error. Use of legacy
syntax that is still supported now prints a deprecation warning.
--- mpv 0.31.0 ---
- add `--resume-playback-check-mtime` to check consistent mtime when
restoring playback state.
- add `--d3d11-output-csp` to enable explicit selection of a D3D11
swap chain color space.
- the --sws- options and similar now affect vo_image and screenshot
conversion (does not matter as much for vo_gpu, which does most of this
with shaders)
- add a builtin "sw-fast" profile, which restores performance settings
for software video conversion. These were switched to higher quality since
mpv 0.30.0 (related to the previous changelog entry). This affects video
outputs like vo_x11 and vo_drm, and screenshots, but not much else.
- deprecate --input-file (there are no plans to remove this short-term,
but it will probably eventually go away <- that was a lie)
- deprecate --video-sync=display-adrop (might be removed if it's in the way;
undeprecated or readded if it's not too much of a problem)
- deprecate all input section commands (these will be changed/removed, as
soon as mpv internals do not require them anymore)
- remove deprecated --playlist-pos alias (use --playlist-start)
- deprecate --display-fps, introduce --override-display-fps. The display-fps
property now is unavailable if no VO exists (or the VO did not return a
display FPS), instead of returning the option value in this case. The
property will keep existing, but writing to it is deprecated.
- the vf/af properties now do not reject the set value anymore, even if
filter chain initialization fails. Instead, the vf/af options are always
set to the user's value, even if it does not reflect the "runtime" vf/af
chain.
- the vid/aid/sid/secondary-sid properties (and their aliases: "audio",
"video", "sub") will now allow setting any track ID; before this change,
only IDs of actually existing tracks could be set (the restriction was
active the MPV_EVENT_FILE_LOADED/"file-loaded" event was sent). Setting
an ID for which no track exists is equivalent to disabling it. Note that
setting the properties to non-existing tracks may report it as selected
track for a small time window, until it's forced back to "no". The exact
details how this is handled may change in the future.
- remove old Apple Remote support, including --input-appleremote
- add MediaPlayer support and remove the old Media Key event tap on macOS.
this possibly also re-adds the Apple Remote support
- the "edition" property now strictly returns the value of the option,
instead of the runtime value. The new "current-edition" property needs to
be queried to read the runtime-chosen edition. This is a breaking change
for any users which expected "edition" to return the runtime-chosen
edition at default settings (--edition=auto).
- the "window-scale" property now strictly returns the value of the option,
instead of the actual size of the window. The new "current-window-scale"
property needs to be queried to read the value as indicated by the current
window size. This is a breaking change.
- explicitly deprecate passing more than 1 item to "-add" suffix in key/value
options (for example --script-opts-add). This was actually always
deprecated, like with other list options, but the option parser did not
print a warning in this particular case.
- deprecate -del for list options (use -remove instead, which is by content
instead of by integer index)
- if `--fs` is used but `--fs-screen` is not set, mpv will now use `--screen`
instead.
- change the default of --hwdec to "no" on RPI. The default used to be "mmal"
specifically if 'Raspberry Pi support' was enabled at configure time
(equivalent to --enable-rpi). Use --hwdec=mmal to get the old behavior.
--- mpv 0.30.0 ---
- add `--d3d11-output-format` to enable explicit selection of a D3D11
swap chain format.
- rewrite DVB channel switching to use an integer value
`--dvbin-channel-switch-offset` for switching instead of the old
stream controls which are now gone. Cycling this property up or down will
change the offset to the channel which was initially tuned to.
Example for `input.conf`: `H cycle dvbin-channel-switch-offset up`,
`K cycle dvbin-channel-switch-offset down`.
- adapt `stream_dvb` to support writing to `dvbin-prog` at runtime
and also to consistently use dvbin-configuration over URI parameters
when provided
- add `--d3d11-adapter` to enable explicit selection of a D3D11 rendering
adapter by name.
- rename `--drm-osd-plane-id` to `--drm-draw-plane`, `--drm-video-plane-id` to
`--drm-drmprime-video-plane` and `--drm-osd-size` to `--drm-draw-surface-size`
to better reflect what the options actually control, that the values they
accept aren't actually internal DRM ID's (like with similar options in
ffmpeg's KMS support), and that the video plane is only used when the drmprime
overlay hwdec interop is active, with the video being drawn to the draw plane
otherwise.
- in addition to the above, the `--drm-draw-plane` and `--drm-drmprime-video-plane`
options now accept either an integer index, or the values primary or overlay.
`--drm-draw-plane` now defaults to primary and `--drm-drmprime-video-plane`
defaults to overlay. This should be similar to previous behavior on most drivers
due to how planes are usually sorted.
- rename --opensles-frames-per-buffer to --opensles-frames-per-enqueue to
better reflect its purpose. In the past it overrides the buffer size the AO
requests (but not the default/value of the generic --audio-buffer option).
Now it only guarantees that the soft buffer size will not be smaller than
itself while setting the size per Enqueue.
- add --opensles-buffer-size-in-ms, allowing user to tune the soft buffer size.
It overrides the --audio-buffer option unless it's set to 0 (with the default
being 250).
- remove `--linear-scaling`, replaced by `--linear-upscaling` and
`--linear-downscaling`. This means that `--sigmoid-upscaling` no longer
implies linear light downscaling as well, which was confusing.
- the built-in `gpu-hq` profile now includes` --linear-downscaling`.
- support for `--spirv-compiler=nvidia` has been removed, leaving `shaderc`
as the only option. The `--spirv-compiler` option itself has been marked
as deprecated, and may be removed in the future.
- split up `--tone-mapping-desaturate`` into strength + exponent, instead of
only using a single value (which previously just controlled the exponent).
The strength now linearly blends between the linear and nonlinear tone
mapped versions of a color.
- add --hdr-peak-decay-rate and --hdr-scene-threshold-low/high
- add --tone-mapping-max-boost
- ipc: require that "request_id" fields are integers. Other types are still
accepted for compatibility, but this will stop in the future. Also, if no
request_id is provided, 0 will be assumed.
- mpv_command_node() and mp.command_native() now support named arguments
(see manpage). If you want to use them, use a new version of the manpage
as reference, which lists the definitive names.
- edition and disc title switching will now fully reload playback (may have
consequences for scripts, client API, or when using file-local options)
- with the removal of the stream cache, the following properties and options were
dropped: `cache`, `cache-size`, `cache-free`, `cache-used`, `--cache-default`,
`--cache-initial`, `--cache-seek-min`, `--cache-backbuffer`, `--cache-file`,
`--cache-file-size`
- the --cache option does not take a number value anymore
- remove async playback abort hack. This may make it impossible to abort
playback if --demuxer-thread=no is forced.
- remove `--macos-title-bar-style`, replaced by `--macos-title-bar-material`
and `--macos-title-bar-appearance`.
- The default for `--vulkan-async-compute` has changed to `yes` from `no`
with the move to libplacebo as the back-end for vulkan rendering.
- Remove "disc-titles", "disc-title", "disc-title-list", and "angle"
properties. dvd:// does not support title ranges anymore.
- Remove all "tv-..." options and properties, along with the classic Linux
analog TV support.
- remove "program" property (no replacement)
- always prefer EGL over GLX, which helps with AMD/vaapi, but will break
vdpau with --vo=gpu - use --gpu-context=x11 to be able to use vdpau. This
does not affect --vo=vdpau or --hwdec=vdpau-copy.
- remove deprecated --chapter option
- deprecate --record-file
- add `--demuxer-cue-codepage`
- add ``track-list/N/demux-bitrate``, ``track-list/N/demux-rotation`` and
``track-list/N/demux-par`` property
- Deprecate ``--video-aspect`` and add ``--video-aspect-override`` to
replace it. (The `video-aspect` option remains unchanged.)
--- mpv 0.29.0 ---
- drop --opensles-sample-rate, as --audio-samplerate should be used if desired
- drop deprecated --videotoolbox-format, --ff-aid, --ff-vid, --ff-sid,
--ad-spdif-dtshd, --softvol options
- fix --external-files: strictly never select any tracks from them, unless
explicitly selected (this may or may not be expected)
- --ytdl is now always enabled, even for libmpv
- add a number of --audio-resample-* options, which should from now on be
used instead of --af-defaults=lavrresample:...
- deprecate --vf-defaults and --af-defaults. These didn't work with the
lavfi bridge, so they have very little use left. The only potential use
is with af_lavrresample (going to be deprecated, --audio-resample-... set
its defaults), and various hw deinterlacing filters (like vf_vavpp), for
which you will have to stop using --deinterlace=yes, and instead use the
vf toggle commands and the filter enable/disable flag to customize it.
- deprecate --af=lavrresample. Use the ``--audio-resample-...`` options to
customize resampling, or the libavfilter ``--af=aresample`` filter.
- add --osd-on-seek
- remove outfmt sub-parameter from "format" video filter (no replacement)
- some behavior changes in the video filter chain, including:
- before, using an incompatible filter with hwdec would disable hwdec;
now it disables the filter at runtime instead
- inserting an incompatible filter with hwdec at runtime would refuse
to insert the filter; now it will add it successfully, but disables
the filter slightly later
- some behavior changes in the audio filter chain, including:
- a manually inserted lavrresample filter is not necessarily used for
sample format conversion anymore, so it's pretty useless
- changing playback speed will not respect --af-defaults anymore
- having libavfilter based filters after the scaletempo or rubberband
filters is not supported anymore, and may desync if playback speed is
changed (libavfilter does not support the metadata for playback speed)
- the lavcac3enc filter does not auto detach itself anymore; instead it
passes through the data after converting it to the sample rate and
channel configuration the ac3 encoder expects; also, if the audio
format changes midstream in a way that causes the filter to switch
between PCM and AC3 output, the audio output won't be reconfigured,
and audio playback will fail due to libswresample being unable to
convert between PCM and AC3 (Note: the responsible developer didn't
give a shit. Later changes might have improved or worsened this.)
- inserting a filter that changes the output sample format will not
reconfigure the AO - you need to run an additional "ao-reload"
command to force this if you want that
- using "strong" gapless audio (--gapless-audio=yes) can fail if the
audio formats are not convertible (such as switching between PCM and
AC3 passthrough)
- if filters do not pass through PTS values correctly, A/V sync can
result over time. Some libavfilter filters are known to be affected by
this, such as af_loudnorm, which can desync over time, depending on
how the audio track was muxed (af_lavfi's fix-pts suboption can help).
- remove out-format sub-parameter from "format" audio filter (no replacement)
- --lavfi-complex now requires uniquely named filter pads. In addition,
unconnected filter pads are not allowed anymore (that means every filter
pad must be connected either to another filter, or to a video/audio track
or video/audio output). If they are disconnected at runtime, the stream
will probably stall.
- rename --vo=opengl-cb to --vo=libmpv (goes in hand with the opengl-cb
API deprecation, see client-api-changes.rst)
- deprecate the OpenGL cocoa backend, option choice --gpu-context=cocoa
when used with --gpu-api=opengl (use --vo=libmpv)
- make --deinterlace=yes always deinterlace, instead of trying to check
certain unreliable video metadata. Also flip the defaults of all builtin
HW deinterlace filters to always deinterlace.
- change vf_vavpp default to use the best deinterlace algorithm by default
- remove a compatibility hack that allowed CLI aliases to be set as property
(such as "sub-file"), deprecated in mpv 0.26.0
- deprecate the old command based hook API, and introduce a proper C API
(the high level Lua API for this does not change)
- rename the the lua-settings/ config directory to script-opts/
- the way the player waits for scripts getting loaded changes slightly. Now
scripts are loaded in parallel, and block the player from continuing
playback only in the player initialization phase. It could change again in
the future. (This kind of waiting was always a feature to prevent that
playback is started while scripts are only half-loaded.)
- deprecate --ovoffset, --oaoffset, --ovfirst, --oafirst
- remove the following encoding options: --ocopyts (now the default, old
timestamp handling is gone), --oneverdrop (now default), --oharddup (you
need to use --vf=fps=VALUE), --ofps, --oautofps, --omaxfps
- remove --video-stereo-mode. This option was broken out of laziness, and
nobody wants to fix it. Automatic 3D down-conversion to 2D is also broken,
although you can just insert the stereo3d filter manually. The obscurity
of 3D content doesn't justify such an option anyway.
- change cycle-values command to use the current value, instead of an
internal counter that remembered the current position.
- remove deprecated ao/vo auto profiles. Consider using scripts like
auto-profiles.lua instead.
- --[c]scale-[w]param[1|2] and --tone-mapping-param now accept "default",
and if set to that value, reading them as property will also return
"default", instead of float nan as in previous versions
--- mpv 0.28.0 ---
- rename --hwdec=mediacodec option to mediacodec-copy, to reflect
conventions followed by other hardware video decoding APIs
- drop previously deprecated --heartbeat-cmd and --heartbeat--interval
options
- rename --vo=opengl to --vo=gpu
- rename --opengl-backend to --gpu-context
- rename --opengl-shaders to --glsl-shaders
- rename --opengl-shader-cache-dir to --gpu-shader-cache-dir
- rename --opengl-tex-pad-x/y to --gpu-tex-pad-x/y
- rename --opengl-fbo-format to --fbo-format
- rename --opengl-gamma to --gamma-factor
- rename --opengl-debug to --gpu-debug
- rename --opengl-sw to --gpu-sw
- rename --opengl-vsync-fences to --swapchain-depth, and the interpretation
slightly changed. Now defaults to 3.
- rename the built-in profile `opengl-hq` to `gpu-hq`
- the semantics of --opengl-es=yes are slightly changed -> now requires GLES
- remove the (deprecated) alias --gpu-context=drm-egl
- remove the (deprecated) --vo=opengl-hq
- remove --opengl-es=force2 (use --opengl-es=yes --opengl-restrict=300)
- the --msg-level option now affects --log-file
- drop "audio-out-detected-device" property - this was unavailable on all
audio output drivers for quite a while (coreaudio used to provide it)
- deprecate --videotoolbox-format (use --hwdec-image-format, which affects
most other hwaccels)
- remove deprecated --demuxer-max-packets
- remove most of the deprecated audio and video filters
- remove the deprecated --balance option/property
- rename the --opengl-hwdec-interop option to --gpu-hwdec-interop, and
change some of its semantics: extend it take the strings "auto" and
"all". "all" loads all backends. "auto" behaves like "all" for
vo_opengl_cb, while on vo_gpu it loads nothing, but allows on demand
loading by the decoder. The empty string as option value behaves like
"auto". Old --hwdec values do not work anymore.
This option is hereby declared as unstable and may change any time - its
old use is deprecated, and it has very little use outside of debugging
now.
- change the --hwdec option from a choice to a plain string (affects
introspection of the option/property), also affects some properties
- rename --hwdec=rpi to --hwdec=mmal, same for the -copy variant (no
backwards compatibility)
- deprecate the --ff-aid, --ff-vid, --ff-sid options and properties (there is
no replacement, but you can manually query the track property and use the
"ff-index" field to find the mpv track ID to imitate this behavior)
- rename --no-ometadata to --no-ocopy-metadata
--- mpv 0.27.0 ---
- drop previously deprecated --field-dominance option
- drop previously deprecated "osd" command
- remove client API compatibility handling for "script", "sub-file",
"audio-file", "external-file" (these cases used to log a deprecation
warning)
- drop deprecated --video-aspect-method=hybrid option choice
- rename --hdr-tone-mapping to --tone-mapping (and generalize it)
- --opengl-fbo-format changes from a choice to a string. Also, its value
will be checked only on renderer initialization, rather than when the
option is set.
- Using opengl-cb now always assumes 8 bit per component depth, and dithers
to this size. Before, it tried to figure out the depth of the first
framebuffer that was ever passed to the renderer. Having GL framebuffers
with a size larger than 8 bit per component is quite rare. If you need
it, set the --dither-depth option instead.
- --lavfi-complex can now be set during runtime. If you set this in
expectation it would be applied only after a reload, you might observe
weird behavior.
- add --track-auto-selection to help with scripts/applications that
make exclusive use of --lavfi-complex.
- undeprecate --loop, and map it from --loop-playlist to --loop-file (the
deprecation was to make sure no API user gets broken by a sudden behavior
change)
- remove previously deprecated vf_eq
- remove that hardware deinterlace filters (vavpp, d3d11vpp, vdpaupp)
changed their deinterlacing-enabled setting depending on what the
--deinterlace option or property was set to. Now, a filter always does
what its filter options and defaults imply. The --deinterlace option and
property strictly add/remove its own filters. For example, if you run
"mpv --vf=vavpp --deinterlace=yes", this will insert another, redundant
filter, which is probably not what you want. For toggling a deinterlace
filter manually, use the "vf toggle" command, and do not set the
deinterlace option/property. To customize the filter that will be
inserted automatically, use --vf-defaults. Details how this works will
probably change in the future.
- remove deinterlace=auto (this was not deprecated, but had only a very
obscure use that stopped working with the change above. It was also
prone to be confused with a feature not implemented by it: auto did _not_
mean that deinterlacing was enabled on demand.)
- add shortened mnemonic names for mouse button bindings, eg. mbtn_left
the old numeric names (mouse_btn0) are deprecated
- remove mouse_btn3_dbl and up, since they are only generated for buttons
0-2 (these now print an error when sent from the 'mouse' command)
- rename the axis bindings to wheel_up/down/etc. axis scrolling and mouse
wheel scrolling are now conceptually the same thing
the old axis_up/down names remain as deprecated aliases
--- mpv 0.26.0 ---
- remove remaining deprecated audio device options, like --alsa-device
Some of them were removed in earlier releases.
- introduce --replaygain... options, which replace the same functionality
provided by the deprecated --af=volume:replaygain... mechanism.
- drop the internal "mp-rawvideo" codec (used by --demuxer=rawvideo)
- rename --sub-ass-style-override to --sub-ass-override, and rename the
`--sub-ass-override=signfs` setting to `--sub-ass-override=scale`.
- change default of --video-aspect-method to "bitstream". The "hybrid"
method (old default) is deprecated.
- remove property "video-params/nom-peak"
- remove option --target-brightness
- replace vf_format's `peak` suboption by `sig-peak`, which is relative to
the reference white level instead of in cd/m^2
- renamed the TRCs `st2084` and `std-b67` to `pq` and `hlg` respectively
- the "osd" command is deprecated (use "cycle osd-level")
- --field-dominance is deprecated (use --vf=setfield=bff or tff)
- --really-quiet subtle behavior change
- the deprecated handling of setting "no-" options via client API is dropped
- the following options change to append-by-default (and possibly separator):
--script
also, the following options are deprecated:
--sub-paths => --sub-file-paths
the following options are deprecated for setting via API:
"script" (use "scripts")
"sub-file" (use "sub-files")
"audio-file" (use "audio-files")
"external-file" (use "external-files")
(the compatibility hacks for this will be removed after this release)
- remove property `vo-performance`, and add `vo-passes` as a more general
replacement
- deprecate passing multiple arguments to -add/-pre options (affects the
vf/af commands too)
- remove --demuxer-lavf-cryptokey. Use --demux-lavf-o=cryptokey=<hex> or
--demux-lavf-o=decryption_key=<hex> instead (whatever fits your situation).
- rename --opengl-dumb-mode=no to --opengl-dumb-mode=auto, and make `no`
always disable it (unless forced on by hardware limitation).
- generalize --scale-clamp, --cscale-clamp etc. to accept a float between
0.0 and 1.0 instead of just being a flag. A value of 1.0 corresponds to
the old `yes`, and a value of 0.0 corresponds to the old `no`.
--- mpv 0.25.0 ---
- remove opengl-cb dxva2 dummy hwdec interop
(see git "vo_opengl: remove dxva2 dummy hwdec backend")
- remove ppm, pgm, pgmyuv, tga choices from the --screenshot-format and
--vo-image-format options
- the "jpeg" choice in the option above now leads to a ".jpg" file extension
- --af=drc is gone (you can use e.g. lavfi/acompressor instead)
- remove image_size predefined uniform from OpenGL user shaders. Use
input_size instead
- add --sub-filter-sdh
- add --sub-filter-sdh-harder
- remove --input-app-events option (macOS)
- deprecate most --vf and --af filters. Only some filters not in libavfilter
will be kept.
Also, you can use libavfilter filters directly (e.g. you can use
--vf=name=opts instead of --vf=lavfi=[name=opts]), as long as the
libavfilter filter's name doesn't clash with a mpv builtin filter.
In the long term, --vf/--af syntax might change again, but if it does, it
will switch to libavfilter's native syntax. (The above mentioned direct
support for lavfi filters still has some differences, such as how strings
are escaped.) If this happens, the non-deprecated builtin filters might be
moved to "somewhere else" syntax-wise.
- deprecate --loop - after a deprecation period, it will be undeprecated,
but changed to alias --loop-file
- add --keep-open-pause=no
- deprecate --demuxer-max-packets
- change --audio-file-auto default from "exact" to "no" (mpv won't load
files with the same filename as the video, but different extension, as
audio track anymore)
--- mpv 0.24.0 ---
- deprecate --hwdec-api and replace it with --opengl-hwdec-interop.
The new option accepts both --hwdec values, as well as named backends.
A minor difference is that --hwdec-api=no (which used to be the default)
now actually does not preload any interop layer, while the new default
("") uses the value of --hwdec.
- drop deprecated --ad/--vd features
- drop deprecated --sub-codepage syntax
- rename properties:
- "drop-frame-count" to "decoder-frame-drop-count"
- "vo-drop-frame-count" to "frame-drop-count"
The old names still work, but are deprecated.
- remove the --stream-capture option and property. No replacement.
(--record-file might serve as alternative)
- add --sub-justify
- add --sub-ass-justify
- internally there's a different way to enable the demuxer cache now
it can be auto-enabled even if the stream cache remains disabled
--- mpv 0.23.0 ---
- remove deprecated vf_vdpaurb (use "--hwdec=vdpau-copy" instead)
- the following properties now have new semantics:
- "demuxer" (use "current-demuxer")
- "fps" (use "container-fps")
- "idle" (use "idle-active")
- "cache" (use "cache-percent")
- "audio-samplerate" (use "audio-params/samplerate")
- "audio-channels" (use "audio-params/channel-count")
- "audio-format" (use "audio-codec-name")
(the properties equivalent to the old semantics are in parentheses)
- remove deprecated --vo and --ao sub-options (like --vo=opengl:...), and
replace them with global options. A somewhat complete list can be found
here: https://github.com/mpv-player/mpv/wiki/Option-replacement-list#mpv-0210
- remove --vo-defaults and --ao-defaults as well
- remove deprecated global sub-options (like -demuxer-rawaudio format=...),
use flat options (like --demuxer-rawaudio-format=...)
- the --sub-codepage option changes in incompatible ways:
- detector-selection and fallback syntax is deprecated
- enca/libguess are removed and deprecated (behaves as if they hadn't
been compiled-in)
- --sub-codepage=<codepage> does not force the codepage anymore
(this requires different and new syntax)
- remove --fs-black-out-screens option for macOS
- change how spdif codecs are selected. You can't enable spdif passthrough
with --ad anymore. This was deprecated; use --audio-spdif instead.
- deprecate the "family" selection with --ad/--vd
forcing/excluding codecs with "+", "-", "-" is deprecated as well
- explicitly mark --ad-spdif-dtshd as deprecated (it was done so a long time
ago, but it didn't complain when using the option)
--- mpv 0.22.0 ---
- the "audio-device-list" property now sets empty device description to the
device name as a fallback
- add --hidpi-window-scale option for macOS
- add audiounit audio output for iOS
- make --start-time work with --rebase-start-time=no
- add --opengl-early-flush=auto mode
- add --hwdec=vdpau-copy, deprecate vf_vdpaurb
- add tct video output for true-color and 256-color terminals
--- mpv 0.21.0 ---
- unlike in older versions, setting options at runtime will now take effect
immediately (see for example issue #3281). On the other hand, it will also
do runtime verification and reject option changes that do not work
(example: setting the "vf" option to a filter during playback, which fails
to initialize - the option value will remain at its old value). In general,
"set name value" should be mostly equivalent to "set options/name value"
in cases where the "name" property is not deprecated and "options/name"
exists - deviations from this are either bugs, or documented as caveats
in the "Inconsistencies between options and properties" manpage section.
- deprecate _all_ --vo and --ao suboptions. Generally, all suboptions are
replaced by global options, which do exactly the same. For example,
"--vo=opengl:scale=nearest" turns into "--scale=nearest". In some cases,
the global option is prefixed, e.g. "--vo=opengl:pbo" turns into
"--opengl-pbo".
Most of the exact replacements are documented here:
https://github.com/mpv-player/mpv/wiki/Option-replacement-list
- remove --vo=opengl-hq. Set --profile=opengl-hq instead. Note that this
profile does not force the VO. This means if you use the --vo option to
set another VO, it won't work. But this also means it can be used with
opengl-cb.
- remove the --vo=opengl "pre-shaders", "post-shaders" and "scale-shader"
sub-options: they were deprecated in favor of "user-shaders"
- deprecate --vo-defaults (no replacement)
- remove the vo-cmdline command. You can set OpenGL renderer options
directly via properties instead.
- deprecate the device/sink options on all AOs. Use --audio-device instead.
- deprecate "--ao=wasapi:exclusive" and "--ao=coreaudio:exclusive",
use --audio-exclusive instead.
- subtle changes in how "--no-..." options are treated mean that they are
not accessible under "options/..." anymore (instead, these are resolved
at parsing time). This does not affect options which start with "--no-",
but do not use the mechanism for negation options.
(Also see client API change for API version 1.23.)
- rename the following properties
- "demuxer" -> "current-demuxer"
- "fps" -> "container-fps"
- "idle" -> "idle-active"
- "cache" -> "cache-percent"
the old names are deprecated and will change behavior in mpv 0.23.0.
- remove deprecated "hwdec-active" and "hwdec-detected" properties
- deprecate the ao and vo auto-profiles (they never made any sense)
- deprecate "--vo=direct3d_shaders" - use "--vo=direct3d" instead.
Change "--vo=direct3d" to always use shaders by default.
- deprecate --playlist-pos option, renamed to --playlist-start
- deprecate the --chapter option, as it is redundant with --start/--end,
and conflicts with the semantics of the "chapter" property
- rename --sub-text-* to --sub-* and --ass-* to --sub-ass-* (old options
deprecated)
- incompatible change to cdda:// protocol options: the part after cdda://
now always sets the device, not the span or speed to be played. No
separating extra "/" is needed. The hidden --cdda-device options is also
deleted (it was redundant with the documented --cdrom-device).
- deprecate --vo=rpi. It will be removed in mpv 0.23.0. Its functionality
was folded into --vo=opengl, which now uses RPI hardware decoding by
treating it as a hardware overlay (without applying GL filtering). Also
to be changed in 0.23.0: the --fs flag will be reset to "no" by default
(like on the other platforms).
- deprecate --mute=auto (informally has been since 0.18.1)
- deprecate "resume" and "suspend" IPC commands. They will be completely
removed in 0.23.0.
- deprecate mp.suspend(), mp.resume(), mp.resume_all() Lua scripting
commands, as well as setting mp.use_suspend. They will be completely
removed in 0.23.0.
- the "seek" command's absolute seek mode will now interpret negative
seek times as relative from the end of the file (and clamps seeks that
still go before 0)
- add almost all options to the property list, meaning you can change
options without adding "options/" to the property name (a new section
has been added to the manpage describing some conflicting behavior
between options and properties)
- implement changing sub-speed during playback
- make many previously fixed options changeable at runtime (for example
--terminal, --osc, --ytdl, can all be enable/disabled after
mpv_initialize() - this can be extended to other still fixed options
on user requests)
--- mpv 0.20.0 ---
- add --image-display-duration option - this also means that image duration
is not influenced by --mf-fps anymore in the general case (this is an
incompatible change)
--- mpv 0.19.0 ---
- deprecate "balance" option/property (no replacement)
--- mpv 0.18.1 ---
- deprecate --heartbeat-cmd
- remove --softvol=no capability:
- deprecate --softvol, it now does nothing
- --volume, --mute, and the corresponding properties now always control
softvol, and behave as expected without surprises (e.g. you can set
them normally while no audio is initialized)
- rename --softvol-max to --volume-max (deprecated alias is added)
- the --volume-restore-data option and property are removed without
replacement. They were _always_ internal, and used for watch-later
resume/restore. Now --volume/--mute are saved directly instead.
- the previous point means resuming files with older watch-later configs
will print an error about missing --volume-restore-data (which you can
ignore), and will not restore the previous value
- as a consequence, volume controls will no longer control PulseAudio
per-application value, or use the system mixer's per-application
volume processing
- system or per-application volume can still be controlled with the
ao-volume and ao-mute properties (there are no command line options)
--- mpv 0.18.0 ---
- now ab-loops are active even if one of the "ab-loop-a"/"-b" properties is
unset ("no"), in which case the start of the file is used if the A loop
point is unset, and the end of the file for an unset B loop point
- deprecate --sub-ass=no option by --ass-style-override=strip
(also needs --embeddedfonts=no)
- add "hwdec-interop" and "hwdec-current" properties
- deprecated "hwdec-active" and "hwdec-detected" properties (to be removed
in mpv 0.20.0)
- choice option/property values that are "yes" or "no" will now be returned
as booleans when using the mpv_node functions in the client API, the
"native" property accessors in Lua, and the JSON API. They can be set as
such as well.
- the VO opengl fbo-format sub-option does not accept "rgb" or "rgba"
anymore
- all VO opengl prescalers have been removed (replaced by user scripts)
--- mpv 0.17.0 ---
- deprecate "track-list/N/audio-channels" property (use
"track-list/N/demux-channel-count" instead)
- remove write access to "stream-pos", and change semantics for read access
- Lua scripts now don't suspend mpv by default while script code is run
- add "cache-speed" property
- rename --input-unix-socket to --input-ipc-server, and make it work on
Windows too
- change the exact behavior of the "video-zoom" property
- --video-unscaled no longer disables --video-zoom and --video-aspect
To force the old behavior, set --video-zoom=0 and --video-aspect=0
--- mpv 0.16.0 ---
- change --audio-channels default to stereo (use --audio-channels=auto to
get the old default)
- add --audio-normalize-downmix
- change the default downmix behavior (--audio-normalize-downmix=yes to get
the old default)
- VO opengl custom shaders must now use "sample_pixel" as function name,
instead of "sample"
- change VO opengl scaler-resizes-only default to enabled
- add VO opengl "interpolation-threshold" suboption (introduces new default
behavior, which can change e.g. ``--video-sync=display-vdrop`` to the
worse, but is usually what you want)
- make "volume" and "mute" properties changeable even if no audio output is
active (this gives not-ideal behavior if --softvol=no is used)
- add "volume-max" and "mixer-active" properties
- ignore --input-cursor option for events injected by input commands like
"mouse", "keydown", etc.
--- mpv 0.15.0 ---
- change "yadif" video filter defaults
--- mpv 0.14.0 ---
- vo_opengl interpolation now requires --video-sync=display-... to be set
- change some vo_opengl defaults (including changing tscale)
- add "vsync-ratio", "estimated-display-fps" properties
- add --rebase-start-time option
This is a breaking change to start time handling. Instead of making start
time handling an aspect of different options and properties (like
"time-pos" vs. "playback-time"), make it dependent on the new option. For
compatibility, the "time-start" property now always returns 0, so code
which attempted to handle rebasing manually will not break.
--- mpv 0.13.0 ---
- remove VO opengl-cb frame queue suboptions (no replacement)
--- mpv 0.12.0 ---
- remove --use-text-osd (useless; fontconfig isn't a requirement anymore,
and text rendering is also lazily initialized)
- some time properties (at least "playback-time", "time-pos",
"time-remaining", "playtime-remaining") now are unavailable if the time
is unknown, instead of just assuming that the internal playback position
is 0
- add --audio-fallback-to-null option
- replace vf_format outputlevels suboption with "video-output-levels" global
property/option; also remove "colormatrix-output-range" property
- vo_opengl: remove sharpen3/sharpen5 scale filters, add sharpen sub-option
--- mpv 0.11.0 ---
- add "af-metadata" property
--- mpv 0.10.0 ---
- add --video-aspect-method option
- add --playlist-pos option
- add --video-sync* options
"display-sync-active" property
"vo-missed-frame-count" property
"audio-speed-correction" and "video-speed-correction" properties
- remove --demuxer-readahead-packets and --demuxer-readahead-bytes
add --demuxer-max-packets and --demuxer-max-bytes
(the new options are not replacement and have very different semantics)
- change "video-aspect" property: always settable, even if no video is
running; always return the override - if no override is set, return
the video's aspect ratio
- remove disc-nav (DVD, BD) related properties and commands
- add "option-info/<name>/set-locally" property
- add --cache-backbuffer; change --cache-default default to 75MB
the new total cache size is the sum of backbuffer and the cache size
specified by --cache-default or --cache
- add ``track-list/N/audio-channels`` property
- change --screenshot-tag-colorspace default value
- add --stretch-image-subs-to-screen
- add "playlist/N/title" property
- add --video-stereo-mode=no to disable auto-conversions
- add --force-seekable, and change default seekability in some cases
- add vf yadif/vavpp/vdpaupp interlaced-only suboptions
Also, the option is enabled by default (Except vf_yadif, which has
it enabled only if it's inserted by the deinterlace property.)
- add --hwdec-preload
- add ao coreaudio exclusive suboption
- add ``track-list/N/forced`` property
- add audio-params/channel-count and ``audio-params-out/channel-count props.
- add af volume replaygain-fallback suboption
- add video-params/stereo-in property
- add "keypress", "keydown", and "keyup" commands
- deprecate --ad-spdif-dtshd and enabling passthrough via --ad
add --audio-spdif as replacement
- remove "get_property" command
- remove --slave-broken
- add vo opengl custom shader suboptions (source-shader, scale-shader,
pre-shaders, post-shaders)
- completely change how the hwdec properties work:
- "hwdec" now reflects the --hwdec option
- "hwdec-detected" does partially what the old "hwdec" property did
(and also, "detected-hwdec" is removed)
- "hwdec-active" is added
- add protocol-list property
- deprecate audio-samplerate and audio-channels properties
(audio-params sub-properties are the replacement)
- add audio-params and audio-out-params properties
- deprecate "audio-format" property, replaced with "audio-codec-name"
- deprecate --media-title, replaced with --force-media-title
- deprecate "length" property, replaced with "duration"
- change volume property:
- the value 100 is now always "unchanged volume" - with softvol, the
range is 0 to --softvol-max, without it is 0-100
- the minimum value of --softvol-max is raised to 100
- remove vo opengl npot suboption
- add relative seeking by percentage to "seek" command
- add playlist_shuffle command
- add --force-window=immediate
- add ao coreaudio change-physical-format suboption
- remove vo opengl icc-cache suboption, add icc-cache-dir suboption
- add --screenshot-directory
- add --screenshot-high-bit-depth
- add --screenshot-jpeg-source-chroma
- default action for "rescan_external_files" command changes
--- mpv 0.9.0 ---
-251
View File
@@ -1,251 +0,0 @@
AUDIO FILTERS
=============
Audio filters allow you to modify the audio stream and its properties. The
syntax is:
``--af=...``
Setup a chain of audio filters. See ``--vf`` (`VIDEO FILTERS`_) for the
full syntax.
.. note::
To get a full list of available audio filters, see ``--af=help``.
Also, keep in mind that most actual filters are available via the ``lavfi``
wrapper, which gives you access to most of libavfilter's filters. This
includes all filters that have been ported from MPlayer to libavfilter.
The ``--vf`` description describes how libavfilter can be used and how to
workaround deprecated mpv filters.
See ``--vf`` group of options for info on how ``--af-defaults``, ``--af-add``,
``--af-pre``, ``--af-del``, ``--af-clr``, and possibly others work.
Available filters are:
``lavcac3enc[=options]``
Encode multi-channel audio to AC-3 at runtime using libavcodec. Supports
16-bit native-endian input format, maximum 6 channels. The output is
big-endian when outputting a raw AC-3 stream, native-endian when
outputting to S/PDIF. If the input sample rate is not 48 kHz, 44.1 kHz or
32 kHz, it will be resampled to 48 kHz.
``tospdif=<yes|no>``
Output raw AC-3 stream if ``no``, output to S/PDIF for
pass-through if ``yes`` (default).
``bitrate=<rate>``
The bitrate use for the AC-3 stream. Set it to 384 to get 384 kbps.
The default is 640. Some receivers might not be able to handle this.
Valid values: 32, 40, 48, 56, 64, 80, 96, 112, 128,
160, 192, 224, 256, 320, 384, 448, 512, 576, 640.
The special value ``auto`` selects a default bitrate based on the
input channel number:
:1ch: 96
:2ch: 192
:3ch: 224
:4ch: 384
:5ch: 448
:6ch: 448
``minch=<n>``
If the input channel number is less than ``<minch>``, the filter will
detach itself (default: 3).
``encoder=<name>``
Select the libavcodec encoder used. Currently, this should be an AC-3
encoder, and using another codec will fail horribly.
``format=format:srate:channels:out-srate:out-channels``
Does not do any format conversion itself. Rather, it may cause the
filter system to insert necessary conversion filters before or after this
filter if needed. It is primarily useful for controlling the audio format
going into other filters. To specify the format for audio output, see
``--audio-format``, ``--audio-samplerate``, and ``--audio-channels``. This
filter is able to force a particular format, whereas ``--audio-*``
may be overridden by the ao based on output compatibility.
All parameters are optional. The first 3 parameters restrict what the filter
accepts as input. They will therefore cause conversion filters to be
inserted before this one. The ``out-`` parameters tell the filters or audio
outputs following this filter how to interpret the data without actually
doing a conversion. Setting these will probably just break things unless you
really know you want this for some reason, such as testing or dealing with
broken media.
``<format>``
Force conversion to this format. Use ``--af=format=format=help`` to get
a list of valid formats.
``<srate>``
Force conversion to a specific sample rate. The rate is an integer,
48000 for example.
``<channels>``
Force mixing to a specific channel layout. See ``--audio-channels`` option
for possible values.
``<out-srate>``
``<out-channels>``
*NOTE*: this filter used to be named ``force``. The old ``format`` filter
used to do conversion itself, unlike this one which lets the filter system
handle the conversion.
``scaletempo[=option1:option2:...]``
Scales audio tempo without altering pitch, optionally synced to playback
speed (default).
This works by playing 'stride' ms of audio at normal speed then consuming
'stride*scale' ms of input audio. It pieces the strides together by
blending 'overlap'% of stride with audio following the previous stride. It
optionally performs a short statistical analysis on the next 'search' ms
of audio to determine the best overlap position.
``scale=<amount>``
Nominal amount to scale tempo. Scales this amount in addition to
speed. (default: 1.0)
``stride=<amount>``
Length in milliseconds to output each stride. Too high of a value will
cause noticeable skips at high scale amounts and an echo at low scale
amounts. Very low values will alter pitch. Increasing improves
performance. (default: 60)
``overlap=<percent>``
Percentage of stride to overlap. Decreasing improves performance.
(default: .20)
``search=<amount>``
Length in milliseconds to search for best overlap position. Decreasing
improves performance greatly. On slow systems, you will probably want
to set this very low. (default: 14)
``speed=<tempo|pitch|both|none>``
Set response to speed change.
tempo
Scale tempo in sync with speed (default).
pitch
Reverses effect of filter. Scales pitch without altering tempo.
Add this to your ``input.conf`` to step by musical semi-tones::
[ multiply speed 0.9438743126816935
] multiply speed 1.059463094352953
.. warning::
Loses sync with video.
both
Scale both tempo and pitch.
none
Ignore speed changes.
.. admonition:: Examples
``mpv --af=scaletempo --speed=1.2 media.ogg``
Would play media at 1.2x normal speed, with audio at normal
pitch. Changing playback speed would change audio tempo to match.
``mpv --af=scaletempo=scale=1.2:speed=none --speed=1.2 media.ogg``
Would play media at 1.2x normal speed, with audio at normal
pitch, but changing playback speed would have no effect on audio
tempo.
``mpv --af=scaletempo=stride=30:overlap=.50:search=10 media.ogg``
Would tweak the quality and performance parameters.
``mpv --af=scaletempo=scale=1.2:speed=pitch audio.ogg``
Would play media at 1.2x normal speed, with audio at normal pitch.
Changing playback speed would change pitch, leaving audio tempo at
1.2x.
``scaletempo2[=option1:option2:...]``
Scales audio tempo without altering pitch.
The algorithm is ported from chromium and uses the
Waveform Similarity Overlap-and-add (WSOLA) method.
It seems to achieve a higher audio quality than scaletempo and rubberband.
By default, the ``search-interval`` and ``window-size`` parameters
have the same values as in chromium.
``min-speed=<speed>``
Mute audio if the playback speed is below ``<speed>``. (default: 0.25)
``max-speed=<speed>``
Mute audio if the playback speed is above ``<speed>``
and ``<speed> != 0``. (default: 4.0)
``search-interval=<amount>``
Length in milliseconds to search for best overlap position. (default: 30)
``window-size=<amount>``
Length in milliseconds of the overlap-and-add window. (default: 20)
``rubberband``
High quality pitch correction with librubberband. This can be used in place
of ``scaletempo``, and will be used to adjust audio pitch when playing
at speed different from normal. It can also be used to adjust audio pitch
without changing playback speed.
``<pitch-scale>``
Sets the pitch scaling factor. Frequencies are multiplied by this value.
This filter has a number of additional sub-options. You can list them with
``mpv --af=rubberband=help``. This will also show the default values
for each option. The options are not documented here, because they are
merely passed to librubberband. Look at the librubberband documentation
to learn what each option does:
http://breakfastquay.com/rubberband/code-doc/classRubberBand_1_1RubberBandStretcher.html
(The mapping of the mpv rubberband filter sub-option names and values to
those of librubberband follows a simple pattern: ``"Option" + Name + Value``.)
This filter supports the following ``af-command`` commands:
``set-pitch``
Set the ``<pitch-scale>`` argument dynamically. This can be used to
change the playback pitch at runtime. Note that speed is controlled
using the standard ``speed`` property, not ``af-command``.
``multiply-pitch <factor>``
Multiply the current value of ``<pitch-scale>`` dynamically. For
example: 0.5 to go down by an octave, 1.5 to go up by a perfect fifth.
If you want to go up or down by semi-tones, use 1.059463094352953 and
0.9438743126816935
``lavfi=graph``
Filter audio using FFmpeg's libavfilter.
``<graph>``
Libavfilter graph. See ``lavfi`` video filter for details - the graph
syntax is the same.
.. warning::
Don't forget to quote libavfilter graphs as described in the lavfi
video filter section.
``o=<string>``
AVOptions.
``fix-pts=<yes|no>``
Determine PTS based on sample count (default: no). If this is enabled,
the player won't rely on libavfilter passing through PTS accurately.
Instead, it pass a sample count as PTS to libavfilter, and compute the
PTS used by mpv based on that and the input PTS. This helps with filters
which output a recomputed PTS instead of the original PTS (including
filters which require the PTS to start at 0). mpv normally expects
filters to not touch the PTS (or only to the extent of changing frame
boundaries), so this is not the default, but it will be needed to use
broken filters. In practice, these broken filters will either cause slow
A/V desync over time (with some files), or break playback completely if
you seek or start playback from the middle of a file.
``drop``
This filter drops or repeats audio frames to adapt to playback speed. It
always operates on full audio frames, because it was made to handle SPDIF
(compressed audio passthrough). This is used automatically if the
``--video-sync=display-adrop`` option is used. Do not use this filter (or
the given option); they are extremely low quality.
-220
View File
@@ -1,220 +0,0 @@
AUDIO OUTPUT DRIVERS
====================
Audio output drivers are interfaces to different audio output facilities. The
syntax is:
``--ao=<driver1,driver2,...[,]>``
Specify a priority list of audio output drivers to be used.
If the list has a trailing ',', mpv will fall back on drivers not contained
in the list.
.. note::
See ``--ao=help`` for a list of compiled-in audio output drivers. The
driver ``--ao=alsa`` is preferred. ``--ao=pulse`` is preferred on systems
where PulseAudio is used.
Available audio output drivers are:
``alsa`` (Linux only)
ALSA audio output driver
See `ALSA audio output options`_ for options specific to this AO.
.. warning::
To get multichannel/surround audio, use ``--audio-channels=auto``. The
default for this option is ``auto-safe``, which makes this audio output
explicitly reject multichannel output, as there is no way to detect
whether a certain channel layout is actually supported.
You can also try `using the upmix plugin <http://git.io/vfuAy>`_.
This setup enables multichannel audio on the ``default`` device
with automatic upmixing with shared access, so playing stereo
and multichannel audio at the same time will work as expected.
``jack``
JACK (Jack Audio Connection Kit) audio output driver.
The following global options are supported by this audio output:
``--jack-port=<name>``
Connects to the ports with the given name (default: physical ports).
``--jack-name=<client>``
Client name that is passed to JACK (default: ``mpv``). Useful
if you want to have certain connections established automatically.
``--jack-autostart=<yes|no>``
Automatically start jackd if necessary (default: disabled). Note that
this tends to be unreliable and will flood stdout with server messages.
``--jack-connect=<yes|no>``
Automatically create connections to output ports (default: enabled).
When enabled, the maximum number of output channels will be limited to
the number of available output ports.
``--jack-std-channel-layout=<waveext|any>``
Select the standard channel layout (default: waveext). JACK itself has no
notion of channel layouts (i.e. assigning which speaker a given
channel is supposed to map to) - it just takes whatever the application
outputs, and reroutes it to whatever the user defines. This means the
user and the application are in charge of dealing with the channel
layout. ``waveext`` uses WAVE_FORMAT_EXTENSIBLE order, which, even
though it was defined by Microsoft, is the standard on many systems.
The value ``any`` makes JACK accept whatever comes from the audio
filter chain, regardless of channel layout and without reordering. This
mode is probably not very useful, other than for debugging or when used
with fixed setups.
``coreaudio`` (Mac OS X only)
Native Mac OS X audio output driver using AudioUnits and the CoreAudio
sound server.
Automatically redirects to ``coreaudio_exclusive`` when playing compressed
formats.
The following global options are supported by this audio output:
``--coreaudio-change-physical-format=<yes|no>``
Change the physical format to one similar to the requested audio format
(default: no). This has the advantage that multichannel audio output
will actually work. The disadvantage is that it will change the
system-wide audio settings. This is equivalent to changing the ``Format``
setting in the ``Audio Devices`` dialog in the ``Audio MIDI Setup``
utility. Note that this does not affect the selected speaker setup.
``--coreaudio-spdif-hack=<yes|no>``
Try to pass through AC3/DTS data as PCM. This is useful for drivers
which do not report AC3 support. It converts the AC3 data to float,
and assumes the driver will do the inverse conversion, which means
a typical A/V receiver will pick it up as compressed IEC framed AC3
stream, ignoring that it's marked as PCM. This disables normal AC3
passthrough (even if the device reports it as supported). Use with
extreme care.
``coreaudio_exclusive`` (Mac OS X only)
Native Mac OS X audio output driver using direct device access and
exclusive mode (bypasses the sound server).
``openal``
OpenAL audio output driver. This is broken and does not work.
``--openal-num-buffers=<2-128>``
Specify the number of audio buffers to use. Lower values are better for
lower CPU usage. Default: 4.
``--openal-num-samples=<256-32768>``
Specify the number of complete samples to use for each buffer. Higher
values are better for lower CPU usage. Default: 8192.
``--openal-direct-channels=<yes|no>``
Enable OpenAL Soft's direct channel extension when available to avoid
tinting the sound with ambisonics or HRTF.
Channels are dropped when when they are not available as downmixing
will be disabled. Default: no.
``pulse``
PulseAudio audio output driver
The following global options are supported by this audio output:
``--pulse-host=<host>``
Specify the host to use. An empty <host> string uses a local connection,
"localhost" uses network transfer (most likely not what you want).
``--pulse-buffer=<1-2000|native>``
Set the audio buffer size in milliseconds. A higher value buffers
more data, and has a lower probability of buffer underruns. A smaller
value makes the audio stream react faster, e.g. to playback speed
changes.
``--pulse-latency-hacks=<yes|no>``
Enable hacks to workaround PulseAudio timing bugs (default: no). If
enabled, mpv will do elaborate latency calculations on its own. If
disabled, it will use PulseAudio automatically updated timing
information. Disabling this might help with e.g. networked audio or
some plugins, while enabling it might help in some unknown situations
(it used to be required to get good behavior on old PulseAudio versions).
If you have stuttering video when using pulse, try to enable this
option. (Or try to update PulseAudio.)
``--pulse-allow-suspended=<yes|no>``
Allow mpv to use PulseAudio even if the sink is suspended (default: no).
Can be useful if PulseAudio is running as a bridge to jack and mpv has its sink-input set to the one jack is using.
``sdl``
SDL 1.2+ audio output driver. Should work on any platform supported by SDL
1.2, but may require the ``SDL_AUDIODRIVER`` environment variable to be set
appropriately for your system.
.. note:: This driver is for compatibility with extremely foreign
environments, such as systems where none of the other drivers
are available.
The following global options are supported by this audio output:
``--sdl-buflen=<length>``
Sets the audio buffer length in seconds. Is used only as a hint by the
sound system. Playing a file with ``-v`` will show the requested and
obtained exact buffer size. A value of 0 selects the sound system
default.
``null``
Produces no audio output but maintains video playback speed. You can use
``--ao=null --ao-null-untimed`` for benchmarking.
The following global options are supported by this audio output:
``--ao-null-untimed``
Do not simulate timing of a perfect audio device. This means audio
decoding will go as fast as possible, instead of timing it to the
system clock.
``--ao-null-buffer``
Simulated buffer length in seconds.
``--ao-null-outburst``
Simulated chunk size in samples.
``--ao-null-speed``
Simulated audio playback speed as a multiplier. Usually, a real audio
device will not go exactly as fast as the system clock. It will deviate
just a little, and this option helps to simulate this.
``--ao-null-latency``
Simulated device latency. This is additional to EOF.
``--ao-null-broken-eof``
Simulate broken audio drivers, which always add the fixed device
latency to the reported audio playback position.
``--ao-null-broken-delay``
Simulate broken audio drivers, which don't report latency correctly.
``--ao-null-channel-layouts``
If not empty, this is a ``,`` separated list of channel layouts the
AO allows. This can be used to test channel layout selection.
``--ao-null-format``
Force the audio output format the AO will accept. If unset accepts any.
``pcm``
Raw PCM/WAVE file writer audio output
The following global options are supported by this audio output:
``--ao-pcm-waveheader=<yes|no>``
Include or do not include the WAVE header (default: included). When
not included, raw PCM will be generated.
``--ao-pcm-file=<filename>``
Write the sound to ``<filename>`` instead of the default
``audiodump.wav``. If ``no-waveheader`` is specified, the default is
``audiodump.pcm``.
``--ao-pcm-append=<yes|no>``
Append to the file, instead of overwriting it. Always use this with the
``no-waveheader`` option - with ``waveheader`` it's broken, because
it will write a WAVE header every time the file is opened.
``wasapi``
Audio output to the Windows Audio Session API.
-20
View File
@@ -1,20 +0,0 @@
CHANGELOG
=========
There is no real changelog, but you can look at the following things:
* The release changelog, which should contain most user-visible changes,
including new features and bug fixes:
https://github.com/mpv-player/mpv/releases
* The git log, which is the "real" changelog
* The file https://github.com/mpv-player/mpv/blob/master/DOCS/interface-changes.rst
documents changes to the command and user interface, such as options and
properties. (It usually documents breaking changes only, additions and
enhancements are often not listed.)
* C API changes are listed in
https://github.com/mpv-player/mpv/blob/master/DOCS/client-api-changes.rst
* The file ``mplayer-changes.rst`` in the ``DOCS`` sub directory on the git
repository, which used to be in place of this section. It documents some
changes that happened since mplayer2 forked off MPlayer. (Not updated
anymore.)
-113
View File
@@ -1,113 +0,0 @@
CONSOLE
=======
The console is a REPL for mpv input commands. It is displayed on the video
window. It also shows log messages. It can be disabled entirely using the
``--load-osd-console=no`` option.
Keybindings
-----------
\`
Show the console.
ESC
Hide the console.
ENTER
Run the typed command.
Shift+ENTER
Type a literal newline character.
Ctrl+LEFT and Ctrl+RIGHT
Move cursor to previous/next word.
UP and DOWN
Navigate command history.
PGUP
Go to the first command in the history.
PGDN
Stop navigating command history.
INSERT
Toggle insert mode.
Shift+INSERT
Paste text (uses the primary selection on X11).
TAB
Complete the command or property name at the cursor.
Ctrl+C
Clear current line.
Ctrl+K
Delete text from the cursor to the end of the line.
Ctrl+L
Clear all log messages from the console.
Ctrl+U
Delete text from the cursor to the beginning of the line.
Ctrl+V
Paste text (uses the clipboard on X11).
Ctrl+W
Delete text from the cursor to the beginning of the current word.
Commands
--------
``script-message-to console type <text> [<cursor_pos>]``
Show the console and pre-fill it with the provided text, optionally
specifying the initial cursor position as a positive integer starting from
1.
.. admonition:: Example for input.conf
``% script-message-to console type "seek absolute-percent" 6``
Known issues
------------
- Pasting text is slow on Windows
- Non-ASCII keyboard input has restrictions
- The cursor keys move between Unicode code-points, not grapheme clusters
Configuration
-------------
This script can be customized through a config file ``script-opts/console.conf``
placed in mpv's user directory and through the ``--script-opts`` command-line
option. The configuration syntax is described in `ON SCREEN CONTROLLER`_.
Key bindings can be changed in a standard way, see for example stats.lua
documentation.
Configurable Options
~~~~~~~~~~~~~~~~~~~~
``scale``
Default: 1
All drawing is scaled by this value, including the text borders and the
cursor.
If the VO backend in use has HiDPI scale reporting implemented, the option
value is scaled with the reported HiDPI scale.
``font``
Default: unset (picks a hardcoded font depending on detected platform)
Set the font used for the REPL and the console. This probably doesn't
have to be a monospaced font.
``font_size``
Default: 16
Set the font size used for the REPL and the console. This will be
multiplied by "scale."
+20
View File
@@ -0,0 +1,20 @@
[latex2e writer]
use-latex-docinfo: yes
use-latex-toc: yes
hyperlink-color: Blue!30!RoyalPurple!70!Black
latex-preamble: \usepackage[usenames,dvipsnames]{xcolor}
\usepackage{fullpage}
\usepackage{graphicx}
\renewcommand{\familydefault}{\sfdefault}
\makeatletter
\renewcommand{\maketitle}{
\begin{center}
\includegraphics{etc/mpv-icon-8bit-64x64.png}\\
\vspace*{-1.5em}
\begin{Huge}
\@title
\end{Huge}
\end{center}
}
\makeatother
+573
View File
@@ -0,0 +1,573 @@
AUDIO FILTERS
=============
Audio filters allow you to modify the audio stream and its properties. The
syntax is:
``--af=<filter1[=parameter1:parameter2:...],filter2,...>``
Setup a chain of audio filters.
.. note::
To get a full list of available audio filters, see ``--af=help``.
Audio filters are managed in lists. There are a few commands to manage the
filter list:
``--af-add=<filter1[,filter2,...]>``
Appends the filters given as arguments to the filter list.
``--af-pre=<filter1[,filter2,...]>``
Prepends the filters given as arguments to the filter list.
``--af-del=<index1[,index2,...]>``
Deletes the filters at the given indexes. Index numbers start at 0,
negative numbers address the end of the list (-1 is the last).
``--af-clr``
Completely empties the filter list.
Available filters are:
``lavrresample[=option1:option2:...]``
This filter uses libavresample (or libswresample, depending on the build)
to change sample rate, sample format, or channel layout of the audio stream.
This filter is automatically enabled if the audio output does not support
the audio configuration of the file being played.
It supports only the following sample formats: u8, s16ne, s32ne, floatne.
``filter-size=<length>``
Length of the filter with respect to the lower sampling rate. (default:
16)
``phase-shift=<count>``
Log2 of the number of polyphase entries. (..., 10->1024, 11->2048,
12->4096, ...) (default: 10->1024)
``cutoff=<cutoff>``
Cutoff frequency (0.0-1.0), default set depending upon filter length.
``linear``
If set then filters will be linearly interpolated between polyphase
entries. (default: no)
``no-detach``
Do not detach if input and output audio format/rate/channels match.
You should add this option if you specify additional parameters, as
automatically inserted lavrresample instances will use the default
settings.
``o=<string>``
Set AVOptions on the SwrContext or AVAudioResampleContext. These should
be documented by FFmpeg or Libav.
``lavcac3enc[=tospdif[:bitrate[:minchn]]]``
Encode multi-channel audio to AC-3 at runtime using libavcodec. Supports
16-bit native-endian input format, maximum 6 channels. The output is
big-endian when outputting a raw AC-3 stream, native-endian when
outputting to S/PDIF. If the input sample rate is not 48 kHz, 44.1 kHz or
32 kHz, it will be resampled to 48 kHz.
``<tospdif>``
Output raw AC-3 stream if zero or not set, output to S/PDIF for
passthrough when ``<tospdif>`` is set non-zero.
``<bitrate>``
The bitrate use for the AC-3 stream. Set it to either 384 or 384000
to get 384 kbps.
Valid values: 32, 40, 48, 56, 64, 80, 96, 112, 128,
160, 192, 224, 256, 320, 384, 448, 512, 576, 640.
Default bitrate is based on the input channel number:
:1ch: 96
:2ch: 192
:3ch: 224
:4ch: 384
:5ch: 448
:6ch: 448
``<minchn>``
If the input channel number is less than ``<minchn>``, the filter will
detach itself (default: 5).
``sweep[=speed]``
Produces a sine sweep.
``<0.0-1.0>``
Sine function delta, use very low values to hear the sweep.
``sinesuppress[=freq:decay]``
Remove a sine at the specified frequency. Useful to get rid of the 50/60Hz
noise on low quality audio equipment. It only works on mono input.
``<freq>``
The frequency of the sine which should be removed (in Hz) (default:
50)
``<decay>``
Controls the adaptivity (a larger value will make the filter adapt to
amplitude and phase changes quicker, a smaller value will make the
adaptation slower) (default: 0.0001). Reasonable values are around
0.001.
``bs2b[=option1:option2:...]``
Bauer stereophonic to binaural transformation using libbs2b. Improves the
headphone listening experience by making the sound similar to that from
loudspeakers, allowing each ear to hear both channels and taking into
account the distance difference and the head shadowing effect. It is
applicable only to 2-channel audio.
``fcut=<300-1000>``
Set cut frequency in Hz.
``feed=<10-150>``
Set feed level for low frequencies in 0.1*dB.
``profile=<value>``
Several profiles are available for convenience:
:default: will be used if nothing else was specified (fcut=700,
feed=45)
:cmoy: Chu Moy circuit implementation (fcut=700, feed=60)
:jmeier: Jan Meier circuit implementation (fcut=650, feed=95)
If ``fcut`` or ``feed`` options are specified together with a profile, they
will be applied on top of the selected profile.
``hrtf[=flag]``
Head-related transfer function: Converts multichannel audio to 2-channel
output for headphones, preserving the spatiality of the sound.
==== ===================================
Flag Meaning
==== ===================================
m matrix decoding of the rear channel
s 2-channel matrix decoding
0 no matrix decoding (default)
==== ===================================
``equalizer=[g1:g2:g3:...:g10]``
10 octave band graphic equalizer, implemented using 10 IIR band-pass
filters. This means that it works regardless of what type of audio is
being played back. The center frequencies for the 10 bands are:
=== ==========
No. frequency
=== ==========
0 31.25 Hz
1 62.50 Hz
2 125.00 Hz
3 250.00 Hz
4 500.00 Hz
5 1.00 kHz
6 2.00 kHz
7 4.00 kHz
8 8.00 kHz
9 16.00 kHz
=== ==========
If the sample rate of the sound being played is lower than the center
frequency for a frequency band, then that band will be disabled. A known
bug with this filter is that the characteristics for the uppermost band
are not completely symmetric if the sample rate is close to the center
frequency of that band. This problem can be worked around by upsampling
the sound using a resampling filter before it reaches this filter.
``<g1>:<g2>:<g3>:...:<g10>``
floating point numbers representing the gain in dB for each frequency
band (-12-12)
.. admonition:: Example
``mpv --af=equalizer=11:11:10:5:0:-12:0:5:12:12 media.avi``
Would amplify the sound in the upper and lower frequency region
while canceling it almost completely around 1kHz.
``channels=nch[:nr:from1:to1:from2:to2:from3:to3:...]``
Can be used for adding, removing, routing and copying audio channels. If
only ``<nch>`` is given, the default routing is used. It works as follows:
If the number of output channels is greater than the number of input
channels, empty channels are inserted (except when mixing from mono to
stereo; then the mono channel is duplicated). If the number of output
channels is less than the number of input channels, the exceeding
channels are truncated.
``<nch>``
number of output channels (1-8)
``<nr>``
number of routes (1-8)
``<from1:to1:from2:to2:from3:to3:...>``
Pairs of numbers between 0 and 7 that define where to route each
channel.
.. admonition:: Examples
``mpv --af=channels=4:4:0:1:1:0:2:2:3:3 media.avi``
Would change the number of channels to 4 and set up 4 routes that
swap channel 0 and channel 1 and leave channel 2 and 3 intact.
Observe that if media containing two channels were played back,
channels 2 and 3 would contain silence but 0 and 1 would still be
swapped.
``mpv --af=channels=6:4:0:0:0:1:0:2:0:3 media.avi``
Would change the number of channels to 6 and set up 4 routes that
copy channel 0 to channels 0 to 3. Channel 4 and 5 will contain
silence.
``force=in-format:in-srate:in-channels:out-format:out-srate:out-channels``
Force a specific audio format/configuration without actually changing the
audio data. Keep in mind that the filter system might auto-insert actual
conversion filters before or after this filter if needed.
All parameters are optional. The ``in-`` variants restrict what the filter
accepts as input. The ``out-`` variants change the audio format, without
actually doing a conversion. The data will be 'reinterpreted' by the
filters or audio outputs following this filter.
``<in-format>``
Force conversion to this format. See ``format`` filter for valid audio
format values.
``<in-srate>``
Force conversion to a specific sample rate. The rate is an integer,
48000 for example.
``<in-channels>``
Force mixing to a specific channel layout. See ``--channels`` option
for possible values.
``<out-format>``
``<out-srate>``
``<out-channels>``
``format[=format]``
Convert between different sample formats. Automatically enabled when
needed by the audio output or another filter. See also ``--format``.
``<format>``
Sets the desired format. The general form is 'sbe', where 's' denotes
the sign (either 's' for signed or 'u' for unsigned), 'b' denotes the
number of bits per sample (16, 24 or 32) and 'e' denotes the
endianness ('le' means little-endian, 'be' big-endian and 'ne' the
endianness of the computer mpv is running on). Valid values (amongst
others) are: 's16le', 'u32be' and 'u24ne'. Exceptions to this rule that
are also valid format specifiers: u8, s8, floatle, floatbe, floatne,
mpeg2, and ac3.
``volume[=v[:sc[:fast]]]``
Implements software volume control. Use this filter with caution since it
can reduce the signal to noise ratio of the sound. In most cases it is
best to use the *Master* volume control of your sound card or the volume
knob on your amplifier.
This filter has a second feature: It measures the overall maximum sound
level and prints out that level when mpv exits. This feature currently
only works with floating-point data.
*NOTE*: This filter is not reentrant and can therefore only be enabled
once for every audio stream.
``<v>``
Sets the desired gain in dB for all channels in the stream from -200dB
to +60dB, where -200dB mutes the sound completely and +60dB equals a
gain of 1000 (default: 0).
``<sc>``
Turns soft clipping on (1) or off (0). Soft-clipping can make the
sound more smooth if very high volume levels are used. Enable this
option if the dynamic range of the loudspeakers is very low.
*WARNING*: This feature creates distortion and should be considered a
last resort.
``<fast>``
Force S16 sample format if set to 1. Lower quality, but might be faster
in some situations.
.. admonition:: Example
``mpv --af=volume=10.1:0 media.avi``
Would amplify the sound by 10.1dB and hard-clip if the sound level
is too high.
``pan=n[:L00:L01:L02:...L10:L11:L12:...Ln0:Ln1:Ln2:...]``
Mixes channels arbitrarily. Basically a combination of the volume and the
channels filter that can be used to down-mix many channels to only a few,
e.g. stereo to mono, or vary the "width" of the center speaker in a
surround sound system. This filter is hard to use, and will require some
tinkering before the desired result is obtained. The number of options for
this filter depends on the number of output channels. An example how to
downmix a six-channel file to two channels with this filter can be found
in the examples section near the end.
``<n>``
Number of output channels (1-8).
``<Lij>``
How much of input channel i is mixed into output channel j (0-1). So
in principle you first have n numbers saying what to do with the first
input channel, then n numbers that act on the second input channel
etc. If you do not specify any numbers for some input channels, 0 is
assumed.
.. admonition:: Examples
``mpv --af=pan=1:0.5:0.5 media.avi``
Would downmix from stereo to mono.
``mpv --af=pan=3:1:0:0.5:0:1:0.5 media.avi``
Would give 3 channel output leaving channels 0 and 1 intact, and mix
channels 0 and 1 into output channel 2 (which could be sent to a
subwoofer for example).
.. note::
If you just want to force remixing to a certain output channel layout,
it is easier to use the ``force`` filter. For example,
``mpv '--af=force=channels=5.1' '--channels=5.1'`` would always force
remixing audio to 5.1 and output it like this.
``sub[=fc:ch]``
Adds a subwoofer channel to the audio stream. The audio data used for
creating the subwoofer channel is an average of the sound in channel 0 and
channel 1. The resulting sound is then low-pass filtered by a 4th order
Butterworth filter with a default cutoff frequency of 60Hz and added to a
separate channel in the audio stream.
.. warning::
Disable this filter when you are playing media with an LFE channel
(e.g. 5.1 surround sound), otherwise this filter will disrupt the sound
to the subwoofer.
``<fc>``
cutoff frequency in Hz for the low-pass filter (20Hz to 300Hz)
(default: 60Hz) For the best result try setting the cutoff frequency
as low as possible. This will improve the stereo or surround sound
experience.
``<ch>``
Determines the channel number in which to insert the sub-channel
audio. Channel number can be between 0 and 7 (default: 5). Observe
that the number of channels will automatically be increased to <ch> if
necessary.
.. admonition:: Example
``mpv --af=sub=100:4 --channels=5 media.avi``
Would add a subwoofer channel with a cutoff frequency of 100Hz to
output channel 4.
``center``
Creates a center channel from the front channels. May currently be low
quality as it does not implement a high-pass filter for proper extraction
yet, but averages and halves the channels instead.
``<ch>``
Determines the channel number in which to insert the center channel.
Channel number can be between 0 and 7 (default: 5). Observe that the
number of channels will automatically be increased to ``<ch>`` if
necessary.
``surround[=delay]``
Decoder for matrix encoded surround sound like Dolby Surround. Some files
with 2-channel audio actually contain matrix encoded surround sound.
``<delay>``
delay time in ms for the rear speakers (0 to 1000) (default: 20) This
delay should be set as follows: If d1 is the distance from the
listening position to the front speakers and d2 is the distance from
the listening position to the rear speakers, then the delay should be
set to 15ms if d1 <= d2 and to 15 + 5*(d1-d2) if d1 > d2.
.. admonition:: Example
``mpv --af=surround=15 --channels=4 media.avi``
Would add surround sound decoding with 15ms delay for the sound to
the rear speakers.
``delay[=ch1:ch2:...]``
Delays the sound to the loudspeakers such that the sound from the
different channels arrives at the listening position simultaneously. It is
only useful if you have more than 2 loudspeakers.
``ch1,ch2,...``
The delay in ms that should be imposed on each channel (floating point
number between 0 and 1000).
To calculate the required delay for the different channels, do as follows:
1. Measure the distance to the loudspeakers in meters in relation to your
listening position, giving you the distances s1 to s5 (for a 5.1
system). There is no point in compensating for the subwoofer (you will
not hear the difference anyway).
2. Subtract the distances s1 to s5 from the maximum distance, i.e.
``s[i] = max(s) - s[i]; i = 1...5``.
3. Calculate the required delays in ms as ``d[i] = 1000*s[i]/342; i =
1...5``.
.. admonition:: Example
``mpv --af=delay=10.5:10.5:0:0:7:0 media.avi``
Would delay front left and right by 10.5ms, the two rear channels
and the subwoofer by 0ms and the center channel by 7ms.
``export[=mmapped_file[:nsamples]]``
Exports the incoming signal to other processes using memory mapping
(``mmap()``). Memory mapped areas contain a header::
int nch /* number of channels */
int size /* buffer size */
unsigned long long counter /* Used to keep sync, updated every time
new data is exported. */
The rest is payload (non-interleaved) 16-bit data.
``<mmapped_file>``
File to map data to (default: ``~/.mpv/mpv-af_export``).
``<nsamples>``
number of samples per channel (default: 512).
.. admonition:: Example
``mpv --af=export=/tmp/mpv-af_export:1024 media.avi``
Would export 1024 samples per channel to ``/tmp/mpv-af_export``.
``extrastereo[=mul]``
(Linearly) increases the difference between left and right channels which
adds some sort of "live" effect to playback.
``<mul>``
Sets the difference coefficient (default: 2.5). 0.0 means mono sound
(average of both channels), with 1.0 sound will be unchanged, with
-1.0 left and right channels will be swapped.
``drc[=method:target]``
Applies dynamic range compression. This maximizes the volume by compressing
the audio signal's dynamic range. (Formerly called ``volnorm``.)
``<method>``
Sets the used method.
1
Use a single sample to smooth the variations via the standard
weighted mean over past samples (default).
2
Use several samples to smooth the variations via the standard
weighted mean over past samples.
``<target>``
Sets the target amplitude as a fraction of the maximum for the sample
type (default: 0.25).
.. note::
This filter can cause distortion with audio signals that have a very
large dynamic range.
``ladspa=file:label[:controls...]``
Load a LADSPA (Linux Audio Developer's Simple Plugin API) plugin. This
filter is reentrant, so multiple LADSPA plugins can be used at once.
``<file>``
Specifies the LADSPA plugin library file.
.. note::
See also the note about the ``LADSPA_PATH`` variable in the
`ENVIRONMENT VARIABLES`_ section.
``<label>``
Specifies the filter within the library. Some libraries contain only
one filter, but others contain many of them. Entering 'help' here
will list all available filters within the specified library, which
eliminates the use of 'listplugins' from the LADSPA SDK.
``<controls>``
Controls are zero or more floating point values that determine the
behavior of the loaded plugin (for example delay, threshold or gain).
In verbose mode (add ``-v`` to the mpv command line), all
available controls and their valid ranges are printed. This eliminates
the use of 'analyseplugin' from the LADSPA SDK.
``karaoke``
Simple voice removal filter exploiting the fact that voice is usually
recorded with mono gear and later 'center' mixed onto the final audio
stream. Beware that this filter will turn your signal into mono. Works
well for 2 channel tracks; do not bother trying it on anything but 2
channel stereo.
``scaletempo[=option1:option2:...]``
Scales audio tempo without altering pitch, optionally synced to playback
speed (default).
This works by playing 'stride' ms of audio at normal speed then consuming
'stride*scale' ms of input audio. It pieces the strides together by
blending 'overlap'% of stride with audio following the previous stride. It
optionally performs a short statistical analysis on the next 'search' ms
of audio to determine the best overlap position.
``scale=<amount>``
Nominal amount to scale tempo. Scales this amount in addition to
speed. (default: 1.0)
``stride=<amount>``
Length in milliseconds to output each stride. Too high of a value will
cause noticeable skips at high scale amounts and an echo at low scale
amounts. Very low values will alter pitch. Increasing improves
performance. (default: 60)
``overlap=<percent>``
Percentage of stride to overlap. Decreasing improves performance.
(default: .20)
``search=<amount>``
Length in milliseconds to search for best overlap position. Decreasing
improves performance greatly. On slow systems, you will probably want
to set this very low. (default: 14)
``speed=<tempo|pitch|both|none>``
Set response to speed change.
tempo
Scale tempo in sync with speed (default).
pitch
Reverses effect of filter. Scales pitch without altering tempo.
Add ``[ speed_mult 0.9438743126816935`` and ``] speed_mult
1.059463094352953`` to your ``input.conf`` to step by musical
semi-tones.
.. warning::
Loses sync with video.
both
Scale both tempo and pitch.
none
Ignore speed changes.
.. admonition:: Examples
``mpv --af=scaletempo --speed=1.2 media.ogg``
Would play media at 1.2x normal speed, with audio at normal
pitch. Changing playback speed would change audio tempo to match.
``mpv --af=scaletempo=scale=1.2:speed=none --speed=1.2 media.ogg``
Would play media at 1.2x normal speed, with audio at normal
pitch, but changing playback speed would have no effect on audio
tempo.
``mpv --af=scaletempo=stride=30:overlap=.50:search=10 media.ogg``
Would tweak the quality and performace parameters.
``mpv --af=format=floatne,scaletempo media.ogg``
Would make scaletempo use float code. Maybe faster on some
platforms.
``mpv --af=scaletempo=scale=1.2:speed=pitch audio.ogg``
Would play media at 1.2x normal speed, with audio at normal pitch.
Changing playback speed would change pitch, leaving audio tempo at
1.2x.
``lavfi=graph``
Filter audio using ffmpeg's libavfilter.
``<graph>``
Libavfilter graph. See ``lavfi`` video filter for details - the graph
syntax is the same.
.. warning::
Don't forget to quote libavfilter graphs as described in the lavfi
video filter section.
``o=<string>``
AVOptions.
+204
View File
@@ -0,0 +1,204 @@
AUDIO OUTPUT DRIVERS
====================
Audio output drivers are interfaces to different audio output facilities. The
syntax is:
``--ao=<driver1[:suboption1[=value]:...],driver2,...[,]>``
Specify a priority list of audio output drivers to be used.
If the list has a trailing ',', mpv will fall back on drivers not contained
in the list. Suboptions are optional and can mostly be omitted.
.. note::
See ``--ao=help`` for a list of compiled-in audio output drivers.
.. admonition:: Examples
- ``--ao=alsa,oss,`` Try the ALSA driver, then the OSS driver, then others.
- ``--ao=alsa:no-block:device=[hw:0,3]`` Sets noblock-mode and the
device-name as first card, fourth device.
Available audio output drivers are:
``alsa`` (Linux only)
ALSA 0.9/1.x audio output driver
``no-block``
Sets noblock-mode.
``device=<device>``
Sets the device name. For ac3 output via S/PDIF, use an "iec958" or
"spdif" device, unless you really know how to set it correctly.
``mixer-device=<device>``
Set the mixer device used with ``--no-softvol`` (default: ``default``).
``mixer-name=<name>``
Set the name of the mixer element (default: ``Master``). This is for
example ``PCM`` or ``Master``.
``mixer-index=<number>``
Set the index of the mixer channel (default: 0). Consider the output of
"``amixer scontrols``", then the index is the number that follows the
name of the element.
.. note::
MPlayer and mplayer2 required you to replace any ',' with '.' and
any ':' with '=' in the ALSA device name. mpv does not do this anymore.
Instead, quote the device name:
``--ao=alsa:device=[plug:surround50]``
Note that the ``[`` and ``]`` simply quote the device name. With some
shells (like zsh), you have to quote the option string to prevent the
shell from interpreting the brackets instead of passing them to mpv.
``oss``
OSS audio output driver
``<dsp-device>``
Sets the audio output device (default: ``/dev/dsp``).
``<mixer-device>``
Sets the audio mixer device (default: ``/dev/mixer``).
``<mixer-channel>``
Sets the audio mixer channel (default: ``pcm``). Other valid values
include **vol, pcm, line**. For a complete list of options look for
``SOUND_DEVICE_NAMES`` in ``/usr/include/linux/soundcard.h``.
``jack``
JACK (Jack Audio Connection Kit) audio output driver
``port=<name>``
Connects to the ports with the given name (default: physical ports).
``name=<client>``
Client name that is passed to JACK (default: ``mpv``). Useful
if you want to have certain connections established automatically.
``(no-)estimate``
Estimate the audio delay, supposed to make the video playback smoother
(default: enabled).
``(no-)autostart``
Automatically start jackd if necessary (default: disabled). Note that
this tends to be unreliable and will flood stdout with server messages.
``(no-)connect``
Automatically create connections to output ports (default: enabled).
When enabled, the maximum number of output channels will be limited to
the number of available output ports.
``std-channel-layout=alsa|waveext|any``
Select the standard channel layout (default: alsa). JACK itself has no
notion of channel layouts (i.e. assigning which speaker a given
channel is supposed to map to) - it just takes whatever the application
outputs, and reroutes it to whatever the user defines. This means the
user and the application are in charge of dealing with the channel
layout. ``alsa`` uses the old MPlayer layout, which is inspired by
ALSA's standard layouts. In this mode, ao_jack will refuse to play 3
or 7 channels (because these do not really have a defined meaning in
MPlayer). ``waveext`` uses WAVE_FORMAT_EXTENSIBLE order, which, even
though it was defined by Microsoft, is the standard on many systems.
The value ``any`` makes JACK accept whatever comes from the audio
filter chain, regardless of channel layout and without reordering. This
mode is probably not very useful, other than for debugging or when used
with fixed setups.
``coreaudio`` (Mac OS X only)
Native Mac OS X audio output driver
``device_id=<id>``
ID of output device to use (0 = default device)
``help``
List all available output devices with their IDs.
``openal``
Experimental OpenAL audio output driver
``pulse``
PulseAudio audio output driver
``[<host>][:<output sink>]``
Specify the host and optionally output sink to use. An empty <host>
string uses a local connection, "localhost" uses network transfer
(most likely not what you want).
``portaudio``
PortAudio audio output driver. This works on all platforms, and has
extensive MS Windows support.
``device``
Specify the subdevice to use. Giving ``help`` as device name lists all
devices found by PortAudio. Devices can be given as numeric values,
starting from ``1``.
``dsound`` (Windows only)
DirectX DirectSound audio output driver
``device=<devicenum>``
Sets the device number to use. Playing a file with ``-v`` will show a
list of available devices.
``sdl``
SDL 1.2+ audio output driver. Should work on any platform supported by SDL
1.2, but may require the ``SDL_AUDIODRIVER`` environment variable to be set
appropriately for your system.
``buflen=<length>``
Sets the audio buffer length in seconds. Is used only as a hint by the
sound system. Playing a file with ``-v`` will show the requested and
obtained exact buffer size. A value of 0 selects the sound system
default.
``bufcnt=<count>``
Sets the number of extra audio buffers in mpv. Usually needs not be
changed.
``null``
Produces no audio output but maintains video playback speed. Use
``--no-audio`` for benchmarking.
``pcm``
Raw PCM/WAVE file writer audio output
``(no-)waveheader``
Include or do not include the WAVE header (default: included). When
not included, raw PCM will be generated.
``file=<filename>``
Write the sound to ``<filename>`` instead of the default
``audiodump.wav``. If ``no-waveheader`` is specified, the default is
``audiodump.pcm``.
``rsound``
Audio output to an RSound daemon
``host=<name/path>``
Set the address of the server (default: localhost). Can be either a
network hostname for TCP connections or a Unix domain socket path
starting with '/'.
``port=<number>``
Set the TCP port used for connecting to the server (default: 12345).
Not used if connecting to a Unix domain socket.
``sndio``
Audio output to the OpenBSD sndio sound system
(Note: only supports mono, stereo, 4.0, 5.1 and 7.1 channel
layouts.)
``device=<device>``
sndio device to use (default: ``$AUDIODEVICE``, resp. ``snd0``).
``wasapi``
Audio output to the Windows Audio Session API.
``device=<id>``
Uses the requested endpoint instead of the system's default audio
endpoint. Both the number and the ID String are valid; the ID String
is guaranteed to not change unless the driver is uninstalled.
Also supports searching active devices by name. If more than one
device matches the name, refuses loading it.
To get a list of the valid devices, give ``help`` as the id. The
list is the same as the ``list`` suboption, but stops the player
initialization.
``exclusive``
Requests exclusive, direct hardware access. By definition prevents
sound playback of any other program until mpv exits.
``list``
Lists all audio endpoints (output devices) present in the system.
+280
View File
@@ -0,0 +1,280 @@
CHANGES FROM OTHER VERSIONS OF MPLAYER
======================================
**mpv** is based on mplayer2, which in turn is based on the original
MPlayer (also called mplayer, mplayer-svn, mplayer1). Many changes
have been made. Some changes are incompatible, or completely change how the
player behaves.
General Changes for MPlayer to mplayer2
---------------------------------------
* Removal of the internal GUI, MEncoder, OSD menu
* Better pause handling (do not unpause on a command)
* Better MKV support (such as ordered chapters)
* vo_vdpau improvements
* Precise seeking support
* No embedded copy of ffmpeg and other libraries
* Native OpenGL backend for OSX
* General OSX improvements
* Improvements in audio/video sync handling
* Cleaned up terminal output
* Gapless audio support (``--gapless-audio``)
* Improved responsiveness on user input
* Support for modifier keys (alt, shift, ctrl) in input.conf
* OSS4 volume control
* More correct color reproduction (color matrix generation)
* Use libass for subtitle rendering by default (better quality)
* Generally preferring ffmpeg/libav over internal demuxers and decoders
* Improvements when playing multiple files (``--fixed-vo``)
* Screenshot improvements (instant screenshots without 1-frame delay, allow
taking screenshots even with hardware decoding)
* Improved support for PulseAudio
* General code cleanups
* Many more changes
General Changes for mplayer2 to mpv
-----------------------------------
* Switch back to GPLv2+.
* Removal of lots of unneeded code to encourage developer activity (less
obscure scary zombie code that kills any desire for hacking the codebase)
* Removal of dust and dead bodies (code-wise), such as kernel drivers for
decades old hardware
* Removal of support for dead platforms
* Generally improved MS Windows support (dealing with unicode filenames,
improved ``--vo=direct3d``, improved window handling)
* Better OSD rendering (using libass). This has full unicode support, and
languages like Arabic should be better supported.
* Cleaned up terminal output (nicer status line, less useless noise)
* Support for playing URLs of popular streaming sites directly
(e.g. ``mpv https://www.youtube.com/watch?v=...``)
* Improved OpenGL output (``--vo=opengl-hq``)
* Make ``--softvol`` default (**mpv** is not a mixer control panel)
* Improved support for .cue files
* Screenshot improvements (can save screenshots as JPG or PNG, configurable
filenames, support for taking screenshots with or without subtitles - the
``screenshot`` video filter is not needed anymore, and should not be put
into the mpv config file)
* Removal of teletext support
* Removal of most builtin demuxers, using libavformat instead
* Removal of builtin network support, using libavformat instead (also,
support https via libavformat)
* Replace image VOs (``--vo=jpeg`` etc.) with ``--vo=image``
* Do not lose settings when playing a new file in the same player instance
* New location for config files, new name for the binary.
* Slave mode compatibility broken (see below)
* Encoding functionality (replacement for mencoder, see ``DOCS/encoding.rst``)
* Remove ``--vo=gif89a``, ``--vo=md5sum``, ``--vo=yuv4mpeg``, as encoding can
handle these use cases. For yuv4mpeg, for example, use:
``mpv input.mkv -o output.y4m --no-audio --oautofps --oneverdrop``.
* Image subtitles (DVDs etc.) are rendered in color and use more correct
positioning (color can be disabled with ``--sub-gray``)
* Wayland support
* Support for precise scrolling which scales the parameter of commands. If the
input doesn't support precise scrolling the scale factor stays 1.
* OSX: Cocoa event loop is independent from mplayer's event loop, so user
actions like accessing menus and live resizing do not block the playback.
* OSX: Apple Remote support.
* OSX: Media Keys support.
* Windows: Added WASAPI audio output.
* New OSD bar with chapter marks and not positioned in the middle of the video
(though this can be customized with the ``--osd-bar-align-y`` option).
* Allow customizing whether a key binding for seeking shows the video time, the
OSD bar, or nothing (see section `Input Command Prefixes`_).
* Display list of chapters and audio/subtitle tracks on OSD (see section
`Properties`_).
* ``--keep-open`` option to stop the player from closing the window and
exiting after playback ends.
* Re-enable screensaver while the player is paused.
* Matroska edition switching at runtime.
* Support for libavfilter (for video->video and audio->audio). This allows
using most of FFmpeg's filters, which improve greatly on the old MPlayer
filters in features, performance, and correctness.
* Improved downmixing and output of surround audio. Instead of using hardcoded
pan filters to do remixing, use libavresample. Channel maps are used to
identify the channel layout, so e.g. ``3.0`` and ``2.1`` audio can be
distinguished.
* Allow resuming playback at a later point with ``Shift+q``, also see
``quit_watch_later`` input command.
* Support mapping multiple commands to one key.
* Allow changing/adjusting video filters at runtime. (This is also used to make
the ``D`` key insert vf_yadif if deinterlacing is not supported otherwise.)
* Native VAAPI support
* OSX: VDA support using libavcodec hwaccel API insted of FFmpeg's decoder. Up
to 2-2.5x reduction in CPU usage.
* General bug fixes and removal of long-standing issues
* General code cleanups (including refactoring or rewrites of many parts)
* Many more changes
Detailed Listing of User-visible Changes
----------------------------------------
This listing is about changed command line switches, slave commands, and similar
things. Completely removed features are not listed.
Command Line Switches
~~~~~~~~~~~~~~~~~~~~~
* There is a new command line syntax, which is generally preferred over the old
syntax. ``-optname optvalue`` becomes ``--optname=optvalue``.
The old syntax will not be removed in the near future. However, the new
syntax is mentioned in all documentation and so on, so it is a good thing to
know about this change.
(The new syntax was introduced in mplayer2.)
* In general, negating switches like ``-noopt`` now have to be written as
``-no-opt``, or better ``--no-opt``.
* Per-file options are not the default anymore. You can explicitly specify
file-local options. See ``Usage`` section.
* Table of renamed/replaced switches:
=========================== ========================================
Old New
=========================== ========================================
``-no<opt>`` ``--no-<opt>`` (add a dash)
``-nosound`` ``--no-audio``
``-use-filename-title`` ``--title="${filename}"``
``-loop 0`` ``--loop=inf``
``-hardframedrop`` ``--framedrop=hard``
``-osdlevel`` ``--osd-level``
``-delay`` ``--audio-delay``
``-subdelay`` ``--sub-delay``
``-subpos`` ``--sub-pos``
``-forcedsubsonly`` ``--sub-forced-only``
``-benchmark`` ``--untimed`` (no stats)
``-xineramascreen`` ``--screen`` (different values)
``-ss`` ``--start``
``-endpos`` ``--length``
``-cursor-autohide-delay`` ``--cursor-autohide``
``-sub-fuzziness`` ``--autosub-match``
``-subfont`` ``--sub-text-font``
``-font`` ``--osd-font``
``-subfont-*`` ``--sub-text-*``, ``--osd-*``
``-subfont-text-scale`` ``--sub-scale``
``-spugauss`` ``--sub-gauss``
``-vobsub`` ``--sub`` (pass the .idx file)
``-ass-bottom-margin`` ``--vf=sub=bottom:top``
``-vc ffh264vdpau`` (etc.) ``--hwdec=vdpau``
``-ac spdifac3`` ``--ad=spdif:ac3`` (see ``--ad=help``)
``-afm hwac3`` ``--ad=spdif:ac3,spdif:dts``
``-x W``, ``-y H`` ``--geometry=WxH`` + ``--no-keepaspect``
``-xy W`` ``--autofit=W``
``-a52drc level`` ``--ad-lavc-ac3drc=level``
``-dumpstream`` ``--stream-dump=<filename>``
``-capture`` ``--stream-capture=<filename>``
``-stop-xscreensaver`` ``--stop-screensaver``
``-subfile`` ``--sub``
``-lavdopts ...`` ``--vd-lavc-...``
``-lavfdopts`` ``--demuxer-lavf-...``
``-rawaudio ...`` ``--demuxer-rawaudio-...``
``-rawvideo ...`` ``--demuxer-rawvideo-...``
``-mixer`` AO suboptions (``alsa``, ``oss``)
``-mixer-channel`` AO suboptions (``alsa``, ``oss``)
``-ao alsa:device=hw=0.3`` ``--ao=alsa:device=[hw:0,3]``
``-af volnorm`` ``--af=drc`` (renamed)
``-zoom`` Inverse available as ``--video-unscaled``
``-panscanrange`` ``--video-zoom``, ``--video-pan-x/y``
=========================== ========================================
.. note::
``-opt val`` becomes ``--opt=val``.
input.conf and Slave Commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Table of renamed input commands:
This lists only commands that are not always gracefully handled by the
internal legacy translation layer. If an input.conf contains any legacy
commands, a warning will be printed when starting the player. The warnings
also show the replacement commands.
Properties containing ``_`` to separate words use ``-`` instead.
+--------------------------------+----------------------------------------+
| Old | New |
+================================+========================================+
| ``pt_step 1 [0|1]`` | ``playlist_next [weak|force]`` |
| | (translation layer cannot deal with |
| | whitespace) |
+--------------------------------+----------------------------------------+
| ``pt_step -1 [0|1]`` | ``playlist_prev [weak|force] (same)`` |
+--------------------------------+----------------------------------------+
| ``switch_ratio [<ratio>]`` | ``set aspect <ratio>`` |
| | |
| | ``set aspect 0`` (to reset aspect) |
+--------------------------------+----------------------------------------+
| ``step_property_osd <prop>`` | ``cycle <prop> <step>`` (wraps), |
| ``<step> <dir>`` | ``add <prop> <step>`` (clamps). |
| | ``<dir>`` parameter unsupported. Use |
| | a negative ``<step>`` instead. |
+--------------------------------+----------------------------------------+
| ``step_property <prop>`` | Prefix ``cycle`` or ``add`` with |
| ``<step> <dir>`` | ``no-osd``: ``no-osd cycle <prop>`` |
| | ``<step>`` |
+--------------------------------+----------------------------------------+
| ``osd_show_property_text`` | ``show_text <text>`` |
| ``<text>`` | The property expansion format string |
| | syntax slightly changed. |
+--------------------------------+----------------------------------------+
| ``osd_show_text`` | Now does the same as |
| | ``osd_show_property_text``. Use the |
| | ``raw`` prefix to disable property |
| | expansion. |
+--------------------------------+----------------------------------------+
| ``show_tracks`` | ``show_text ${track-list}`` |
+--------------------------------+----------------------------------------+
| ``show_chapters`` | ``show_text ${chapter-list}`` |
+--------------------------------+----------------------------------------+
| ``af_switch``, ``af_add``, ... | ``af set|add|...`` |
+--------------------------------+----------------------------------------+
Other
~~~~~
* The playtree has been removed. **mpv**'s internal playlist is a simple and
flat list now. This simplifies the code and makes **mpv** usage less
confusing.
* Slave mode is broken. This mode is entirely insane in the ``old`` versions of
MPlayer. A proper slave mode application needed tons of code and hacks to get
it right. The main problem is that slave mode is a bad and incomplete
interface, and to get around that, applications parsed output messages
intended for users. It is hard to know which messages exactly are parsed by
slave mode applications. This makes it virtually impossible to improve
terminal output intended for users without possibly breaking something.
This is absolutely insane, and **mpv** will not try to keep slave mode
compatible. If you are a developer of a slave mode application, contact us,
and a new and better protocol can be developed.
Policy for Removed Features
---------------------------
Features are a good thing, because they make users happy. As such, it is
attempted to preserve useful features as far as possible. But if a feature is
likely to be not used by many, and causes problems otherwise, it will be
removed. Developers should not be burdened with fixing or cleaning up code that
has no actual use.
It is always possible to add back removed features. File a feature request if a
feature you relied on has been removed, and you want it back. Though it might be
rejected in the worst case, it is much more likely that it will be either added
back, or that a better solution will be implemented.
Why this Fork?
--------------
* MPlayer wants to maintain old code, even if it is very bad code. It seems
mplayer2 was forked because MPlayer developers refused to get rid of all the
cruft. The mplayer2 and MPlayer codebases also deviated enough to make a
reunification unlikely.
* mplayer2 development is slow, and it is hard to get in changes. Details
withheld as to not turn this into a rant.
* MPlayer rarely merged from mplayer2, and mplayer2 practically stopped
merging from MPlayer (not even code cleanups or new features are merged)
* **mpv** intends to continuously merge from mplayer-svn and mplayer2, while
speeding up development. There is willingness for significant changes, even
if this means breaking compatibility.
+151
View File
@@ -0,0 +1,151 @@
ENCODING
========
You can encode files from one format/codec to another using this facility.
``-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``). This can be a comma separated
list of possible formats to try. See ``--of=help`` for a full list of
supported formats.
``--ofopts=<options>``
Specifies the output format options for libavformat.
See ``--ofopts=help`` for a full list of supported options.
Options are managed in lists. There are a few commands to manage the
options list.
``--ofopts-add=<options1[,options2,...]>``
Appends the options given as arguments to the options list.
``--ofopts-pre=<options1[,options2,...]>``
Prepends the options given as arguments to the options list.
``--ofopts-del=<index1[,index2,...]>``
Deletes the options at the given indexes. Index numbers start at 0,
negative numbers address the end of the list (-1 is the last).
``--ofopts-clr``
Completely empties the options list.
``--ofps=<float value>``
Specifies the output format time base (default: 24000). Low values like 25
limit video fps by dropping frames.
``--oautofps``
Sets the output format time base to the guessed frame rate of the input
video (simulates mencoder behavior, useful for AVI; may cause frame drops).
Note that not all codecs and not all formats support VFR encoding, and some
which do have bugs when a target bitrate is specified - use ``--ofps`` or
``--oautofps`` to force CFR encoding in these cases.
``--omaxfps=<float value>``
Specifies the minimum distance of adjacent frames (default: 0, which means
unset). Content of lower frame rate is not readjusted to this frame rate;
content of higher frame rate is decimated to this frame rate.
``--oharddup``
If set, the frame rate given by ``--ofps`` is attained not by skipping time
codes, but by duplicating frames (constant frame rate mode).
``--oneverdrop``
If set, frames are never dropped. Instead, time codes of video are
readjusted to always increase. This may cause AV desync, though; to work
around this, use a high-fps time base using ``--ofps`` and absolutely
avoid ``--oautofps``.
``--oac=<codec>``
Specifies the output audio codec. This can be a comma separated list of
possible codecs to try. See ``--oac=help`` for a full list of supported
codecs.
``--oaoffset=<value>``
Shifts audio data by the given time (in seconds) by adding/removing
samples at the start.
``--oacopts=<options>``
Specifies the output audio codec options for libavcodec.
See ``--oacopts=help`` for a full list of supported options.
.. admonition:: Example
"``--oac=libmp3lame --oacopts=b=128000``"
selects 128kbps MP3 encoding.
Options are managed in lists. There are a few commands to manage the
options list.
``--oacopts-add=<options1[,options2,...]>``
Appends the options given as arguments to the options list.
``--oacopts-pre=<options1[,options2,...]>``
Prepends the options given as arguments to the options list.
``--oacopts-del=<index1[,index2,...]>``
Deletes the options at the given indexes. Index numbers start at 0,
negative numbers address the end of the list (-1 is the last).
``--oacopts-clr``
Completely empties the options list.
``--oafirst``
Force the audio stream to become the first stream in the output. By default
the order is unspecified.
``--ovc=<codec>``
Specifies the output video codec. This can be a comma separated list of
possible codecs to try. See ``--ovc=help`` for a full list of supported
codecs.
``--ovoffset=<value>``
Shifts video data by the given time (in seconds) by shifting the pts
values.
``--ovcopts <options>``
Specifies the output video codec options for libavcodec.
See --ovcopts=help for a full list of supported options.
.. admonition:: Examples
``"--ovc=mpeg4 --oacopts=qscale=5"``
selects constant quantizer scale 5 for MPEG-4 encoding.
``"--ovc=libx264 --ovcopts=crf=23"``
selects VBR quality factor 23 for H.264 encoding.
Options are managed in lists. There are a few commands to manage the
options list.
``--ovcopts-add=<options1[,options2,...]>``
Appends the options given as arguments to the options list.
``--ovcopts-pre=<options1[,options2,...]>``
Prepends the options given as arguments to the options list.
``--ovcopts-del=<index1[,index2,...]>``
Deletes the options at the given indexes. Index numbers start at 0,
negative numbers address the end of the list (-1 is the last).
``--ovcopts-clr``
Completely empties the options list.
``--ovfirst``
Force the video stream to become the first stream in the output. By default
the order is unspecified.
``--ocopyts``
Copies input pts to the output video (not supported by some output
container formats, e.g. AVI). Discontinuities are still fixed.
By default, audio pts are set to playback time and video pts are
synchronized to match audio pts, as some output formats do not support
anything else.
``--orawts``
Copies input pts to the output video (not supported by some output
container formats, e.g. AVI). In this mode, discontinuities are not fixed
and all pts are passed through as-is. Never seek backwards or use multiple
input files in this mode!
+651
View File
@@ -0,0 +1,651 @@
INPUT.CONF
==========
The input.conf file consists of a list of key bindings, for example::
s screenshot # take a screenshot with the s key
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.
A list of special keys can be obtained with
``mpv --input-keylist``
In general, keys can be combined with ``Shift``, ``Ctrl`` and ``Alt``::
ctrl+q quit
**mpv** can be started in input test mode, which displays key bindings and the
commands they're bound to on the OSD, instead of executing the commands::
mpv --input-test --demuxer=rawvideo --demuxer-rawvideo=w=1280:h=720 /dev/zero
(Commands which normally close the player will not work in this mode, and you
must kill **mpv** externally to make it exit.)
General Input Command Syntax
----------------------------
``[Shift+][Ctrl+][Alt+][Meta+]<key> [{<section>}] [<prefixes>] <command> (<argument>)* [; <command>]``
Newlines always start a new binding. ``#`` starts a comment (outside of quoted
string arguments). To bind commands to the ``#`` key, ``SHARP`` can be used.
``<key>`` is either the literal character the key produces (ASCII or Unicode
character), or a symbolic name (as printed by ``--input-keylist``).
``<section>`` (braced with ``{`` and ``}``) is the input section for this
command.
Arguments are separated by whitespace. This applies even to string arguments.
For this reason, string arguments should be quoted with ``"``. Inside quotes,
C-style escaping can be used.
Optional arguments can be skipped with ``-``.
You can bind multiple commands to one key. For example:
| a show_text "command 1" ; show_text "command 2"
Note that some magic is disabled for keys: seek commands inside lists are not
coalesced (seeking will appear slower), and no check is done for abort commands
(so these commands can't be used to abort playback if the network cache is
stuck).
List of Input Commands
----------------------
``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 <seconds> [relative|absolute|absolute-percent|- [default-precise|exact|keyframes]]``
Change the playback position. By default, seeks by a relative amount of
seconds.
The second argument sets the seek mode:
relative (default)
Seek relative to current position (a negative value seeks backwards).
absolute
Seek to a given time.
absolute-percent
Seek to a given percent position.
The third argument defines how exact the seek is:
default-precise (default)
Follow the default behavior as set by ``--hr-seek``, which by default
does imprecise seeks (like ``keyframes``).
exact
Always do exact/hr/precise seeks (slow).
keyframes
Always restart playback at keyframe boundaries (fast).
``frame_step``
Play one frame, then pause.
``frame_back_step``
Go back by one frame, then pause. Note that this can be very slow (it tries
to be precise, not fast), and sometimes fails to behave as expected. How
well this works depends on whether precise seeking works correctly (e.g.
see the ``--hr-seek-demuxer-offset`` option). Video filters or other video
postprocessing that modifies timing of frames (e.g. deinterlacing) should
usually work, but might make backstepping silently behave incorrectly in
corner cases.
This does not work with audio-only playback.
``set <property> "<value>"``
Set the given property to the given value.
``add <property> [<value>]``
Add the given value to the property. On overflow or underflow, clamp the
property to the maximum. If ``<value>`` is omitted, assume ``1``.
``cycle <property> [up|down]``
Cycle the given property. ``up`` and ``down`` set the cycle direction. On
overflow, set the property back to the minimum, on underflow set it to the
maximum. If ``up`` or ``down`` is omitted, assume ``up``.
``speed_mult <value>``
Multiply the ``speed`` property by the given value.
``screenshot [subtitles|video|window|- [single|each-frame]]``
Take a screenshot.
First argument:
<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, and
if no support is available, this will act like ``video``.
Second argument:
<single> (default)
Take a single screenshot.
<each-frame>
Take a screenshot each frame. Issue this command again to stop taking
screenshots.
``screenshot_to_file "<filename>" [subtitles|video|window]``
Take a screenshot and save it to a given file. The format of the file will
be guessed by the extension (and ``--screenshot-format`` is ignored - the
behavior when the extension is missing or unknown is arbitrary).
The second argument is like the first argument to ``screenshot``.
This command tries to never overwrite files. If the file already exists,
it fails.
Like all input command parameters, the filename is subject to property
expansion as described in `Property Expansion`_.
``playlist_next [weak|force]``
Go to the next entry on the playlist.
weak (default)
If the last file on the playlist is currently played, do nothing.
force
Terminate playback if there are no more files on the playlist.
``playlist_prev [weak|force]``
Go to the previous entry on the playlist.
weak (default)
If the first file on the playlist is currently played, do nothing.
force
Terminate playback if the first file is being played.
``loadfile "<file>" [replace|append]``
Load the given file and play it.
Second argument:
<replace> (default)
Stop playback of the current file, and play the new file immediately.
<append>
Append the file to the playlist.
``loadlist "<playlist>" [replace|append]``
Load the given playlist file (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. You cannot remove the entry for the currently played file.
``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.)
``run "<command>"``
Run the given command with ``/bin/sh -c``. The string is expanded like in
`Property Expansion`_.
``quit [<code>]``
Exit the player using the given exit code.
``quit_watch_later``
Exit player, and store current playback position. Playing that file later
will seek to the previous position on start.
``sub_add "<file>"``
Load the given subtitle file. It is not 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.)
``sub_reload [<id>]``
Reload the given subtitle tracks. If the ``id`` argument is missing, remove
the current track. (Works on external subtitle files only.)
This works by unloading and re-adding the subtitle track.
``sub_step <skip>``
Change subtitle timing such, that the subtitle event after the next
``<skip>`` subtitle events is displayed. ``<skip>`` can be negative to step
backwards.
``sub_seek <skip>``
Seek to the next (skip set to 1) or the previous (skip set to -1) subtitle.
This is similar to ``sub_step``, except that it seeks video and audio
instead of adjusting the subtitle delay.
Like with ``sub_step``, this works with external text subtitles only. For
embedded text subtitles (like with Matroska), this works only with subtitle
events that have already been displayed.
``osd [<level>]``
Toggle OSD level. If ``<level>`` is specified, set the OSD mode
(see ``--osd-level`` for valid values).
``print_text "<string>"``
Print text to stdout. The string can contain properties (see
`Property Expansion`_).
``show_text "<string>" [<duration>|- [<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.
<duration>
The time in ms to show the message for. By default, it uses the same
value as ``--osd-duration``.
<level>
The minimum OSD level to show the text at (see ``--osd-level``).
``show_progress``
Show the progress bar, the elapsed time and the total duration of the file
on the OSD.
Input Commands that are Possibly Subject to Change
--------------------------------------------------
``af set|add|toggle|del|clr "filter1=params,filter2,..."``
Change audio filter chain. See ``vf`` command.
``vf set|add|toggle|del|clr "filter1=params,filter2,..."``
Change video filter chain.
The first argument decides what happens:
set
Overwrite the previous filter chain with the new one.
add
Append the new filter chain to the previous one.
toggle
Check if the given filter (with the exact parameters) is already
in the video chain. If yes, remove the filter. If no, add the filter.
(If several filters are passed to the command, this is done for
each filter.)
del
Remove the given filters from the video chain. Unlike in the other
cases, the second parameter is a comma separated list of filter names
or integer indexes. ``0`` would denote the first filter. Negative
indexes start from the last filter, and ``-1`` denotes the last
filter.
clr
Remove all filters. Note that like the other sub-commands, this does
not control automatically inserted filters.
You can assign labels to filter by prefixing them with ``@name:`` (where
``name`` is a user-chosen arbitrary identifier). Labels can be used to
refer to filters by name in all of the filter chain modification commands.
For ``add``, using an already used label will replace the existing filter.
The ``vf`` command shows the list of requested filters on the OSD after
changing the filter chain. This is roughly equivalent to
``show_text ${vf}``. Note that auto-inserted filters for format conversion
are not shown on the list, only what was requested by the user.
.. admonition:: Example for input.conf
- ``a vf set flip`` turn video upside-down on the ``a`` key
- ``b vf set ""`` remove all video filters on ``b``
- ``c vf toggle lavfi=gradfun`` toggle debanding on ``c``
``enable_section "<section>" [default|exclusive]``
Enable all key bindings in the named input section.
The enabled input sections form a stack. Bindings in sections on the top of
the stack are preferred to lower sections. This command puts the section
on top of the stack. If the section was already on the stack, it is
implicitly removed beforehand. (A section cannot be on the stack more than
once.)
If ``exclusive`` is specified as second argument, all sections below the
newly enabled section are disabled. They will be re-enabled as soon as
all exclusive sections above them are removed.
``disable_section "<section>"``
Disable the named input section. Undoes ``enable_section``.
``overlay_add <id> <x> <y> "<file>" <offset> "<fmt>" <w> <h> <stride>``
Add an OSD overlay sourced from raw data. This might be useful for scripts
and applications controlling mpv, and which want to display things on top
of the video window.
Overlays are usually displayed in screen resolution, but with some VOs,
the resolution is reduced to that of the video's. You can read the
``osd-width`` and ``osd-height`` properties. At least with ``--vo-xv`` and
anamorphic video (such as DVD), ``osd-par`` should be read as well, and the
overlay should be aspect-compensated. (Future directions: maybe mpv should
take care of some of these things automatically, but it's hard to tell
where to draw the line.)
``id`` is an integer between 0 and 63 identifying the overlay element. The
ID can be used to add multiple overlay parts, update a part by using this
command with an already existing ID, or to remove a part with
``overlay_remove``. Using a previously unused ID will add a new overlay,
while reusing an ID will update it. (Future directions: there should be
something to ensure different programs wanting to create overlays don't
conflict with each others, should that ever be needed.)
``x`` and ``y`` specify the position where the OSD should be displayed.
``file`` specifies the file the raw image data is read from. It can be
either a numeric UNIX file descriptor prefixed with ``@`` (e.g. ``@4``),
or a filename. The file will be mapped into memory with ``mmap()``. Some VOs
will pass the mapped pointer directly to display APIs (e.g. opengl or
vdpau), so no actual copying is involved. Truncating the source file while
the overlay is active will crash the player. You shouldn't change the data
while the overlay is active, because the data is essentially accessed at
random points. Instead, call ``overlay_add`` again (preferably with a
different memory region to prevent tearing).
``offset`` is the offset of the first pixel in the source file. It is
passed directly to ``mmap`` and is subject to certain restrictions
(see ``man mmap`` for details). In particular, this value has to be a
multiple of the system's page size.
``fmt`` is a string identifying the image format. Currently, only ``bgra``
is defined. This format has 4 bytes per pixels, with 8 bits per component.
The least significant 8 bits are blue, and the most significant 8 bits
are alpha (in little endian, the components are B-G-R-A, with B as first
byte). This uses premultiplied alpha: every color component is already
multiplied with the alpha component. This means the numeric value of each
component is equal to or smaller than the alpha component. (Violating this
rule will lead to different results with different VOs: numeric overflows
resulting from blending broken alpha values is considered something that
shouldn't happen, and consequently implementations don't ensure that you
get predictable behavior in this case.)
``w``, ``h``, and ``stride`` specify the size of the overlay. ``w`` is the
visible width of the overlay, while ``stride`` gives the width in bytes in
memory. In the simple case, and with the ``bgra`` format, ``stride==4*w``.
In general, the total amount of memory accessed is ``stride * h``.
(Technically, the minimum size would be ``stride * (h - 1) + w * 4``, but
for simplicity, the player will access all ``stride * h`` bytes.)
.. admonition:: Warning
When updating the overlay, you should prepare a second shared memory
region (e.g. make use of the offset parameter) and add this as overlay,
instead of reusing the same memory every time. Otherwise, you might
get the equivalent of tearing, when your application and mpv write/read
the buffer at the same time. Also, keep in mind that mpv might access
an overlay's memory at random times whenever it feels the need to do
so, for example when redrawing the screen.
``overlay_remove <id>``
Remove an overlay added with ``overlay_add`` and the same ID. Does nothing
if no overlay with this ID exists.
Undocumented commands: ``tv_start_scan``, ``tv_step_channel``, ``tv_step_norm``,
``tv_step_chanlist``, ``tv_set_channel``, ``tv_last_channel``, ``tv_set_freq``,
``tv_step_freq``, ``tv_set_norm``, ``dvb_set_channel``, ``radio_step_channel``,
``radio_set_channel``, ``radio_set_freq``, ``radio_step_freq`` (all of these
should be replaced by properties), ``stop`` (questionable use), ``get_property``
(?), ``vo_cmdline`` (experimental).
Input Command Prefixes
----------------------
These prefixes are placed between key name and the actual command. Multiple
prefixes can be specified. They are separated by whitespace.
``osd-auto`` (default)
Use the default behavior for this command.
``no-osd``
Do not use any OSD for this command.
``osd-bar``
If possible, show a bar with this command. Seek commands will show the
progress bar, property changing commands may show the newly set value.
``osd-msg``
If possible, show an OSD message with this command. Seek command show
the current playback time, property changing commands show the newly set
value as text.
``osd-msg-bar``
Combine osd-bar and osd-msg.
``raw``
Do not expand properties in string arguments. (Like ``"${property-name}"``.)
``expand-properties`` (default)
All string arguments are expanded as described in `Property Expansion`_.
All of the osd prefixes are still overridden by the global ``--osd-level``
settings.
Undocumented prefixes: ``pausing``, ``pausing_keep``, ``pausing_toggle``,
``pausing_keep_force``. (Should these be made official?)
Input Sections
--------------
Input sections group a set of bindings, and enable or disable them at once.
In ``input.conf``, each key binding is assigned to an input section, rather
than actually having explicit text sections.
Also see ``enable_section`` and ``disable_section`` commands.
Predefined bindings:
``default``
Bindings without input section are implicitly assigned to this section. It
is enabled by default during normal playback.
``encode``
Section which is active in encoding mode. It is enabled exclusively, so
that bindings in the ``default`` sections are ignored.
Properties
----------
Properties are used to set mpv options during runtime, or to query arbitrary
information. They can be manipulated with the ``set``/``add``/``cycle``
commands, and retrieved with ``show_text``, or anything else that uses property
expansion. (See `Property Expansion`_.)
The ``W`` column indicates whether the property is generally writable. If an
option is referenced, the property should take/return exactly the same values
as the option.
=============================== = ==================================================
Name W Comment
=============================== = ==================================================
``osd-level`` x see ``--osd-level``
``osd-scale`` x osd font size multiplicator, see ``--osd-scale``
``loop`` x see ``--loop``
``speed`` x see ``--speed``
``filename`` currently played file (path stripped)
``path`` currently played file (full path)
``media-title`` filename, title tag, or libquvi ``QUVIPROP_PAGETITLE``
``demuxer``
``stream-path`` filename (full path) of stream layer filename
``stream-pos`` x byte position in source stream
``stream-start`` start byte offset in source stream
``stream-end`` end position in bytes in source stream
``stream-length`` length in bytes (``${stream-end} - ${stream-start}``)
``stream-time-pos`` x time position in source stream (also see ``time-pos``)
``length`` length of the current file in seconds
``avsync`` last A/V synchronization difference
``percent-pos`` x position in current file (0-100)
``ratio-pos`` x position in current file (0.0-1.0)
``time-pos`` x position in current file in seconds
``time-remaining`` estimated remaining length of the file in seconds
``chapter`` x current chapter number
``edition`` x current MKV edition number
``titles`` number of DVD titles
``chapters`` number of chapters
``editions`` number of MKV editions
``angle`` x current DVD angle
``metadata`` metadata key/value pairs
``metadata/<key>`` value of metadata entry ``<key>``
``chapter-metadata`` metadata of current chapter (works similar)
``pause`` x pause status (bool)
``cache`` network cache fill state (0-100)
``pts-association-mode`` x see ``--pts-association-mode``
``hr-seek`` x see ``--hr-seek``
``volume`` x current volume (0-100)
``mute`` x current mute status (bool)
``audio-delay`` x see ``--audio-delay``
``audio-format`` audio format (string)
``audio-codec`` audio codec selected for decoding
``audio-bitrate`` audio bitrate
``samplerate`` audio samplerate
``channels`` number of audio channels
``aid`` x current audio track (similar to ``--aid``)
``audio`` x alias for ``aid``
``balance`` x audio channel balance
``fullscreen`` x see ``--fullscreen``
``deinterlace`` x similar to ``--deinterlace``
``colormatrix`` x see ``--colormatrix``
``colormatrix-input-range`` x see ``--colormatrix-input-range``
``colormatrix-output-range`` x see ``--colormatrix-output-range``
``ontop`` x see ``--ontop``
``border`` x see ``--border``
``framedrop`` x see ``--framedrop``
``gamma`` x see ``--gamma``
``brightness`` x see ``--brightness``
``contrast`` x see ``--contrast``
``saturation`` x see ``--saturation``
``hue`` x see ``--hue``
``panscan`` x see ``--panscan``
``video-format`` video format (string)
``video-codec`` video codec selected for decoding
``video-bitrate`` video bitrate
``width`` video width (container or decoded size)
``height`` video height
``fps`` container FPS (may contain bogus values)
``dwidth`` video width (after filters and aspect scaling)
``dheight`` video height
``aspect`` x video aspect
``osd-width`` last known OSD width (can be 0)
``osd-height`` last known OSD height (can be 0)
``osd-par`` last known OSD display pixel aspect (can be 0)
``vid`` x current video track (similar to ``--vid``)
``video`` x alias for ``vid``
``video-align-x`` x see ``--video-align-x``
``video-align-y`` x see ``--video-align-y``
``video-pan-x`` x see ``--video-pan-x``
``video-pan-y`` x see ``--video-pan-y``
``video-zoom`` x see ``--video-zoom``
``program`` x switch TS program (write-only)
``sid`` x current subtitle track (similar to ``--sid``)
``sub`` x alias for ``sid``
``sub-delay`` x see ``--sub-delay``
``sub-pos`` x see ``--sub-pos``
``sub-visibility`` x see ``--sub-visibility``
``sub-forced-only`` x see ``--sub-forced-only``
``sub-scale`` x subtitle font size multiplicator
``ass-use-margins`` x see ``--ass-use-margins``
``ass-vsfilter-aspect-compat`` x see ``--ass-vsfilter-aspect-compat``
``ass-style-override`` x see ``--ass-style-override``
``stream-capture`` x a filename, see ``--capture``
``tv-brightness`` x
``tv-contrast`` x
``tv-saturation`` x
``tv-hue`` x
``playlist-pos`` current position on playlist
``playlist-count`` number of total playlist entries
``playlist`` playlist, current entry marked
``track-list`` list of audio/video/sub tracks, current entry marked
``chapter-list`` list of chapters, current entry marked
``quvi-format`` x see ``--quvi-format``
``af`` x see ``--af``
``vf`` x see ``--vf``
``options/name`` read-only access to value of option ``--name``
=============================== = ==================================================
Property Expansion
------------------
All string arguments to input commands as well as certain options (like
``--playing-msg``) are subject to property expansion.
.. admonition:: Example for input.conf
``i show_text "Filename: ${filename}"``
shows the filename of the current file when pressing the ``i`` key
Within ``input.conf``, property expansion can be inhibited by putting the
``raw`` prefix in front of commands.
The following expansions are supported:
``${NAME}``
Expands to the value of the property ``NAME``. If retrieving the property
fails, expand to an error string. (Use ``${NAME:}`` with a trailing
``:`` to expand to an empty string instead.)
If ``NAME`` is prefixed with ``=``, expand to the raw value of the property
(see section below).
``${NAME:STR}``
Expands to the value of the property ``NAME``, or ``STR`` if the
property cannot be retrieved. ``STR`` is expanded recursively.
``${?NAME:STR}``
Expands to ``STR`` (recursively) if the property ``NAME`` is available.
``${!NAME:STR}``
Expands to ``STR`` (recursively) if the property ``NAME`` cannot be
retrieved.
``${?NAME==VALUE:STR}``
Expands to ``STR`` (recursively) if the property ``NAME`` expands to a
string equal to ``VALUE``. You can prefix ``NAME`` with ``=`` in order to
compare the raw value of a property (see section below). If the property
is unavailable, or other errors happen when retrieving it, the value is
never considered equal.
Note that ``VALUE`` can't contain any of the characters ``:`` or ``}``.
Also, it is possible that escaping with ``"`` or ``%`` might be added in
the future, should the need arise.
``${!NAME==VALUE:STR}``
Same as with the ``?`` variant, but ``STR`` is expanded if the value is
not equal. (Using the same semantics as with ``?``.)
``$$``
Expands to ``$``.
``$}``
Expands to ``}``. (To produce this character inside recursive
expansion.)
``$>``
Disable property expansion and special handling of ``$`` for the rest
of the string.
In places where property expansion is allowed, C-style escapes are often
accepted as well. Example:
- ``\n`` becomes a newline character
- ``\\`` expands to ``\``
Raw and Formatted Properties
----------------------------
Normally, properties are formatted as human-readable text, meant to be
displayed on OSD or on the terminal. It is possible to retrieve an unformatted
(raw) value from a property by prefixing its name with ``=``. These raw values
can be parsed by other programs and follow the same conventions as the options
associated with the properties.
.. admonition:: Examples
- ``${time-pos}`` expands to ``00:14:23`` (if playback position is at 14
minutes 23 seconds)
- ``${=time-pos}`` expands to ``863.4`` (same time, plus 400 milliseconds -
milliseconds are normally not shown in the formatted case)
Sometimes, the difference in amount of information carried by raw and formatted
property values can be rather big. In some cases, raw values have more
information, like higher precision than seconds with ``time-pos``. Sometimes
it is the other way around, e.g. ``aid`` shows track title and language in the
formatted case, but only the track number if it is raw.
+18
View File
@@ -0,0 +1,18 @@
LUA SCRIPTING
=============
mpv can load Lua scripts. These scripts can be used to control mpv in a similar
way to slave mode. mpv provides the builtin module ``mp`` (can be loaded
with ``require 'mpv'``), which provides functions to send commands to the
mpv core and to retrieve information about playback state, user settings,
file information, and so on.
.. admonition:: Warning
Lua scripting is work in progress, and it's in a very early stage. When
writing scripts, rely only on the features and functions documented here.
Everything else is subject to change.
.. admonition:: Warning
Nothing is finished and documented yet.
+628
View File
@@ -0,0 +1,628 @@
mpv
###
##############
a movie player
##############
:Author: wm4
:Copyright: GPLv2+
:Manual section: 1
:Manual group: multimedia
.. raw:: latex
\tableofcontents
\pagebreak
SYNOPSIS
========
| **mpv** [options] [file|URL|-]
| **mpv** [options] --playlist=PLAYLIST
| **mpv** [options] files
| **mpv** [options] {group of files and options}
| **mpv** [bd]://[title][/device] [options]
| **mpv** dvd://[title|[start\_title]-end\_title][/device] [options]
| **mpv** \vcd://[/device]
| **mpv** \tv://[channel][/input_id] [options]
| **mpv** radio://[channel|frequency][/capture] [options]
| **mpv** \pvr:// [options]
| **mpv** \dvb://[card\_number@]channel [options]
| **mpv** \mf://[filemask|\@listfile] [-mf options] [options]
| **mpv** cdda://track[-endtrack][:speed][/device] [options]
| **mpv** [file|mms[t]|http|httpproxy|rt[s]p|ftp|udp|smb]://[user:pass\@]URL[:port] [options]
DESCRIPTION
===========
**mpv** is a movie player based on MPlayer and mplayer2. 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 examples to get you started quickly can be found at the end of this man
page.
INTERACTIVE CONTROL
===================
mpv has a fully configurable, command-driven control layer which allows you
to control mpv using keyboard, mouse, joystick or remote control (with
LIRC). See the ``--input-`` options for ways to customize it.
Keyboard Control
----------------
LEFT and RIGHT
Seek backward/forward 10 seconds. Shift+arrow does a 1 second exact seek
(see ``--hr-seek``).
UP and DOWN
Seek forward/backward 1 minute. Shift+arrow does a 5 second exact seek (see
``--hr-seek``).
PGUP and PGDWN
Seek forward/backward 10 minutes.
[ and ]
Decrease/increase current playback speed by 10%.
{ and }
Halve/double current playback speed.
BACKSPACE
Reset playback speed to normal.
< and >
Go backward/forward in the playlist.
ENTER
Go forward in the playlist, even over the end.
p / SPACE
Pause (pressing again unpauses).
\.
Step forward. Pressing once will pause movie, every consecutive press will
play one frame and then go into pause mode again.
q / ESC
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.
U
Stop playing (and quit if ``--idle`` is not used).
\+ and -
Adjust audio delay by +/- 0.1 seconds.
/ and *
Decrease/increase volume.
9 and 0
Decrease/increase volume.
( and )
Adjust audio balance in favor of left/right channel.
m
Mute sound.
\_
Cycle through the available video tracks.
\#
Cycle through the available audio tracks.
TAB (MPEG-TS and libavformat only)
Cycle through the available programs.
f
Toggle fullscreen (see also ``--fs``).
T
Toggle stay-on-top (see also ``--ontop``).
w and e
Decrease/increase pan-and-scan range.
o
Toggle OSD states: none / seek / seek + timer / seek + timer + total time.
d
Toggle frame dropping states: none / skip display / skip decoding (see
``--framedrop``).
v
Toggle subtitle visibility.
j and J
Cycle through the available subtitles.
F
Toggle displaying "forced subtitles".
x and z
Adjust subtitle delay by +/- 0.1 seconds.
V
Toggle subtitle VSFilter aspect compatibility mode. See
``--ass-vsfilter-aspect-compat`` for more info.
r and t
Move subtitles up/down.
s
Take a screenshot.
S
Take a screenshot, without subtitles. (Whether this works depends on VO
driver support.)
I
Show filename on the OSD.
P
Show progression bar, elapsed time and total duration on the OSD.
! and @
Seek to the beginning of the previous/next chapter. In most cases,
"previous" will actually go to the beginning of the current chapter; see
``--chapter-seek-threshold``.
D (``--vo=vdpau``, ``--vf=yadif`` only)
Activate/deactivate deinterlacer.
A
Cycle through the available DVD angles.
c
Change YUV colorspace.
(The following keys are valid only when using a video output that supports the
corresponding adjustment, or the software equalizer (``--vf=eq``).)
1 and 2
Adjust contrast.
3 and 4
Adjust brightness.
5 and 6
Adjust gamma.
7 and 8
Adjust saturation.
(The following keys are valid only on OSX.)
command + 0
Resize movie window to half its original size.
command + 1
Resize movie window to its original size.
command + 2
Resize movie window to double its original size.
command + f
Toggle fullscreen (see also ``--fs``).
command + [ and command + ]
Set movie window alpha.
(The following keys are valid if you have a keyboard with multimedia keys.)
PAUSE
Pause.
STOP
Stop playing and quit.
PREVIOUS and NEXT
Seek backward/forward 1 minute.
(The following keys are only valid if you compiled with TV or DVB input
support.)
h and k
Select previous/next channel.
n
Change norm.
u
Change channel list.
Mouse Control
-------------
button 3 and button 4
Seek backward/forward 1 minute.
button 5 and button 6
Decrease/increase volume.
USAGE
=====
Every *flag* option has a *no-flag* counterpart, e.g. the opposite of the
``--fs`` option is ``--no-fs``. ``--fs=yes`` is same as ``--fs``, ``--fs=no``
is the same as ``--no-fs``.
If an option is marked as *(XXX only)*, it will only work in combination with
the *XXX* option or if *XXX* is compiled in.
.. note::
The suboption parser (used for example for ``--ao=pcm`` suboptions)
supports a special kind of string-escaping intended for use with external
GUIs.
It has the following format::
%n%string_of_length_n
.. admonition:: Examples
``mpv --ao=pcm:file=%10%C:test.wav test.avi``
Or in a script:
``mpv --ao=pcm:file=%`expr length "$NAME"`%"$NAME" test.avi``
Per-File Options
----------------
When playing multiple files, any option given on the command line usually
affects all files. Example::
mpv --a file1.mkv --b file2.mkv --c
=============== ===========================
File Active options
=============== ===========================
file1.mkv ``--a --b --c``
file2.mkv ``--a --b --c``
=============== ===========================
(This is different from MPlayer and mplayer2.)
Also, if any option is changed at runtime (via input commands), they are not
reset when a new file is played.
Sometimes, it is useful to change options per-file. This can be achieved by
adding the special per-file markers ``--{`` and ``--}``. (Note that you must
escape these on some shells.) Example::
mpv --a file1.mkv --b --\{ --c file2.mkv --d file3.mkv --e --\} file4.mkv --f
=============== ===========================
File Active options
=============== ===========================
file1.mkv ``--a --b --f``
file2.mkv ``--a --b --f --c --d --e``
file3.mkv ``--a --b --f --c --d --e``
file4.mkv ``--a --b --f``
=============== ===========================
Additionally, any file-local option changed at runtime is reset when the current
file stops playing. If option ``--c`` is changed during playback of
``file2.mkv``, it is reset when advancing to ``file3.mkv``. This only affects
file-local options. The option ``--a`` is never reset here.
CONFIGURATION FILES
===================
Location and Syntax
-------------------
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 ``~/.mpv/config``.
User-specific options override system-wide options and options given on the
command line override either. The syntax of the configuration files is
``option=<value>``; everything after a *#* is considered a comment. Options
that work without values can be enabled by setting them to *yes* and disabled by
setting them to *no*. Even suboptions can be specified in this way.
.. admonition:: Example configuration file
::
# Use opengl video output by default.
vo=opengl
# Use quotes for text that can contain spaces:
status-msg="Time: ${time-pos}"
Putting Command Line Options into the Configuration File
--------------------------------------------------------
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"``
======================= ========================
File-specific Configuration Files
---------------------------------
You can also write file-specific configuration files. If you wish to have a
configuration file for a file called 'movie.avi', create a file named
'movie.avi.conf' with the file-specific options in it and put it in
``~/.mpv/``. You can also put the configuration file in the same directory
as the file to be played, as long as you give the ``--use-filedir-conf``
option (either on the command line or in your global config file). If a
file-specific configuration file is found in the same directory, no
file-specific configuration is loaded from ``~/.mpv``. In addition, the
``--use-filedir-conf`` option enables directory-specific configuration files.
For this, mpv first tries to load a mpv.conf from the same directory
as the file played and then tries to load any file-specific configuration.
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.
.. admonition:: Example mpv profile
::
[vo.vdpau]
# Use hardware decoding (might break playback of some h264 files)
hwdec=vdpau
[protocol.dvd]
profile-desc="profile for dvd:// streams"
vf=pp=hb/vb/dr/al/fd
alang=en
[extension.flv]
profile-desc="profile for .flv files"
flip=yes
[ao.alsa]
device=spdif
TAKING SCREENSHOTS
==================
Screenshots of the currently played file can be taken using the 'screenshot'
input mode command, which is by default bound to the ``s`` key. Files named
``shotNNNN.jpg`` will be saved in the working directory, using the first
available number - no files will be overwritten.
A screenshot will usually contain the unscaled video contents at the end of the
video filter chain and subtitles. By default, ``S`` takes screenshots without
subtitles, while ``s`` includes subtitles.
The ``screenshot`` video filter is not required when using a recommended GUI
video output driver. It should normally not be added to the config file, as
taking screenshots is handled by the VOs, and adding the screenshot filter will
break hardware decoding. (The filter may still be useful for taking screenshots
at a certain point within the video chain when using multiple video filters.)
.. include:: options.rst
.. include:: ao.rst
.. include:: vo.rst
.. include:: af.rst
.. include:: vf.rst
.. include:: encode.rst
.. include:: input.rst
.. include:: osc.rst
.. include:: lua.rst
.. include:: changes.rst
ENVIRONMENT VARIABLES
=====================
There are a number of environment variables that can be used to control the
behavior of mpv.
``HOME``
Used to determine mpv config directory: ``$HOME/.mpv``
``TERM``
Used to determine terminal type.
``MPV_HOME``
Directory where mpv looks for user settings. Overrides ``HOME``, and mpv
will try to load the config file as ``$MPV_HOME/config``.
``MPV_LOCALEDIR``
Directory where mpv looks for gettext translation files (if enabled).
``MPV_VERBOSE`` (see also ``-v`` and ``--msglevel``)
Set the initial verbosity level across all message modules (default: 0).
The resulting verbosity corresponds to that of ``--msglevel=5`` plus the
value of ``MPV_VERBOSE``.
``MPV_LEAK_REPORT``
If set to ``1``, enable internal talloc leak reporting. Note that this can
cause trouble with multithreading, so only developers should use this.
``LADSPA_PATH``
Specifies the search path for LADSPA plugins. If it is unset, fully
qualified path names must be used.
``DISPLAY``
Standard X11 display name to use.
FFmpeg/Libav:
This library accesses various environment variables. However, they are not
centrally documented, and documenting them is not our job. Therefore, this
list is incomplete.
Notable environment variables:
``http_proxy``
URL to proxy for ``http://`` and ``https://`` URLs.
``no_proxy``
List of domain patterns for which no proxy should be used.
List entries are separated by ``,``. Patterns can include ``*``.
libdvdcss:
``DVDCSS_CACHE``
Specify a directory in which to store title key values. This will
speed up descrambling of DVDs which are in the cache. The
``DVDCSS_CACHE`` directory is created if it does not exist, and a
subdirectory is created named after the DVD's title or manufacturing
date. If ``DVDCSS_CACHE`` is not set or is empty, libdvdcss will use
the default value which is ``${HOME}/.dvdcss/`` under Unix and
the roaming application data directory (``%APPDATA%``) under
Windows. The special value "off" disables caching.
``DVDCSS_METHOD``
Sets the authentication and decryption method that libdvdcss will use
to read scrambled discs. Can be one of ``title``, ``key`` or ``disc``.
key
is the default method. libdvdcss will use a set of calculated
player keys to try and get the disc key. This can fail if the drive
does not recognize any of the player keys.
disc
is a fallback method when key has failed. Instead of using player
keys, libdvdcss will crack the disc key using a brute force
algorithm. This process is CPU intensive and requires 64 MB of
memory to store temporary data.
title
is the fallback when all other methods have failed. It does not
rely on a key exchange with the DVD drive, but rather uses a crypto
attack to guess the title key. On rare cases this may fail because
there is not enough encrypted data on the disc to perform a
statistical attack, but on the other hand it is the only way to
decrypt a DVD stored on a hard disc, or a DVD with the wrong region
on an RPC2 drive.
``DVDCSS_RAW_DEVICE``
Specify the raw device to use. Exact usage will depend on your
operating system, the Linux utility to set up raw devices is raw(8)
for instance. Please note that on most operating systems, using a raw
device requires highly aligned buffers: Linux requires a 2048 bytes
alignment (which is the size of a DVD sector).
``DVDCSS_VERBOSE``
Sets the libdvdcss verbosity level.
:0: Outputs no messages at all.
:1: Outputs error messages to stderr.
:2: Outputs error messages and debug messages to stderr.
``DVDREAD_NOKEYS``
Skip retrieving all keys on startup. Currently disabled.
``HOME``
FIXME: Document this.
EXIT CODES
==========
Normally **mpv** returns 0 as exit code after finishing playback successfully.
If errors happen, the following exit codes can be returned:
:1: Error initializing mpv. This is also returned if unknown options are
passed to mpv.
:2: The file passed to mpv couldn't be played. This is somewhat fuzzy:
currently, playback of a file is considered to be successful if
initialization was mostly successful, even if playback fails
immediately after initialization.
:3: There were some files that could be played, and some files which
couldn't (using the definition of success from above).
Note that quitting the player manually will always lead to exit code 0,
overriding the exit code that would be returned normally. Also, the ``quit``
input command can take an exit code: in this case, that exit code is returned.
FILES
=====
``/usr/local/etc/mpv/mpv.conf``
mpv system-wide settings (depends on ``--prefix`` passed to configure)
``~/.mpv/config``
mpv user settings
``~/.mpv/input.conf``
input bindings (see ``--input-keylist`` for the full list)
EXAMPLES OF MPV USAGE
=====================
Blu-ray playback:
- ``mpv bd:////path/to/disc``
- ``mpv bd:// --bluray-device=/path/to/disc``
Play in Japanese with English subtitles:
``mpv dvd://1 --alang=ja --slang=en``
Play only chapters 5, 6, 7:
``mpv dvd://1 --chapter=5-7``
Play only titles 5, 6, 7:
``mpv dvd://5-7``
Play a multiangle DVD:
``mpv dvd://1 --dvdangle=2``
Play from a different DVD device:
``mpv dvd://1 --dvd-device=/dev/dvd2``
Play DVD video from a directory with VOB files:
``mpv dvd://1 --dvd-device=/path/to/directory/``
Stream from HTTP:
``mpv http://example.com/example.avi``
Stream using RTSP:
``mpv rtsp://server.example.com/streamName``
Play a libavfilter graph:
``mpv avdevice://lavfi:mandelbrot``
AUTHORS
=======
mpv is a MPlayer fork based on mplayer2, which in turn is a fork of MPlayer.
MPlayer was initially written by Arpad Gereoffy. See the ``AUTHORS`` file for
a list of some of the many other contributors.
MPlayer is (C) 2000-2013 The MPlayer Team
This man page was written mainly by Gabucino, Jonas Jermann and Diego Biurrun.
File diff suppressed because it is too large. Load diff
+198
View File
@@ -0,0 +1,198 @@
ON SCREEN CONTROLLER
====================
The On Screen Controller (short: OSC) is a minimal GUI integrated with mpv to
offer basic mouse-controllability. It is intended to make interaction easier
for new users and to enable precise and direct seeking.
The OSC is enabled by default if mpv was compiled with lua support. It can be
disabled using ``--osc=no``.
Using the OSC
-------------
By default, the OSC will show up whenever the mouse is moved inside the
player window and will hide if the mouse is not moved outside the OSC for
0.5 seconds or if the mouse leaves the window.
The Interface
~~~~~~~~~~~~~
::
+------------------+-----------+--------------------+
| playlist prev | title | playlist next |
+-------+------+---+--+------+-+----+------+--------+
| audio | skip | seek | | seek | skip | full |
+-------+ back | back | play | frwd | frwd | screen |
| sub | | | | | | |
+-------+------+------+------+------+------+--------+
| seekbar |
+----------------+--------------+-------------------+
| time passed | cache status | time remaining |
+----------------+--------------+-------------------+
playlist prev
============= ================================================
left-click play previous file in playlist
shift+L-click show playlist
============= ================================================
title
| Displays current media-title or filename
============= ================================================
left-click show playlist position and length and full title
right-click show filename
============= ================================================
playlist next
============= ================================================
left-click play next file in playlist
shift+L-click show playlist
============= ================================================
audio and sub
| Displays selected track and amount of available tracks
============= ================================================
left-click cycle audio/sub tracks forward
right-click cycle audio/sub tracks backwards
shift+L-click show available audio/sub tracks
============= ================================================
skip back
============= ================================================
left-click go to beginning of chapter / previous chapter
shift+L-click show chapters
============= ================================================
seek back
============= ================================================
left-click skip back 5 seconds
right-click skip back 30 seconds
shift-L-click skip back 1 frame
============= ================================================
play
============= ================================================
left-click toggle play/pause
============= ================================================
seek frwd
============= ================================================
left-click skip forward 10 seconds
right-click skip forward 60 seconds
shift-L-click skip forward 1 frame
============= ================================================
skip frwd
============= ================================================
left-click go to next chapter
shift+L-click show chapters
============= ================================================
fullscreen
============= ================================================
left-click toggle fullscreen
============= ================================================
seekbar
| Indicates current playback position and position of chapters
============= ================================================
left-click seek to position
============= ================================================
time passed
| Shows current playback position timestamp
============= ================================================
left-click toggle displaying timecodes with milliseconds
============= ================================================
cache status
| Shows current cache fill status (only visible when below 48%)
time remaining
| Shows remaining playback time timestamp
============= ================================================
left-click toggle between total and remaining time
============= ================================================
Configuration
-------------
The OSC offers limited configuration through a config file ``plugin_osc.conf``
placed in mpv's user dir.
Config Syntax
~~~~~~~~~~~~~
The config file must exactly follow the following syntax::
# this is a comment
parameter1=value1
parameter2=value2
``#`` can only be used at the beginning of a line and there may be no
spaces around the ``=`` or anywhere else.
Configurable parameters
~~~~~~~~~~~~~~~~~~~~~~~
``showwindowed``
| Default: yes
| Show OSC when windowed?
``showfullscreen``
| Default: yes
| Show OSC when fullscreen?
``scalewindowed``
| Default: 1
| Scaling of the controller when windowed
``scalefullscreen``
| Default: 1
| Scaling of the controller when fullscreen
``scaleforcedwindow``
| Default: 2
| Scaling of the controller when rendered on a forced (dummy) window
``vidscale``
| Default: yes
| Scale the controller with the video?
``valign``
| Default: 0.8
| Vertical alignment, -1 (top) to 1 (bottom)
``halign``
| Default: 0
| Horizontal alignment, -1 (left) to 1 (right)
``hidetimeout``
| Default: 500
| Duration in ms until the OSC hides if no mouse movement, negative value
disables auto-hide
``fadeduration``
| Default: 200
| Duration of fade out in ms, 0 = no fade
``deadzonesize``
| Default: 0
| Size of the deadzone. The deadzone is an area that makes the mouse act
like leaving the window. Movement there won't make the OSC show up and
it will hide immediately if the mouse enters it.
``minmousemove``
| Default: 3
| Minimum amount of pixels the mouse has to move between ticks to make
the OSC show up
+880
View File
@@ -0,0 +1,880 @@
VIDEO FILTERS
=============
Video filters allow you to modify the video stream and its properties. The
syntax is:
``--vf=<filter1[=parameter1:parameter2:...],filter2,...>``
Setup a chain of video filters.
Many parameters are optional and set to default values if omitted. To
explicitly use a default value, set a parameter to '-1'. Parameters ``w:h``
means width x height in pixels, ``x:y`` means x;y position counted from the
upper left corner of the bigger image.
.. note::
To get a full list of available video filters, see ``--vf=help``.
Video filters are managed in lists. There are a few commands to manage the
filter list.
``--vf-add=<filter1[,filter2,...]>``
Appends the filters given as arguments to the filter list.
``--vf-pre=<filter1[,filter2,...]>``
Prepends the filters given as arguments to the filter list.
``--vf-del=<index1[,index2,...]>``
Deletes the filters at the given indexes. Index numbers start at 0,
negative numbers address the end of the list (-1 is the last).
``--vf-clr``
Completely empties the filter list.
With filters that support it, you can access parameters by their name.
``--vf=<filter>=help``
Prints the parameter names and parameter value ranges for a particular
filter.
``--vf=<filter=named_parameter1=value1[:named_parameter2=value2:...]>``
Sets a named parameter to the given value. Use on and off or yes and no to
set flag parameters.
Available filters are:
``crop[=w:h:x:y]``
Crops the given part of the image and discards the rest. Useful to remove
black bands from widescreen movies.
``<w>,<h>``
Cropped width and height, defaults to original width and height.
``<x>,<y>``
Position of the cropped picture, defaults to center.
``expand[=w:h:x:y:aspect:round]``
Expands (not scales) movie resolution to the given value and places the
unscaled original at coordinates x, y.
``<w>,<h>``
Expanded width,height (default: original width,height). Negative
values for w and h are treated as offsets to the original size.
.. admonition:: Example
``expand=0:-50:0:0``
Adds a 50 pixel border to the bottom of the picture.
``<x>,<y>``
position of original image on the expanded image (default: center)
``<aspect>``
Expands to fit an aspect instead of a resolution (default: 0).
.. admonition:: Example
``expand=800:::::4/3``
Expands to 800x600, unless the source is higher resolution, in
which case it expands to fill a 4/3 aspect.
``<round>``
Rounds up to make both width and height divisible by <r> (default: 1).
``flip``
Flips the image upside down. See also ``--flip``.
``mirror``
Mirrors the image on the Y axis.
``rotate[=<0-7>]``
Rotates the image by 90 degrees and optionally flips it. For values
between 4-7 rotation is only done if the movie geometry is portrait and
not landscape.
:0: Rotate by 90 degrees clockwise and flip (default).
:1: Rotate by 90 degrees clockwise.
:2: Rotate by 90 degrees counterclockwise.
:3: Rotate by 90 degrees counterclockwise and flip.
``scale[=w:h[:interlaced[:chr_drop[:par[:par2[:noup[:arnd]]]]]]]``
Scales the image with the software scaler (slow) and performs a YUV<->RGB
colorspace conversion (see also ``--sws``).
``<w>,<h>``
scaled width/height (default: original width/height)
:0: scaled d_width/d_height
:-1: original width/height
:-2: Calculate w/h using the other dimension and the prescaled
aspect ratio.
:-3: Calculate w/h using the other dimension and the original
aspect ratio.
:-(n+8): Like -n above, but rounding the dimension to the closest
multiple of 16.
``<chr_drop>``
chroma skipping
:0: Use all available input lines for chroma.
:1: Use only every 2. input line for chroma.
:2: Use only every 4. input line for chroma.
:3: Use only every 8. input line for chroma.
``<par>[:<par2>]`` (see also ``--sws``)
Set some scaling parameters depending on the type of scaler selected
with ``--sws``::
--sws=2 (bicubic): B (blurring) and C (ringing)
0.00:0.60 default
0.00:0.75 VirtualDub's "precise bicubic"
0.00:0.50 Catmull-Rom spline
0.33:0.33 Mitchell-Netravali spline
1.00:0.00 cubic B-spline
--sws=7 (gaussian): sharpness (0 (soft) - 100 (sharp))
--sws=9 (lanczos): filter length (1-10)
``<noup>``
Disallow upscaling past the original dimensions.
:0: Allow upscaling (default).
:1: Disallow upscaling if one dimension exceeds its original value.
:2: Disallow upscaling if both dimensions exceed their original values.
``<arnd>``
Accurate rounding for the vertical scaler, which may be faster or
slower than the default rounding.
:0: Disable accurate rounding (default).
:1: Enable accurate rounding.
``dsize[=aspect|w:h:aspect-method:r]``
Changes the intended display size/aspect at an arbitrary point in the
filter chain. Aspect can be given as a fraction (4/3) or floating point
number (1.33). Alternatively, you may specify the exact display width and
height desired. Note that this filter does *not* do any scaling itself; it
just affects what later scalers (software or hardware) will do when
auto-scaling to correct aspect.
``<w>,<h>``
New display width and height.
Can also be these special values:
:0: original display width and height
:-1: original video width and height (default)
:-2: Calculate w/h using the other dimension and the original display
aspect ratio.
:-3: Calculate w/h using the other dimension and the original video
aspect ratio.
.. admonition:: Example
``dsize=800:-2``
Specifies a display resolution of 800x600 for a 4/3 aspect
video, or 800x450 for a 16/9 aspect video.
``<aspect-method>``
Modifies width and height according to original aspect ratios.
:-1: Ignore original aspect ratio (default).
:0: Keep display aspect ratio by using ``<w>`` and ``<h>`` as maximum
resolution.
:1: Keep display aspect ratio by using ``<w>`` and ``<h>`` as minimum
resolution.
:2: Keep video aspect ratio by using ``<w>`` and ``<h>`` as maximum
resolution.
:3: Keep video aspect ratio by using ``<w>`` and ``<h>`` as minimum
resolution.
.. admonition:: Example
``dsize=800:600:0``
Specifies a display resolution of at most 800x600, or smaller,
in order to keep aspect.
``<r>``
Rounds up to make both width and height divisible by ``<r>``
(default: 1).
``format[=fmt[:outfmt]]``
Restricts the color space for the next filter without doing any conversion.
Use together with the scale filter for a real conversion.
.. note::
For a list of available formats, see ``format=fmt=help``.
``<fmt>``
Format name, e.g. rgb15, bgr24, 420p, etc. (default: yuyv).
``<outfmt>``
Format name that should be substituted for the output. If this is not
100% compatible with the ``<fmt>`` value, it will crash.
.. admonition:: Examples
====================== =====================
Valid Invalid (will crash)
====================== =====================
``format=rgb24:bgr24`` ``format=rgb24:420p``
``format=yuyv:uyvy``
====================== =====================
``noformat[=fmt]``
Restricts the colorspace for the next filter without doing any conversion.
Unlike the format filter, this will allow any colorspace except the one
you specify.
.. note:: For a list of available formats, see ``noformat=fmt=help``.
``<fmt>``
Format name, e.g. rgb15, bgr24, 420p, etc. (default: 420p).
``pp[=filter1[:option1[:option2...]]/[-]filter2...]``
Enables the specified chain of postprocessing subfilters. Subfilters must
be separated by '/' and can be disabled by prepending a '-'. Each
subfilter and some options have a short and a long name that can be used
interchangeably, i.e. ``dr``/``dering`` are the same. All subfilters share
common options to determine their scope:
``a/autoq``
Automatically switch the subfilter off if the CPU is too slow.
``c/chrom``
Do chrominance filtering, too (default).
``y/nochrom``
Do luminance filtering only (no chrominance).
``n/noluma``
Do chrominance filtering only (no luminance).
.. note::
``--pphelp`` shows a list of available subfilters.
Available subfilters are:
``hb/hdeblock[:difference[:flatness]]``
horizontal deblocking filter
:<difference>: Difference factor where higher values mean more
deblocking (default: 32).
:<flatness>: Flatness threshold where lower values mean more
deblocking (default: 39).
``vb/vdeblock[:difference[:flatness]]``
vertical deblocking filter
:<difference>: Difference factor where higher values mean more
deblocking (default: 32).
:<flatness>: Flatness threshold where lower values mean more
deblocking (default: 39).
``ha/hadeblock[:difference[:flatness]]``
accurate horizontal deblocking filter
:<difference>: Difference factor where higher values mean more
deblocking (default: 32).
:<flatness>: Flatness threshold where lower values mean more
deblocking (default: 39).
``va/vadeblock[:difference[:flatness]]``
accurate vertical deblocking filter
:<difference>: Difference factor where higher values mean more
deblocking (default: 32).
:<flatness>: Flatness threshold where lower values mean more
deblocking (default: 39).
The horizontal and vertical deblocking filters share the difference and
flatness values so you cannot set different horizontal and vertical
thresholds.
``h1/x1hdeblock``
experimental horizontal deblocking filter
``v1/x1vdeblock``
experimental vertical deblocking filter
``dr/dering``
deringing filter
``tn/tmpnoise[:threshold1[:threshold2[:threshold3]]]``
temporal noise reducer
:<threshold1>: larger -> stronger filtering
:<threshold2>: larger -> stronger filtering
:<threshold3>: larger -> stronger filtering
``al/autolevels[:f/fullyrange]``
automatic brightness / contrast correction
:f/fullyrange: Stretch luminance to (0-255).
``lb/linblenddeint``
Linear blend deinterlacing filter that deinterlaces the given block by
filtering all lines with a (1 2 1) filter.
``li/linipoldeint``
Linear interpolating deinterlacing filter that deinterlaces the given
block by linearly interpolating every second line.
``ci/cubicipoldeint``
Cubic interpolating deinterlacing filter deinterlaces the given block
by cubically interpolating every second line.
``md/mediandeint``
Median deinterlacing filter that deinterlaces the given block by
applying a median filter to every second line.
``fd/ffmpegdeint``
FFmpeg deinterlacing filter that deinterlaces the given block by
filtering every second line with a (-1 4 2 4 -1) filter.
``l5/lowpass5``
Vertically applied FIR lowpass deinterlacing filter that deinterlaces
the given block by filtering all lines with a (-1 2 6 2 -1) filter.
``fq/forceQuant[:quantizer]``
Overrides the quantizer table from the input with the constant
quantizer you specify.
:<quantizer>: quantizer to use
``de/default``
default pp filter combination (hb:a,vb:a,dr:a)
``fa/fast``
fast pp filter combination (h1:a,v1:a,dr:a)
``ac``
high quality pp filter combination (ha:a:128:7,va:a,dr:a)
.. note::
This filter is only available if FFmpeg/libav has been compiled
with libpostproc enabled.
.. admonition:: Examples
``--vf=pp=hb/vb/dr/al``
horizontal and vertical deblocking, deringing and automatic
brightness/contrast
``--vf=pp=de/-al``
default filters without brightness/contrast correction
``--vf=pp=default/tmpnoise:1:2:3``
Enable default filters & temporal denoiser.
``--vf=pp=hb:y/vb:a``
Horizontal deblocking on luminance only, and switch vertical
deblocking on or off automatically depending on available CPU time.
``lavfi=graph[:sws_flags[:o=opts]]``
Filter video using FFmpeg's libavfilter.
``<graph>``
The libavfilter graph string. The filter must have a single video input
pad and a single video output pad.
See `<https://ffmpeg.org/ffmpeg-filters.html>`_ for syntax and available
filters.
.. warning::
If you want to use the full filter syntax with this option, you have
to quote the filter graph in order to prevent mpv's syntax and the
filter graph syntax from clashing.
.. admonition:: Examples
``-vf lavfi=[gradfun=20:30,vflip]``
``gradfun`` filter with nonsense parameters, followed by a
``vflip`` filter. (This demonstrates how libavfilter takes a
graph and not just a single filter.) The filter graph string is
quoted with ``[`` and ``]``. This requires no additional quoting
or escaping with some shells (like bash), while others (like
zsh) require additional ``"`` quotes around the option string.
``'--vf=lavfi="gradfun=20:30,vflip"'``
Same as before, but uses quoting that should be safe with all
shells. The outer ``'`` quotes make sure that the shell does not
remove the ``"`` quotes needed by mpv.
``'--vf=lavfi=graph="gradfun=radius=30:strength=20,vflip"'``
Same as before, but uses named parameters for everything.
``<sws_flags>``
If libavfilter inserts filters for pixel format conversion, this
option gives the flags which should be passed to libswscale. This
option is numeric and takes a bit-wise combination of ``SWS_`` flags.
See ``http://git.videolan.org/?p=ffmpeg.git;a=blob;f=libswscale/swscale.h``.
``<o>``
Set AVFilterGraph options. These should be documented by FFmpeg.
.. admonition:: Example
``'--vf=lavfi=yadif:o="threads=2,thread_type=slice"'``
forces a specific threading configuration.
``noise[=luma[u][t|a][h][p]:chroma[u][t|a][h][p]]``
Adds noise.
:<0-100>: luma noise
:<0-100>: chroma noise
:u: uniform noise (gaussian otherwise)
:t: temporal noise (noise pattern changes between frames)
:a: averaged temporal noise (smoother, but a lot slower)
:h: high quality (slightly better looking, slightly slower)
:p: mix random noise with a (semi)regular pattern
.. note::
Deprecated. Use libavfilter's ``noise`` filter through ``--vf=lavfi``
instead.
``hqdn3d[=luma_spatial:chroma_spatial:luma_tmp:chroma_tmp]``
This filter aims to reduce image noise producing smooth images and making
still images really still (This should enhance compressibility.).
``<luma_spatial>``
spatial luma strength (default: 4)
``<chroma_spatial>``
spatial chroma strength (default: 3)
``<luma_tmp>``
luma temporal strength (default: 6)
``<chroma_tmp>``
chroma temporal strength (default:
``luma_tmp*chroma_spatial/luma_spatial``)
.. note::
Deprecated. Use libavfilter's ``hqdn3d`` filter through ``--vf=lavfi``
instead.
``eq[=gamma:contrast:brightness:saturation:rg:gg:bg:weight]``
Software equalizer that uses lookup tables (slow), allowing gamma correction
in addition to simple brightness and contrast adjustment. The parameters are
given as floating point values.
``<0.1-10>``
initial gamma value (default: 1.0)
``<-2-2>``
initial contrast, where negative values result in a negative image
(default: 1.0)
``<-1-1>``
initial brightness (default: 0.0)
``<0-3>``
initial saturation (default: 1.0)
``<0.1-10>``
gamma value for the red component (default: 1.0)
``<0.1-10>``
gamma value for the green component (default: 1.0)
``<0.1-10>``
gamma value for the blue component (default: 1.0)
``<0-1>``
The weight parameter can be used to reduce the effect of a high gamma
value on bright image areas, e.g. keep them from getting overamplified
and just plain white. A value of 0.0 turns the gamma correction all
the way down while 1.0 leaves it at its full strength (default: 1.0).
``ilpack[=mode]``
When interlaced video is stored in YUV 4:2:0 formats, chroma interlacing
does not line up properly due to vertical downsampling of the chroma
channels. This filter packs the planar 4:2:0 data into YUY2 (4:2:2) format
with the chroma lines in their proper locations, so that in any given
scanline, the luma and chroma data both come from the same field.
``<mode>``
Select the sampling mode.
:0: nearest-neighbor sampling, fast but incorrect
:1: linear interpolation (default)
``unsharp[=l|cWxH:amount[:l|cWxH:amount]]``
unsharp mask / gaussian blur
``l``
Apply effect on luma component.
``c``
Apply effect on chroma components.
``<width>x<height>``
width and height of the matrix, odd sized in both directions (min =
3x3, max = 13x11 or 11x13, usually something between 3x3 and 7x7)
``amount``
Relative amount of sharpness/blur to add to the image (a sane range
should be -1.5-1.5).
:<0: blur
:>0: sharpen
.. note::
Deprecated. Use libavfilter's ``unsharp`` filter through ``--vf=lavfi``
instead.
``swapuv``
Swap U & V plane.
.. note::
Deprecated. Use libavfilter's ``swapuv`` filter through ``--vf=lavfi``
instead.
``pullup[=jl:jr:jt:jb:sb:mp]``
Pulldown reversal (inverse telecine) filter, capable of handling mixed
hard-telecine, 24000/1001 fps progressive, and 30000/1001 fps progressive
content. The ``pullup`` filter makes use of future context in making its
decisions. It is stateless in the sense that it does not lock onto a pattern
to follow, but it instead looks forward to the following fields in order to
identify matches and rebuild progressive frames.
``jl``, ``jr``, ``jt``, and ``jb``
These options set the amount of "junk" to ignore at the left, right,
top, and bottom of the image, respectively. Left/right are in units of
8 pixels, while top/bottom are in units of 2 lines. The default is 8
pixels on each side.
``sb`` (strict breaks)
Setting this option to 1 will reduce the chances of ``pullup``
generating an occasional mismatched frame, but it may also cause an
excessive number of frames to be dropped during high motion sequences.
Conversely, setting it to -1 will make ``pullup`` match fields more
easily. This may help processing of video where there is slight
blurring between the fields, but may also cause there to be interlaced
frames in the output.
``mp`` (metric plane)
This option may be set to 1 or 2 to use a chroma plane instead of the
luma plane for doing ``pullup``'s computations. This may improve accuracy
on very clean source material, but more likely will decrease accuracy,
especially if there is chroma noise (rainbow effect) or any grayscale
video. The main purpose of setting ``mp`` to a chroma plane is to reduce
CPU load and make pullup usable in realtime on slow machines.
``divtc[=options]``
Inverse telecine for deinterlaced video. If 3:2-pulldown telecined video
has lost one of the fields or is deinterlaced using a method that keeps
one field and interpolates the other, the result is a juddering video that
has every fourth frame duplicated. This filter is intended to find and
drop those duplicates and restore the original film framerate. Two
different modes are available: One-pass mode is the default and is
straightforward to use, but has the disadvantage that any changes in the
telecine phase (lost frames or bad edits) cause momentary judder until the
filter can resync again. Two-pass mode avoids this by analyzing the entire
video beforehand so it will have forward knowledge about the phase changes
and can resync at the exact spot. These passes do *not* correspond to pass
one and two of the encoding process. You must run an extra pass using
``divtc`` pass one before the actual encoding throwing the resulting video
away. Then use ``divtc`` pass two for the actual encoding. If you use
multiple encoder passes, use ``divtc`` pass two for all of them.
The options are:
``pass=1|2``
Use two pass mode.
``file=<filename>``
Set the two pass log filename (default: ``framediff.log``).
``threshold=<value>``
Set the minimum strength the telecine pattern must have for the filter
to believe in it (default: 0.5). This is used to avoid recognizing
false pattern from the parts of the video that are very dark or very
still.
``window=<numframes>``
Set the number of past frames to look at when searching for pattern
(default: 30). Longer window improves the reliability of the pattern
search, but shorter window improves the reaction time to the changes
in the telecine phase. This only affects the one-pass mode. The
two-pass mode currently uses fixed window that extends to both future
and past.
``phase=0|1|2|3|4``
Sets the initial telecine phase for one pass mode (default: 0). The
two-pass mode can see the future, so it is able to use the correct
phase from the beginning, but one-pass mode can only guess. It catches
the correct phase when it finds it, but this option can be used to fix
the possible juddering at the beginning. The first pass of the two
pass mode also uses this, so if you save the output from the first
pass, you get constant phase result.
``deghost=<value>``
Set the deghosting threshold (0-255 for one-pass mode, -255-255 for
two-pass mode, default 0). If nonzero, deghosting mode is used. This
is for video that has been deinterlaced by blending the fields
together instead of dropping one of the fields. Deghosting amplifies
any compression artifacts in the blended frames, so the parameter
value is used as a threshold to exclude those pixels from deghosting
that differ from the previous frame less than specified value. If two
pass mode is used, then negative value can be used to make the filter
analyze the whole video in the beginning of pass-2 to determine
whether it needs deghosting or not and then select either zero or the
absolute value of the parameter. Specify this option for pass 2, it
makes no difference on pass 1.
``phase[=t|b|p|a|u|T|B|A|U][:v]``
Delay interlaced video by one field time so that the field order changes.
The intended use is to fix PAL movies that have been captured with the
opposite field order to the film-to-video transfer. The options are:
``t``
Capture field order top-first, transfer bottom-first. Filter will
delay the bottom field.
``b``
Capture bottom-first, transfer top-first. Filter will delay the top
field.
``p``
Capture and transfer with the same field order. This mode only exists
for the documentation of the other options to refer to, but if you
actually select it, the filter will faithfully do nothing ;-)
``a``
Capture field order determined automatically by field flags, transfer
opposite. Filter selects among ``t`` and ``b`` modes on a frame by frame
basis using field flags. If no field information is available, then this
works just like ``u``.
``u``
Capture unknown or varying, transfer opposite. Filter selects among
``t`` and ``b`` on a frame by frame basis by analyzing the images and
selecting the alternative that produces best match between the fields.
``T``
Capture top-first, transfer unknown or varying. Filter selects among
``t`` and ``p`` using image analysis.
``B``
Capture bottom-first, transfer unknown or varying. Filter selects
among ``b`` and ``p`` using image analysis.
``A``
Capture determined by field flags, transfer unknown or varying. Filter
selects among ``t``, ``b`` and ``p`` using field flags and image
analysis. If no field information is available, then this works just
like ``U``. This is the default mode.
``U``
Both capture and transfer unknown or varying. Filter selects among
``t``, ``b`` and ``p`` using image analysis only.
``v``
Verbose operation. Prints the selected mode for each frame and the
average squared difference between fields for ``t``, ``b``, and ``p``
alternatives.
``yadif=[mode[:enabled=yes|no]]``
Yet another deinterlacing filter
``<mode>``
:0: Output 1 frame for each frame.
:1: Output 1 frame for each field.
:2: Like 0 but skips spatial interlacing check.
:3: Like 1 but skips spatial interlacing check.
``<enabled>``
:yes: Filter is active (default).
:no: Filter is not active, but can be activated with the ``D`` key
(or any other key that toggles the ``deinterlace`` property).
.. note::
Deprecated. Use libavfilter's ``yadif`` filter through ``--vf=lavfi``
instead.
This filter, or libavfilter's implementation if available, is automatically
inserted when using the ``D`` key (or any other key that toggles the
``deinterlace`` property), assuming the video output does not have native
deinterlacing support.
``down3dright[=lines]``
Reposition and resize stereoscopic images. Extracts both stereo fields and
places them side by side, resizing them to maintain the original movie
aspect.
``<lines>``
number of lines to select from the middle of the image (default: 12)
``delogo[=x:y:w:h:t]``
Suppresses a TV station logo by a simple interpolation of the surrounding
pixels. Just set a rectangle covering the logo and watch it disappear (and
sometimes something even uglier appear - your mileage may vary).
``<x>,<y>``
top left corner of the logo
``<w>,<h>``
width and height of the cleared rectangle
``<t>``
Thickness of the fuzzy edge of the rectangle (added to ``w`` and
``h``). When set to -1, a green rectangle is drawn on the screen to
simplify finding the right ``x``,``y``,``w``,``h`` parameters.
``file=<file>``
You can specify a text file to load the coordinates from. Each line
must have a timestamp (in seconds, and in ascending order) and the
``x:y:w:h:t`` coordinates (``t`` can be omitted).
.. note::
Deprecated. Use libavfilter's ``delogo`` or ``removelogo`` filters
through ``--vf=lavfi`` instead.
``screenshot``
Optional filter for screenshot support. This is only needed if the video
output does not provide working direct screenshot support. Note that it is
not always safe to insert this filter by default. See `TAKING SCREENSHOTS`_
for details.
``sub=[=bottom-margin:top-margin]``
Moves subtitle rendering to an arbitrary point in the filter chain, or force
subtitle rendering in the video filter as opposed to using video output OSD
support.
``<bottom-margin>``
Adds a black band at the bottom of the frame. The SSA/ASS renderer can
place subtitles there (with ``--ass-use-margins``).
``<top-margin>``
Black band on the top for toptitles (with ``--ass-use-margins``).
.. admonition:: Examples
``--vf=sub,eq``
Moves sub rendering before the eq filter. This will put both
subtitle colors and video under the influence of the video equalizer
settings.
``stereo3d[=in:out]``
Stereo3d converts between different stereoscopic image formats.
``<in>``
Stereoscopic image format of input. Possible values:
``sbsl`` or ``side_by_side_left_first``
side by side parallel (left eye left, right eye right)
``sbsr`` or ``side_by_side_right_first``
side by side crosseye (right eye left, left eye right)
``abl`` or ``above_below_left_first``
above-below (left eye above, right eye below)
``abr`` or ``above_below_right_first``
above-below (right eye above, left eye below)
``ab2l`` or ``above_below_half_height_left_first``
above-below with half height resolution (left eye above, right eye
below)
``ab2r`` or ``above_below_half_height_right_first``
above-below with half height resolution (right eye above, left eye
below)
``<out>``
Stereoscopic image format of output. Possible values are all the input
formats as well as:
``arcg`` or ``anaglyph_red_cyan_gray``
anaglyph red/cyan gray (red filter on left eye, cyan filter on
right eye)
``arch`` or ``anaglyph_red_cyan_half_color``
anaglyph red/cyan half colored (red filter on left eye, cyan filter
on right eye)
``arcc`` or ``anaglyph_red_cyan_color``
anaglyph red/cyan color (red filter on left eye, cyan filter on
right eye)
``arcd`` or ``anaglyph_red_cyan_dubois``
anaglyph red/cyan color optimized with the least squares
projection of dubois (red filter on left eye, cyan filter on right
eye)
``agmg`` or ``anaglyph_green_magenta_gray``
anaglyph green/magenta gray (green filter on left eye, magenta
filter on right eye)
``agmh`` or ``anaglyph_green_magenta_half_color``
anaglyph green/magenta half colored (green filter on left eye,
magenta filter on right eye)
``agmc`` or ``anaglyph_green_magenta_color``
anaglyph green/magenta colored (green filter on left eye, magenta
filter on right eye)
``aybg`` or ``anaglyph_yellow_blue_gray``
anaglyph yellow/blue gray (yellow filter on left eye, blue filter
on right eye)
``aybh`` or ``anaglyph_yellow_blue_half_color``
anaglyph yellow/blue half colored (yellow filter on left eye, blue
filter on right eye)
``aybc`` or ``anaglyph_yellow_blue_color``
anaglyph yellow/blue colored (yellow filter on left eye, blue
filter on right eye)
``irl`` or ``interleave_rows_left_first``
Interleaved rows (left eye has top row, right eye starts on next
row)
``irr`` or ``interleave_rows_right_first``
Interleaved rows (right eye has top row, left eye starts on next
row)
``ml`` or ``mono_left``
mono output (left eye only)
``mr`` or ``mono_right``
mono output (right eye only)
.. note::
Deprecated. Use libavfilter's ``stereo3d`` filter through ``--vf=lavfi``
instead.
``gradfun[=strength[:radius]]``
Fix the banding artifacts that are sometimes introduced into nearly flat
regions by truncation to 8bit color depth. Interpolates the gradients that
should go where the bands are, and dithers them.
``<strength>``
Maximum amount by which the filter will change any one pixel. Also the
threshold for detecting nearly flat regions (default: 1.2).
``<radius>``
Neighborhood to fit the gradient to. Larger radius makes for smoother
gradients, but also prevents the filter from modifying pixels near
detailed regions (default: 16).
.. note::
Deprecated. Use libavfilter's ``gradfun`` filter through ``--vf=lavfi``
instead.
``dlopen=dll[:a0[:a1[:a2[:a3]]]]``
Loads an external library to filter the image. The library interface
is the ``vf_dlopen`` interface specified using ``libmpcodecs/vf_dlopen.h``.
``dll=<library>``
Specify the library to load. This may require a full file system path
in some cases. This argument is required.
``a0=<string>``
Specify the first parameter to pass to the library.
``a1=<string>``
Specify the second parameter to pass to the library.
``a2=<string>``
Specify the third parameter to pass to the library.
``a3=<string>``
Specify the fourth parameter to pass to the library.
``vavpp``
VA-API video post processing. Works with ``--vo=vaapi`` only. Currently
deinterlaces. This filter is automatically inserted if deinterlacing is
requested (either using the ``D`` key, by default mapped to the command
``cycle deinterlace``, or the ``--deinterlace`` option).
``deint=<method>``
Select the deinterlacing algorithm.
no
Don't perform deinterlacing.
first-field
Show only first field (going by ``--field-dominance``).
bob
bob deinterlacing (default).
+779
View File
@@ -0,0 +1,779 @@
VIDEO OUTPUT DRIVERS
====================
Video output drivers are interfaces to different video output facilities. The
syntax is:
``--vo=<driver1[:suboption1[=value]:...],driver2,...[,]>``
Specify a priority list of video output drivers to be used.
If the list has a trailing ',', mpv will fall back on drivers not contained
in the list. Suboptions are optional and can mostly be omitted.
.. note::
See ``--vo=help`` for a list of compiled-in video output drivers.
.. admonition:: Example
``--vo=opengl,xv,``
Try the ``opengl`` driver, then the ``xv`` driver, then others.
Available video output drivers are:
``xv`` (X11 only)
Uses the XVideo extension to enable hardware-accelerated display. This is
the most compatible VO on X, but may be low-quality, and has issues with
OSD and subtitle display.
``adaptor=<number>``
Select a specific XVideo adaptor (check xvinfo results).
``port=<number>``
Select a specific XVideo port.
``ck=<cur|use|set>``
Select the source from which the colorkey is taken (default: cur).
cur
The default takes the colorkey currently set in Xv.
use
Use but do not set the colorkey from mpv (use the ``--colorkey``
option to change it).
set
Same as use but also sets the supplied colorkey.
``ck-method=<man|bg|auto>``
Sets the colorkey drawing method (default: man).
man
Draw the colorkey manually (reduces flicker in some cases).
bg
Set the colorkey as window background.
auto
Let Xv draw the colorkey.
``colorkey=<number>``
Changes the colorkey to an RGB value of your choice. ``0x000000`` is
black and ``0xffffff`` is white.
``no-colorkey``
Disables colorkeying.
``x11`` (X11 only)
Shared memory video output driver without hardware acceleration that works
whenever X11 is present.
.. note:: This is a fallback only, and should not be normally used.
``vdpau`` (X11 only)
Uses the VDPAU interface to display and optionally also decode video.
Hardware decoding is used with ``--hwdec=vdpau``.
``sharpen=<-1-1>``
For positive values, apply a sharpening algorithm to the video, for
negative values a blurring algorithm (default: 0).
``denoise=<0-1>``
Apply a noise reduction algorithm to the video (default: 0; no noise
reduction).
``deint=<-4-4>``
Select deinterlacing mode (default: -3). Positive values choose mode
and enable deinterlacing. Corresponding negative values select the
same deinterlacing mode, but do not enable deinterlacing on startup
(useful in configuration files to specify which mode will be enabled by
the "D" key). All modes respect ``--field-dominance``.
0
Same as -3.
1
Show only first field.
2
Bob deinterlacing.
3
Motion-adaptive temporal deinterlacing. May lead to A/V desync
with slow video hardware and/or high resolution.
4
Motion-adaptive temporal deinterlacing with edge-guided spatial
interpolation. Needs fast video hardware.
``chroma-deint``
Makes temporal deinterlacers operate both on luma and chroma (default).
Use no-chroma-deint to solely use luma and speed up advanced
deinterlacing. Useful with slow video memory.
``pullup``
Try to apply inverse telecine, needs motion adaptive temporal
deinterlacing.
``hqscaling=<0-9>``
0
Use default VDPAU scaling (default).
1-9
Apply high quality VDPAU scaling (needs capable hardware).
``fps=<number>``
Override autodetected display refresh rate value (the value is needed
for framedrop to allow video playback rates higher than display
refresh rate, and for vsync-aware frame timing adjustments). Default 0
means use autodetected value. A positive value is interpreted as a
refresh rate in Hz and overrides the autodetected value. A negative
value disables all timing adjustment and framedrop logic.
``composite-detect``
NVIDIA's current VDPAU implementation behaves somewhat differently
under a compositing window manager and does not give accurate frame
timing information. With this option enabled, the player tries to
detect whether a compositing window manager is active. If one is
detected, the player disables timing adjustments as if the user had
specified ``fps=-1`` (as they would be based on incorrect input). This
means timing is somewhat less accurate than without compositing, but
with the composited mode behavior of the NVIDIA driver, there is no
hard playback speed limit even without the disabled logic. Enabled by
default, use ``no-composite-detect`` to disable.
``queuetime_windowed=<number>`` and ``queuetime_fs=<number>``
Use VDPAU's presentation queue functionality to queue future video
frame changes at most this many milliseconds in advance (default: 50).
See below for additional information.
``output_surfaces=<2-15>``
Allocate this many output surfaces to display video frames (default:
3). See below for additional information.
``colorkey=<#RRGGBB|#AARRGGBB>``
Set the VDPAU presentation queue background color, which in practice
is the colorkey used if VDPAU operates in overlay mode (default:
``#020507``, some shade of black). If the alpha component of this value
is 0, the default VDPAU colorkey will be used instead (which is usually
green).
``force-yuv``
Never accept RGBA input. This means mpv will insert a filter to convert
to a YUV format before the VO. Sometimes useful to force availability
of certain YUV-only features, like video equalizer or deinterlacing.
Using the VDPAU frame queueing functionality controlled by the queuetime
options makes mpv's frame flip timing less sensitive to system CPU load and
allows mpv to start decoding the next frame(s) slightly earlier, which can
reduce jitter caused by individual slow-to-decode frames. However, the
NVIDIA graphics drivers can make other window behavior such as window moves
choppy if VDPAU is using the blit queue (mainly happens if you have the
composite extension enabled) and this feature is active. If this happens on
your system and it bothers you then you can set the queuetime value to 0 to
disable this feature. The settings to use in windowed and fullscreen mode
are separate because there should be no reason to disable this for
fullscreen mode (as the driver issue should not affect the video itself).
You can queue more frames ahead by increasing the queuetime values and the
``output_surfaces`` count (to ensure enough surfaces to buffer video for a
certain time ahead you need at least as many surfaces as the video has
frames during that time, plus two). This could help make video smoother in
some cases. The main downsides are increased video RAM requirements for
the surfaces and laggier display response to user commands (display
changes only become visible some time after they're queued). The graphics
driver implementation may also have limits on the length of maximum
queuing time or number of queued surfaces that work well or at all.
``direct3d_shaders`` (Windows only)
Video output driver that uses the Direct3D interface.
``prefer-stretchrect``
Use ``IDirect3DDevice9::StretchRect`` over other methods if possible.
``disable-stretchrect``
Never render the video using ``IDirect3DDevice9::StretchRect``.
``disable-textures``
Never render the video using D3D texture rendering. Rendering with
textures + shader will still be allowed. Add ``disable-shaders`` to
completely disable video rendering with textures.
``disable-shaders``
Never use shaders when rendering video.
``only-8bit``
Never render YUV video with more than 8 bits per component.
Using this flag will force software conversion to 8-bit.
``disable-texture-align``
Normally texture sizes are always aligned to 16. With this option
enabled, the video texture will always have exactly the same size as
the video itself.
Debug options. These might be incorrect, might be removed in the future,
might crash, might cause slow downs, etc. Contact the developers if you
actually need any of these for performance or proper operation.
``force-power-of-2``
Always force textures to power of 2, even if the device reports
non-power-of-2 texture sizes as supported.
``texture-memory=N``
Only affects operation with shaders/texturing enabled, and (E)OSD.
Values for N:
0
default, will often use an additional shadow texture + copy
1
use ``D3DPOOL_MANAGED``
2
use ``D3DPOOL_DEFAULT``
3
use ``D3DPOOL_SYSTEMMEM``, but without shadow texture
``swap-discard``
Use ``D3DSWAPEFFECT_DISCARD``, which might be faster.
Might be slower too, as it must(?) clear every frame.
``exact-backbuffer``
Always resize the backbuffer to window size.
``direct3d`` (Windows only)
Same as ``direct3d_shaders``, but with the options ``disable-textures``
and ``disable-shaders`` forced.
``corevideo`` (Mac OS X 10.6 and later)
Mac OS X CoreVideo video output driver. Uses the CoreVideo APIs to fill
PixelBuffers and generate OpenGL textures from them (useful as a fallback
for ``opengl``).
``opengl``
OpenGL video output driver. It supports extended scaling methods, dithering
and color management.
By default, it tries to use fast and fail-safe settings. Use the alias
``opengl-hq`` to use this driver with defaults set to high quality
rendering.
Requires at least OpenGL 2.1 and the ``GL_ARB_texture_rg`` extension. For
older drivers, ``opengl-old`` may work.
Some features are available with OpenGL 3 capable graphics drivers only
(or if the necessary extensions are available).
``lscale=<filter>``
``bilinear``
Bilinear hardware texture filtering (fastest, mid-quality).
This is the default.
``lanczos2``
Lanczos scaling with radius=2. Provides good quality and speed.
This is the default when using ``opengl-hq``.
``lanczos3``
Lanczos with radius=3.
``bicubic_fast``
Bicubic filter. Has a blurring effect on the image, even if no
scaling is done.
``sharpen3``
Unsharp masking (sharpening) with radius=3 and a default strength
of 0.5 (see ``lparam1``).
``sharpen5``
Unsharp masking (sharpening) with radius=5 and a default strength
of 0.5 (see ``lparam1``).
``mitchell``
Mitchell-Netravali. The ``b`` and ``c`` parameters can be set with
``lparam1`` and ``lparam2``. Both are set to 1/3 by default.
There are some more filters. For a complete list, pass ``help`` as
value, e.g.::
mpv --vo=opengl:lscale=help
``lparam1=<value>``
Set filter parameters. Ignored if the filter is not tunable. These are
unset by default, and use the filter specific default if applicable.
``lparam2=<value>``
See ``lparam1``.
``scaler-resizes-only``
Disable the scaler if the video image is not resized. In that case,
``bilinear`` is used instead whatever is set with ``lscale``. Bilinear
will reproduce the source image perfectly if no scaling is performed.
Note that this option never affects ``cscale``, although the different
processing chain might do chroma scaling differently if ``lscale`` is
disabled.
``stereo=<value>``
Select a method for stereo display. You may have to use ``--aspect`` to
fix the aspect value. Experimental, do not expect too much from it.
no
Normal 2D display
red-cyan
Convert side by side input to full-color red-cyan stereo.
green-magenta
Convert side by side input to full-color green-magenta stereo.
quadbuffer
Convert side by side input to quadbuffered stereo. Only supported
by very few OpenGL cards.
``srgb``
Enable gamma-correct scaling by working in linear light. This
makes use of sRGB textures and framebuffers.
This option forces the options ``indirect`` and ``gamma``.
.. note::
for YUV colorspaces, gamma 1/0.45 (2.222) is assumed. RGB input is
always assumed to be in sRGB.
This option is not really useful, as gamma-correct scaling has not much
influence on typical video playback. Most visible effect comes from
slightly different gamma.
``pbo``
Enable use of PBOs. This is faster, but can sometimes lead to sporadic
and temporary image corruption.
``dither-depth=<N|no|auto>``
Set dither target depth to N. Default: no.
no
Disable any dithering done by mpv.
auto
Automatic selection. If output bit depth cannot be detected,
8 bits per component are assumed.
8
Dither to 8 bit output.
Note that the depth of the connected video display device can not be
detected. Often, LCD panels will do dithering on their own, which
conflicts with ``opengl``'s dithering and leads to ugly output.
``dither-size-fruit=<2-8>``
Set the size of the dither matrix (default: 6). The actual size of
the matrix is ``(2^N) x (2^N)`` for an option value of ``N``, so a
value of 6 gives a size of 64x64. The matrix is generated at startup
time, and a large matrix can take rather long to compute (seconds).
Used in ``dither=fruit`` mode only.
``dither=<fruit|ordered|no>``
Select dithering algorithm (default: fruit).
``temporal-dither``
Enable temporal dithering. (Only active if dithering is enabled in
general.) This changes between 8 different dithering pattern on each
frame by changing the orientation of the tiled dithering matrix.
Unfortunately, this can lead to flicker on LCD displays, since these
have a high reaction time.
``debug``
Check for OpenGL errors, i.e. call ``glGetError()``. Also request a
debug OpenGL context (which does nothing with current graphics drivers
as of this writing).
``swapinterval=<n>``
Interval in displayed frames between two buffer swaps.
1 is equivalent to enable VSYNC, 0 to disable VSYNC.
``no-scale-sep``
When using a separable scale filter for luma, usually two filter
passes are done. This is often faster. However, it forces
conversion to RGB in an extra pass, so it can actually be slower
if used with fast filters on small screen resolutions. Using
this options will make rendering a single operation.
Note that chroma scalers are always done as 1-pass filters.
``cscale=<n>``
As ``lscale``, but for chroma (2x slower with little visible effect).
Note that with some scaling filters, upscaling is always done in
RGB. If chroma is not subsampled, this option is ignored, and the
luma scaler is used instead. Setting this option is often useless.
``fancy-downscaling``
When using convolution based filters, extend the filter size
when downscaling. Trades quality for reduced downscaling performance.
``no-npot``
Force use of power-of-2 texture sizes. For debugging only.
Borders will be distorted due to filtering.
``glfinish``
Call ``glFinish()`` before swapping buffers
``sw``
Continue even if a software renderer is detected.
``backend=<sys>``
The value ``auto`` (the default) selects the windowing backend. You
can also pass ``help`` to get a complete list of compiled in backends
(sorted by autoprobe order).
auto
auto-select (default)
cocoa
Cocoa/OSX
win
Win32/WGL
x11
X11/GLX
wayland
Wayland/EGL
``indirect``
Do YUV conversion and scaling as separate passes. This will first render
the video into a video-sized RGB texture, and draw the result on screen.
The luma scaler is used to scale the RGB image when rendering to screen.
The chroma scaler is used only on YUV conversion, and only if the video
is chroma-subsampled (usually the case).
This mechanism is disabled on RGB input.
Specifying this option directly is generally useful for debugging only.
``fbo-format=<fmt>``
Selects the internal format of textures used for FBOs. The format can
influence performance and quality of the video output. (FBOs are not
always used, and typically only when using extended scalers.)
``fmt`` can be one of: rgb, rgba, rgb8, rgb10, rgb10_a2, rgb16, rgb16f,
rgb32f, rgba12, rgba16, rgba16f, rgba32f.
Default: rgb.
``gamma``
Always enable gamma control. (Disables delayed enabling.)
``icc-profile=<file>``
Load an ICC profile and use it to transform linear RGB to screen output.
Needs LittleCMS2 support compiled in.
``icc-cache=<file>``
Store and load the 3D LUT created from the ICC profile in this file.
This can be used to speed up loading, since LittleCMS2 can take a while
to create the 3D LUT. Note that this file contains an uncompressed LUT.
Its size depends on the ``3dlut-size``, and can be very big.
``icc-intent=<value>``
0
perceptual
1
relative colorimetric
2
saturation
3
absolute colorimetric (default)
``3dlut-size=<r>x<g>x<b>``
Size of the 3D LUT generated from the ICC profile in each dimension.
Default is 128x256x64.
Sizes must be a power of two, and 256 at most.
``alpha=<blend|yes|no>``
Decides what to do if the input has an alpha component (default: blend).
blend
Blend the frame against a black background.
yes
Try to create a framebuffer with alpha component. This only makes sense
if the video contains alpha information (which is extremely rare). May
not be supported on all platforms. If alpha framebuffers are
unavailable, it silently falls back on a normal framebuffer. Note
that when using FBO indirections (such as with ``opengl-hq``), an FBO
format with alpha must be specified with the ``fbo-format`` option.
no
Ignore alpha component.
``chroma-location=<auto|center|left>``
Set the YUV chroma sample location. auto means use the bitstream
flags (default: auto).
``opengl-hq``
Same as ``opengl``, but with default settings for high quality rendering.
This is equivalent to::
--vo=opengl:lscale=lanczos2:dither-depth=auto:pbo:fbo-format=rgb16
Note that some cheaper LCDs do dithering that gravely interferes with
``opengl``'s dithering. Disabling dithering with ``dither-depth=no`` helps.
Unlike ``opengl``, ``opengl-hq`` makes use of FBOs by default. Sometimes you
can achieve better quality or performance by changing the ``fbo-format``
suboption to ``rgb16f``, ``rgb32f`` or ``rgb``. Known problems include
Mesa/Intel not accepting ``rgb16``, Mesa sometimes not being compiled with
float texture support, and some OSX setups being very slow with ``rgb16``
but fast with ``rgb32f``.
``opengl-old``
OpenGL video output driver, old version. Video size must be smaller
than the maximum texture size of your OpenGL implementation. Intended to
work even with the most basic OpenGL implementations, but also makes use
of newer extensions which allow support for more color spaces.
The code performs very few checks, so if a feature does not work, this
might be because it is not supported by your card and/or OpenGL
implementation, even if you do not get any error message. Use ``glxinfo``
or a similar tool to display the supported OpenGL extensions.
``(no-)ati-hack``
ATI drivers may give a corrupted image when PBOs are used (when using
``force-pbo``). This option fixes this, at the expense of using a bit
more memory.
``(no-)force-pbo``
Always uses PBOs to transfer textures even if this involves an extra
copy. Currently this gives a little extra speed with NVIDIA drivers
and a lot more speed with ATI drivers. May need the ``ati-hack``
suboption to work correctly.
``(no-)scaled-osd``
Scales the OSD and subtitles instead of rendering them at display size
(default: disabled).
``rectangle=<0,1,2>``
Select usage of rectangular textures, which saves video RAM, but often
is slower (default: 0).
0
Use power-of-two textures (default).
1
Use the ``GL_ARB_texture_rectangle`` extension.
2
Use the ``GL_ARB_texture_non_power_of_two`` extension. In some
cases only supported in software and thus very slow.
``swapinterval=<n>``
Minimum interval between two buffer swaps, counted in displayed frames
(default: 1). 1 is equivalent to enabling VSYNC, 0 to disabling VSYNC.
Values below 0 will leave it at the system default. This limits the
framerate to (horizontal refresh rate / n). Requires
``GLX_SGI_swap_control`` support to work. With some (most/all?)
implementations this only works in fullscreen mode.
``ycbcr``
Use the ``GL_MESA_ycbcr_texture`` extension to convert YUV to RGB. In
most cases this is probably slower than doing software conversion to
RGB.
``yuv=<n>``
Select the type of YUV to RGB conversion. The default is
auto-detection deciding between values 0 and 2.
0
Use software conversion. Compatible with all OpenGL versions.
Provides brightness, contrast and saturation control.
1
Same as 2. This used to use NVIDIA-specific extensions, which
did not provide any advantages over using fragment programs, except
possibly on very ancient graphics cards. It produced a gray-ish
output, which is why it has been removed.
2
Use a fragment program. Needs the ``GL_ARB_fragment_program``
extension and at least three texture units. Provides brightness,
contrast, saturation and hue control.
3
Use a fragment program using the ``POW`` instruction. Needs the
``GL_ARB_fragment_program`` extension and at least three texture
units. Provides brightness, contrast, saturation, hue and gamma
control. Gamma can also be set independently for red, green and
blue. Method 4 is usually faster.
4
Use a fragment program with additional lookup. Needs the
``GL_ARB_fragment_program`` extension and at least four texture
units. Provides brightness, contrast, saturation, hue and gamma
control. Gamma can also be set independently for red, green and
blue.
5
Use ATI-specific method (for older cards). This uses an
ATI-specific extension (``GL_ATI_fragment_shader`` - not
``GL_ARB_fragment_shader``!). At least three texture units are
needed. Provides saturation and hue control. This method is fast
but inexact.
6
Use a 3D texture to do conversion via lookup. Needs the
``GL_ARB_fragment_program extension`` and at least four texture
units. Extremely slow (software emulation) on some (all?) ATI
cards since it uses a texture with border pixels. Provides
brightness, contrast, saturation, hue and gamma control. Gamma can
also be set independently for red, green and blue. Speed depends
more on GPU memory bandwidth than other methods.
``lscale=<n>``
Select the scaling function to use for luminance scaling. Only valid
for yuv modes 2, 3, 4 and 6.
0
Use simple linear filtering (default).
1
Use bicubic B-spline filtering (better quality). Needs one
additional texture unit. Older cards will not be able to handle
this for chroma at least in fullscreen mode.
2
Use cubic filtering in horizontal, linear filtering in vertical
direction. Works on a few more cards than method 1.
3
Same as 1 but does not use a lookup texture. Might be faster on
some cards.
4
Use experimental unsharp masking with 3x3 support and a default
strength of 0.5 (see ``filter-strength``).
5
Use experimental unsharp masking with 5x5 support and a default
strength of 0.5 (see ``filter-strength``).
``cscale=<n>``
Select the scaling function to use for chrominance scaling. For
details see ``lscale``.
``filter-strength=<value>``
Set the effect strength for the ``lscale``/``cscale`` filters that
support it.
``stereo=<value>``
Select a method for stereo display. You may have to use ``--aspect`` to
fix the aspect value. Experimental, do not expect too much from it.
0
Normal 2D display
1
Convert side by side input to full-color red-cyan stereo.
2
Convert side by side input to full-color green-magenta stereo.
3
Convert side by side input to quadbuffered stereo. Only supported
by very few OpenGL cards.
The following options are only useful if writing your own fragment programs.
``customprog=<filename>``
Load a custom fragment program from ``<filename>``.
``customtex=<filename>``
Load a custom "gamma ramp" texture from ``<filename>``. This can be used
in combination with ``yuv=4`` or with the ``customprog`` option.
``(no-)customtlin``
If enabled (default) use ``GL_LINEAR`` interpolation, otherwise use
``GL_NEAREST`` for customtex texture.
``(no-)customtrect``
If enabled, use ``texture_rectangle`` for the ``customtex`` texture.
Default is disabled.
``(no-)mipmapgen``
If enabled, mipmaps for the video are automatically generated. This
should be useful together with the ``customprog`` and the ``TXB``
instruction to implement blur filters with a large radius. For most
OpenGL implementations, this is very slow for any non-RGB formats.
Default is disabled.
Normally there is no reason to use the following options; they mostly
exist for testing purposes.
``(no-)glfinish``
Call ``glFinish()`` before swapping buffers. Slower but in some cases
more correct output (default: disabled).
``(no-)manyfmts``
Enables support for more (RGB and BGR) color formats (default: enabled).
Needs OpenGL version >= 1.2.
``slice-height=<0-...>``
Number of lines copied to texture in one piece (default: 0). 0 for
whole image.
``sw``
Continue even if a software renderer is detected.
``backend=<sys>``
auto
auto-select (default)
cocoa
Cocoa/OSX
win
Win32/WGL
x11
X11/GLX
wayland
Wayland/EGL
``sdl``
SDL 2.0+ Render video output driver, depending on system with or without
hardware acceleration. Should work on all platforms supported by SDL 2.0.
For tuning, refer to your copy of the file ``SDL_hints.h``.
``sw``
Continue even if a software renderer is detected.
``switch-mode``
Instruct SDL to switch the monitor video mode when going fullscreen.
``vaapi``
Intel VA API video output driver with support for hardware decoding. Note
that there is absolutely no reason to use this, other than wanting to use
hardware decoding to save power on laptops, or possibly preventing video
tearing with some setups.
``scaling=<algorithm>``
default
Driver default (mpv default as well).
fast
Fast, but low quality.
hq
Unspecified driver dependent high-quality scaling, slow.
nla
``non-linear anamorphic scaling``
``deint-mode=<mode>``
Select deinterlacing algorithm. Note that by default deinterlacing is
initially always off, and needs to be enabled with the ``D`` key
(default key binding for ``cycle deinterlace``).
This option doesn't apply if libva supports video post processing (vpp).
In this case, the default for ``deint-mode`` is ``no``, and enabling
deinterlacing via user interaction using the methods mentioned above
actually inserts the ``vavpp`` video filter. If vpp is not actually
supported with the libva backend in use, you can use this option to
forcibly enable VO based deinterlacing.
no
Don't allow deinterlacing (default for newer libva).
first-field
Show only first field (going by ``--field-dominance``).
bob
bob deinterlacing (default for older libva).
``scaled-osd=<yes|no>``
If enabled, then the OSD is rendered at video resolution and scaled to
display resolution. By default, this is disabled, and the OSD is
rendered at display resolution if the driver supports it.
``null``
Produces no video output. Useful for benchmarking.
``caca``
Color ASCII art video output driver that works on a text console.
``image``
Output each frame into an image file in the current directory. Each file
takes the frame number padded with leading zeros as name.
``format=<format>``
Select the image file format.
jpg
JPEG files, extension .jpg. (Default.)
jpeg
JPEG files, extension .jpeg.
png
PNG files.
ppm
Portable bitmap format.
pgm
Portable graymap format.
pgmyuv
Portable graymap format, using the YV12 pixel format.
tga
Truevision TGA.
``png-compression=<0-9>``
PNG compression factor (speed vs. file size tradeoff) (default: 7)
``png-filter=<0-5>``
Filter applied prior to PNG compression (0 = none; 1 = sub; 2 = up;
3 = average; 4 = Paeth; 5 = mixed) (default: 5)
``jpeg-quality=<0-100>``
JPEG quality factor (default: 90)
``(no-)jpeg-progressive``
Specify standard or progressive JPEG (default: no).
``(no-)jpeg-baseline``
Specify use of JPEG baseline or not (default: yes).
``jpeg-optimize=<0-100>``
JPEG optimization factor (default: 100)
``jpeg-smooth=<0-100>``
smooth factor (default: 0)
``jpeg-dpi=<1->``
JPEG DPI (default: 72)
``outdir=<dirname>``
Specify the directory to save the image files to (default: ``./``).
``wayland`` (Wayland only)
Wayland shared memory video output as fallback for ``opengl``.
``default-format``
Use the default RGB32 format instead of an auto-detected one.
``alpha``
Use a buffer format that supports videos and images with alpha
information
-123
View File
@@ -1,123 +0,0 @@
ENCODING
========
You can encode files from one format/codec to another using this facility.
``--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.
``--ofopts=<options>``
Specifies the output format options for libavformat.
See ``--ofopts=help`` for a full list of supported options.
This is a key/value list option. See `List Options`_ for details.
``--ofopts-add=<option>``
Appends the option given as an argument to the options list. (Passing
multiple options is currently still possible, but deprecated.)
``--ofopts=""``
Completely empties the options list.
``--oac=<codec>``
Specifies the output audio codec. See ``--oac=help`` for a full list of
supported codecs.
``--oaoffset=<value>``
Shifts audio data by the given time (in seconds) by adding/removing
samples at the start. Deprecated.
``--oacopts=<options>``
Specifies the output audio codec options for libavcodec.
See ``--oacopts=help`` for a full list of supported options.
.. admonition:: Example
"``--oac=libmp3lame --oacopts=b=128000``"
selects 128 kbps MP3 encoding.
This is a key/value list option. See `List Options`_ for details.
``--oacopts-add=<option>``
Appends the option given as an argument to the options list. (Passing
multiple options is currently still possible, but deprecated.)
``--oacopts=""``
Completely empties the options list.
``--oafirst``
Force the audio stream to become the first stream in the output.
By default, the order is unspecified. Deprecated.
``--ovc=<codec>``
Specifies the output video codec. See ``--ovc=help`` for a full list of
supported codecs.
``--ovoffset=<value>``
Shifts video data by the given time (in seconds) by shifting the pts
values. Deprecated.
``--ovcopts=<options>``
Specifies the output video codec options for libavcodec.
See --ovcopts=help for a full list of supported options.
.. admonition:: Examples
``"--ovc=mpeg4 --ovcopts=qscale=5"``
selects constant quantizer scale 5 for MPEG-4 encoding.
``"--ovc=libx264 --ovcopts=crf=23"``
selects VBR quality factor 23 for H.264 encoding.
This is a key/value list option. See `List Options`_ for details.
``--ovcopts-add=<option>``
Appends the option given as an argument to the options list. (Passing
multiple options is currently still possible, but deprecated.)
``--ovcopts=""``
Completely empties the options list.
``--ovfirst``
Force the video stream to become the first stream in the output.
By default, the order is unspecified. Deprecated.
``--orawts``
Copies input pts to the output video (not supported by some output
container formats, e.g. AVI). In this mode, discontinuities are not fixed
and all pts are passed through as-is. Never seek backwards or use multiple
input files in this mode!
``--no-ocopy-metadata``
Turns off copying of metadata from input files to output files when
encoding (which is enabled by default).
``--oset-metadata=<metadata-tag[,metadata-tag,...]>``
Specifies metadata to include in the output file.
Supported keys vary between output formats. For example, Matroska (MKV) and
FLAC allow almost arbitrary keys, while support in MP4 and MP3 is more
limited.
This is a key/value list option. See `List Options`_ for details.
.. admonition:: Example
"``--oset-metadata=title="Output title",comment="Another tag"``"
adds a title and a comment to the output file.
``--oremove-metadata=<metadata-tag[,metadata-tag,...]>``
Specifies metadata to exclude from the output file when copying from the
input file.
This is a string list option. See `List Options`_ for details.
.. admonition:: Example
"``--oremove-metadata=comment,genre``"
excludes copying of the the comment and genre tags to the output
file.
-3470
View File
File diff suppressed because it is too large. Load diff
-387
View File
@@ -1,387 +0,0 @@
JSON IPC
========
mpv can be controlled by external programs using the JSON-based IPC protocol.
It can be enabled by specifying the path to a unix socket or a named pipe using
the option ``--input-ipc-server``. Clients can connect to this socket and send
commands to the player or receive events from it.
.. warning::
This is not intended to be a secure network protocol. It is explicitly
insecure: there is no authentication, no encryption, and the commands
themselves are insecure too. For example, the ``run`` command is exposed,
which can run arbitrary system commands. The use-case is controlling the
player locally. This is not different from the MPlayer slave protocol.
Socat example
-------------
You can use the ``socat`` tool to send commands (and receive replies) from the
shell. Assuming mpv was started with:
::
mpv file.mkv --input-ipc-server=/tmp/mpvsocket
Then you can control it using socat:
::
> echo '{ "command": ["get_property", "playback-time"] }' | socat - /tmp/mpvsocket
{"data":190.482000,"error":"success"}
In this case, socat copies data between stdin/stdout and the mpv socket
connection.
See the ``--idle`` option how to make mpv start without exiting immediately or
playing a file.
It's also possible to send input.conf style text-only commands:
::
> echo 'show-text ${playback-time}' | socat - /tmp/mpvsocket
But you won't get a reply over the socket. (This particular command shows the
playback time on the player's OSD.)
Command Prompt example
----------------------
Unfortunately, it's not as easy to test the IPC protocol on Windows, since
Windows ports of socat (in Cygwin and MSYS2) don't understand named pipes. In
the absence of a simple tool to send and receive from bidirectional pipes, the
``echo`` command can be used to send commands, but not receive replies from the
command prompt.
Assuming mpv was started with:
::
mpv file.mkv --input-ipc-server=\\.\pipe\mpvsocket
You can send commands from a command prompt:
::
echo show-text ${playback-time} >\\.\pipe\mpvsocket
To be able to simultaneously read and write from the IPC pipe, like on Linux,
it's necessary to write an external program that uses overlapped file I/O (or
some wrapper like .NET's NamedPipeClientStream.)
You can open the pipe in PuTTY as "serial" device. This is not very
comfortable, but gives a way to test interactively without having to write code.
Protocol
--------
The protocol uses UTF-8-only JSON as defined by RFC-8259. Unlike standard JSON,
"\u" escape sequences are not allowed to construct surrogate pairs. To avoid
getting conflicts, encode all text characters including and above codepoint
U+0020 as UTF-8. mpv might output broken UTF-8 in corner cases (see "UTF-8"
section below).
Clients can execute commands on the player by sending JSON messages of the
following form:
::
{ "command": ["command_name", "param1", "param2", ...] }
where ``command_name`` is the name of the command to be executed, followed by a
list of parameters. Parameters must be formatted as native JSON values
(integers, strings, booleans, ...). Every message **must** be terminated with
``\n``. Additionally, ``\n`` must not appear anywhere inside the message. In
practice this means that messages should be minified before being sent to mpv.
mpv will then send back a reply indicating whether the command was run
correctly, and an additional field holding the command-specific return data (it
can also be null).
::
{ "error": "success", "data": null }
mpv will also send events to clients with JSON messages of the following form:
::
{ "event": "event_name" }
where ``event_name`` is the name of the event. Additional event-specific fields
can also be present. See `List of events`_ for a list of all supported events.
Because events can occur at any time, it may be difficult at times to determine
which response goes with which command. Commands may optionally include a
``request_id`` which, if provided in the command request, will be copied
verbatim into the response. mpv does not intrepret the ``request_id`` in any
way; it is solely for the use of the requester. The only requirement is that
the ``request_id`` field must be an integer (a number without fractional parts
in the range ``-2^63..2^63-1``). Using other types is deprecated and will
currently show a warning. In the future, this will raise an error.
For example, this request:
::
{ "command": ["get_property", "time-pos"], "request_id": 100 }
Would generate this response:
::
{ "error": "success", "data": 1.468135, "request_id": 100 }
If you don't specify a ``request_id``, command replies will set it to 0.
All commands, replies, and events are separated from each other with a line
break character (``\n``).
If the first character (after skipping whitespace) is not ``{``, the command
will be interpreted as non-JSON text command, as they are used in input.conf
(or ``mpv_command_string()`` in the client API). Additionally, lines starting
with ``#`` and empty lines are ignored.
Currently, embedded 0 bytes terminate the current line, but you should not
rely on this.
Data flow
---------
Currently, the mpv-side IPC implementation does not service the socket while a
command is executed and the reply is written. It is for example not possible
that other events, that happened during the execution of the command, are
written to the socket before the reply is written.
This might change in the future. The only guarantee is that replies to IPC
messages are sent in sequence.
Also, since socket I/O is inherently asynchronous, it is possible that you read
unrelated event messages from the socket, before you read the reply to the
previous command you sent. In this case, these events were queued by the mpv
side before it read and started processing your command message.
If the mpv-side IPC implementation switches away from blocking writes and
blocking command execution, it may attempt to send events at any time.
You can also use asynchronous commands, which can return in any order, and
which do not block IPC protocol interaction at all while the command is
executed in the background.
Asynchronous commands
---------------------
Command can be run asynchronously. This behaves exactly as with normal command
execution, except that execution is not blocking. Other commands can be sent
while it's executing, and command completion can be arbitrarily reordered.
The ``async`` field controls this. If present, it must be a boolean. If missing,
``false`` is assumed.
For example, this initiates an asynchronous command:
::
{ "command": ["screenshot"], "request_id": 123, "async": true }
And this is the completion:
::
{"request_id":123,"error":"success","data":null}
By design, you will not get a confirmation that the command was started. If a
command is long running, sending the message will lead to any reply until much
later when the command finishes.
Some commands execute synchronously, but these will behave like asynchronous
commands that finished execution immediately.
Cancellation of asynchronous commands is available in the libmpv API, but has
not yet been implemented in the IPC protocol.
Commands with named arguments
-----------------------------
If the ``command`` field is a JSON object, named arguments are expected. This
is described in the C API ``mpv_command_node()`` documentation (the
``MPV_FORMAT_NODE_MAP`` case). In some cases, this may make commands more
readable, while some obscure commands basically require using named arguments.
Currently, only "proper" commands (as listed by `List of Input Commands`_)
support named arguments.
Commands
--------
In addition to the commands described in `List of Input Commands`_, a few
extra commands can also be used as part of the protocol:
``client_name``
Return the name of the client as string. This is the string ``ipc-N`` with
N being an integer number.
``get_time_us``
Return the current mpv internal time in microseconds as a number. This is
basically the system time, with an arbitrary offset.
``get_property``
Return the value of the given property. The value will be sent in the data
field of the replay message.
Example:
::
{ "command": ["get_property", "volume"] }
{ "data": 50.0, "error": "success" }
``get_property_string``
Like ``get_property``, but the resulting data will always be a string.
Example:
::
{ "command": ["get_property_string", "volume"] }
{ "data": "50.000000", "error": "success" }
``set_property``
Set the given property to the given value. See `Properties`_ for more
information about properties.
Example:
::
{ "command": ["set_property", "pause", true] }
{ "error": "success" }
``set_property_string``
Alias for ``set_property``. Both commands accept native values and strings.
``observe_property``
Watch a property for changes. If the given property is changed, then an
event of type ``property-change`` will be generated
Example:
::
{ "command": ["observe_property", 1, "volume"] }
{ "error": "success" }
{ "event": "property-change", "id": 1, "data": 52.0, "name": "volume" }
.. warning::
If the connection is closed, the IPC client is destroyed internally,
and the observed properties are unregistered. This happens for example
when sending commands to a socket with separate ``socat`` invocations.
This can make it seem like property observation does not work. You must
keep the IPC connection open to make it work.
``observe_property_string``
Like ``observe_property``, but the resulting data will always be a string.
Example:
::
{ "command": ["observe_property_string", 1, "volume"] }
{ "error": "success" }
{ "event": "property-change", "id": 1, "data": "52.000000", "name": "volume" }
``unobserve_property``
Undo ``observe_property`` or ``observe_property_string``. This requires the
numeric id passed to the observed command as argument.
Example:
::
{ "command": ["unobserve_property", 1] }
{ "error": "success" }
``request_log_messages``
Enable output of mpv log messages. They will be received as events. The
parameter to this command is the log-level (see ``mpv_request_log_messages``
C API function).
Log message output is meant for humans only (mostly for debugging).
Attempting to retrieve information by parsing these messages will just
lead to breakages with future mpv releases. Instead, make a feature request,
and ask for a proper event that returns the information you need.
``enable_event``, ``disable_event``
Enables or disables the named event. Mirrors the ``mpv_request_event`` C
API function. If the string ``all`` is used instead of an event name, all
events are enabled or disabled.
By default, most events are enabled, and there is not much use for this
command.
``get_version``
Returns the client API version the C API of the remote mpv instance
provides.
See also: ``DOCS/client-api-changes.rst``.
UTF-8
-----
Normally, all strings are in UTF-8. Sometimes it can happen that strings are
in some broken encoding (often happens with file tags and such, and filenames
on many Unixes are not required to be in UTF-8 either). This means that mpv
sometimes sends invalid JSON. If that is a problem for the client application's
parser, it should filter the raw data for invalid UTF-8 sequences and perform
the desired replacement, before feeding the data to its JSON parser.
mpv will not attempt to construct invalid UTF-8 with broken "\u" escape
sequences. This includes surrogate pairs.
JSON extensions
---------------
The following non-standard extensions are supported:
- a list or object item can have a trailing ","
- object syntax accepts "=" in addition of ":"
- object keys can be unquoted, if they start with a character in "A-Za-z\_"
and contain only characters in "A-Za-z0-9\_"
- byte escapes with "\xAB" are allowed (with AB being a 2 digit hex number)
Example:
::
{ objkey = "value\x0A" }
Is equivalent to:
::
{ "objkey": "value\n" }
Alternative ways of starting clients
------------------------------------
You can create an anonymous IPC connection without having to set
``--input-ipc-server``. This is achieved through a mpv pseudo scripting backend
that starts processes.
You can put ``.run`` file extension in the mpv scripts directory in its config
directory (see the `FILES`_ section for details), or load them through other
means (see `Script location`_). These scripts are simply executed with the OS
native mechanism (as if you ran them in the shell). They must have a proper
shebang and have the executable bit set.
When executed, a socket (the IPC connection) is passed to them through file
descriptor inheritance. The file descriptor is indicated as the special command
line argument ``--mpv-ipc-fd=N``, where ``N`` is the numeric file descriptor.
The rest is the same as with a normal ``--input-ipc-server`` IPC connection. mpv
does not attempt to observe or other interact with the started script process.
This does not work in Windows yet.
-389
View File
@@ -1,389 +0,0 @@
JAVASCRIPT
==========
JavaScript support in mpv is near identical to its Lua support. Use this section
as reference on differences and availability of APIs, but otherwise you should
refer to the Lua documentation for API details and general scripting in mpv.
Example
-------
JavaScript code which leaves fullscreen mode when the player is paused:
::
function on_pause_change(name, value) {
if (value == true)
mp.set_property("fullscreen", "no");
}
mp.observe_property("pause", "bool", on_pause_change);
Similarities with Lua
---------------------
mpv tries to load a script file as JavaScript if it has a ``.js`` extension, but
otherwise, the documented Lua options, script directories, loading, etc apply to
JavaScript files too.
Script initialization and lifecycle is the same as with Lua, and most of the Lua
functions at the modules ``mp``, ``mp.utils``, ``mp.msg`` and ``mp.options`` are
available to JavaScript with identical APIs - including running commands,
getting/setting properties, registering events/key-bindings/hooks, etc.
Differences from Lua
--------------------
No need to load modules. ``mp``, ``mp.utils``, ``mp.msg`` and ``mp.options``
are preloaded, and you can use e.g. ``var cwd = mp.utils.getcwd();`` without
prior setup.
Errors are slightly different. Where the Lua APIs return ``nil`` for error,
the JavaScript ones return ``undefined``. Where Lua returns ``something, error``
JavaScript returns only ``something`` - and makes ``error`` available via
``mp.last_error()``. Note that only some of the functions have this additional
``error`` value - typically the same ones which have it in Lua.
Standard APIs are preferred. For instance ``setTimeout`` and ``JSON.stringify``
are available, but ``mp.add_timeout`` and ``mp.utils.format_json`` are not.
No standard library. This means that interaction with anything outside of mpv is
limited to the available APIs, typically via ``mp.utils``. However, some file
functions were added, and CommonJS ``require`` is available too - where the
loaded modules have the same privileges as normal scripts.
Language features - ECMAScript 5
--------------------------------
The scripting backend which mpv currently uses is MuJS - a compatible minimal
ES5 interpreter. As such, ``String.substring`` is implemented for instance,
while the common but non-standard ``String.substr`` is not. Please consult the
MuJS pages on language features and platform support - http://mujs.com .
Unsupported Lua APIs and their JS alternatives
----------------------------------------------
``mp.add_timeout(seconds, fn)`` JS: ``id = setTimeout(fn, ms)``
``mp.add_periodic_timer(seconds, fn)`` JS: ``id = setInterval(fn, ms)``
``utils.parse_json(str [, trail])`` JS: ``JSON.parse(str)``
``utils.format_json(v)`` JS: ``JSON.stringify(v)``
``utils.to_string(v)`` see ``dump`` below.
``mp.suspend()`` JS: none (deprecated).
``mp.resume()`` JS: none (deprecated).
``mp.resume_all()`` JS: none (deprecated).
``mp.get_next_timeout()`` see event loop below.
``mp.dispatch_events([allow_wait])`` see event loop below.
Scripting APIs - identical to Lua
---------------------------------
(LE) - Last-Error, indicates that ``mp.last_error()`` can be used after the
call to test for success (empty string) or failure (non empty reason string).
Where the Lua APIs use ``nil`` to indicate error, JS APIs use ``undefined``.
``mp.command(string)`` (LE)
``mp.commandv(arg1, arg2, ...)`` (LE)
``mp.command_native(table [,def])`` (LE)
``id = mp.command_native_async(table [,fn])`` (LE) Notes: ``id`` is true-thy on
success, ``fn`` is called always a-sync, ``error`` is empty string on success.
``mp.abort_async_command(id)``
``mp.get_property(name [,def])`` (LE)
``mp.get_property_osd(name [,def])`` (LE)
``mp.get_property_bool(name [,def])`` (LE)
``mp.get_property_number(name [,def])`` (LE)
``mp.get_property_native(name [,def])`` (LE)
``mp.set_property(name, value)`` (LE)
``mp.set_property_bool(name, value)`` (LE)
``mp.set_property_number(name, value)`` (LE)
``mp.set_property_native(name, value)`` (LE)
``mp.get_time()``
``mp.add_key_binding(key, name|fn [,fn [,flags]])``
``mp.add_forced_key_binding(...)``
``mp.remove_key_binding(name)``
``mp.register_event(name, fn)``
``mp.unregister_event(fn)``
``mp.observe_property(name, type, fn)``
``mp.unobserve_property(fn)``
``mp.get_opt(key)``
``mp.get_script_name()``
``mp.get_script_directory()``
``mp.osd_message(text [,duration])``
``mp.get_wakeup_pipe()``
``mp.register_idle(fn)``
``mp.unregister_idle(fn)``
``mp.enable_messages(level)``
``mp.register_script_message(name, fn)``
``mp.unregister_script_message(name)``
``mp.create_osd_overlay(format)``
``mp.get_osd_size()`` (returned object has properties: width, height, aspect)
``mp.msg.log(level, ...)``
``mp.msg.fatal(...)``
``mp.msg.error(...)``
``mp.msg.warn(...)``
``mp.msg.info(...)``
``mp.msg.verbose(...)``
``mp.msg.debug(...)``
``mp.msg.trace(...)``
``mp.utils.getcwd()`` (LE)
``mp.utils.readdir(path [, filter])`` (LE)
``mp.utils.file_info(path)`` (LE)
``mp.utils.split_path(path)``
``mp.utils.join_path(p1, p2)``
``mp.utils.subprocess(t)``
``mp.utils.subprocess_detached(t)``
``mp.utils.get_env_list()``
``mp.utils.getpid()`` (LE)
``mp.add_hook(type, priority, fn(hook))``
``mp.options.read_options(obj [, identifier [, on_update]])`` (types:
string/boolean/number)
Additional utilities
--------------------
``mp.last_error()``
If used after an API call which updates last error, returns an empty string
if the API call succeeded, or a non-empty error reason string otherwise.
``Error.stack`` (string)
When using ``try { ... } catch(e) { ... }``, then ``e.stack`` is the stack
trace of the error - if it was created using the ``Error(...)`` constructor.
``print`` (global)
A convenient alias to ``mp.msg.info``.
``dump`` (global)
Like ``print`` but also expands objects and arrays recursively.
``mp.utils.getenv(name)``
Returns the value of the host environment variable ``name``, or
``undefined`` if the variable is not defined.
``mp.utils.get_user_path(path)``
Expands (mpv) meta paths like ``~/x``, ``~~/y``, ``~~desktop/z`` etc.
``read_file``, ``write_file`` and ``require`` already use this internaly.
``mp.utils.read_file(fname [,max])``
Returns the content of file ``fname`` as string. If ``max`` is provided and
not negative, limit the read to ``max`` bytes.
``mp.utils.write_file(fname, str)``
(Over)write file ``fname`` with text content ``str``. ``fname`` must be
prefixed with ``file://`` as simple protection against accidental arguments
switch, e.g. ``mp.utils.write_file("file://~/abc.txt", "hello world")``.
Note: ``read_file`` and ``write_file`` throw on errors, allow text content only.
``mp.get_time_ms()``
Same as ``mp.get_time()`` but in ms instead of seconds.
``mp.get_script_file()``
Returns the file name of the current script.
``exit()`` (global)
Make the script exit at the end of the current event loop iteration.
Note: please remove added key bindings before calling ``exit()``.
``mp.utils.compile_js(fname, content_str)``
Compiles the JS code ``content_str`` as file name ``fname`` (without loading
anything from the filesystem), and returns it as a function. Very similar
to a ``Function`` constructor, but shows at stack traces as ``fname``.
``mp.module_paths``
Global modules search paths array for the ``require`` function (see below).
Timers (global)
---------------
The standard HTML/node.js timers are available:
``id = setTimeout(fn [,duration [,arg1 [,arg2...]]])``
``id = setTimeout(code_string [,duration])``
``clearTimeout(id)``
``id = setInterval(fn [,duration [,arg1 [,arg2...]]])``
``id = setInterval(code_string [,duration])``
``clearInterval(id)``
``setTimeout`` and ``setInterval`` return id, and later call ``fn`` (or execute
``code_string``) after ``duration`` ms. Interval also repeat every ``duration``.
``duration`` has a minimum and default value of 0, ``code_string`` is
a plain string which is evaluated as JS code, and ``[,arg1 [,arg2..]]`` are used
as arguments (if provided) when calling back ``fn``.
The ``clear...(id)`` functions cancel timer ``id``, and are irreversible.
Note: timers always call back asynchronously, e.g. ``setTimeout(fn)`` will never
call ``fn`` before returning. ``fn`` will be called either at the end of this
event loop iteration or at a later event loop iteration. This is true also for
intervals - which also never call back twice at the same event loop iteration.
Additionally, timers are processed after the event queue is empty, so it's valid
to use ``setTimeout(fn)`` as a one-time idle observer.
CommonJS modules and ``require(id)``
------------------------------------
CommonJS Modules are a standard system where scripts can export common functions
for use by other scripts. Specifically, a module is a script which adds
properties (functions, etc) to its pre-existing ``exports`` object, which
another script can access with ``require(module-id)``. This runs the module and
returns its ``exports`` object. Further calls to ``require`` for the same module
will return its cached ``exports`` object without running the module again.
Modules and ``require`` are supported, standard compliant, and generally similar
to node.js. However, most node.js modules won't run due to missing modules such
as ``fs``, ``process``, etc, but some node.js modules with minimal dependencies
do work. In general, this is for mpv modules and not a node.js replacement.
A ``.js`` file extension is always added to ``id``, e.g. ``require("./foo")``
will load the file ``./foo.js`` and return its ``exports`` object.
An id which starts with ``./`` or ``../`` is relative to the script or module
which ``require`` it. Otherwise it's considered a top-level id (CommonJS term).
Top-level id is evaluated as absolute filesystem path if possible, e.g. ``/x/y``
or ``~/x``. Otherwise it's considered a global module id and searched according
to ``mp.module_paths`` in normal array order, e.g. ``require("x")`` tries to
load ``x.js`` at one of the array paths, and id ``foo/x`` tries to load ``x.js``
inside dir ``foo`` at one of the paths.
The ``mp.module_paths`` array is empty by default except for scripts which are
loaded as a directory where it contains one item - ``<directory>/modules/`` .
The array may be updated from a script (or using custom init - see below) which
will affect future calls to ``require`` for global module id's which are not
already loaded/cached.
No ``global`` variable, but a module's ``this`` at its top lexical scope is the
global object - also in strict mode. If you have a module which needs ``global``
as the global object, you could do ``this.global = this;`` before ``require``.
Functions and variables declared at a module don't pollute the global object.
Custom initialization
---------------------
After mpv initializes the JavaScript environment for a script but before it
loads the script - it tries to run the file ``.init.js`` at the root of the mpv
configuration directory. Code at this file can update the environment further
for all scripts. E.g. if it contains ``mp.module_paths.push("/foo")`` then
``require`` at all scripts will search global module id's also at ``/foo``.
The event loop
--------------
The event loop poll/dispatch mpv events as long as the queue is not empty, then
processes the timers, then waits for the next event, and repeats this forever.
You could put this code at your script to replace the built-in event loop, and
also print every event which mpv sends to your script:
::
function mp_event_loop() {
var wait = 0;
do {
var e = mp.wait_event(wait);
dump(e); // there could be a lot of prints...
if (e.event != "none") {
mp.dispatch_event(e);
wait = 0;
} else {
wait = mp.process_timers() / 1000;
if (wait != 0) {
mp.notify_idle_observers();
wait = mp.peek_timers_wait() / 1000;
}
}
} while (mp.keep_running);
}
``mp_event_loop`` is a name which mpv tries to call after the script loads.
The internal implementation is similar to this (without ``dump`` though..).
``e = mp.wait_event(wait)`` returns when the next mpv event arrives, or after
``wait`` seconds if positive and no mpv events arrived. ``wait`` value of 0
returns immediately (with ``e.event == "none"`` if the queue is empty).
``mp.dispatch_event(e)`` calls back the handlers registered for ``e.event``,
if there are such (event handlers, property observers, script messages, etc).
``mp.process_timers()`` calls back the already-added, non-canceled due timers,
and returns the duration in ms till the next due timer (possibly 0), or -1 if
there are no pending timers. Must not be called recursively.
``mp.notify_idle_observers()`` calls back the idle observers, which we do when
we're about to sleep (wait != 0), but the observers may add timers or take
non-negligible duration to complete, so we re-calculate ``wait`` afterwards.
``mp.peek_timers_wait()`` returns the same values as ``mp.process_timers()``
but without doing anything. Invalid result if called from a timer callback.
Note: ``exit()`` is also registered for the ``shutdown`` event, and its
implementation is a simple ``mp.keep_running = false``.
-75
View File
@@ -1,75 +0,0 @@
EMBEDDING INTO OTHER PROGRAMS (LIBMPV)
======================================
mpv can be embedded into other programs as video/audio playback backend. The
recommended way to do so is using libmpv. See ``libmpv/client.h`` in the mpv
source code repository. This provides a C API. Bindings for other languages
might be available (see wiki).
Since libmpv merely allows access to underlying mechanisms that can control
mpv, further documentation is spread over a few places:
- https://github.com/mpv-player/mpv/blob/master/libmpv/client.h
- http://mpv.io/manual/master/#options
- http://mpv.io/manual/master/#list-of-input-commands
- http://mpv.io/manual/master/#properties
- https://github.com/mpv-player/mpv-examples/tree/master/libmpv
C PLUGINS
=========
You can write C plugins for mpv. These use the libmpv API, although they do not
use the libmpv library itself.
Currently, they must be explicitly enabled at build time with
``--enable-cplugins``. They are available on Linux/BSD platforms only.
C plugins location
------------------
C plugins are put into the mpv scripts directory in its config directory
(see the `FILES`_ section for details). They must have a ``.so`` file extension.
They can also be explicitly loaded with the ``--script`` option.
API
---
A C plugin must export the following function::
int mpv_open_cplugin(mpv_handle *handle)
The plugin function will be called on loading time. This function does not
return as long as your plugin is loaded (it runs in its own thread). The
``handle`` will be deallocated as soon as the plugin function returns.
The return value is interpreted as error status. A value of ``0`` is
interpreted as success, while ``-1`` signals an error. In the latter case,
the player prints an uninformative error message that loading failed.
Return values other than ``0`` and ``-1`` are reserved, and trigger undefined
behavior.
Within the plugin function, you can call libmpv API functions. The ``handle``
is created by ``mpv_create_client()`` (or actually an internal equivalent),
and belongs to you. You can call ``mpv_wait_event()`` to wait for things
happening, and so on.
Note that the player might block until your plugin calls ``mpv_wait_event()``
for the first time. This gives you a chance to install initial hooks etc.
before playback begins.
The details are quite similar to Lua scripts.
Linkage to libmpv
-----------------
The current implementation requires that your plugins are **not** linked against
libmpv. What your plugins uses are not symbols from a libmpv binary, but
symbols from the mpv host binary.
Examples
--------
See:
- https://github.com/mpv-player/mpv-examples/tree/master/cplugins
-911
View File
@@ -1,911 +0,0 @@
LUA SCRIPTING
=============
mpv can load Lua scripts. (See `Script location`_.)
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.
These scripts can be used to control mpv in a similar way to slave mode.
Technically, the Lua code uses the client API internally.
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)
Script location
---------------
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/``).
A script can be a single file. The file extension is used to select the
scripting backend to use for it. For Lua, it is ``.lua``. If the extension is
not recognized, an error is printed. (If an error happens, the extension is
either mistyped, or the backend was not compiled into your mpv binary.)
Entries with ``.disable`` extension are always ignored.
If a script is a directory (either if a directory is passed to ``--script``,
or any sub-directories in the script directory, such as for example
``~/.config/mpv/scripts/something/``), then the directory represents a single
script. The player will try to load a file named ``main.x``, where ``x`` is
replaced with the file extension. For example, if ``main.lua`` exists, it is
loaded with the Lua scripting backend.
You must not put any other files or directories that start with ``main.`` into
the script's top level directory. If the script directory contains for example
both ``main.lua`` and ``main.js``, only one of them will be loaded (and which
one depends on mpv internals that may change any time). Likewise, if there is
for example ``main.foo``, your script will break as soon as mpv adds a backend
that uses the ``.foo`` file extension.
mpv also appends the top level directory of the script to the start of Lua's
package path so you can import scripts from there too. Be aware that this will
shadow Lua libraries that use the same package path. (Single file scripts do not
include mpv specific directory the Lua package path. This was silently changed
in mpv 0.32.0.)
Using a script directory is the recommended way to package a script that
consists of multiple source files, or requires other files (you can use
``mp.get_script_directory()`` to get the location and e.g. load data files).
Making a script a git repository, basically a repository which contains a
``main.lua``` file in the root directory, makes scripts easily updateable
(without the dangers of auto-updates). Another suggestion is to use git
submodules to share common files or libraries.
Details on the script initialization and lifecycle
--------------------------------------------------
Your script will be loaded by the player at program start from the ``scripts``
configuration subdirectory, or from a path specified with the ``--script``
option. Some scripts are loaded internally (like ``--osc``). Each script runs in
its own thread. Your script is first run "as is", and once that is done, the event loop
is entered. This event loop will dispatch events received by mpv and call your
own event handlers which you have registered with ``mp.register_event``, or
timers added with ``mp.add_timeout`` or similar. Note that since the
script starts execution concurrently with player initialization, some properties
may not be populated with meaningful values until the relevant subsystems have
initialized.
When the player quits, all scripts will be asked to terminate. This happens via
a ``shutdown`` event, which by default will make the event loop return. If your
script got into an endless loop, mpv will probably behave fine during playback,
but it won't terminate when quitting, because it's waiting on your script.
Internally, the C code will call the Lua function ``mp_event_loop`` after
loading a Lua script. This function is normally defined by the default prelude
loaded before your script (see ``player/lua/defaults.lua`` in the mpv sources).
The event loop will wait for events and dispatch events registered with
``mp.register_event``. It will also handle timers added with ``mp.add_timeout``
and similar (by waiting with a timeout).
Since mpv 0.6.0, the player will wait until the script is fully loaded before
continuing normal operation. The player considers a script as fully loaded as
soon as it starts waiting for mpv events (or it exits). In practice this means
the player will more or less hang until the script returns from the main chunk
(and ``mp_event_loop`` is called), or the script calls ``mp_event_loop`` or
``mp.dispatch_events`` directly. This is done to make it possible for a script
to fully setup event handlers etc. before playback actually starts. In older
mpv versions, this happened asynchronously. With mpv 0.29.0, this changes
slightly, and it merely waits for scripts to be loaded in this manner before
starting playback as part of the player initialization phase. Scripts run though
initialization in parallel. This might change again.
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.
See `List of Input Commands`_.
By default, this will show something on the OSD (depending on the command),
as if it was used in ``input.conf``. See `Input Command Prefixes`_ how
to influence OSD usage per command.
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.command_native(table [,def])``
Similar to ``mp.commandv``, but pass the argument list as table. This has
the advantage that in at least some cases, arguments can be passed as
native types. It also allows you to use named argument.
If the table is an array, each array item is like an argument in
``mp.commandv()`` (but can be a native type instead of a string).
If the table contains string keys, it's interpreted as command with named
arguments. This requires at least an entry with the key ``name`` to be
present, which must be a string, and contains the command name. The special
entry ``_flags`` is optional, and if present, must be an array of
`Input Command Prefixes`_ to apply. All other entries are interpreted as
arguments.
Returns a result table on success (usually empty), or ``def, error`` on
error. ``def`` is the second parameter provided to the function, and is
nil if it's missing.
``mp.command_native_async(table [,fn])``
Like ``mp.command_native()``, but the command is ran asynchronously (as far
as possible), and upon completion, fn is called. fn has three arguments:
``fn(success, result, error)``:
``success``
Always a Boolean and is true if the command was successful,
otherwise false.
``result``
The result value (can be nil) in case of success, nil otherwise (as
returned by ``mp.command_native()``).
``error``
The error string in case of an error, nil otherwise.
Returns a table with undefined contents, which can be used as argument for
``mp.abort_async_command``.
If starting the command failed for some reason, ``nil, error`` is returned,
and ``fn`` is called indicating failure, using the same error value.
``mp.abort_async_command(t)``
Abort a ``mp.command_native_async`` call. The argument is the return value
of that command (which starts asynchronous execution of the command).
Whether this works and how long it takes depends on the command and the
situation. The abort call itself is asynchronous. Does not return anything.
``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}``
(see `Property Expansion`_).
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. See ``mp.get_property``
and `Properties`_ for more information about properties.
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``.
Trying to map multiple commands to a key will essentially prefer a random
binding, while the other bindings are not called. It is guaranteed that
user defined bindings in the central input.conf are preferred over bindings
added with this function (but see ``mp.add_forced_key_binding``).
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.add_forced_key_binding(...)``
This works almost the same as ``mp.add_key_binding``, but registers the
key binding in a way that will overwrite the user's custom bindings in their
input.conf. (``mp.add_key_binding`` overwrites default key bindings only,
but not those by the user's input.conf.)
``mp.remove_key_binding(name)``
Remove a key binding added with ``mp.add_key_binding`` or
``mp.add_forced_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.register_event(name, fn)``
Call a specific function when an event happens. The event name is a string,
and the function fn is a Lua function value.
Some events have associated data. This is put into a Lua table and passed
as argument to fn. The Lua table by default contains a ``name`` field,
which is a string containing the event name. If the event has an error
associated, the ``error`` field is set to a string describing the error,
on success it's not set.
If multiple functions are registered for the same event, they are run in
registration order, which the first registered function running before all
the other ones.
Returns true if such an event exists, false otherwise.
See `Events`_ and `List of events`_ for details.
``mp.unregister_event(fn)``
Undo ``mp.register_event(..., fn)``. This removes all event handlers that
are equal to the ``fn`` parameter. This uses normal Lua ``==`` comparison,
so be careful when dealing with closures.
``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)``
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.
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)``
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 http://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.get_opt(key)``
Return a setting from the ``--script-opts`` option. It's up to the user and
the script how this mechanism is used. Currently, all scripts can access
this equally, so you should be careful about collisions.
``mp.get_script_name()``
Return the name of the current script. The name is usually made of the
filename of the script, with directory and file extension removed. If
there are several scripts which would have the same name, it's made unique
by appending a number.
.. admonition:: Example
The script ``/path/to/fooscript.lua`` becomes ``fooscript``.
``mp.get_script_directory()``
Return the directory if this is a script packaged as directory (see
`Script location`_ for a description). Return nothing if this is a single
file script.
``mp.osd_message(text [,duration])``
Show an OSD message on the screen. ``duration`` is in seconds, and is
optional (uses ``--osd-duration`` by default).
Advanced mp functions
---------------------
These also live in the ``mp`` module, but are documented separately as they
are useful only in special situations.
``mp.suspend()``
This function has been deprecated in mpv 0.21.0 and does nothing starting
with mpv 0.23.0 (no replacement).
``mp.resume()``
This function has been deprecated in mpv 0.21.0 and does nothing starting
with mpv 0.23.0 (no replacement).
``mp.resume_all()``
This function has been deprecated in mpv 0.21.0 and does nothing starting
with mpv 0.23.0 (no replacement).
``mp.get_wakeup_pipe()``
Calls ``mpv_get_wakeup_pipe()`` and returns the read end of the wakeup
pipe. This is deprecated, but still works. (See ``client.h`` for details.)
``mp.get_next_timeout()``
Return the relative time in seconds when the next timer (``mp.add_timeout``
and similar) expires. If there is no timer, return ``nil``.
``mp.dispatch_events([allow_wait])``
This can be used to run custom event loops. If you want to have direct
control what the Lua script does (instead of being called by the default
event loop), you can set the global variable ``mp_event_loop`` to your
own function running the event loop. From your event loop, you should call
``mp.dispatch_events()`` to dequeue and dispatch mpv events.
If the ``allow_wait`` parameter is set to ``true``, the function will block
until the next event is received or the next timer expires. Otherwise (and
this is the default behavior), it returns as soon as the event loop is
emptied. It's strongly recommended to use ``mp.get_next_timeout()`` and
``mp.get_wakeup_pipe()`` if you're interested in properly working
notification of new events and working timers.
``mp.register_idle(fn)``
Register an event loop idle handler. Idle handlers are called before the
script goes to sleep after handling all new events. This can be used for
example to delay processing of property change events: if you're observing
multiple properties at once, you might not want to act on each property
change, but only when all change notifications have been received.
``mp.unregister_idle(fn)``
Undo ``mp.register_idle(fn)``. This removes all idle handlers that
are equal to the ``fn`` parameter. This uses normal Lua ``==`` comparison,
so be careful when dealing with closures.
``mp.enable_messages(level)``
Set the minimum log level of which mpv message output to receive. These
messages are normally printed to the terminal. By calling this function,
you can set the minimum log level of messages which should be received with
the ``log-message`` event. See the description of this event for details.
The level is a string, see ``msg.log`` for allowed log levels.
``mp.register_script_message(name, fn)``
This is a helper to dispatch ``script-message`` or ``script-message-to``
invocations to Lua functions. ``fn`` is called if ``script-message`` or
``script-message-to`` (with this script as destination) is run
with ``name`` as first parameter. The other parameters are passed to ``fn``.
If a message with the given name is already registered, it's overwritten.
Used by ``mp.add_key_binding``, so be careful about name collisions.
``mp.unregister_script_message(name)``
Undo a previous registration with ``mp.register_script_message``. Does
nothing if the ``name`` wasn't registered.
``mp.create_osd_overlay(format)``
Create an OSD overlay. This is a very thin wrapper around the ``osd-overlay``
command. The function returns a table, which mostly contains fields that
will be passed to ``osd-overlay``. The ``format`` parameter is used to
initialize the ``format`` field. The ``data`` field contains the text to
be used as overlay. For details, see the ``osd-overlay`` command.
In addition, it provides the following methods:
``update()``
Commit the OSD overlay to the screen, or in other words, run the
``osd-overlay`` command with the current fields of the overlay table.
Returns the result of the ``osd-overlay`` command itself.
``remove()``
Remove the overlay from the screen. A ``update()`` call will add it
again.
Example:
::
ov = mp.create_osd_overlay("ass-events")
ov.data = "{\\an5}{\\b1}hello world!"
ov:update()
The advantage of using this wrapper (as opposed to running ``osd-overlay``
directly) is that the ``id`` field is allocated automatically.
``mp.get_osd_size()``
Returns a tuple of ``osd_width, osd_height, osd_par``. The first two give
the size of the OSD in pixels (for video ouputs like ``--vo=xv``, this may
be "scaled" pixels). The third is the display pixel aspect ratio.
May return invalid/nonsense values if OSD is not initialized yet.
mp.msg functions
----------------
This module allows outputting messages to the terminal, and can be loaded
with ``require 'mp.msg'``.
``msg.log(level, ...)``
The level parameter is the message priority. It's a string and one of
``fatal``, ``error``, ``warn``, ``info``, ``v``, ``debug``, ``trace``. The
user's settings will determine which of these messages will be
visible. Normally, all messages are visible, except ``v``, ``debug`` and
``trace``.
The parameters after that are all converted to strings. Spaces are inserted
to separate multiple parameters.
You don't need to add newlines.
``msg.fatal(...)``, ``msg.error(...)``, ``msg.warn(...)``, ``msg.info(...)``, ``msg.verbose(...)``, ``msg.debug(...)``, ``msg.trace(...)``
All of these are shortcuts and equivalent to the corresponding
``msg.log(level, ...)`` call.
mp.options functions
--------------------
mpv comes with a built-in module to manage options from config-files and the
command-line. All you have to do is to supply a table with default options to
the read_options function. The function will overwrite the default values
with values found in the config-file and the command-line (in that order).
``options.read_options(table [, identifier [, on_update]])``
A ``table`` with key-value pairs. The type of the default values is
important for converting the values read from the config file or
command-line back. Do not use ``nil`` as a default value!
The ``identifier`` is used to identify the config-file and the command-line
options. These needs to unique to avoid collisions with other scripts.
Defaults to ``mp.get_script_name()`` if the parameter is ``nil`` or missing.
The ``on_update`` parameter enables run-time updates of all matching option
values via the ``script-opts`` option/property. If any of the matching
options changes, the values in the ``table`` (which was originally passed to
the function) are changed, and ``on_update(list)`` is called. ``list`` is
a table where each updated option has a ``list[option_name] = true`` entry.
There is no initial ``on_update()`` call. This never re-reads the config file.
``script-opts`` is always applied on the original config file, ignoring
previous ``script-opts`` values (for example, if an option is removed from
``script-opts`` at runtime, the option will have the value in the config
file). ``table`` entries are only written for option values whose values
effectively change (this is important if the script changes ``table``
entries independently).
Example implementation::
require 'mp.options'
local options = {
optionA = "defaultvalueA",
optionB = -0.5,
optionC = true,
}
read_options(options, "myscript")
print(options.optionA)
The config file will be stored in ``script-opts/identifier.conf`` in mpv's user
folder. Comment lines can be started with # and stray spaces are not removed.
Boolean values will be represented with yes/no.
Example config::
# comment
optionA=Hello World
optionB=9999
optionC=no
Command-line options are read from the ``--script-opts`` parameter. To avoid
collisions, all keys have to be prefixed with ``identifier-``.
Example command-line::
--script-opts=myscript-optionA=TEST,myscript-optionB=0,myscript-optionC=yes
mp.utils functions
------------------
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 (on Windows, always 755 (octal) for directories
and 644 (octal) for files)
``size``
size in bytes
``atime``
time of last access
``mtime``
time of last modification
``ctime``
time of last metadata change (Linux) / time of creation (Windows)
``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 (eg. 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.subprocess(t)``
Runs an external process and waits until it exits. Returns process status
and the captured output. This is a legacy wrapper around calling the
``subprocess`` command with ``mp.command_native``. It does the following
things:
- copy the table ``t``
- rename ``cancellable`` field to ``playback_only``
- rename ``max_size`` to ``capture_size``
- set ``capture_stdout`` field to ``true`` if unset
- set ``name`` field to ``subprocess``
- call ``mp.command_native(copied_t)``
- if the command failed, create a dummy result table
- copy ``error_string`` to ``error`` field if the string is non-empty
- return the result table
It is recommended to use ``mp.command_native`` or ``mp.command_native_async``
directly, instead of calling this legacy wrapper. It is for compatibility
only.
See the ``subprocess`` documentation for semantics and further parameters.
``utils.subprocess_detached(t)``
Runs an external process and detaches it from mpv's control.
The parameter ``t`` is a table. The function reads the following entries:
``args``
Array of strings of the same semantics as the ``args`` used in the
``subprocess`` function.
The function returns ``nil``.
This is a legacy wrapper around calling the ``run`` command with
``mp.commandv`` and other functions.
``utils.getpid()``
Returns the process ID of the running mpv process. This can be used to identify
the calling mpv when launching (detached) subprocesses.
``utils.get_env_list()``
Returns the C environment as a list of strings. (Do not confuse this with
the Lua "environment", which is an unrelated concept.)
``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.
Events
------
Events are notifications from player core to scripts. You can register an
event handler with ``mp.register_event``.
Note that all scripts (and other parts of the player) receive events equally,
and there's no such thing as blocking other scripts from receiving events.
Example:
::
function my_fn(event)
print("start of playback!")
end
mp.register_event("file-loaded", my_fn)
For the existing event types, see `List of events`_.
Extras
------
This documents experimental features, or features that are "too special" to
guarantee a stable interface.
``mp.add_hook(type, priority, fn)``
Add a hook callback for ``type`` (a string identifying a certain kind of
hook). These hooks allow the player to call script functions and wait for
their result (normally, the Lua scripting interface is asynchronous from
the point of view of the player core). ``priority`` is an arbitrary integer
that allows ordering among hooks of the same kind. Using the value 50 is
recommended as neutral default value.
``fn(hook)`` is the function that will be called during execution of the
hook. The parameter passed to it (``hook``) is a Lua object that can control
further aspects about the currently invoked hook. It provides the following
methods:
``defer()``
Returning from the hook function should not automatically continue
the hook. Instead, the API user wants to call ``hook:cont()`` on its
own at a later point in time (before or after the function has
returned).
``cont()``
Continue the hook. Doesn't need to be called unless ``defer()`` was
called.
See `Hooks`_ for currently existing hooks and what they do - only the hook
list is interesting; handling hook execution is done by the Lua script
function automatically.
-1619
View File
File diff suppressed because it is too large. Load diff
-6803
View File
File diff suppressed because it is too large. Load diff
-403
View File
@@ -1,403 +0,0 @@
ON SCREEN CONTROLLER
====================
The On Screen Controller (short: OSC) is a minimal GUI integrated with mpv to
offer basic mouse-controllability. It is intended to make interaction easier
for new users and to enable precise and direct seeking.
The OSC is enabled by default if mpv was compiled with Lua support. It can be
disabled entirely using the ``--osc=no`` option.
Using the OSC
-------------
By default, the OSC will show up whenever the mouse is moved inside the
player window and will hide if the mouse is not moved outside the OSC for
0.5 seconds or if the mouse leaves the window.
The Interface
~~~~~~~~~~~~~
::
+---------+----------+------------------------------------------+----------+
| pl prev | pl next | title | cache |
+------+--+---+------+---------+-----------+------+-------+-----+-----+----+
| play | skip | skip | time | seekbar | time | audio | sub | vol | fs |
| | back | frwd | elapsed | | left | | | | |
+------+------+------+---------+-----------+------+-------+-----+-----+----+
pl prev
============= ================================================
left-click play previous file in playlist
right-click show playlist
shift+L-click show playlist
============= ================================================
pl next
============= ================================================
left-click play next file in playlist
right-click show playlist
shift+L-click show playlist
============= ================================================
title
| Displays current media-title, filename, or custom title
============= ================================================
left-click show playlist position and length and full title
right-click show filename
============= ================================================
cache
| Shows current cache fill status
play
============= ================================================
left-click toggle play/pause
============= ================================================
skip back
============= ================================================
left-click go to beginning of chapter / previous chapter
right-click show chapters
shift+L-click show chapters
============= ================================================
skip frwd
============= ================================================
left-click go to next chapter
right-click show chapters
shift+L-click show chapters
============= ================================================
time elapsed
| Shows current playback position timestamp
============= ================================================
left-click toggle displaying timecodes with milliseconds
============= ================================================
seekbar
| Indicates current playback position and position of chapters
============= ================================================
left-click seek to position
============= ================================================
time left
| Shows remaining playback time timestamp
============= ================================================
left-click toggle between total and remaining time
============= ================================================
audio and sub
| Displays selected track and amount of available tracks
============= ================================================
left-click cycle audio/sub tracks forward
right-click cycle audio/sub tracks backwards
shift+L-click show available audio/sub tracks
============= ================================================
vol
============= ================================================
left-click toggle mute
mouse wheel volume up/down
============= ================================================
fs
============= ================================================
left-click toggle fullscreen
============= ================================================
Key Bindings
~~~~~~~~~~~~
These key bindings are active by default if nothing else is already bound to
these keys. In case of collision, the function needs to be bound to a
different key. See the `Script Commands`_ section.
============= ================================================
del Cycles visibility between never / auto (mouse-move) / always
============= ================================================
Configuration
-------------
The OSC offers limited configuration through a config file
``script-opts/osc.conf`` placed in mpv's user dir and through the
``--script-opts`` command-line option. Options provided through the command-line
will override those from the config file.
Config Syntax
~~~~~~~~~~~~~
The config file must exactly follow the following syntax::
# this is a comment
optionA=value1
optionB=value2
``#`` can only be used at the beginning of a line and there may be no
spaces around the ``=`` or anywhere else.
Command-line Syntax
~~~~~~~~~~~~~~~~~~~
To avoid collisions with other scripts, all options need to be prefixed with
``osc-``.
Example::
--script-opts=osc-optionA=value1,osc-optionB=value2
Configurable Options
~~~~~~~~~~~~~~~~~~~~
``layout``
Default: bottombar
The layout for the OSC. Currently available are: box, slimbox,
bottombar and topbar. Default pre-0.21.0 was 'box'.
``seekbarstyle``
Default: bar
Sets the style of the playback position marker and overall shape
of the seekbar: ``bar``, ``diamond`` or ``knob``.
``seekbarhandlesize``
Default: 0.6
Size ratio of the seek handle if ``seekbarstyle`` is set to ``dimaond``
or ``knob``. This is relative to the full height of the seekbar.
``seekbarkeyframes``
Default: yes
Controls the mode used to seek when dragging the seekbar (default: true). If
set to true, default seeking mode is used (usually keyframes, but player
defaults and heuristics can change it to exact). If set to false, exact
seeking on mouse drags will be used instead. Keyframes are preferred, but
exact seeks may be useful in cases where keyframes cannot be found. Note
that using exact seeks can potentially make mouse dragging much slower.
``seekrangestyle``
Default: inverted
Display seekable ranges on the seekbar. ``bar`` shows them on the full
height of the bar, ``line`` as a thick line and ``inverted`` as a thin
line that is inverted over playback position markers. ``none`` will hide
them. Additionally, ``slider`` will show a permanent handle inside the seekbar
with cached ranges marked inside. Note that these will look differently
based on the seekbarstyle option. Also, ``slider`` does not work with
``seekbarstyle`` set to ``bar``.
``seekrangeseparate``
Default: yes
Controls whether to show line-style seekable ranges on top of the
seekbar or separately if ``seekbarstyle`` is set to ``bar``.
``seekrangealpha``
Default: 200
Alpha of the seekable ranges, 0 (opaque) to 255 (fully transparent).
``deadzonesize``
Default: 0.5
Size of the deadzone. The deadzone is an area that makes the mouse act
like leaving the window. Movement there won't make the OSC show up and
it will hide immediately if the mouse enters it. The deadzone starts
at the window border opposite to the OSC and the size controls how much
of the window it will span. Values between 0.0 and 1.0, where 0 means the
OSC will always popup with mouse movement in the window, and 1 means the
OSC will only show up when the mouse hovers it. Default pre-0.21.0 was 0.
``minmousemove``
Default: 0
Minimum amount of pixels the mouse has to move between ticks to make
the OSC show up. Default pre-0.21.0 was 3.
``showwindowed``
Default: yes
Enable the OSC when windowed
``showfullscreen``
Default: yes
Enable the OSC when fullscreen
``scalewindowed``
Default: 1.0
Scale factor of the OSC when windowed.
``scalefullscreen``
Default: 1.0
Scale factor of the OSC when fullscreen
``scaleforcedwindow``
Default: 2.0
Scale factor of the OSC when rendered on a forced (dummy) window
``vidscale``
Default: yes
Scale the OSC with the video
``no`` tries to keep the OSC size constant as much as the window size allows
``valign``
Default: 0.8
Vertical alignment, -1 (top) to 1 (bottom)
``halign``
Default: 0.0
Horizontal alignment, -1 (left) to 1 (right)
``barmargin``
Default: 0
Margin from bottom (bottombar) or top (topbar), in pixels
``boxalpha``
Default: 80
Alpha of the background box, 0 (opaque) to 255 (fully transparent)
``hidetimeout``
Default: 500
Duration in ms until the OSC hides if no mouse movement, must not be
negative
``fadeduration``
Default: 200
Duration of fade out in ms, 0 = no fade
``title``
Default: ${media-title}
String that supports property expansion that will be displayed as
OSC title.
ASS tags are escaped, and newlines and trailing slashes are stripped.
``tooltipborder``
Default: 1
Size of the tooltip outline when using bottombar or topbar layouts
``timetotal``
Default: no
Show total time instead of time remaining
``timems``
Default: no
Display timecodes with milliseconds
``visibility``
Default: auto (auto hide/show on mouse move)
Also supports ``never`` and ``always``
``boxmaxchars``
Default: 80
Max chars for the osc title at the box layout. mpv does not measure the
text width on screen and so it needs to limit it by number of chars. The
default is conservative to allow wide fonts to be used without overflow.
However, with many common fonts a bigger number can be used. YMMV.
``boxvideo``
Default: no
Whether to overlay the osc over the video (``no``), or to box the video
within the areas not covered by the osc (``yes``). If this option is set,
the osc may overwrite the ``--video-margin-ratio-*`` options, even if the
user has set them. (It will not overwrite them if all of them are set to
default values.) Additionally, ``visibility`` must be set to ``always``.
Otherwise, this option does nothing.
Currently, this is supported for the ``bottombar`` and ``topbar`` layout
only. The other layouts do not change if this option is set. Separately,
if window controls are present (see below), they will be affected
regardless of which osc layout is in use.
The border is static and appears even if the OSC is configured to appear
only on mouse interaction. If the OSC is invisible, the border is simply
filled with the background color (black by default).
This currently still makes the OSC overlap with subtitles (if the
``--sub-use-margins`` option is set to ``yes``, the default). This may be
fixed later.
This does not work correctly with video outputs like ``--vo=xv``, which
render OSD into the unscaled video.
``windowcontrols``
Default: auto (Show window controls if there is no window border)
Whether to show window management controls over the video, and if so,
which side of the window to place them. This may be desirable when the
window has no decorations, either because they have been explicitly
disabled (``border=no``) or because the current platform doesn't support
them (eg: gnome-shell with wayland).
The set of window controls is fixed, offering ``minimize``, ``maximize``,
and ``quit``. Not all platforms implement ``minimize`` and ``maximize``,
but ``quit`` will always work.
``windowcontrols_alignment``
Default: right
If window controls are shown, indicates which side should they be aligned
to.
Supports ``left`` and ``right`` which will place the controls on those
respective sides.
``greenandgrumpy``
Default: no
Set to ``yes`` to reduce festivity (i.e. disable santa hat in December.)
Script Commands
~~~~~~~~~~~~~~~
The OSC script listens to certain script commands. These commands can bound
in ``input.conf``, or sent by other scripts.
``osc-message``
Show a message on screen using the OSC. First argument is the message,
second the duration in seconds.
``osc-visibility``
Controls visibility mode ``never`` / ``auto`` (on mouse move) / ``always``
and also ``cycle`` to cycle between the modes
Example
You could put this into ``input.conf`` to hide the OSC with the ``a`` key and
to set auto mode (the default) with ``b``::
a script-message osc-visibility never
b script-message osc-visibility auto
``osc-playlist``, ``osc-chapterlist``, ``osc-tracklist``
Shows a limited view of the respective type of list using the OSC. First
argument is duration in seconds.
-221
View File
@@ -1,221 +0,0 @@
STATS
=====
This builtin script displays information and statistics for the currently
played file. It is enabled by default if mpv was compiled with Lua support.
It can be disabled entirely using the ``--load-stats-overlay=no`` option.
Usage
-----
The following key bindings are active by default unless something else is
already bound to them:
==== ==============================================
i Show stats for a fixed duration
I Toggle stats (shown until toggled again)
==== ==============================================
While the stats are visible on screen the following key bindings are active,
regardless of existing bindings. They allow you to switch between *pages* of
stats:
==== ==================
1 Show usual stats
2 Show frame timings (scroll)
3 Input cache stats
4 Internal stuff (scroll)
==== ==================
On pages which support scroll, these key bindings are also active:
==== ==================
UP Scroll one line up
DOWN Scroll one line down
==== ==================
Font
~~~~
For optimal visual experience, a font with support for many font weights and
monospaced digits is recommended. By default, the open source font
`Source Sans Pro <https://github.com/adobe-fonts/source-sans-pro>`_ is used.
Configuration
-------------
This script can be customized through a config file ``script-opts/stats.conf``
placed in mpv's user directory and through the ``--script-opts`` command-line
option. The configuration syntax is described in `ON SCREEN CONTROLLER`_.
Configurable Options
~~~~~~~~~~~~~~~~~~~~
``key_oneshot``
Default: i
``key_toggle``
Default: I
Key bindings to display stats.
``key_page_1``
Default: 1
``key_page_2``
Default: 2
``key_page_3``
Default: 3
``key_page_4``
Default: 4
Key bindings for page switching while stats are displayed.
``key_scroll_up``
Default: UP
``key_scroll_down``
Default: DOWN
``scroll_lines``
Default: 1
Scroll key bindings and number of lines to scroll on pages which support it.
``duration``
Default: 4
How long the stats are shown in seconds (oneshot).
``redraw_delay``
Default: 1
How long it takes to refresh the displayed stats in seconds (toggling).
``persistent_overlay``
Default: no
When `no`, other scripts printing text to the screen can overwrite the
displayed stats. When `yes`, displayed stats are persistently shown for the
respective duration. This can result in overlapping text when multiple
scripts decide to print text at the same time.
``plot_perfdata``
Default: yes
Show graphs for performance data (page 2).
``plot_vsync_ratio``
Default: yes
``plot_vsync_jitter``
Default: yes
Show graphs for vsync and jitter values (page 1). Only when toggled.
``flush_graph_data``
Default: yes
Clear data buffers used for drawing graphs when toggling.
``font``
Default: Source Sans Pro
Font name. Should support as many font weights as possible for optimal
visual experience.
``font_mono``
Default: Source Sans Pro
Font name for parts where monospaced characters are necessary to align
text. Currently, monospaced digits are sufficient.
``font_size``
Default: 8
Font size used to render text.
``font_color``
Default: FFFFFF
Font color.
``border_size``
Default: 0.8
Size of border drawn around the font.
``border_color``
Default: 262626
Color of drawn border.
``alpha``
Default: 11
Transparency for drawn text.
``plot_bg_border_color``
Default: 0000FF
Border color used for drawing graphs.
``plot_bg_color``
Default: 262626
Background color used for drawing graphs.
``plot_color``
Default: FFFFFF
Color used for drawing graphs.
Note: colors are given as hexadecimal values and use ASS tag order: BBGGRR
(blue green red).
Different key bindings
~~~~~~~~~~~~~~~~~~~~~~
A different key binding can be defined with the aforementioned options
``key_oneshot`` and ``key_toggle`` but also with commands in ``input.conf``,
for example::
e script-binding stats/display-stats
E script-binding stats/display-stats-toggle
Using ``input.conf``, it is also possible to directly display a certain page::
i script-binding stats/display-page-1
e script-binding stats/display-page-2
Internal stuff page
~~~~~~~~~~~~~~~~~~~
Most entries shown on this page have rather vague meaning. Likely none of this
is useful for you. Don't attempt to use it. Forget its existence.
Selecting this for the first time will start collecting some internal
performance data. That means performance will be slightly lower than normal for
the rest of the time the player is running (even if the stats page is closed).
Note that the stats page itself uses a lot of CPU and even GPU resources, and
may have a heavy impact on performance.
The displayed information is accumulated over the redraw delay (shown as
``poll-time`` field).
This adds entries for each Lua script. If there are too many scripts running,
parts of the list will simply be out of the screen, but it can be scrolled.
If the underlying platform does not support pthread per thread times, the
displayed times will be 0 or something random (I suspect that at time of this
writing, only Linux provides the correct via pthread APIs for per thread times).
Most entries are added lazily and only during data collection, which is why
entries may pop up randomly after some time. It's also why the memory usage
entries for scripts that have been inactive since the start of data collection
are missing.
Memory usage is approximate and does not reflect internal fragmentation.
JS scripts memory reporting is disabled by default because collecting the data
at the JS side has an overhead. It can be enabled by exporting the env var
``MPV_LEAK_REPORT=1`` before starting mpv, and will increase JS memory usage.
If entries have ``/time`` and ``/cpu`` variants, the former gives the real time
(monotonic clock), while the latter the thread CPU time (only if the
corresponding pthread API works and is supported).
-779
View File
@@ -1,779 +0,0 @@
VIDEO FILTERS
=============
Video filters allow you to modify the video stream and its properties. All of
the information described in this section applies to audio filters as well
(generally using the prefix ``--af`` instead of ``--vf``).
The exact syntax is:
``--vf=<filter1[=parameter1:parameter2:...],filter2,...>``
Setup a chain of video filters. This consists on the filter name, and an
option list of parameters after ``=``. The parameters are separated by
``:`` (not ``,``, as that starts a new filter entry).
Before the filter name, a label can be specified with ``@name:``, where
name is an arbitrary user-given name, which identifies the filter. This
is only needed if you want to toggle the filter at runtime.
A ``!`` before the filter name means the filter is disabled by default. It
will be skipped on filter creation. This is also useful for runtime filter
toggling.
See the ``vf`` command (and ``toggle`` sub-command) for further explanations
and examples.
The general filter entry syntax is:
``["@"<label-name>":"] ["!"] <filter-name> [ "=" <filter-parameter-list> ]``
or for the special "toggle" syntax (see ``vf`` command):
``"@"<label-name>``
and the ``filter-parameter-list``:
``<filter-parameter> | <filter-parameter> "," <filter-parameter-list>``
and ``filter-parameter``:
``( <param-name> "=" <param-value> ) | <param-value>``
``param-value`` can further be quoted in ``[`` / ``]`` in case the value
contains characters like ``,`` or ``=``. This is used in particular with
the ``lavfi`` filter, which uses a very similar syntax as mpv (MPlayer
historically) to specify filters and their parameters.
Filters can be manipulated at run time. You can use ``@`` labels as described
above in combination with the ``vf`` command (see `COMMAND INTERFACE`_) to get
more control over this. Initially disabled filters with ``!`` are useful for
this as well.
You can also set defaults for each filter. The defaults are applied before the
normal filter parameters. This is deprecated and never worked for the
libavfilter bridge.
``--vf-defaults=<filter1[=parameter1:parameter2:...],filter2,...>``
Set defaults for each filter. (Deprecated. ``--af-defaults`` is deprecated
as well.)
.. note::
To get a full list of available video filters, see ``--vf=help`` and
http://ffmpeg.org/ffmpeg-filters.html .
Also, keep in mind that most actual filters are available via the ``lavfi``
wrapper, which gives you access to most of libavfilter's filters. This
includes all filters that have been ported from MPlayer to libavfilter.
Most builtin filters are deprecated in some ways, unless they're only available
in mpv (such as filters which deal with mpv specifics, or which are
implemented in mpv only).
If a filter is not builtin, the ``lavfi-bridge`` will be automatically
tried. This bridge does not support help output, and does not verify
parameters before the filter is actually used. Although the mpv syntax
is rather similar to libavfilter's, it's not the same. (Which means not
everything accepted by vf_lavfi's ``graph`` option will be accepted by
``--vf``.)
You can also prefix the filter name with ``lavfi-`` to force the wrapper.
This is helpful if the filter name collides with a deprecated mpv builtin
filter. For example ``--vf=lavfi-scale=args`` would use libavfilter's
``scale`` filter over mpv's deprecated builtin one.
Video filters are managed in lists. There are a few commands to manage the
filter list.
``--vf-append=filter``
Appends the filter given as arguments to the filter list.
``--vf-add=filter``
Appends the filter given as arguments to the filter list. (Passing multiple
filters is currently still possible, but deprecated.)
``--vf-pre=filter``
Prepends the filters given as arguments to the filter list. (Passing
multiple filters is currently still possible, but deprecated.)
``--vf-remove=filter``
Deletes the filter from the list. The filter can be either given the way it
was added (filter name and its full argument list), or by label (prefixed
with ``@``). Matching of filters works as follows: if either of the compared
filters has a label set, only the labels are compared. If none of the
filters have a label, the filter name, arguments, and argument order are
compared. (Passing multiple filters is currently still possible, but
deprecated.)
``-vf-toggle=filter``
Add the given filter to the list if it was not present yet, or remove it
from the list if it was present. Matching of filters works as described in
``--vf-remove``.
``--vf-del=filter``
Sort of like ``--vf-remove``, but also accepts an index number. Index
numbers start at 0, negative numbers address the end of the list (-1 is the
last). Deprecated.
``--vf-clr``
Completely empties the filter list.
With filters that support it, you can access parameters by their name.
``--vf=<filter>=help``
Prints the parameter names and parameter value ranges for a particular
filter.
Available mpv-only filters are:
``format=fmt=<value>:colormatrix=<value>:...``
Applies video parameter overrides, with optional conversion. By default,
this overrides the video's parameters without conversion (except for the
``fmt`` parameter), but can be made to perform an appropriate conversion
with ``convert=yes`` for parameters for which conversion is supported.
``<fmt>``
Image format name, e.g. rgb15, bgr24, 420p, etc. (default: don't change).
This filter always performs conversion to the given format.
.. note::
For a list of available formats, use ``--vf=format=fmt=help``.
``<convert=yes|no>``
Force conversion of color parameters (default: no).
If this is disabled (the default), the only conversion that is possibly
performed is format conversion if ``<fmt>`` is set. All other parameters
(like ``<colormatrix>``) are forced without conversion. This mode is
typically useful when files have been incorrectly tagged.
If this is enabled, libswscale or zimg is used if any of the parameters
mismatch. zimg is used of the input/output image formats are supported
by mpv's zimg wrapper, and if ``--sws-allow-zimg=yes`` is used. Both
libraries may not support all kinds of conversions. This typically
results in silent incorrect conversion. zimg has in many cases a better
chance of performing the conversion correctly.
In both cases, the color parameters are set on the output stage of the
image format conversion (if ``fmt`` was set). The difference is that
with ``convert=no``, the color parameters are not passed on to the
converter.
If input and output video parameters are the same, conversion is always
skipped.
.. admonition:: Examples
``mpv test.mkv --vf=format:colormatrix=ycgco``
Results in incorrect colors (if test.mkv was tagged correctly).
``mpv test.mkv --vf=format:colormatrix=ycgco:convert=yes --sws-allow-zimg``
Results in true conversion to ``ycgco``, assuming the renderer
supports it (``--vo=gpu`` normally does). You can add ``--vo=xv``
to force a VO which definitely does not support it, which should
show incorrect colors as confirmation.
Using ``--sws-allow-zimg=no`` (or disabling zimg at build time)
will use libswscale, which cannot perform this conversion as
of this writing.
``<colormatrix>``
Controls the YUV to RGB color space conversion when playing video. There
are various standards. Normally, BT.601 should be used for SD video, and
BT.709 for HD video. (This is done by default.) Using incorrect color space
results in slightly under or over saturated and shifted colors.
These options are not always supported. Different video outputs provide
varying degrees of support. The ``gpu`` and ``vdpau`` video output
drivers usually offer full support. The ``xv`` output can set the color
space if the system video driver supports it, but not input and output
levels. The ``scale`` video filter can configure color space and input
levels, but only if the output format is RGB (if the video output driver
supports RGB output, you can force this with ``-vf scale,format=rgba``).
If this option is set to ``auto`` (which is the default), the video's
color space flag will be used. If that flag is unset, the color space
will be selected automatically. This is done using a simple heuristic that
attempts to distinguish SD and HD video. If the video is larger than
1279x576 pixels, BT.709 (HD) will be used; otherwise BT.601 (SD) is
selected.
Available color spaces are:
:auto: automatic selection (default)
:bt.601: ITU-R BT.601 (SD)
:bt.709: ITU-R BT.709 (HD)
:bt.2020-ncl: ITU-R BT.2020 non-constant luminance system
:bt.2020-cl: ITU-R BT.2020 constant luminance system
:smpte-240m: SMPTE-240M
``<colorlevels>``
YUV color levels used with YUV to RGB conversion. This option is only
necessary when playing broken files which do not follow standard color
levels or which are flagged wrong. If the video does not specify its
color range, it is assumed to be limited range.
The same limitations as with ``<colormatrix>`` apply.
Available color ranges are:
:auto: automatic selection (normally limited range) (default)
:limited: limited range (16-235 for luma, 16-240 for chroma)
:full: full range (0-255 for both luma and chroma)
``<primaries>``
RGB primaries the source file was encoded with. Normally this should be set
in the file header, but when playing broken or mistagged files this can be
used to override the setting.
This option only affects video output drivers that perform color
management, for example ``gpu`` with the ``target-prim`` or
``icc-profile`` suboptions set.
If this option is set to ``auto`` (which is the default), the video's
primaries flag will be used. If that flag is unset, the color space will
be selected automatically, using the following heuristics: If the
``<colormatrix>`` is set or determined as BT.2020 or BT.709, the
corresponding primaries are used. Otherwise, if the video height is
exactly 576 (PAL), BT.601-625 is used. If it's exactly 480 or 486 (NTSC),
BT.601-525 is used. If the video resolution is anything else, BT.709 is
used.
Available primaries are:
:auto: automatic selection (default)
:bt.601-525: ITU-R BT.601 (SD) 525-line systems (NTSC, SMPTE-C)
:bt.601-625: ITU-R BT.601 (SD) 625-line systems (PAL, SECAM)
:bt.709: ITU-R BT.709 (HD) (same primaries as sRGB)
:bt.2020: ITU-R BT.2020 (UHD)
:apple: Apple RGB
:adobe: Adobe RGB (1998)
:prophoto: ProPhoto RGB (ROMM)
:cie1931: CIE 1931 RGB
:dci-p3: DCI-P3 (Digital Cinema)
:v-gamut: Panasonic V-Gamut primaries
``<gamma>``
Gamma function the source file was encoded with. Normally this should be set
in the file header, but when playing broken or mistagged files this can be
used to override the setting.
This option only affects video output drivers that perform color management.
If this option is set to ``auto`` (which is the default), the gamma will
be set to BT.1886 for YCbCr content, sRGB for RGB content and Linear for
XYZ content.
Available gamma functions are:
:auto: automatic selection (default)
:bt.1886: ITU-R BT.1886 (EOTF corresponding to BT.601/BT.709/BT.2020)
:srgb: IEC 61966-2-4 (sRGB)
:linear: Linear light
:gamma1.8: Pure power curve (gamma 1.8)
:gamma2.0: Pure power curve (gamma 2.0)
:gamma2.2: Pure power curve (gamma 2.2)
:gamma2.4: Pure power curve (gamma 2.4)
:gamma2.6: Pure power curve (gamma 2.6)
:gamma2.8: Pure power curve (gamma 2.8)
:prophoto: ProPhoto RGB (ROMM) curve
:pq: ITU-R BT.2100 PQ (Perceptual quantizer) curve
:hlg: ITU-R BT.2100 HLG (Hybrid Log-gamma) curve
:v-log: Panasonic V-Log transfer curve
:s-log1: Sony S-Log1 transfer curve
:s-log2: Sony S-Log2 transfer curve
``<sig-peak>``
Reference peak illumination for the video file, relative to the
signal's reference white level. This is mostly interesting for HDR, but
it can also be used tone map SDR content to simulate a different
exposure. Normally inferred from tags such as MaxCLL or mastering
metadata.
The default of 0.0 will default to the source's nominal peak luminance.
``<light>``
Light type of the scene. This is mostly correctly inferred based on the
gamma function, but it can be useful to override this when viewing raw
camera footage (e.g. V-Log), which is normally scene-referred instead
of display-referred.
Available light types are:
:auto: Automatic selection (default)
:display: Display-referred light (most content)
:hlg: Scene-referred using the HLG OOTF (e.g. HLG content)
:709-1886: Scene-referred using the BT709+BT1886 interaction
:gamma1.2: Scene-referred using a pure power OOTF (gamma=1.2)
``<stereo-in>``
Set the stereo mode the video is assumed to be encoded in. Use
``--vf format:stereo-in=help`` to list all available modes. Check with
the ``stereo3d`` filter documentation to see what the names mean.
``<stereo-out>``
Set the stereo mode the video should be displayed as. Takes the
same values as the ``stereo-in`` option.
``<rotate>``
Set the rotation the video is assumed to be encoded with in degrees.
The special value ``-1`` uses the input format.
``<w>``, ``<h>``
If not 0, perform conversion to the given size. Ignored if
``convert=yes`` is not set.
``<dw>``, ``<dh>``
Set the display size. Note that setting the display size such that
the video is scaled in both directions instead of just changing the
aspect ratio is an implementation detail, and might change later.
``<dar>``
Set the display aspect ratio of the video frame. This is a float,
but values such as ``[16:9]`` can be passed too (``[...]`` for quoting
to prevent the option parser from interpreting the ``:`` character).
``<force-scaler=auto|zimg|sws>``
Force a specific scaler backend, if applicable. This is a debug option
and could go away any time.
``<alpha=auto|straight|premul>``
Set the kind of alpha the video uses. Undefined effect if the image
format has no alpha channel (could be ignored or cause an error,
depending on how mpv internals evolve). Setting this may or may not
cause downstream image processing to treat alpha differently, depending
on support. With ``convert`` and zimg used, this will convert the alpha.
libswscale and other FFmpeg components completely ignore this.
``lavfi=graph[:sws-flags[:o=opts]]``
Filter video using FFmpeg's libavfilter.
``<graph>``
The libavfilter graph string. The filter must have a single video input
pad and a single video output pad.
See `<https://ffmpeg.org/ffmpeg-filters.html>`_ for syntax and available
filters.
.. warning::
If you want to use the full filter syntax with this option, you have
to quote the filter graph in order to prevent mpv's syntax and the
filter graph syntax from clashing. To prevent a quoting and escaping
mess, consider using ``--lavfi-complex`` if you know which video
track you want to use from the input file. (There is only one video
track for nearly all video files anyway.)
.. admonition:: Examples
``--vf=lavfi=[gradfun=20:30,vflip]``
``gradfun`` filter with nonsense parameters, followed by a
``vflip`` filter. (This demonstrates how libavfilter takes a
graph and not just a single filter.) The filter graph string is
quoted with ``[`` and ``]``. This requires no additional quoting
or escaping with some shells (like bash), while others (like
zsh) require additional ``"`` quotes around the option string.
``'--vf=lavfi="gradfun=20:30,vflip"'``
Same as before, but uses quoting that should be safe with all
shells. The outer ``'`` quotes make sure that the shell does not
remove the ``"`` quotes needed by mpv.
``'--vf=lavfi=graph="gradfun=radius=30:strength=20,vflip"'``
Same as before, but uses named parameters for everything.
``<sws-flags>``
If libavfilter inserts filters for pixel format conversion, this
option gives the flags which should be passed to libswscale. This
option is numeric and takes a bit-wise combination of ``SWS_`` flags.
See ``http://git.videolan.org/?p=ffmpeg.git;a=blob;f=libswscale/swscale.h``.
``<o>``
Set AVFilterGraph options. These should be documented by FFmpeg.
.. admonition:: Example
``'--vf=lavfi=yadif:o="threads=2,thread_type=slice"'``
forces a specific threading configuration.
``sub=[=bottom-margin:top-margin]``
Moves subtitle rendering to an arbitrary point in the filter chain, or force
subtitle rendering in the video filter as opposed to using video output OSD
support.
``<bottom-margin>``
Adds a black band at the bottom of the frame. The SSA/ASS renderer can
place subtitles there (with ``--sub-use-margins``).
``<top-margin>``
Black band on the top for toptitles (with ``--sub-use-margins``).
.. admonition:: Examples
``--vf=sub,eq``
Moves sub rendering before the eq filter. This will put both
subtitle colors and video under the influence of the video equalizer
settings.
``vapoursynth=file:buffered-frames:concurrent-frames``
Loads a VapourSynth filter script. This is intended for streamed
processing: mpv actually provides a source filter, instead of using a
native VapourSynth video source. The mpv source will answer frame
requests only within a small window of frames (the size of this window
is controlled with the ``buffered-frames`` parameter), and requests outside
of that will return errors. As such, you can't use the full power of
VapourSynth, but you can use certain filters.
.. warning::
Do not use this filter, unless you have expert knowledge in VapourSynth,
and know how to fix bugs in the mpv VapourSynth wrapper code.
If you just want to play video generated by VapourSynth (i.e. using
a native VapourSynth video source), it's better to use ``vspipe`` and a
pipe or FIFO to feed the video to mpv. The same applies if the filter script
requires random frame access (see ``buffered-frames`` parameter).
``file``
Filename of the script source. Currently, this is always a python
script (``.vpy`` in VapourSynth convention).
The variable ``video_in`` is set to the mpv video source, and it is
expected that the script reads video from it. (Otherwise, mpv will
decode no video, and the video packet queue will overflow, eventually
leading to only audio playing, or worse.)
The filter graph created by the script is also expected to pass through
timestamps using the ``_DurationNum`` and ``_DurationDen`` frame
properties.
See the end of the option list for a full list of script variables
defined by mpv.
.. admonition:: Example:
::
import vapoursynth as vs
core = vs.get_core()
core.std.AddBorders(video_in, 10, 10, 20, 20).set_output()
.. warning::
The script will be reloaded on every seek. This is done to reset
the filter properly on discontinuities.
``buffered-frames``
Maximum number of decoded video frames that should be buffered before
the filter (default: 4). This specifies the maximum number of frames
the script can request in backward direction.
E.g. if ``buffered-frames=5``, and the script just requested frame 15,
it can still request frame 10, but frame 9 is not available anymore.
If it requests frame 30, mpv will decode 15 more frames, and keep only
frames 25-30.
The only reason why this buffer exists is to serve the random access
requests the VapourSynth filter can make.
The VapourSynth API has a ``getFrameAsync`` function, which takes an
absolute frame number. Source filters must respond to all requests. For
example, a source filter can request frame 2432, and then frame 3.
Source filters typically implement this by pre-indexing the entire
file.
mpv on the other hand is stream oriented, and does not allow filters to
seek. (And it would not make sense to allow it, because it would ruin
performance.) Filters get frames sequentially in playback direction, and
cannot request them out of order.
To compensate for this mismatch, mpv allows the filter to access frames
within a certain window. ``buffered-frames`` controls the size of this
window. Most VapourSynth filters happen to work with this, because mpv
requests frames sequentially increasing from it, and most filters only
require frames "close" to the requested frame.
If the filter requests a frame that has a higher frame number than the
highest buffered frame, new frames will be decoded until the requested
frame number is reached. Excessive frames will be flushed out in a FIFO
manner (there are only at most ``buffered-frames`` in this buffer).
If the filter requests a frame that has a lower frame number than the
lowest buffered frame, the request cannot be satisfied, and an error
is returned to the filter. This kind of error is not supposed to happen
in a "proper" VapourSynth environment. What exactly happens depends on
the filters involved.
Increasing this buffer will not improve performance. Rather, it will
waste memory, and slow down seeks (when enough frames to fill the buffer
need to be decoded at once). It is only needed to prevent the error
described in the previous paragraph.
How many frames a filter requires depends on filter implementation
details, and mpv has no way of knowing. A scale filter might need only
1 frame, an interpolation filter may require a small number of frames,
and the ``Reverse`` filter will require an infinite number of frames.
If you want reliable operation to the full extend VapourSynth is
capable, use ``vspipe``.
The actual number of buffered frames also depends on the value of the
``concurrent-frames`` option. Currently, both option values are
multiplied to get the final buffer size.
``concurrent-frames``
Number of frames that should be requested in parallel. The
level of concurrency depends on the filter and how quickly mpv can
decode video to feed the filter. This value should probably be
proportional to the number of cores on your machine. Most time,
making it higher than the number of cores can actually make it
slower.
Technically, mpv will call the VapourSynth ``getFrameAsync`` function
in a loop, until there are ``concurrent-frames`` frames that have not
been returned by the filter yet. This also assumes that the rest of the
mpv filter chain reads the output of the ``vapoursynth`` filter quickly
enough. (For example, if you pause the player, filtering will stop very
soon, because the filtered frames are waiting in a queue.)
Actual concurrency depends on many other factors.
By default, this uses the special value ``auto``, which sets the option
to the number of detected logical CPU cores.
The following ``.vpy`` script variables are defined by mpv:
``video_in``
The mpv video source as vapoursynth clip. Note that this has an
incorrect (very high) length set, which confuses many filters. This is
necessary, because the true number of frames is unknown. You can use the
``Trim`` filter on the clip to reduce the length.
``video_in_dw``, ``video_in_dh``
Display size of the video. Can be different from video size if the
video does not use square pixels (e.g. DVD).
``container_fps``
FPS value as reported by file headers. This value can be wrong or
completely broken (e.g. 0 or NaN). Even if the value is correct,
if another filter changes the real FPS (by dropping or inserting
frames), the value of this variable will not be useful. Note that
the ``--fps`` command line option overrides this value.
Useful for some filters which insist on having a FPS.
``display_fps``
Refresh rate of the current display. Note that this value can be 0.
``vavpp``
VA-API video post processing. Requires the system to support VA-API,
i.e. Linux/BSD only. Works with ``--vo=vaapi`` and ``--vo=gpu`` only.
Currently deinterlaces. This filter is automatically inserted if
deinterlacing is requested (either using the ``d`` key, by default mapped to
the command ``cycle deinterlace``, or the ``--deinterlace`` option).
``deint=<method>``
Select the deinterlacing algorithm.
no
Don't perform deinterlacing.
auto
Select the best quality deinterlacing algorithm (default). This
goes by the order of the options as documented, with
``motion-compensated`` being considered best quality.
first-field
Show only first field.
bob
bob deinterlacing.
weave, motion-adaptive, motion-compensated
Advanced deinterlacing algorithms. Whether these actually work
depends on the GPU hardware, the GPU drivers, driver bugs, and
mpv bugs.
``<interlaced-only>``
:no: Deinterlace all frames (default).
:yes: Only deinterlace frames marked as interlaced.
``reversal-bug=<yes|no>``
:no: Use the API as it was interpreted by older Mesa drivers. While
this interpretation was more obvious and inuitive, it was
apparently wrong, and not shared by Intel driver developers.
:yes: Use Intel interpretation of surface forward and backwards
references (default). This is what Intel drivers and newer Mesa
drivers expect. Matters only for the advanced deinterlacing
algorithms.
``vdpaupp``
VDPAU video post processing. Works with ``--vo=vdpau`` and ``--vo=gpu``
only. This filter is automatically inserted if deinterlacing is requested
(either using the ``d`` key, by default mapped to the command
``cycle deinterlace``, or the ``--deinterlace`` option). When enabling
deinterlacing, it is always preferred over software deinterlacer filters
if the ``vdpau`` VO is used, and also if ``gpu`` is used and hardware
decoding was activated at least once (i.e. vdpau was loaded).
``sharpen=<-1-1>``
For positive values, apply a sharpening algorithm to the video, for
negative values a blurring algorithm (default: 0).
``denoise=<0-1>``
Apply a noise reduction algorithm to the video (default: 0; no noise
reduction).
``deint=<yes|no>``
Whether deinterlacing is enabled (default: no). If enabled, it will use
the mode selected with ``deint-mode``.
``deint-mode=<first-field|bob|temporal|temporal-spatial>``
Select deinterlacing mode (default: temporal).
Note that there's currently a mechanism that allows the ``vdpau`` VO to
change the ``deint-mode`` of auto-inserted ``vdpaupp`` filters. To avoid
confusion, it's recommended not to use the ``--vo=vdpau`` suboptions
related to filtering.
first-field
Show only first field.
bob
Bob deinterlacing.
temporal
Motion-adaptive temporal deinterlacing. May lead to A/V desync
with slow video hardware and/or high resolution.
temporal-spatial
Motion-adaptive temporal deinterlacing with edge-guided spatial
interpolation. Needs fast video hardware.
``chroma-deint``
Makes temporal deinterlacers operate both on luma and chroma (default).
Use no-chroma-deint to solely use luma and speed up advanced
deinterlacing. Useful with slow video memory.
``pullup``
Try to apply inverse telecine, needs motion adaptive temporal
deinterlacing.
``interlaced-only=<yes|no>``
If ``yes``, only deinterlace frames marked as interlaced (default: no).
``hqscaling=<0-9>``
0
Use default VDPAU scaling (default).
1-9
Apply high quality VDPAU scaling (needs capable hardware).
``d3d11vpp``
Direct3D 11 video post processing. Currently requires D3D11 hardware
decoding for use.
``deint=<yes|no>``
Whether deinterlacing is enabled (default: no).
``interlaced-only=<yes|no>``
If ``yes``, only deinterlace frames marked as interlaced (default: no).
``mode=<blend|bob|adaptive|mocomp|ivctc|none>``
Tries to select a video processor with the given processing capability.
If a video processor supports multiple capabilities, it is not clear
which algorithm is actually selected. ``none`` always falls back. On
most if not all hardware, this option will probably do nothing, because
a video processor usually supports all modes or none.
``fingerprint=...``
Compute video frame fingerprints and provide them as metadata. Actually, it
currently barely deserved to be called ``fingerprint``, because it does not
compute "proper" fingerprints, only tiny downscaled images (but which can be
used to compute image hashes or for similarity matching).
The main purpose of this filter is to support the ``skip-logo.lua`` script.
If this script is dropped, or mpv ever gains a way to load user-defined
filters (other than VapourSynth), this filter will be removed. Due to the
"special" nature of this filter, it will be removed without warning.
The intended way to read from the filter is using ``vf-metadata`` (also
see ``clear-on-query`` filter parameter). The property will return a list
of key/value pairs as follows:
::
fp0.pts = 1.2345
fp0.hex = 1234abcdef...bcde
fp1.pts = 1.4567
fp1.hex = abcdef1234...6789
...
fpN.pts = ...
fpN.hex = ...
type = gray-hex-16x16
Each ``fp<N>`` entry is for a frame. The ``pts`` entry specifies the
timestamp of the frame (within the filter chain; in simple cases this is
the same as the display timestamp). The ``hex`` field is the hex encoded
fingerprint, whose size and meaning depend on the ``type`` filter option.
The ``type`` field has the same value as the option the filter was created
with.
This returns the frames that were filtered since the last query of the
property. If ``clear-on-query=no`` was set, a query doesn't reset the list
of frames. In both cases, a maximum of 10 frames is returned. If there are
more frames, the oldest frames are discarded. Frames are returned in filter
order.
(This doesn't return a structured list for the per-frame details because the
internals of the ``vf-metadata`` mechanism suck. The returned format may
change in the future.)
This filter uses zimg for speed and profit. However, it will fallback to
libswscale in a number of situations: lesser pixel formats, unaligned data
pointers or strides, or if zimg fails to initialize for unknown reasons. In
these cases, the filter will use more CPU. Also, it will output different
fingerprints, because libswscale cannot perform the full range expansion we
normally request from zimg. As a consequence, the filter may be slower and
not work correctly in random situations.
``type=...``
What fingerprint to compute. Available types are:
:gray-hex-8x8: grayscale, 8 bit, 8x8 size
:gray-hex-16x16: grayscale, 8 bit, 16x16 size (default)
Both types simply remove all colors, downscale the image, concatenate
all pixel values to a byte array, and convert the array to a hex string.
``clear-on-query=yes|no``
Clear the list of frame fingerprints if the ``vf-metadata`` property for
this filter is queried (default: yes). This requires some care by the
user. Some types of accesses might query the filter multiple times,
which leads to lost frames.
``print=yes|no``
Print computed fingerprints the the terminal (default: no). This is
mostly for testing and such. Scripts should use ``vf-metadata`` to
read information from this filter instead.
``gpu=...``
Convert video to RGB using the OpenGL renderer normally used with
``--vo=gpu``. This requires that the EGL implementation supports off-screen
rendering on the default display. (This is the case with Mesa.)
Sub-options:
``w=<pixels>``, ``h=<pixels>``
Size of the output in pixels (default: 0). If not positive, this will
use the size of the first filtered input frame.
.. warning::
This is highly experimental. Performance is bad, and it will not work
everywhere in the first place. Some features are not supported.
.. warning::
This does not do OSD rendering. If you see OSD, then it has been
rendered by the VO backend. (Subtitles are rendered by the ``gpu``
filter, if possible.)
.. warning::
If you use this with encoding mode, keep in mind that encoding mode will
convert the RGB filter's output back to yuv420p in software, using the
configured software scaler. Using ``zimg`` might improve this, but in
any case it might go against your goals when using this filter.
.. warning::
Do not use this with ``--vo=gpu``. It will apply filtering twice, since
most ``--vo=gpu`` options are unconditionally applied to the ``gpu``
filter. There is no mechanism in mpv to prevent this.
-651
View File
@@ -1,651 +0,0 @@
VIDEO OUTPUT DRIVERS
====================
Video output drivers are interfaces to different video output facilities. The
syntax is:
``--vo=<driver1,driver2,...[,]>``
Specify a priority list of video output drivers to be used.
If the list has a trailing ``,``, mpv will fall back on drivers not contained
in the list.
.. note::
See ``--vo=help`` for a list of compiled-in video output drivers.
The recommended output driver is ``--vo=gpu``, which is the default. All
other drivers are for compatibility or special purposes. If the default
does not work, it will fallback to other drivers (in the same order as
listed by ``--vo=help``).
Available video output drivers are:
``xv`` (X11 only)
Uses the XVideo extension to enable hardware-accelerated display. This is
the most compatible VO on X, but may be low-quality, and has issues with
OSD and subtitle display.
.. note:: This driver is for compatibility with old systems.
The following global options are supported by this video output:
``--xv-adaptor=<number>``
Select a specific XVideo adapter (check xvinfo results).
``--xv-port=<number>``
Select a specific XVideo port.
``--xv-ck=<cur|use|set>``
Select the source from which the color key is taken (default: cur).
cur
The default takes the color key currently set in Xv.
use
Use but do not set the color key from mpv (use the ``--colorkey``
option to change it).
set
Same as use but also sets the supplied color key.
``--xv-ck-method=<none|man|bg|auto>``
Sets the color key drawing method (default: man).
none
Disables color-keying.
man
Draw the color key manually (reduces flicker in some cases).
bg
Set the color key as window background.
auto
Let Xv draw the color key.
``--xv-colorkey=<number>``
Changes the color key to an RGB value of your choice. ``0x000000`` is
black and ``0xffffff`` is white.
``--xv-buffers=<number>``
Number of image buffers to use for the internal ringbuffer (default: 2).
Increasing this will use more memory, but might help with the X server
not responding quickly enough if video FPS is close to or higher than
the display refresh rate.
``x11`` (X11 only)
Shared memory video output driver without hardware acceleration that works
whenever X11 is present.
Since mpv 0.30.0, you may need to use ``--profile=sw-fast`` to get decent
performance.
.. note:: This is a fallback only, and should not be normally used.
``vdpau`` (X11 only)
Uses the VDPAU interface to display and optionally also decode video.
Hardware decoding is used with ``--hwdec=vdpau``.
.. note::
Earlier versions of mpv (and MPlayer, mplayer2) provided sub-options
to tune vdpau post-processing, like ``deint``, ``sharpen``, ``denoise``,
``chroma-deint``, ``pullup``, ``hqscaling``. These sub-options are
deprecated, and you should use the ``vdpaupp`` video filter instead.
The following global options are supported by this video output:
``--vo-vdpau-sharpen=<-1-1>``
(Deprecated. See note about ``vdpaupp``.)
For positive values, apply a sharpening algorithm to the video, for
negative values a blurring algorithm (default: 0).
``--vo-vdpau-denoise=<0-1>``
(Deprecated. See note about ``vdpaupp``.)
Apply a noise reduction algorithm to the video (default: 0; no noise
reduction).
``--vo-vdpau-chroma-deint``
(Deprecated. See note about ``vdpaupp``.)
Makes temporal deinterlacers operate both on luma and chroma (default).
Use no-chroma-deint to solely use luma and speed up advanced
deinterlacing. Useful with slow video memory.
``--vo-vdpau-pullup``
(Deprecated. See note about ``vdpaupp``.)
Try to apply inverse telecine, needs motion adaptive temporal
deinterlacing.
``--vo-vdpau-hqscaling=<0-9>``
(Deprecated. See note about ``vdpaupp``.)
0
Use default VDPAU scaling (default).
1-9
Apply high quality VDPAU scaling (needs capable hardware).
``--vo-vdpau-fps=<number>``
Override autodetected display refresh rate value (the value is needed
for framedrop to allow video playback rates higher than display
refresh rate, and for vsync-aware frame timing adjustments). Default 0
means use autodetected value. A positive value is interpreted as a
refresh rate in Hz and overrides the autodetected value. A negative
value disables all timing adjustment and framedrop logic.
``--vo-vdpau-composite-detect``
NVIDIA's current VDPAU implementation behaves somewhat differently
under a compositing window manager and does not give accurate frame
timing information. With this option enabled, the player tries to
detect whether a compositing window manager is active. If one is
detected, the player disables timing adjustments as if the user had
specified ``fps=-1`` (as they would be based on incorrect input). This
means timing is somewhat less accurate than without compositing, but
with the composited mode behavior of the NVIDIA driver, there is no
hard playback speed limit even without the disabled logic. Enabled by
default, use ``--vo-vdpau-composite-detect=no`` to disable.
``--vo-vdpau-queuetime-windowed=<number>`` and ``queuetime-fs=<number>``
Use VDPAU's presentation queue functionality to queue future video
frame changes at most this many milliseconds in advance (default: 50).
See below for additional information.
``--vo-vdpau-output-surfaces=<2-15>``
Allocate this many output surfaces to display video frames (default:
3). See below for additional information.
``--vo-vdpau-colorkey=<#RRGGBB|#AARRGGBB>``
Set the VDPAU presentation queue background color, which in practice
is the colorkey used if VDPAU operates in overlay mode (default:
``#020507``, some shade of black). If the alpha component of this value
is 0, the default VDPAU colorkey will be used instead (which is usually
green).
``--vo-vdpau-force-yuv``
Never accept RGBA input. This means mpv will insert a filter to convert
to a YUV format before the VO. Sometimes useful to force availability
of certain YUV-only features, like video equalizer or deinterlacing.
Using the VDPAU frame queuing functionality controlled by the queuetime
options makes mpv's frame flip timing less sensitive to system CPU load and
allows mpv to start decoding the next frame(s) slightly earlier, which can
reduce jitter caused by individual slow-to-decode frames. However, the
NVIDIA graphics drivers can make other window behavior such as window moves
choppy if VDPAU is using the blit queue (mainly happens if you have the
composite extension enabled) and this feature is active. If this happens on
your system and it bothers you then you can set the queuetime value to 0 to
disable this feature. The settings to use in windowed and fullscreen mode
are separate because there should be no reason to disable this for
fullscreen mode (as the driver issue should not affect the video itself).
You can queue more frames ahead by increasing the queuetime values and the
``output_surfaces`` count (to ensure enough surfaces to buffer video for a
certain time ahead you need at least as many surfaces as the video has
frames during that time, plus two). This could help make video smoother in
some cases. The main downsides are increased video RAM requirements for
the surfaces and laggier display response to user commands (display
changes only become visible some time after they're queued). The graphics
driver implementation may also have limits on the length of maximum
queuing time or number of queued surfaces that work well or at all.
``direct3d`` (Windows only)
Video output driver that uses the Direct3D interface.
.. note:: This driver is for compatibility with systems that don't provide
proper OpenGL drivers, and where ANGLE does not perform well.
The following global options are supported by this video output:
``--vo-direct3d-disable-texture-align``
Normally texture sizes are always aligned to 16. With this option
enabled, the video texture will always have exactly the same size as
the video itself.
Debug options. These might be incorrect, might be removed in the future,
might crash, might cause slow downs, etc. Contact the developers if you
actually need any of these for performance or proper operation.
``--vo-direct3d-force-power-of-2``
Always force textures to power of 2, even if the device reports
non-power-of-2 texture sizes as supported.
``--vo-direct3d-texture-memory=<mode>``
Only affects operation with shaders/texturing enabled, and (E)OSD.
Possible values:
``default`` (default)
Use ``D3DPOOL_DEFAULT``, with a ``D3DPOOL_SYSTEMMEM`` texture for
locking. If the driver supports ``D3DDEVCAPS_TEXTURESYSTEMMEMORY``,
``D3DPOOL_SYSTEMMEM`` is used directly.
``default-pool``
Use ``D3DPOOL_DEFAULT``. (Like ``default``, but never use a
shadow-texture.)
``default-pool-shadow``
Use ``D3DPOOL_DEFAULT``, with a ``D3DPOOL_SYSTEMMEM`` texture for
locking. (Like ``default``, but always force the shadow-texture.)
``managed``
Use ``D3DPOOL_MANAGED``.
``scratch``
Use ``D3DPOOL_SCRATCH``, with a ``D3DPOOL_SYSTEMMEM`` texture for
locking.
``--vo-direct3d-swap-discard``
Use ``D3DSWAPEFFECT_DISCARD``, which might be faster.
Might be slower too, as it must(?) clear every frame.
``--vo-direct3d-exact-backbuffer``
Always resize the backbuffer to window size.
``gpu``
General purpose, customizable, GPU-accelerated video output driver. It
supports extended scaling methods, dithering, color management, custom
shaders, HDR, and more.
See `GPU renderer options`_ for options specific to this VO.
By default, it tries to use fast and fail-safe settings. Use the
``gpu-hq`` profile to use this driver with defaults set to high quality
rendering. The profile can be applied with ``--profile=gpu-hq`` and its
contents can be viewed with ``--show-profile=gpu-hq``.
This VO abstracts over several possible graphics APIs and windowing
contexts, which can be influenced using the ``--gpu-api`` and
``--gpu-context`` options.
Hardware decoding over OpenGL-interop is supported to some degree. Note
that in this mode, some corner case might not be gracefully handled, and
color space conversion and chroma upsampling is generally in the hand of
the hardware decoder APIs.
``gpu`` makes use of FBOs by default. Sometimes you can achieve better
quality or performance by changing the ``--fbo-format`` option to
``rgb16f``, ``rgb32f`` or ``rgb``. Known problems include Mesa/Intel not
accepting ``rgb16``, Mesa sometimes not being compiled with float texture
support, and some OS X setups being very slow with ``rgb16`` but fast
with ``rgb32f``. If you have problems, you can also try enabling the
``--gpu-dumb-mode=yes`` option.
``sdl``
SDL 2.0+ Render video output driver, depending on system with or without
hardware acceleration. Should work on all platforms supported by SDL 2.0.
For tuning, refer to your copy of the file ``SDL_hints.h``.
.. note:: This driver is for compatibility with systems that don't provide
proper graphics drivers.
The following global options are supported by this video output:
``--sdl-sw``
Continue even if a software renderer is detected.
``--sdl-switch-mode``
Instruct SDL to switch the monitor video mode when going fullscreen.
``vaapi``
Intel VA API video output driver with support for hardware decoding. Note
that there is absolutely no reason to use this, other than compatibility.
This is low quality, and has issues with OSD.
.. note:: This driver is for compatibility with crappy systems. You can
use vaapi hardware decoding with ``--vo=gpu`` too.
The following global options are supported by this video output:
``--vo-vaapi-scaling=<algorithm>``
default
Driver default (mpv default as well).
fast
Fast, but low quality.
hq
Unspecified driver dependent high-quality scaling, slow.
nla
``non-linear anamorphic scaling``
``--vo-vaapi-deint-mode=<mode>``
Select deinterlacing algorithm. Note that by default deinterlacing is
initially always off, and needs to be enabled with the ``d`` key
(default key binding for ``cycle deinterlace``).
This option doesn't apply if libva supports video post processing (vpp).
In this case, the default for ``deint-mode`` is ``no``, and enabling
deinterlacing via user interaction using the methods mentioned above
actually inserts the ``vavpp`` video filter. If vpp is not actually
supported with the libva backend in use, you can use this option to
forcibly enable VO based deinterlacing.
no
Don't allow deinterlacing (default for newer libva).
first-field
Show only first field.
bob
bob deinterlacing (default for older libva).
``--vo-vaapi-scaled-osd=<yes|no>``
If enabled, then the OSD is rendered at video resolution and scaled to
display resolution. By default, this is disabled, and the OSD is
rendered at display resolution if the driver supports it.
``null``
Produces no video output. Useful for benchmarking.
Usually, it's better to disable video with ``--no-video`` instead.
The following global options are supported by this video output:
``--vo-null-fps=<value>``
Simulate display FPS. This artificially limits how many frames the
VO accepts per second.
``caca``
Color ASCII art video output driver that works on a text console.
.. note:: This driver is a joke.
``tct``
Color Unicode art video output driver that works on a text console.
By default depends on support of true color by modern terminals to display
the images at full color range, but 256-colors outout is also supported (see
below). On Windows it requires an ansi terminal such as mintty.
Since mpv 0.30.0, you may need to use ``--profile=sw-fast`` to get decent
performance.
Note: the TCT image output is not synchronized with other terminal output
from mpv, which can lead to broken images. The options ``--no-terminal`` or
``--really-quiet`` can help with that.
``--vo-tct-algo=<algo>``
Select how to write the pixels to the terminal.
half-blocks
Uses unicode LOWER HALF BLOCK character to achieve higher vertical
resolution. (Default.)
plain
Uses spaces. Causes vertical resolution to drop twofolds, but in
theory works in more places.
``--vo-tct-width=<width>`` ``--vo-tct-height=<height>``
Assume the terminal has the specified character width and/or height.
These default to 80x25 if the terminal size cannot be determined.
``--vo-tct-256=<yes|no>`` (default: no)
Use 256 colors - for terminals which don't support true color.
``sixel``
Graphical output for the terminal, using sixels. Tested with ``mlterm`` and
``xterm``.
Note: the Sixel image output is not synchronized with other terminal output
from mpv, which can lead to broken images. The option ``--really-quiet``
can help with that, and is recommended.
You may need to use ``--profile=sw-fast`` to get decent performance.
Note: at the time of writing, ``xterm`` does not enable sixel by default -
launching it as ``xterm -ti 340`` is one way to enable it. Also, ``xterm``
does not display images bigger than 1000x1000 pixels by default.
To render and align sixel images correctly, mpv needs to know the terminal
size both in cells and in pixels. By default it tries to use values which
the terminal reports, however, due to differences between terminals this is
an error-prone process which cannot be automated with certainty - some
terminals report the size in pixels including the padding - e.g. ``xterm``,
while others report the actual usable number of pixels - like ``mlterm``.
Additionally, they may behave differently when maximized or in fullscreen,
and mpv cannot detect this state using standard methods.
Sixel size and alignment options:
``--vo-sixel-cols=<columns>``, ``--vo-sixel-rows=<rows>`` (default: 0)
Specify the terminal size in character cells, otherwise (0) read it
from the terminal, or fall back to 80x25. Note that mpv doesn't use the
the last row with sixel because this seems to result in scrolling.
``--vo-sixel-width=<width>``, ``--vo-sixel-height=<height>`` (default: 0)
Specify the available size in pixels, otherwise (0) read it from the
terminal, or fall back to 320x240. Other than excluding the last line,
the height is also further rounded down to a multiple of 6 (sixel unit
height) to avoid overflowing below the designated size.
``--vo-sixel-left=<col>``, ``--vo-sixel-top=<row>`` (default: 0)
Specify the position in character cells where the image starts (1 is
the first column or row). If 0 (default) then try to automatically
determine it according to the other values and the image aspect ratio
and zoom.
``--vo-sixel-pad-x=<pad_x>``, ``--vo-sixel-pad-y=<pad_y>`` (default: -1)
Used only when mpv reads the size in pixels from the terminal.
Specify the number of padding pixels (on one side) which are included
at the size which the terminal reports. If -1 (default) then the number
of pixels is rounded down to a multiple of number of cells (per axis),
to take into account padding at the report - this only works correctly
when the overall padding per axis is smaller than the number of cells.
Sixel image quality options:
``--vo-sixel-dither=<algo>``
Selects the dither algorithm which libsixel should apply.
Can be one of the below list as per libsixel's documentation.
auto
Choose diffuse type automatically
none
Don't diffuse
atkinson
Diffuse with Bill Atkinson's method. (Default)
fs
Diffuse with Floyd-Steinberg method
jajuni
Diffuse with Jarvis, Judice & Ninke method
stucki
Diffuse with Stucki's method
burkes
Diffuse with Burkes' method
arithmetic
Positionally stable arithmetic dither
xor
Positionally stable arithmetic xor based dither
``--vo-sixel-fixedpalette=<yes|no>`` (default: yes)
Use libsixel's built-in static palette using the XTERM256 profile
for dither. Fixed palette uses 256 colors for dithering. Note that
using ``no`` (at the time of writing) will slow down ``xterm``.
``--vo-sixel-reqcolors=<colors>`` (default: 256)
Set up libsixel to use required number of colors for dynamic palette.
This value depends on the terminal emulator as well. Xterm supports
256 colors. Can set this to a lower value for faster performance.
This option has no effect if fixed palette is used.
``--vo-sixel-threshold=<threshold>`` (default: -1)
When using a dynamic palette, defines the threshold to change the
palette - as percentage of the number of colors, e.g. 20 will change
the palette when the number of colors changed by 20%. It's a simple
measure to reduce the number of palette changes, because it can be slow
in some terminals (``xterm``), however, it seems that in ``mlterm`` it
causes image corruption. The default (-1) will change the palette
on every frame and will have better quality, and no corruption in
``mlterm``.
``image``
Output each frame into an image file in the current directory. Each file
takes the frame number padded with leading zeros as name.
The following global options are supported by this video output:
``--vo-image-format=<format>``
Select the image file format.
jpg
JPEG files, extension .jpg. (Default.)
jpeg
JPEG files, extension .jpeg.
png
PNG files.
webp
WebP files.
``--vo-image-png-compression=<0-9>``
PNG compression factor (speed vs. file size tradeoff) (default: 7)
``--vo-image-png-filter=<0-5>``
Filter applied prior to PNG compression (0 = none; 1 = sub; 2 = up;
3 = average; 4 = Paeth; 5 = mixed) (default: 5)
``--vo-image-jpeg-quality=<0-100>``
JPEG quality factor (default: 90)
``--vo-image-jpeg-optimize=<0-100>``
JPEG optimization factor (default: 100)
``--vo-image-webp-lossless=<yes|no>``
Enable writing lossless WebP files (default: no)
``--vo-image-webp-quality=<0-100>``
WebP quality (default: 75)
``--vo-image-webp-compression=<0-6>``
WebP compression factor (default: 4)
``--vo-image-outdir=<dirname>``
Specify the directory to save the image files to (default: ``./``).
``libmpv``
For use with libmpv direct embedding. As a special case, on OS X it
is used like a normal VO within mpv (cocoa-cb). Otherwise useless in any
other contexts.
(See ``<mpv/render.h>``.)
This also supports many of the options the ``gpu`` VO has, depending on the
backend.
``rpi`` (Raspberry Pi)
Native video output on the Raspberry Pi using the MMAL API.
This is deprecated. Use ``--vo=gpu`` instead, which is the default and
provides the same functionality. The ``rpi`` VO will be removed in
mpv 0.23.0. Its functionality was folded into --vo=gpu, which now uses
RPI hardware decoding by treating it as a hardware overlay (without applying
GL filtering). Also to be changed in 0.23.0: the --fs flag will be reset to
"no" by default (like on the other platforms).
The following deprecated global options are supported by this video output:
``--rpi-display=<number>``
Select the display number on which the video overlay should be shown
(default: 0).
``--rpi-layer=<number>``
Select the dispmanx layer on which the video overlay should be shown
(default: -10). Note that mpv will also use the 2 layers above the
selected layer, to handle the window background and OSD. Actual video
rendering will happen on the layer above the selected layer.
``--rpi-background=<yes|no>``
Whether to render a black background behind the video (default: no).
Normally it's better to kill the console framebuffer instead, which
gives better performance.
``--rpi-osd=<yes|no>``
Enabled by default. If disabled with ``no``, no OSD layer is created.
This also means there will be no subtitles rendered.
``drm`` (Direct Rendering Manager)
Video output driver using Kernel Mode Setting / Direct Rendering Manager.
Should be used when one doesn't want to install full-blown graphical
environment (e.g. no X). Does not support hardware acceleration (if you
need this, check the ``drm`` backend for ``gpu`` VO).
Since mpv 0.30.0, you may need to use ``--profile=sw-fast`` to get decent
performance.
The following global options are supported by this video output:
``--drm-connector=[<gpu_number>.]<name>``
Select the connector to use (usually this is a monitor.) If ``<name>``
is empty or ``auto``, mpv renders the output on the first available
connector. Use ``--drm-connector=help`` to get a list of available
connectors. When using multiple graphic cards, use the ``<gpu_number>``
argument to disambiguate.
(default: empty)
``--drm-mode=<preferred|highest|N|WxH[@R]>``
Mode to use (resolution and frame rate).
Possible values:
:preferred: Use the preferred mode for the screen on the selected
connector. (default)
:highest: Use the mode with the highest resolution available on the
selected connector.
:N: Select mode by index.
:WxH[@R]: Specify mode by width, height, and optionally refresh rate.
In case several modes match, selects the mode that comes
first in the EDID list of modes.
Use ``--drm-mode=help`` to get a list of available modes for all active
connectors.
``--drm-atomic=<no|auto>``
Toggle use of atomic modesetting. Mostly useful for debugging.
:no: Use legacy modesetting.
:auto: Use atomic modesetting, falling back to legacy modesetting if
not available. (default)
Note: Only affects ``gpu-context=drm``. ``vo=drm`` supports legacy
modesetting only.
``--drm-draw-plane=<primary|overlay|N>``
Select the DRM plane to which video and OSD is drawn to, under normal
circumstances. The plane can be specified as ``primary``, which will
pick the first applicable primary plane; ``overlay``, which will pick
the first applicable overlay plane; or by index. The index is zero
based, and related to the CRTC.
(default: primary)
When using this option with the drmprime-drm hwdec interop, only the OSD
is rendered to this plane.
``--drm-drmprime-video-plane=<primary|overlay|N>``
Select the DRM plane to use for video with the drmprime-drm hwdec
interop (used by e.g. the rkmpp hwdec on RockChip SoCs, and v4l2 hwdec:s
on various other SoC:s). The plane is unused otherwise. This option
accepts the same values as ``--drm-draw-plane``. (default: overlay)
To be able to successfully play 4K video on various SoCs you might need
to set ``--drm-draw-plane=overlay --drm-drmprime-video-plane=primary``
and setting ``--drm-draw-surface-size=1920x1080``, to render the OSD at a
lower resolution (the video when handled by the hwdec will be on the
drmprime-video plane and at full 4K resolution)
``--drm-format=<xrgb8888|xrgb2101010>``
Select the DRM format to use (default: xrgb8888). This allows you to
choose the bit depth of the DRM mode. xrgb8888 is your usual 24 bit per
pixel/8 bits per channel packed RGB format with 8 bits of padding.
xrgb2101010 is a packed 30 bits per pixel/10 bits per channel packed RGB
format with 2 bits of padding.
There are cases when xrgb2101010 will work with the ``drm`` VO, but not
with the ``drm`` backend for the ``gpu`` VO. This is because with the
``gpu`` VO, in addition to requiring support in your DRM driver,
requires support for xrgb2101010 in your EGL driver
``--drm-draw-surface-size=<[WxH]>``
Sets the size of the surface used on the draw plane. The surface will
then be upscaled to the current screen resolution. This option can be
useful when used together with the drmprime-drm hwdec interop at high
resolutions, as it allows scaling the draw plane (which in this case
only handles the OSD) down to a size the GPU can handle.
When used without the drmprime-drm hwdec interop this option will just
cause the video to get rendered at a different resolution and then
scaled to screen size.
Note: this option is only available with DRM atomic support.
(default: display resolution)
``mediacodec_embed`` (Android)
Renders ``IMGFMT_MEDIACODEC`` frames directly to an ``android.view.Surface``.
Requires ``--hwdec=mediacodec`` for hardware decoding, along with
``--vo=mediacodec_embed`` and ``--wid=(intptr_t)(*android.view.Surface)``.
Since this video output driver uses native decoding and rendering routines,
many of mpv's features (subtitle rendering, OSD/OSC, video filters, etc)
are not available with this driver.
To use hardware decoding with ``--vo=gpu`` instead, use
``--hwdec=mediacodec-copy`` along with ``--gpu-context=android``.
``wlshm`` (Wayland only)
Shared memory video output driver without hardware acceleration that works
whenever Wayland is present.
Since mpv 0.30.0, you may need to use ``--profile=sw-fast`` to get decent
performance.
.. note:: This is a fallback only, and should not be normally used.
-455
View File
@@ -1,455 +0,0 @@
CHANGES FROM OTHER VERSIONS OF MPLAYER
======================================
**mpv** is based on mplayer2, which in turn is based on the original MPlayer
(also called mplayer, mplayer-svn, mplayer1). Many changes have been made, a
large part of which is incompatible or completely changes how the player
behaves. Although there are still many similarities to its ancestors, **mpv**
should generally be treated as a completely different program.
.. admonition:: Warning
This document is **not updated** anymore, and is **incomplete** and
**outdated**. If you look for old option replacements, always check with
the current mpv manpage, as the options could have changed meanwhile.
General Changes from MPlayer to mpv
-----------------------------------
This listing is about changes introduced by mplayer2 and mpv relatively to
MPlayer.
Player
~~~~~~
* New name for the binary (``mpv``). New location for config files (either
``~/.config/mpv/mpv.conf``, or if you want, ``~/.mpv/config``).
* Encoding functionality (replacement for MEncoder, see the `ENCODING`_ section).
* Support for Lua scripting (see the `LUA SCRIPTING`_ section).
* Better pause handling (e.g. do not unpause on a command).
* Precise seeking support.
* Improvements in audio/video sync handling.
* Do not lose settings when playing a new file in the same player instance.
* Slave mode compatibility broken (see below).
* Re-enable screensaver while the player is paused.
* Allow resuming playback at a later point with ``Shift+q``, also see the
``quit-watch-later`` input command.
* ``--keep-open`` option to stop the player from closing the window and
exiting after playback ends.
* A client API, that allows embedding **mpv** into applications
(see ``libmpv/client.h`` in the sources).
Input
~~~~~
* Improved default keybindings. MPlayer bindings are also available (see
``etc/mplayer-input.conf`` in the source tree).
* Improved responsiveness on user input.
* Support for modifier keys (alt, shift, ctrl) in input.conf.
* Allow customizing whether a key binding for seeking shows the video time, the
OSD bar, or nothing (see the `Input Command Prefixes`_ section).
* Support mapping multiple commands to one key.
* Classic LIRC support was removed. Install remotes as input devices instead.
This way they will send X11 key events to the mpv window, which can be bound
using the normal ``input.conf``.
Also see: http://github.com/mpv-player/mpv/wiki/IR-remotes
* Joystick support was removed. It was considered useless and was the cause
of some problems (e.g. a laptop's accelerator being recognized as joystick).
* Support for relative seeking by percentage.
Audio
~~~~~
* Support for gapless audio (see the ``--gapless-audio`` option).
* Support for OSS4 volume control.
* Improved support for PulseAudio.
* Make ``--softvol`` default (**mpv** is not a mixer control panel).
* By default, do pitch correction if playback speed is increased.
* Improved downmixing and output of surround audio:
- Instead of using hardcoded pan filters to do remixing, libavresample is used
- Channel maps are used to identify the channel layout, so e.g. ``3.0`` and
``2.1`` audio can be distinguished.
Video
~~~~~
* Wayland support.
* Native support for VAAPI and VDA. Improved VDPAU video output.
* Improved GPU-accelerated video output (see the ``gpu-hq`` preset).
* Make hardware decoding work with the ``gpu`` video output.
* Support for libavfilter (for video->video and audio->audio). This allows
using most of FFmpeg's filters, which improve greatly on the old MPlayer
filters in features, performance, and correctness.
* More correct color reproduction (color matrix generation), including support
for BT.2020 (Ultra HD). linear XYZ (Digital Cinema) and SMPTE ST2084 (HDR)
inputs.
* Support for color managed displays, via ICC profiles.
* High-quality image resamplers (see the ``--scale`` suboption).
* Support for scaling in (sigmoidized) linear light.
* Better subtitle rendering using libass by default.
* Improvements when playing multiple files (``-fixed-vo`` is default, do not
reset settings by default when playing a new file).
* Replace image video outputs (``--vo=jpeg`` etc.) with ``--vo=image``.
* Removal of ``--vo=gif89a``, ``--vo=md5sum``, ``--vo=yuv4mpeg``, as encoding
can handle these use cases. For yuv4mpeg, for example, use::
mpv input.mkv -o output.y4m --no-audio --oautofps --oneverdrop
* Image subtitles (DVDs etc.) are rendered in color and use more correct
positioning (color for image subs can be disabled with ``--sub-gray``).
* Support for the X11 video output is removed, since it was considered
deprecated. SDL video output can still be used as a fallback.
OSD and terminal
~~~~~~~~~~~~~~~~
* Cleaned up terminal output: nicer status line, less useless noise.
* Improved OSD rendering using libass, with full Unicode support.
* New OSD bar with chapter marks. Not positioned in the middle of the video
(this can be customized with the ``--osd-bar-align-y`` option).
* Display list of chapters and audio/subtitle tracks on OSD (see the
`Properties`_ section).
Screenshots
~~~~~~~~~~~
* Instant screenshots without 1-frame delay.
* Support for taking screenshots even with hardware decoding.
* Support for saving screenshots as JPEG or PNG.
* Support for configurable file names.
* Support for taking screenshots with or without subtitles.
Note that the ``screenshot`` video filter is not needed anymore, and should not
be put into the mpv config file.
Miscellaneous
~~~~~~~~~~~~~
* Better MKV support (e.g. ordered chapters, 3D metadata).
* Matroska edition switching at runtime.
* Support for playing URLs of popular streaming sites directly.
(e.g. ``mpv https://www.youtube.com/watch?v=...``).
Requires a recent version of ``youtube-dl`` to be installed. Can be
disabled with ``ytdl=no`` in the mpv config file.
* Support for precise scrolling which scales the parameter of commands. If the
input doesn't support precise scrolling the scale factor stays 1.
* Allow changing/adjusting video filters at runtime. (This is also used to make
the ``D`` key insert vf_yadif if deinterlacing is not supported otherwise).
* Improved support for .cue files.
Mac OS X
~~~~~~~~
* Native OpenGL backend.
* Cocoa event loop is independent from MPlayer's event loop, so user
actions like accessing menus and live resizing do not block the playback.
* Media Keys support.
* VDA support using libavcodec hwaccel API instead of FFmpeg's decoder with up
to 2-2.5x reduction in CPU usage.
Windows
~~~~~~~
* Improved support for Unicode file names.
* Improved window handling.
* Do not block playback when moving the window.
* Improved Direct3D video output.
* Added WASAPI audio output.
Internal changes
~~~~~~~~~~~~~~~~
* Switch to GPLv2+ (see ``Copyright`` file for details).
* Removal of lots of cruft:
- Internal GUI (replaced by the OSC, see the `ON SCREEN CONTROLLER`_ section).
- MEncoder (replaced by native encoding, see the `ENCODING`_ section).
- OSD menu.
- Kernel video drivers for Linux 2.4 (including VIDIX).
- Teletext support.
- Support for dead platforms.
- Most built-in demuxers have been replaced by their libavformat counterparts.
- Built-in network support has been replaced by libavformat's (which also
supports https URLs).
- Embedded copies of libraries (such as FFmpeg).
* General code cleanups (including refactoring or rewrites of many parts).
* New build system.
* Many bug fixes and removal of long-standing issues.
* Generally preferring FFmpeg/Libav over internal demuxers, decoders, and
filters.
Detailed Listing of User-visible Changes
----------------------------------------
This listing is about changed command line switches, slave commands, and similar
things. Completely removed features are not listed.
Command Line Switches
~~~~~~~~~~~~~~~~~~~~~
* There is a new command line syntax, which is generally preferred over the old
syntax. ``-optname optvalue`` becomes ``--optname=optvalue``.
The old syntax will not be removed. However, the new syntax is mentioned in
all documentation and so on, and unlike the old syntax is not ambiguous,
so it is a good thing to know about this change.
* In general, negating switches like ``-noopt`` now have to be written as
``-no-opt`` or ``--no-opt``.
* Per-file options are not the default anymore. You can explicitly specify
file-local options. See ``Usage`` section.
* Many options have been renamed, removed or changed semantics. Some options
that are required for a good playback experience with MPlayer are now
superfluous or even worse than the defaults, so make sure to read the manual
before trying to use your existing configuration with **mpv**.
* Table of renamed/replaced switches:
=========================== ========================================
Old New
=========================== ========================================
``-no<opt>`` ``--no-<opt>`` (add a dash)
``-a52drc level`` ``--ad-lavc-ac3drc=level``
``-ac spdifac3`` ``--ad=spdif:ac3`` (see ``--ad=help``)
``-af volnorm`` (removed; use acompressor ffmpeg filter instead)
``-afm hwac3`` ``--ad=spdif:ac3,spdif:dts``
``-ao alsa:device=hw=0.3`` ``--ao=alsa:device=[hw:0,3]``
``-aspect`` ``--video-aspect``
``-ass-bottom-margin`` ``--vf=sub=bottom:top``
``-ass`` ``--sub-ass``
``-audiofile-cache`` (removed; the main cache settings are used)
``-audiofile`` ``--audio-file``
``-benchmark`` ``--untimed`` (no stats)
``-capture`` ``--stream-capture=<filename>``
``-channels`` ``--audio-channels`` (changed semantics)
``-cursor-autohide-delay`` ``--cursor-autohide``
``-delay`` ``--audio-delay``
``-dumpstream`` ``--stream-dump=<filename>``
``-dvdangle`` ``--dvd-angle``
``-endpos`` ``--length``
``-fixed-vo`` (removed; always the default)
``-font`` ``--osd-font``
``-forcedsubsonly`` ``--sub-forced-only``
``-forceidx`` ``--index``
``-format`` ``--audio-format``
``-fsmode-dontuse`` (removed)
``-fstype`` ``--x11-netwm`` (changed semantics)
``-hardframedrop`` ``--framedrop=hard``
``-identify`` (removed; use TOOLS/mpv_identify.sh)
``-idx`` ``--index``
``-lavdopts ...`` ``--vd-lavc-...``
``-lavfdopts`` ``--demuxer-lavf-...``
``-loop 0`` ``--loop=inf``
``-mixer-channel`` AO suboptions (``alsa``, ``oss``)
``-mixer`` AO suboptions (``alsa``, ``oss``)
``-mouse-movements`` ``--input-cursor``
``-msgcolor`` ``--msg-color``
``-msglevel`` ``--msg-level`` (changed semantics)
``-msgmodule`` ``--msg-module``
``-name`` ``--x11-name``
``-noar`` ``(removed; replaced by MediaPlayer framework)``
``-noautosub`` ``--no-sub-auto``
``-noconsolecontrols`` ``--no-input-terminal``
``-nosound`` ``--no-audio``
``-osdlevel`` ``--osd-level``
``-panscanrange`` ``--video-zoom``, ``--video-pan-x/y``
``-playing-msg`` ``--term-playing-msg``
``-pp ...`` ``'--vf=lavfi=[pp=...]'``
``-pphelp`` (See FFmpeg libavfilter documentation.)
``-rawaudio ...`` ``--demuxer-rawaudio-...``
``-rawvideo ...`` ``--demuxer-rawvideo-...``
``-spugauss`` ``--sub-gauss``
``-srate`` ``--audio-samplerate``
``-ss`` ``--start``
``-ssf <sub>`` ``--sws-...``
``-stop-xscreensaver`` ``--stop-screensaver``
``-sub-fuzziness`` ``--sub-auto``
``-sub-text-*`` ``--sub-*``
``-sub`` ``--sub-file``
``-subcp`` ``--sub-codepage``
``-subdelay`` ``--sub-delay``
``-subfile`` ``--sub-file``
``-subfont-*`` ``--sub-*``, ``--osd-*``
``-subfont-text-scale`` ``--sub-scale``
``-subfont`` ``--sub-font``
``-subfps`` ``--sub-fps``
``-subpos`` ``--sub-pos``
``-sws`` ``--sws-scaler``
``-tvscan`` ``--tv-scan``
``-use-filename-title`` ``--title='${filename}'``
``-vc ffh264vdpau`` (etc.) ``--hwdec=vdpau``
``-vobsub`` ``--sub-file`` (pass the .idx file)
``-x W``, ``-y H`` ``--geometry=WxH`` + ``--no-keepaspect``
``-xineramascreen`` ``--screen`` (different values)
``-xy W`` ``--autofit=W``
``-zoom`` Inverse available as ``--video-unscaled``
``dvdnav://`` Removed.
``dvd://1`` ``dvd://0`` (0-based offset)
=========================== ========================================
.. note::
``-opt val`` becomes ``--opt=val``.
.. note::
Quite some video filters, video outputs, audio filters, audio outputs, had
changes in their option parsing. These aren't mentioned in the table above.
Also, some video and audio filters have been removed, and you have to use
libavfilter (using ``--vf=lavfi=[...]`` or ``--af=lavfi=[...]``) to get
them back.
input.conf and Slave Commands
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
* Table of renamed input commands:
This lists only commands that are not always gracefully handled by the
internal legacy translation layer. If an input.conf contains any legacy
commands, a warning will be printed when starting the player. The warnings
also show the replacement commands.
Properties containing ``_`` to separate words use ``-`` instead.
+--------------------------------+----------------------------------------+
| Old | New |
+================================+========================================+
| ``pt_step 1 [0|1]`` | ``playlist-next [weak|force]`` |
| | (translation layer cannot deal with |
| | whitespace) |
+--------------------------------+----------------------------------------+
| ``pt_step -1 [0|1]`` | ``playlist-prev [weak|force] (same)`` |
+--------------------------------+----------------------------------------+
| ``switch_ratio [<ratio>]`` | ``set video-aspect <ratio>`` |
| | |
| | ``set video-aspect 0`` (reset aspect) |
+--------------------------------+----------------------------------------+
| ``step_property_osd <prop>`` | ``cycle <prop> <step>`` (wraps), |
| ``<step> <dir>`` | ``add <prop> <step>`` (clamps). |
| | ``<dir>`` parameter unsupported. Use |
| | a negative ``<step>`` instead. |
+--------------------------------+----------------------------------------+
| ``step_property <prop>`` | Prefix ``cycle`` or ``add`` with |
| ``<step> <dir>`` | ``no-osd``: ``no-osd cycle <prop>`` |
| | ``<step>`` |
+--------------------------------+----------------------------------------+
| ``osd_show_property_text`` | ``show-text <text>`` |
| ``<text>`` | The property expansion format string |
| | syntax slightly changed. |
+--------------------------------+----------------------------------------+
| ``osd_show_text`` | Now does the same as |
| | ``osd_show_property_text``. Use the |
| | ``raw`` prefix to disable property |
| | expansion. |
+--------------------------------+----------------------------------------+
| ``show_tracks`` | ``show-text ${track-list}`` |
+--------------------------------+----------------------------------------+
| ``show_chapters`` | ``show-text ${chapter-list}`` |
+--------------------------------+----------------------------------------+
| ``af_switch``, ``af_add``, ... | ``af set|add|...`` |
+--------------------------------+----------------------------------------+
| ``tv_start_scan`` | ``set tv-scan yes`` |
+--------------------------------+----------------------------------------+
| ``tv_set_channel <val>`` | ``set tv-channel <val>`` |
+--------------------------------+----------------------------------------+
| ``tv_step_channel`` | ``cycle tv-channel`` |
+--------------------------------+----------------------------------------+
| ``dvb_set_channel <v1> <v2>`` | ``set dvb-channel <v1>-<v2>`` |
+--------------------------------+----------------------------------------+
| ``dvb_step_channel`` | ``cycle dvb-channel`` |
+--------------------------------+----------------------------------------+
| ``tv_set_freq <val>`` | ``set tv-freq <val>`` |
+--------------------------------+----------------------------------------+
| ``tv_step_freq`` | ``cycle tv-freq`` |
+--------------------------------+----------------------------------------+
| ``tv_set_norm <norm>`` | ``set tv-norm <norm>`` |
+--------------------------------+----------------------------------------+
| ``tv_step_norm`` | ``cycle tv-norm`` |
+--------------------------------+----------------------------------------+
.. note::
Due to lack of hardware and users using the TV/DVB/PVR features, and
due to the need to cleanup the related command code, it's possible
that the new commands are buggy or behave worse. This can be improved
if testers are available. Otherwise, some of the TV code will be
removed at some point.
Slave mode
~~~~~~~~~~
* Slave mode was removed. A proper slave mode application needed tons of code
and hacks to get
it right. The main problem is that slave mode is a bad and incomplete
interface, and to get around that, applications parsed output messages
intended for users. It is hard to know which messages exactly are parsed by
slave mode applications. This makes it virtually impossible to improve
terminal output intended for users without possibly breaking something.
This is absolutely insane, and since initial improvements to **mpv** quickly
made slave mode incompatible to most applications, it was removed as useless
cruft. The client API (see below) is provided instead.
``--identify`` was replaced by the ``TOOLS/mpv_identify.sh`` wrapper script.
* For some time (until including release 0.4.x), mpv supported a
``--slave-broken`` option. The following options are equivalent:
::
--input-file=/dev/stdin --input-terminal=no
Assuming the system supports ``/dev/stdin``.
(The option was added back in 0.5.1 and sets exactly these options. It was
removed in 0.10.x again.)
* A JSON RPC protocol giving access to the client API is also supported. See
`JSON IPC`_ for more information.
* **mpv** also provides a client API, which can be used to embed the player
by loading it as shared library. (See ``libmpv/client.h`` in the sources.)
It might also be possible to implement a custom slave mode-like protocol
using Lua scripting.
Policy for Removed Features
---------------------------
**mpv** is in active development. If something is in the way of more important
development (such as fixing bugs or implementing new features), we sometimes
remove features. Usually this happens only with old features that either seem
to be useless, or are not used by anyone. Often these are obscure, or
"inherited", or were marked experimental, but never received any particular
praise by any users.
Sometimes, features are replaced by something new. The new code will be either
simpler or more powerful, but doesn't necessarily provide everything the old
feature did.
We can not exclude that we accidentally remove features that are actually
popular. Generally, we do not know how much a specific functionality is used.
If you miss a feature and think it should be re-added, please open an issue
on the mpv bug tracker. Hopefully, a solution can be found. Often, it turns
out that re-adding something is not much of a problem, or that there are
better alternatives.
Why this Fork?
--------------
mplayer2 is practically dead, and mpv started out as a branch containing
new/experimental development. (Some of it was merged right *after* the fork
was made public, seemingly as an acknowledgment that development, or at
least merging, should have been more active.)
MPlayer is focused on not breaking anything, but is stuck with a horrible
codebase resistant to cleanup. (Unless you do what mpv did - merciless and
consequent pruning of bad, old code.) Cleanup and keeping broken things
conflict, so the kind of development mpv strives for can't be done within
MPlayer due to clashing development policies.
Additionally, mplayer2 already had lots of changes over MPlayer, which would
have needed to be backported to the MPlayer codebase. This would not only
have been hard (several years of diverging development), but also would have
been impossible due to the aforementioned MPlayer development policy.
-121
View File
@@ -1,121 +0,0 @@
Release Policy
==============
Once or twice a month, a new release is cut off of the master branch and is
assigned a 0.X.Y version number, where X is incremented each time a release
contains breaking changes, such as changed options or added/removed features,
and Y is incremented if a release contains only bugfixes and other minor
changes.
Releases are tagged on the master branch and will not be maintained separately.
The goal of releases is to provide Linux distributions with something to
package. If you want the newest features, just use the master branch.
We try our best to keep it deployable at all times.
Releases other than the latest release are unsupported and unmaintained.
Release procedure
-----------------
While on master:
- Update the `RELEASE_NOTES` file, replacing the previous release notes.
- Update the `VERSION` file.
- Update `DOCS/client-api-changes.rst` and `DOCS/interface-changes.rst`
(in particular, update the last version numbers if necessary)
- Create signed commit with changes.
- Create signed tag v0.X.Y.
- Add -UNKNOWN suffix to version in `VERSION` file.
- Commit changes, push release branch (`release/0.X`) and tag to GitHub.
- Create a new GitHub release using the content of `RELEASE_NOTES` related to
the new version.
If necessary (to e.g. exclude commits already on master), the release can
be done on a branch with different commit history. The release branch **must**
then be merged to master so `git describe` will pick up the tag.
Release notes template
----------------------
Here is a template that can be used for writing the `RELEASE_NOTES` file.
```markdown
Release 0.X.Y
=============
Features
--------
New
~~~
- List of new features
Removed
~~~~~~~
- List of removed features
Deprecated
~~~~~~~~~~
- List of deprecated features
Behavior
--------
- List of user-visible changes in behavior
Options and Commands
--------------------
Added
~~~~~
- List of added options and commands
Changed
~~~~~~~
- List of changed options and commands
Renamed
~~~~~~~
- List of renamed options and commands
Deprecated
~~~~~~~~~~
- List of deprecated options and commands
Removed
~~~~~~~
- List of removed options and commands
Fixes and Minor Enhancements
----------------------------
- List of fixes and minor enhancements
This listing is not complete. There are many more bug fixes and changes. The
complete change log can be viewed by running `git log <start>..<end>` in
the git repository.
```
Note that the "Release 0.X.Y" title should be removed when creating a new GitHub
release.
When creating a new point release its changes should be added on top of the
`RELEASE_NOTES` file (with the appropriate title) so that all the changes in
the current 0.X branch will be included. This way the `RELEASE_NOTES` file
can be used by distributors as changelog for point releases too.
+104 -521
View File
@@ -1,11 +1,12 @@
This file intends to give a big picture overview of how mpv is structured.
NOTE: DOCS/OUTDATED-tech/* may contain more detailed information, but most of it
is possibly or definitely outdated. This file intends to give a big
picture of how mpv is structured.
player/*.c:
Essentially makes up the player applications, including the main() function
and the playback loop.
Generally, it accesses all other subsystems, initializes them, and pushes
data between them during playback.
mpvcore/mplayer.c:
This contains the main play loop, anything related to mpv and playback
related initializations. It also contains the main function. Generally, it
accesses all other subsystems, initializes them, and pushes data between
them during playback.
The structure is as follows (as of commit e13c05366557cb):
* main():
@@ -15,14 +16,14 @@ player/*.c:
* parse command line, add files from the command line to playlist
(m_config_parse_mp_command_line())
* check help options etc. (call handle_help_options()), possibly exit
* call mp_play_files() function that works down the playlist:
* call play_files() function that works down the playlist:
* run idle loop (idle_loop()), until there are files in the
playlist or an exit command was given (only if --idle it set)
playlist or an exit command was given (slave mode only)
* actually load and play a file in play_current_file():
* run all the dozens of functions to load the file and
initialize playback
* run a small loop that does normal playback, until the file is
done or a command terminates playback
done or a slave command terminates playback
(on each iteration, run_playloop() is called, which is rather
big and complicated - it decodes some audio and video on
each frame, waits for input, etc.)
@@ -30,132 +31,89 @@ player/*.c:
* determine next entry on the playlist to play
* loop, or exit if no next file or quit is requested
(see enum stop_play_reason)
* call mp_destroy()
* run_playloop():
* calls fill_audio_out_buffers()
This checks whether new audio needs to be decoded, and pushes it
to the AO.
* calls write_video()
Decode new video, and push it to the VO.
* determines whether playback of the current file has ended
* determines when to start playback after seeks
* and calls a whole lot of other stuff
(Really, this function does everything.)
* call exit_player_with_rc()
Things worth saying about the playback core:
- most state is in MPContext (core.h), which is not available to the
subsystems (and should not be made available)
- the currently played tracks are in mpctx->current_tracks, and decoder
state in track.dec/d_sub
- the currently played tracks are in sh_video and sh_audio
- the timeline stuff is used only with MKV ordered chapters (and some other
minor features: cue, edl)
- most state is in MPContext (mp_core.h), which is not available to the
subsystems
- the other subsystems rarely call back into the frontend, and the frontend
polls them instead (probably a good thing)
- one exceptions are wakeup callbacks, which notify a "higher" component
of a changed situation in a subsystem
I like to call the player/*.c files the "frontend".
I like to call mplayer.c (and some other files) the "frontend".
ta.h & ta.c:
Hierarchical memory manager inspired by talloc from Samba. It's like a
malloc() with more features. Most importantly, each talloc allocation can
have a parent, and if the parent is free'd, all children will be free'd as
well. The parent is an arbitrary talloc allocation. It's either set by the
allocation call by passing a talloc parent, usually as first argument to the
allocation function. It can also be set or reset later by other calls (at
least talloc_steal()). A talloc allocation that is used as parent is often
called a talloc context.
talloc.h & talloc.c:
Hierarchical memory manager copied from Samba. It's like a malloc() with
more features. Most importantly, each talloc allocation can have a parent,
and if the parent is free'd, all children will be free'd as well. The
parent is an arbitrary talloc allocation. It's either set by the allocation
call by passing a talloc parent, usually as first argument to the allocation
function. It can also be set or reset later by other calls (at least
talloc_steal()). A talloc allocation that is used as parent is often called
a talloc context.
Lots of code still uses malloc() proper, and you should be careful what
type of allocation you're dealing with when returning or free'ing an
allocation. (Needless to say, talloc_free() and free() are completely
different things.)
The copy in mpv has been modified to abort on OOM conditions. An
allocation call will never return NULL.
One very useful feature of talloc is fast tracking of memory leaks. ("Fast"
as in it doesn't require valgrind.) You can enable it by setting the
as in it doesn't require valgrind.) You can enable it by passing the option
--leak-report as first parameter, or better, setting the
MPV_LEAK_REPORT environment variable to "1":
export MPV_LEAK_REPORT=1
Or permanently by building with --enable-ta-leak-report.
This will list all unfree'd allocations on exit.
Documentation can be found here:
http://git.samba.org/?p=samba.git;a=blob;f=lib/talloc/talloc.h;hb=HEAD
For some reason, we're still using API-compatible wrappers instead of TA
directly. The talloc wrapper has only a subset of the functionality, and
in particular the wrappers abort() on memory allocation failure.
Note: unlike tcmalloc, jemalloc, etc., talloc() is not actually a malloc
replacement. It works on top of system malloc and provides additional
features that are supposed to make memory management easier.
player/command.c:
This contains the implementation for client API commands and properties.
Properties are essentially dynamic variables changed by certain commands.
This is basically responsible for all user commands, like initiating
seeking, switching tracks, etc. It calls into other player/*.c files,
where most of the work is done, but also calls other parts of mpv.
Warning: actually, we're not using talloc anymore. talloc in mpv has been
replaced by a custom re-implementation (TA in ta/). It provides
some talloc emulation (just the parts needed by mpv). We will get
rid of the talloc emulation later and use TA natively.
(See ta/README for details.)
player/core.h:
Data structures and function prototypes for most of player/*.c. They are
usually not accessed by other parts of mpv for the sake of modularization.
mpvcore/mp_core.h:
Data structures for mplayer.c and command.c. They are usually not accessed
by other parts of mpv for the sake of modularization.
player/client.c:
This implements the client API (libmpv/client.h). For the most part, this
just calls into other parts of the player. This also manages a ringbuffer
of events from player to clients.
Note that there are lots of global variables floating around everywhere
else. This is an ongoing transition, and eventually there should be no
global variables anymore.
options/options.h, options/options.c
options.h contains the global option struct MPOpts. The option declarations
(option names, types, and MPOpts offsets for the option parser) are in
options.c. Most default values for options and MPOpts are in
mp_default_opts at the end of options.c.
options.h contains the global option struct MPOpts, and its default values
are in defaultopts.c for some reason.
MPOpts is unfortunately quite monolithic, but is being incrementally broken
up into sub-structs. Many components have their own sub-option structs
separate from MPOpts. New options should be bound to the component that uses
them. Add a new option table/struct if needed.
The global MPOpts still contains the sub-structs as fields, which serves to
link them to the option parser. For example, an entry like this may be
typical:
{"", OPT_SUBSTRUCT(demux_opts, demux_conf)},
This directs the option access code to include all options in demux_conf
into the global option list, with no prefix (""), and as part of the
MPOpts.demux_opts field. The MPOpts.demux_opts field is actually not
accessed anywhere, and instead demux.c does this:
struct m_config_cache *opts_cache =
m_config_cache_alloc(demuxer, global, &demux_conf);
struct demux_opts *opts = opts_cache->opts;
... to get a copy of its options.
See m_config.h (below) how to access options.
The actual option parser is spread over m_option.c, m_config.c, and
parse_commandline.c, and uses the option table in options.c.
options/m_config.h & m_config.c:
Code for querying and managing options. This (unfortunately) contains both
declarations for the "legacy-ish" global m_config struct, and ways to access
options in a threads-safe way anywhere, like m_config_cache_alloc().
m_config_cache_alloc() lets anyone read, observe, and write options in any
thread. The only state it needs is struct mpv_global, which is an opaque
type that can be passed "down" the component hierarchy. For safety reasons,
you should not pass down any pointers to option structs (like MPOpts), but
instead pass down mpv_global, and use m_config_cache_alloc() (or similar)
to get a synchronized copy of the options.
input/input.c:
This translates keyboard input coming from VOs and other sources (such
as remote control devices like Apple IR or client API commands) to the
mpvcore/input/input.c:
This translates keyboard input comming from libvo and other sources (such
as remote control devices like Apple IR or slave mode commands) to the
key bindings listed in the user's (or the builtin) input.conf and turns
them into items of type struct mp_cmd. These commands are queued, and read
by playloop.c. They get pushed with run_command() to command.c.
by mplayer.c. They get pushed with run_command() to command.c.
Note that keyboard input and commands used by the client API are the same.
The client API only uses the command parser though, and has its own queue
of input commands somewhere else.
Note that keyboard input and slave mode input are essentially the same
things. Just looking at input.conf should make this clear. (The other
direction of slave mode communication, mpv to application, consists of
random mp_msg() calls all over the code in all parts of the player.)
common/msg.h:
All terminal output must go through mp_msg().
mpvcore/command.c:
This contains the implementation for slave commands and properties.
Properties are essentially dynamic variables changed by certain commands.
This is basically responsible for all user commands, like initiating
seeking, switching tracks, etc. It calls into mplayer.c, where most of the
work is done, but also into other parts of mpv.
mpvcore/mp_msg.h:
All terminal output should go through mp_msg().
stream/*:
File input is implemented here. stream.h/.c provides a simple stream based
@@ -172,6 +130,9 @@ stream/*:
Some stream inputs are just there to invoke special demuxers, like
stream_mf.c. (Basically to make the prefix "mf://" do something special.)
cache.c is a caching wrapper around streams implementations, needed for
smooth network playback.
demux/:
Demuxers split data streams into audio/video/sub streams, which in turn
are split in packets. Packets (see demux_packet.h) are mostly byte chunks
@@ -179,16 +140,13 @@ demux/:
Most demuxers have been removed from this fork, and the only important and
"actual" demuxers left are demux_mkv.c and demux_lavf.c (uses libavformat).
There are some pseudo demuxers like demux_cue.c.
There are some pseudo demuxers like demux_cue.c, which exist only to invoke
other frontend code (tl_cue.c in this case).
The main interface is in demux.h. The stream headers are in stheader.h.
There is a stream header for each audio/video/sub stream, and each of them
holds codec information about the stream and other information.
demux.c is a bit big, the main reason being that it contains the demuxer
cache, which is implemented as a list of packets. The cache is complex
because it support seeking, multiple ranges, prefetching, and so on.
video/:
This contains several things related to audio/video decoding, as well as
video filters.
@@ -197,8 +155,8 @@ video/:
internally.
video/decode/:
vd_*.c are video decoders. (There's only vd_lavc.c left.) dec_video.c
handles most of connecting the frontend with the actual decoder.
vd_*.c are video decoders. (There's only vd_lavc.c left.) dec_video.c/vd.c
handle most of connecting the frontend with the actual decoder.
video/filter/:
vf_*.c and vf.c form the video filter chain. They are fed by the video
@@ -211,36 +169,34 @@ video/out/:
Video output. They also create GUI windows and handle user input. In most
cases, the windowing code is shared among VOs, like x11_common.c for X11 and
w32_common.c for Windows. The VOs stand between frontend and windowing code.
vo_gpu can pick a windowing system at runtime, e.g. the same binary can
vo_opengl can pick a windowing system at runtime, e.g. the same binary can
provide both X11 and Cocoa support on OSX.
VOs can be reconfigured at runtime. A vo_reconfig() call can change the video
VOs can be reconfigured at runtime. A config() call can change the video
resolution and format, without destroying the window.
vo_gpu should be taken as reference.
vo_vdpau and vo_opengl should be taken as reference.
audio/:
format.h/format.c define the uncompressed audio formats. (As well as some
compressed formats used for spdif.)
audio/decode/:
ad_*.c and dec_audio.c handle audio decoding. ad_lavc.c is the
ad_*.c and dec_audio.c/ad.c handle audio decoding. ad_lavc.c is the
decoder using ffmpeg. ad_spdif.c is not really a decoder, but is used for
compressed audio passthrough.
audio/filter/:
Audio filter chain. af_lavrresample is inserted if any form of conversion
between audio formats is needed.
between audio formats is needed. (af_format.c is also used for some corner
cases.)
audio/out/:
Audio outputs.
Unlike VOs, AOs can't be reconfigured on a format change. On audio format
changes, the AO will simply be closed and re-opened.
There are wrappers to support for two types of audio APIs: push.c and
pull.c. ao.c calls into one of these. They contain generic code to deal
with the data flow these APIs impose.
Unlike VOs, AOs can't be reconfigured on a format change. Without
--gapless-audio, even playing a new file will close and re-open the audio
device.
Note that mpv synchronizes the video to the audio. That's the reason
why buggy audio drivers can have a bad influence on playback quality.
@@ -248,410 +204,37 @@ audio/out/:
sub/:
Contains subtitle and OSD rendering.
osd.c/.h is actually the OSD code. It queries dec_sub.c to retrieve
sub.c/.h is actually the OSD code. It queries dec_sub.c to retrieve
decoded/rendered subtitles. osd_libass.c is the actual implementation of
the OSD text renderer (which uses libass, and takes care of all the tricky
fontconfig/freetype API usage and text layouting).
The VOs call osd.c to render OSD and subtitle (via e.g. osd_draw()). osd.c
in turn asks dec_sub.c for subtitle overlay bitmaps, which relays the
request to one of the sd_*.c subtitle decoders/renderers.
Subtitle loading is in demux/. The MPlayer subreader.c is mostly gone - parts
of it survive in demux_subreader.c. It's used as last fallback, or to handle
some text subtitle types on Libav. It should go away eventually. Normally,
subtitles are loaded via demux_lavf.c.
Subtitle loading is now in demux/ instead. demux_libass.c wraps loading
.ass subtitles via libass. demux_lavf.c loads most subtitle types via
FFmpeg. demux_subreader.c is the old MPlayer code. It's used as last
fallback, or to handle some text subtitle types on Libav. (It also can
load UTF-16 encoded subtitles without requiring the use of -subcp.)
demux_subreader.c should eventually go away (maybe).
The subtitles are passed to dec_sub.c and the subtitle decoders in sd_*.c
as they are demuxed. All text subtitles are rendered by sd_ass.c. If text
subtitles are not in the ASS format, the libavcodec subtitle converters are
used (lavc_conv.c).
subtitles are not in the ASS format, subtitle converters are inserted, for
example sd_srt.c, which is used to convert SRT->ASS. sd_srt.c is also used
as general converter for text->ASS (to prevent interpretation of text as
ASS tags).
Text subtitles can be preloaded, in which case they are read fully as soon
as the subtitle is selected. In this case, they are effectively stored in
sd_ass.c's internal state.
as the subtitle is selected, and then effectively stored in an ASS_Track.
It's used for external text subtitles, and required to make codepage
detection as well as timing postprocessing work. (Timing postprocessing
removes tiny gaps or overlaps between subtitle events.)
mpvcore/timeline/:
A timeline is the abstraction used by mplayer.c to combine several files
into one seemingly linear video. It's mainly used for ordered chapters
playback. The high level code to find and load other files containing the
segments for playing an ordered chapters file is in tl_matroska.c.
etc/:
The file input.conf is actually integrated into the mpv binary by the
build system. It contains the default keybindings.
Best practices and Concepts within mpv
======================================
General contribution etc.
-------------------------
See: DOCS/contribute.md
Error checking
--------------
If an error is relevant, it should be handled. If it's interesting, log the
error. However, mpv often keeps errors silent and reports failures somewhat
coarsely by propagating them upwards the caller chain. This is OK, as long as
the errors are not very interesting, or would require a developer to debug it
anyway (in which case using a debugger would be more convenient, and the
developer would need to add temporary debug printfs to get extremely detailed
information which would not be appropriate during normal operation).
Basically, keep a balance on error reporting. But always check them, unless you
have a good argument not to.
Memory allocation errors (OOM) are a special class of errors. Normally such
allocation failures are not handled "properly". Instead, abort() is called.
(New code should use MP_HANDLE_OOM() for this.) This is done out of laziness and
for convenience, and due to the fact that MPlayer/mplayer2 never handled it
correctly. (MPlayer varied between handling it correctly, trying to do so but
failing, and just not caring, while mplayer2 started using abort() for it.)
This is justifiable in a number of ways. Error handling paths are notoriously
untested and buggy, so merely having them won't make your program more reliable.
Having these error handling paths also complicates non-error code, due to the
need to roll back state at any point after a memory allocation.
Take any larger body of code, that is supposed to handle OOM, and test whether
the error paths actually work, for example by overriding malloc with a version
that randomly fails. You will find bugs quickly, and often they will be very
annoying to fix (if you can even reproduce them).
In addition, a clear indication that something went wrong may be missing. On
error your program may exhibit "degraded" behavior by design. Consider a video
encoder dropping frames somewhere in the middle of a video due to temporary
allocation failures, instead of just exiting with an errors. In other cases, it
may open conceptual security holes. Failing fast may be better.
mpv uses GPU APIs, which may be break on allocation errors (because driver
authors will have the same issues as described here), or don't even have a real
concept for dealing with OOM (OpenGL).
libmpv is often used by GUIs, which I predict always break if OOM happens.
Last but not least, OSes like Linux use "overcommit", which basically means that
your program may crash any time OOM happens, even if it doesn't use malloc() at
all!
But still, don't just assume malloc() always succeeds. Use MP_HANDLE_OOM(). The
ta* APIs do this for you. The reason for this is that dereferencing a NULL
pointer can have security relevant consequences if large offsets are involved.
Also, a clear error message is better than a random segfault.
Some big memory allocations are checked anyway. For example, all code must
assume that allocating video frames or packets can fail. (The above example
of dropping video frames during encoding is entirely possible in mpv.)
Undefined behavior
------------------
Undefined behavior (UB) is a concept in the C language. C is famous for being a
language that makes it almost impossible to write working code, because
undefined behavior is so easily triggered, compilers will happily abuse it to
generate "faster" code, debugging tools will shout at you, and sometimes it
even means your code doesn't work.
There is a lot of literature on this topic. Read it.
(In C's defense, UB exists in other languages too, but since they're not used
for low level infrastructure, and/or these languages are at times not rigorously
defined, simply nobody cares. However, the C standard committee is still guilty
for not addressing this. I'll admit that I can't even tell from the standard's
gibberish whether some specific behavior is UB or not. It's written like tax
law.)
In mpv, we generally try to avoid undefined behavior. For one, we want portable
and reliable operation. But more importantly, we want clean output from
debugging tools, in order to find real bugs more quickly and effectively.
Avoid the "works in practice" argument. Once debugging tools come into play, or
simply when "in practice" stops being true, this will all get back to you in a
bad way.
Global state, library safety
----------------------------
Mutable global state is when code uses global variables that are not read-only.
This must be avoided in mpv. Always use context structs that the caller of
your code needs to allocate, and whose pointers are passed to your functions.
Library safety means that your code (or library) can be used by a library
without causing conflicts with other library users in the same process. To any
piece of code, a "safe" library's API can simply be used, without having to
worry about other API users that may be around somewhere.
Libraries are often not library safe, because they they use global mutable state
or other "global" resources. Typical examples include use of signals, simple
global variables (like hsearch() in libc), or internal caches not protected by
locks.
A surprisingly high number of libraries are not library safe because they need
global initialization. Typically they provide an API function, which
"initializes" the library, and which must be called before calling any other
API functions. Often, you are to provide global configuration parameters, which
can change the behavior of the library. If two libraries A and B use library C,
but A and B initialize C with different parameters, something "bad" may happen.
In addition, these global initialization functions are often not thread-safe. So
if A and B try to initialize C at the same time (from different threads and
without knowing about each other), it may cause undefined behavior. (libcurl is
a good example of both of these issues. FFmpeg and some TLS libraries used to be
affected, but improved.)
This is so bad because library A and B from the previous example most likely
have no way to cooperate, because they're from different authors and have no
business knowing each others. They'd need a library D, which wraps library C
in a safe way. Unfortunately, typically something worse happens: libraries get
"infected" by the unsafeness of its sub-libraries, and export a global init API
just to initialize the sub-libraries. In the previous example, libraries A and B
would export global init APIs just to init library C, even though the rest of
A/B are clean and library safe. (Again, libcurl is an example of this, if you
subtract other historic anti-features.)
The main problem with library safety is that its lack propagates to all
libraries using the library.
We require libmpv to be library safe. This is not really possible, because some
libraries are not library safe (FFmpeg, Xlib, partially ALSA). However, for
ideological reasons, there is no global init API, and best effort is made to try
to avoid problems.
libmpv has some features that are not library safe, but which are disabled by
default (such as terminal usage aka stdout, or JSON IPC blocking SIGPIPE for
internal convenience).
A notable, very disgustingly library unsafe behavior of libmpv is calling
abort() on some memory allocation failure. See error checking section.
Logging
-------
All logging and terminal output in mpv goes through the functions and macros
provided in common/msg.h. This is in part for library safety, and in part to
make sure users can silence all output, or to redirect the output elsewhere,
like a log file or the internal console.lua script.
Locking
-------
See generally available literature. In mpv, we use pthread for this.
Always keep locking clean. Don't skip locking just because it will work "in
practice". (See undefined behavior section.) If your use case is simple, you may
use C11 atomics (osdep/atomic.h for partial C99 support), but most likely you
will only hurt yourself and others.
Always make clear which fields in a struct are protected by which lock. If a
field is immutable, or simply not thread-safe (e.g. state for a single worker
thread), document it as well.
Internal mpv APIs are assumed to be not thread-safe by default. If they have
special guarantees (such as being usable by more than one thread at a time),
these should be explicitly documented.
All internal mpv APIs must be free of global state. Even if a component is not
thread-safe, multiple threads can use _different_ instances of it without any
locking.
On a side note, recursive locks may seem convenient at first, but introduce
additional problems with condition variables and locking hierarchies. They
should be avoided.
Locking hierarchy
-----------------
A simple way to avoid deadlocks with classic locking is to define a locking
hierarchy or lock order. If all threads acquire locks in the same order, no
deadlocks will happen.
For example, a "leaf" lock is a lock that is below all other locks in the
hierarchy. You can acquire it any time, as long as you don't acquire other
locks while holding it.
Unfortunately, C has no way to declare or check the lock order, so you should at
least document it.
In addition, try to avoid exposing locks to the outside. Making the declaration
of a lock private to a specific .c file (and _not_ exporting accessors or
lock/unlock functions that manipulate the lock) is a good idea. Your component's
API may acquire internal locks, but should release them when returning. Keeping
the entire locking in a single file makes it easy to check it.
Avoiding callback hell
----------------------
mpv code is separated in components, like the "frontend" (i.e. MPContext mpctx),
VOs, AOs, demuxers, and more. The frontend usually calls "down" the usage
hierarchy: mpctx almost on top, then things like vo/ao, and utility code on the
very bottom.
"Callback hell" is when when components call both up and down the hierarchy,
which for example leads to accidentally recursion, reentrancy problems, or
locking nightmares. This is avoided by (mostly) calling only down the hierarchy.
Basically the call graph forms a DAG. The other direction is handled by event
queues, wakeup callbacks, and similar mechanisms.
Typically, a component provides an API, and does not know anything about its
user. The API user (component higher in the hierarchy) polls the state of the
lower component when needed.
This also enforces some level of modularization, and with some luck the locking
hierarchy. (Basically, locks of lower components automatically become leaf
locks.) Another positive effect is simpler memory management.
(Also see e.g.: http://250bpm.com/blog:24)
Wakeup callbacks
----------------
This is a common concept in mpv. Even the public API uses it. It's used when an
API has internal threads (or otherwise triggers asynchronous events), but the
component call hierarchy needs to be kept. The wakeup callback is the only
exception to the call hierarchy, and always calls up.
For example, vo spawns a thread that the API user (the mpv frontend) does not
need to know about. vo simply provides a single-threaded API (or that looks like
one). This API needs a way to notify the API user of new events. But the vo
event producer is on the vo thread - it can't simply invoke a callback back into
the API user, because then the API user has to deal with locking, despite not
using threads. In addition, this will probably cause problems like mentioned in
the "callback hell" section, especially lock order issues.
The solution is the wakeup callback. It merely unblocks the API user from
waiting, and the API user then uses the normal vo API to examine whether or
which state changed. As a concept, it documents what a wakeup callback is
allowed to do and what not, to avoid the aforementioned problems.
Generally, you are not allowed to call any API from the wakeup callback. You
just do whatever is needed to unblock your thread. For example, if it's waiting
on a mutex/condition variable, acquire the mutex, set a change flag, signal
the condition variable, unlock, return. (This mutex must not be held when
calling the API. It must be a leaf lock.)
Restricting the wakeup callback like this sidesteps any reentrancy issues and
other complexities. The API implementation can simply hold internal (and
non-recursive) locks while invoking the wakeup callback.
The API user still needs to deal with locking (probably), but there's only the
need to implement a single "receiver", that can handle the entire API of the
used component. (Or multiple APIs - MPContext for example has only 1 wakeup
callback that handles all AOs, VOs, input, demuxers, and more. It simple re-runs
the playloop.)
You could get something more advanced by turning this into a message queue. The
API would append a message to the queue, and the API user can read it. But then
you still need a way to "wakeup" the API user (unless you force the API user
to block on your API, which will make things inconvenient for the API user). You
also need to worry about what happens if the message queue overruns (you either
lose messages or have unbounded memory usage). In the mpv public API, the
distinction between message queue and wakeup callback is sort of blurry, because
it does provide a message queue, but an additional wakeup callback, so API
users are not required to call mpv_wait_event() with a high timeout.
mpv itself prefers using wakeup callbacks over a generic event queue, because
most times an event queue is not needed (or complicates things), and it is
better to do it manually.
(You could still abstract the API user side of wakeup callback handling, and
avoid reimplementing it all the time. Although mp_dispatch_queue already
provides mechanisms for this.)
Condition variables
-------------------
They're used whenever a thread needs to wait for something, without nonsense
like sleep calls or busy waiting. mpv uses the standard pthread API for this.
There's a lot of literature on it. Read it.
For initial understanding, it may be helpful to know that condition variables
are not variables that signal a condition. pthread_cond_t does not have any
state per-se. Maybe pthread_cond_t would better be named pthread_interrupt_t,
because its sole purpose is to interrupt a thread waiting via pthread_cond_wait()
(or similar). The "something" in "waiting for something" can be called
predicate (to avoid confusing it with "condition"). Consult literature for the
proper terms.
The very short version is...
Shared declarations:
pthread_mutex_t lock;
pthread_cond_t cond_var;
struct something state_var; // protected by lock, changes signaled by cond_var
Waiter thread:
pthread_mutex_lock(&lock);
// Wait for a change in state_var. We want to wait until predicate_fulfilled()
// returns true.
// Must be a loop for 2 reasons:
// 1. cond_var may be associated with other conditions too
// 2. pthread_cond_wait() can have sporadic wakeups
while (!predicate_fulfilled(&state_var)) {
// This unlocks, waits for cond_var to be signaled, and then locks again.
// The _whole_ point of cond_var is that unlocking and waiting for the
// signal happens atomically.
pthread_cond_wait(&cond_var, &lock);
}
// Here you may react to the state change. The state cannot change
// asynchronously as long as you still hold the lock (and didn't release
// and reacquire it).
// ...
pthread_mutex_unlock(&lock);
Signaler thread:
pthread_mutex_lock(&lock);
// Something changed. Update the shared variable with the new state.
update_state(&state_var);
// Notify that something changed. This will wake up the waiter thread if
// it's blocked in pthread_cond_wait(). If not, nothing happens.
pthread_cond_broadcast(&cond_var);
// Fun fact: good implementations wake up the waiter only when the lock is
// released, to reduce kernel scheduling overhead.
pthread_mutex_unlock(&lock);
Some basic rules:
1. Always access your state under proper locking
2. Always check your predicate before every call to pthread_cond_wait()
(And don't call pthread_cond_wait() if the predicate is fulfilled.)
3. Always call pthread_cond_wait() in a loop
(And only if your predicate failed without releasing the lock..)
4. Always call pthread_cond_broadcast()/_signal() inside of its associated
lock
mpv sometimes violates rule 3, and leaves "retrying" (i.e. looping) to the
caller.
Common pitfalls:
- Thinking that pthread_cond_t is some kind of semaphore, or holds any
application state or the user predicate (it _only_ wakes up threads
that are at the same time blocking on pthread_cond_wait() and friends,
nothing else)
- Changing the predicate, but not updating all pthread_cond_broadcast()/
_signal() calls correctly
- Forgetting that pthread_cond_wait() unlocks the lock (other threads can
and must acquire the lock)
- Holding multiple nested locks while trying to wait (=> deadlock, violates
the lock order anyway)
- Waiting for a predicate correctly, but unlocking/relocking before acting
on it (unlocking allows arbitrary state changes)
- Confusing which lock/condition var. is used to manage a bit of state
Generally available literature probably has better examples and explanations.
Using condition variables the proper way is generally preferred over using more
messy variants of them. (Just saying because on win32, "SetEvent" exists, and
it's inferior to condition variables. Try to avoid the win32 primitives, even if
you're dealing with Windows-only code.)
Threads
-------
Threading should be conservatively used. Normally, mpv code pretends to be
single-threaded, and provides thread-unsafe APIs. Threads are used coarsely,
and if you can avoid messing with threads, you should. For example, VOs and AOs
do not need to deal with threads normally, even though they run on separate
threads. The glue code "isolates" them from any threading issues.
-157
View File
@@ -1,157 +0,0 @@
waf build system overview
=========================
mpv's new build system is based on waf and it should completely replace the
custom ./configure + Makefile based system inherited from MPlayer.
Goals and the choice of waf
===========================
The new system comes with some goals, which can be summed up as: be as good as
the old one at what it did well (customizability) and fix some of it's major
shortcomings:
1) The build system must be uniform in how it handles any single feature check.
Repetition and boilerplate have to be avoided.
When adding a new feature using the old configure, one had to add a fair
amount of code to the shell script to do option parsing, detection of the
feature and declaration of variables for the Makefile to pickup. The worst
part is this pieces are spread apart in the configure and copy pasted for
any single case. That brings us to..
2) --enable-feature has to be overridden by the user and helps them understand that
they have libraries missing and should install them for the feature to be
enabled.
3) Must be customizable, hackable, pleasant to the developer eyes and to work
with in general.
4) Must have separate configuration and build steps.
Goal 2 comes as a given on pretty much any build system, since autotools made
this behaviour very popular among users (and rightly so).
Goal 1+3 were somewhat harder to accomplish as it looks like all of the build
systems we evaluated (waf included!) had problems with them. For reference we
had proof of concept build systems with waf, CMake and autotools.
What puts waf apart from CMake and autotools, is that projects using it use
Python to program their build system. Also while the Waf Book shows really
simple API usages, you can write your own build system on top of waf that is
tailored to the project's specific needs.
mpv's custom configure step on top of waf
=========================================
To some extents mpv has a custom build system written on top of waf. This
document will not go over the standard waf behaviour as that is documented in
the `Waf book <http://docs.waf.googlecode.com/git/book_17/single.html>`_.
All of the configuration process is handled with a declarative approach. Lists
of dictionaries define the checks, and some custom Python code traverses these
lists and depending on the check definition it calls into the actual waf API.
A simple example using pkg-config would be::
{
'name': '--vdpau',
'desc': 'VDPAU acceleration',
'deps': [ 'x11' ],
'func': check_pkg_config('vdpau', '>= 0.2'),
}
This defines a feature called ``vdpau`` which can be enabled or disabled by
the users with configure flags (that's the meaning of ``--``). This feature
depends on another feature whose name is ``x11``, and the autodetection check
consists of running ``pkg-config`` and looking for ``vdpau`` with version
``>= 0.2``. If the check succeeds a ``#define HAVE_VDPAU 1`` will be added to
``config.h``, if not ``#define HAVE_VDPAU 0`` will be added.
The defines names are automatically prepended with ``HAVE_``, capitalized and
special characters are replaced with underscores. This happens in
``waftools/inflectors.py``.
Mandatory fields:
-----------------
``name``: indicates the unique identifier used by the custom dependency code
to refer to a feature. If the unique identifier is prepended with ``--``
the build system will also generate options for ``./waf configure`` so that
the feature can be enabled and disabled.
``desc``: this is the textual representation of the feature used in the
interactions with the users.
``func``: function that will perform the check. These functions are defined in
``waftools/checks``. The reusable checks are all functions that return
functions. The return functions will then be applied using waf's configuration
context.
The source code for the reusable checks is a bit convoluted, but it should be
easy to pick up their usage from the ``wscript``. Their signature mirrors
the semantics of some of the shell functions used in mplayer.
If someone expresses some interest, I will extend this document with official
documentation for each check function.
Optional fields
---------------
``deps``: list of dependencies of this feature. It is a list of names of
other features as defined in the ``name`` field (minus the eventual leading
``--``). All of the dependencies must be satisfied. If they are not the check
will be skipped without even running ``func``.
``deps_any``: like deps but it is satisfied even if only one of the dependencies
is satisfied. You can think of ``deps`` as a 'and' condition and ``deps_any``
as a 'or' condition.
``deps_neg``: like deps but it is satisfied when none of the dependencies is
satisfied.
``req``: defaults to False. If set to True makes this feature a hard
dependency of mpv (configuration will fail if autodetection fails). If set to
True you must also provide ``fmsg``.
``fmsg``: string with the failure message in case a required dependency is not
satisfied.
``os_specific_checks``: this takes a dictionary that has ``os-`` dependencies
as keys (such as ``os-win32``), and by values has another dictionary that is
merged on top of the current feature definition only for that specific OS.
For example::
{
'name': '--pthreads',
'desc': 'POSIX threads',
'func': check_pthreads,
'os_specific_checks': {
'os-win32': {
'func': check_pthreads_w32_static.
}
}
}
will override the value of ``func`` with ``check_pthreads_w32_static`` only
if the target OS of the build is Windows.
``groups``: groups a dependency with another one. This can be used to disabled
all the grouped dependencies with one ``--disable-``. At the moment this is
only used for OpenGL backends, where you want to disable them when
``--disable-gl`` is passed to the configure.
mpv's custom build step on top of waf
=====================================
Build step is pretty much vanilla waf. The only difference being that the list
of source files can contain both strings or tuples. If a tuple is found,
the second element in the tuple will be used to match the features detected
in the configure step (the ``name`` field described above). If this feature
was not enabled during configure, the source file will not be compiled in.
All of the custom Python for this is inside the function ``filtered_sources``
contained in the file ``waftools/dependencies.py``.
Also ``dependencies_use`` and ``dependencies_includes`` collect cflags and
ldflags that were generated from the features checks in the configure step.
View File
File renamed without changes.
-502
View File
@@ -1,502 +0,0 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
+551
View File
@@ -0,0 +1,551 @@
# MPlayer Makefile
#
# copyright (c) 2008 Diego Biurrun
# Rewritten entirely from a set of Makefiles written by Arpi and many others.
#
# This file is part of MPlayer.
#
# MPlayer is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# MPlayer is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with MPlayer; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
include config.mak
###### variable declarations #######
SOURCES_AUDIO_INPUT-$(ALSA) += stream/ai_alsa1x.c
SOURCES_AUDIO_INPUT-$(OSS) += stream/ai_oss.c
SOURCES_AUDIO_INPUT-$(SNDIO) += stream/ai_sndio.c
SOURCES-$(AUDIO_INPUT) += $(SOURCES_AUDIO_INPUT-yes)
SOURCES-$(CDDA) += stream/stream_cdda.c \
stream/cdinfo.c
SOURCES-$(DVBIN) += stream/dvb_tune.c \
stream/stream_dvb.c
SOURCES-$(DVDREAD) += stream/stream_dvd.c \
stream/stream_dvd_common.c
SOURCES-$(HAVE_SYS_MMAN_H) += audio/filter/af_export.c
SOURCES-$(LADSPA) += audio/filter/af_ladspa.c
SOURCES-$(LIBASS) += sub/ass_mp.c sub/sd_ass.c \
demux/demux_libass.c
SOURCES-$(LIBBLURAY) += stream/stream_bluray.c
SOURCES-$(LIBBS2B) += audio/filter/af_bs2b.c
SOURCES-$(LIBPOSTPROC) += video/filter/vf_pp.c
SOURCES-$(LIBSMBCLIENT) += stream/stream_smb.c
SOURCES-$(COCOA) += video/out/cocoa/view.m \
video/out/cocoa/window.m \
video/out/cocoa/additions.m \
video/out/cocoa_common.m \
osdep/macosx_application.m \
osdep/macosx_events.m \
osdep/ar/HIDRemote.m \
osdep/path-macosx.m
SOURCES-$(MNG) += demux/demux_mng.c
SOURCES-$(MPG123) += audio/decode/ad_mpg123.c
SOURCES-$(NEED_GETTIMEOFDAY) += osdep/gettimeofday.c
SOURCES-$(NEED_GLOB) += osdep/glob-win.c
SOURCES-$(WIN32) += osdep/path-win.c
SOURCES-$(PRIORITY) += osdep/priority.c
SOURCES-$(PVR) += stream/stream_pvr.c
SOURCES-$(RADIO) += stream/stream_radio.c
SOURCES-$(RADIO_CAPTURE) += stream/audio_in.c
SOURCES-$(STREAM_CACHE) += stream/cache.c
SOURCES-$(TV) += stream/stream_tv.c stream/tv.c \
stream/frequencies.c stream/tvi_dummy.c
SOURCES-$(TV_V4L2) += stream/tvi_v4l2.c stream/audio_in.c
SOURCES-$(VCD) += stream/stream_vcd.c
SOURCES-$(DUMMY_OSD) += sub/osd_dummy.c
SOURCES-$(LIBASS_OSD) += sub/osd_libass.c
SOURCES-$(ALSA) += audio/out/ao_alsa.c
SOURCES-$(CACA) += video/out/vo_caca.c
SOURCES-$(SDL) += audio/out/ao_sdl.c
SOURCES-$(SDL2) += video/out/vo_sdl.c
SOURCES-$(COREAUDIO) += audio/out/ao_coreaudio.c \
audio/out/ao_coreaudio_utils.c \
audio/out/ao_coreaudio_properties.c
SOURCES-$(COREVIDEO) += video/out/vo_corevideo.c
SOURCES-$(DIRECT3D) += video/out/vo_direct3d.c \
video/out/w32_common.c
SOURCES-$(DSOUND) += audio/out/ao_dsound.c
SOURCES-$(WASAPI) += audio/out/ao_wasapi.c
SOURCES-$(GL) += video/out/gl_common.c video/out/gl_osd.c \
video/out/vo_opengl.c video/out/gl_lcms.c \
video/out/gl_video.c video/out/dither.c \
video/out/vo_opengl_old.c \
video/out/pnm_loader.c
SOURCES-$(ENCODING) += video/out/vo_lavc.c audio/out/ao_lavc.c \
mpvcore/encode_lavc.c
SOURCES-$(GL_WIN32) += video/out/w32_common.c video/out/gl_w32.c
SOURCES-$(GL_X11) += video/out/x11_common.c video/out/gl_x11.c
SOURCES-$(GL_COCOA) += video/out/gl_cocoa.c
SOURCES-$(GL_WAYLAND) += video/out/wayland_common.c \
video/out/gl_wayland.c
SOURCES-$(JACK) += audio/out/ao_jack.c
SOURCES-$(JOYSTICK) += mpvcore/input/joystick.c
SOURCES-$(LIBQUVI) += mpvcore/resolve_quvi.c
SOURCES-$(LIBQUVI9) += mpvcore/resolve_quvi9.c
SOURCES-$(LIRC) += mpvcore/input/lirc.c
SOURCES-$(OPENAL) += audio/out/ao_openal.c
SOURCES-$(OSS) += audio/out/ao_oss.c
SOURCES-$(PULSE) += audio/out/ao_pulse.c
SOURCES-$(PORTAUDIO) += audio/out/ao_portaudio.c
SOURCES-$(RSOUND) += audio/out/ao_rsound.c
SOURCES-$(SNDIO) += audio/out/ao_sndio.c
SOURCES-$(VDPAU) += video/vdpau.c video/out/vo_vdpau.c
SOURCES-$(VDA) += video/decode/vda.c
SOURCES-$(VDPAU_DEC) += video/decode/vdpau.c
SOURCES-$(VDPAU_DEC_OLD) += video/decode/vdpau_old.c
SOURCES-$(VAAPI) += video/out/vo_vaapi.c \
video/decode/vaapi.c \
video/vaapi.c
SOURCES-$(VAAPI_VPP) += video/filter/vf_vavpp.c
SOURCES-$(X11) += video/out/vo_x11.c video/out/x11_common.c
SOURCES-$(XV) += video/out/vo_xv.c
SOURCES-$(WAYLAND) += video/out/vo_wayland.c video/out/wayland_common.c
SOURCES-$(VF_LAVFI) += video/filter/vf_lavfi.c
SOURCES-$(AF_LAVFI) += audio/filter/af_lavfi.c
SOURCES-$(LUA) += mpvcore/mp_lua.c
ifeq ($(HAVE_AVUTIL_REFCOUNTING),no)
SOURCES-yes += video/decode/lavc_dr1.c
endif
SOURCES-$(DLOPEN) += video/filter/vf_dlopen.c
SOURCES = audio/audio.c \
audio/chmap.c \
audio/chmap_sel.c \
audio/fmt-conversion.c \
audio/format.c \
audio/mixer.c \
audio/reorder_ch.c \
audio/decode/ad_lavc.c \
audio/decode/ad_spdif.c \
audio/decode/dec_audio.c \
audio/filter/af.c \
audio/filter/af_center.c \
audio/filter/af_channels.c \
audio/filter/af_delay.c \
audio/filter/af_dummy.c \
audio/filter/af_equalizer.c \
audio/filter/af_extrastereo.c \
audio/filter/af_force.c \
audio/filter/af_format.c \
audio/filter/af_hrtf.c \
audio/filter/af_karaoke.c \
audio/filter/af_lavcac3enc.c \
audio/filter/af_lavrresample.c \
audio/filter/af_pan.c \
audio/filter/af_scaletempo.c \
audio/filter/af_sinesuppress.c \
audio/filter/af_sub.c \
audio/filter/af_surround.c \
audio/filter/af_sweep.c \
audio/filter/af_tools.c \
audio/filter/af_drc.c \
audio/filter/af_volume.c \
audio/filter/filter.c \
audio/filter/window.c \
audio/out/ao.c \
audio/out/ao_null.c \
audio/out/ao_pcm.c \
demux/codec_tags.c \
demux/demux.c \
demux/demux_edl.c \
demux/demux_cue.c \
demux/demux_lavf.c \
demux/demux_mf.c \
demux/demux_mkv.c \
demux/demux_playlist.c \
demux/demux_raw.c \
demux/demux_subreader.c \
demux/ebml.c \
demux/mf.c \
mpvcore/asxparser.c \
mpvcore/av_common.c \
mpvcore/av_log.c \
mpvcore/av_opts.c \
mpvcore/bstr.c \
mpvcore/charset_conv.c \
mpvcore/codecs.c \
mpvcore/command.c \
mpvcore/cpudetect.c \
mpvcore/m_config.c \
mpvcore/m_option.c \
mpvcore/m_property.c \
mpvcore/mp_common.c \
mpvcore/mp_msg.c \
mpvcore/mp_ring.c \
mpvcore/mplayer.c \
mpvcore/options.c \
mpvcore/parser-cfg.c \
mpvcore/parser-mpcmd.c \
mpvcore/path.c \
mpvcore/playlist.c \
mpvcore/playlist_parser.c \
mpvcore/screenshot.c \
mpvcore/version.c \
mpvcore/input/input.c \
mpvcore/timeline/tl_edl.c \
mpvcore/timeline/tl_matroska.c \
mpvcore/timeline/tl_cue.c \
osdep/io.c \
osdep/numcores.c \
osdep/timer.c \
stream/cookies.c \
stream/rar.c \
stream/stream.c \
stream/stream_avdevice.c \
stream/stream_file.c \
stream/stream_lavf.c \
stream/stream_memory.c \
stream/stream_mf.c \
stream/stream_null.c \
stream/stream_rar.c \
sub/dec_sub.c \
sub/draw_bmp.c \
sub/find_subfiles.c \
sub/img_convert.c \
sub/sd_lavc.c \
sub/sd_lavc_conv.c \
sub/sd_lavf_srt.c \
sub/sd_microdvd.c \
sub/sd_movtext.c \
sub/sd_spu.c \
sub/sd_srt.c \
sub/spudec.c \
sub/sub.c \
ta/ta.c \
ta/ta_utils.c \
ta/ta_talloc.c \
video/csputils.c \
video/fmt-conversion.c \
video/image_writer.c \
video/img_format.c \
video/mp_image.c \
video/mp_image_pool.c \
video/sws_utils.c \
video/decode/dec_video.c \
video/decode/vd.c \
video/decode/vd_lavc.c \
video/filter/vf.c \
video/filter/pullup.c \
video/filter/vf_crop.c \
video/filter/vf_delogo.c \
video/filter/vf_divtc.c \
video/filter/vf_down3dright.c \
video/filter/vf_dsize.c \
video/filter/vf_eq.c \
video/filter/vf_expand.c \
video/filter/vf_flip.c \
video/filter/vf_format.c \
video/filter/vf_gradfun.c \
video/filter/vf_hqdn3d.c \
video/filter/vf_ilpack.c \
video/filter/vf_mirror.c \
video/filter/vf_noformat.c \
video/filter/vf_noise.c \
video/filter/vf_phase.c \
video/filter/vf_pullup.c \
video/filter/vf_rotate.c \
video/filter/vf_scale.c \
video/filter/vf_screenshot.c \
video/filter/vf_softpulldown.c \
video/filter/vf_stereo3d.c \
video/filter/vf_sub.c \
video/filter/vf_swapuv.c \
video/filter/vf_unsharp.c \
video/filter/vf_vo.c \
video/filter/vf_yadif.c \
video/out/bitmap_packer.c \
video/out/aspect.c \
video/out/filter_kernels.c \
video/out/vo.c \
video/out/vo_null.c \
video/out/vo_image.c \
osdep/$(GETCH) \
osdep/$(TIMER) \
$(SOURCES-yes)
OBJECTS += $(addsuffix .o, $(basename $(SOURCES)))
OBJECTS-$(PE_EXECUTABLE) += osdep/mpv-rc.o
OBJECTS += $(OBJECTS-yes)
DEP_FILES = $(patsubst %.S,%.d,$(patsubst %.cpp,%.d,$(patsubst %.c,%.d,$(SOURCES:.m=.d) $(SOURCES:.m=.d))))
ALL_TARGETS += mpv$(EXESUF)
INSTALL_BIN += install-mpv
INSTALL_BIN_STRIP += install-mpv-strip
INSTALL_MAN =
INSTALL_PDF =
ifeq ($(BUILD_MAN),yes)
INSTALL_MAN += install-mpv-man
ALL_TARGETS += DOCS/man/en/mpv.1
endif
ifeq ($(BUILD_PDF),yes)
INSTALL_PDF += install-mpv-pdf
ALL_TARGETS += DOCS/man/en/mpv.pdf
endif
DIRS = . \
audio \
audio/decode \
audio/filter \
audio/out \
mpvcore \
mpvcore/input \
mpvcore/timeline \
demux \
osdep \
osdep/ar \
stream \
sub \
video \
video/decode \
video/filter \
video/out
ADDSUFFIXES = $(foreach suf,$(1),$(addsuffix $(suf),$(2)))
ADD_ALL_DIRS = $(call ADDSUFFIXES,$(1),$(DIRS))
ADD_ALL_EXESUFS = $(1) $(call ADDSUFFIXES,$(EXESUFS_ALL),$(1))
###### brief build output #######
ifndef V
$(eval override CC = @printf "CC\t$$@\n"; $(CC))
$(eval override RM = @$(RM))
endif
###### generic rules #######
all: $(ALL_TARGETS)
%.tex: %.rst
$(RST2LATEX) --config=DOCS/man/docutils.conf $< $@
%.pdf: %.tex
pdflatex -interaction=batchmode -jobname=$(basename $@) $<; pdflatex -interaction=batchmode -jobname=$(basename $@) $<
%.1: %.rst
$(RST2MAN) $< $@
%.o: %.S
$(CC) $(DEPFLAGS) $(CFLAGS) -c -o $@ $<
%.o: %.c
$(CC) $(DEPFLAGS) $(CFLAGS) -c -o $@ $<
%.o: %.cpp
$(CC) $(DEPFLAGS) $(CXXFLAGS) -c -o $@ $<
%.o: %.m
$(CC) $(DEPFLAGS) $(CFLAGS) -c -o $@ $<
%-rc.o: %.rc
$(WINDRES) -I. $< $@
mpv$(EXESUF): $(OBJECTS)
mpv$(EXESUF):
$(CC) -o $@ $^ $(EXTRALIBS)
mpvcore/input/input.c: mpvcore/input/input_conf.h
mpvcore/input/input_conf.h: TOOLS/file2string.pl etc/input.conf
./$^ >$@
MKVLIB_DEPS = TOOLS/lib/Parse/Matroska.pm \
TOOLS/lib/Parse/Matroska/Definitions.pm \
TOOLS/lib/Parse/Matroska/Element.pm \
TOOLS/lib/Parse/Matroska/Reader.pm \
TOOLS/lib/Parse/Matroska/Utils.pm \
demux/ebml.c demux/demux_mkv.c: demux/ebml_types.h
demux/ebml_types.h: TOOLS/matroska.pl $(MKVLIB_DEPS)
./$< --generate-header > $@
demux/ebml.c: demux/ebml_defs.c
demux/ebml_defs.c: TOOLS/matroska.pl $(MKVLIB_DEPS)
./$< --generate-definitions > $@
video/out/gl_video.c: video/out/gl_video_shaders.h
video/out/gl_video_shaders.h: TOOLS/file2string.pl video/out/gl_video_shaders.glsl
./$^ >$@
video/out/x11_common.c: video/out/x11_icon.inc
video/out/x11_icon.inc: TOOLS/file2string.pl video/out/x11_icon.bin
./$^ >$@
sub/osd_libass.c: sub/osd_font.h
sub/osd_font.h: TOOLS/file2string.pl sub/osd_font.otf
./$^ >$@
mpvcore/mp_lua.c: mpvcore/lua/defaults.inc
mpvcore/lua/defaults.inc: TOOLS/file2string.pl mpvcore/lua/defaults.lua
./$^ >$@
mpvcore/mp_lua.c: mpvcore/lua/assdraw.inc
mpvcore/lua/assdraw.inc: TOOLS/file2string.pl mpvcore/lua/assdraw.lua
./$^ >$@
mpvcore/mp_lua.c: mpvcore/lua/osc.inc
mpvcore/lua/osc.inc: TOOLS/file2string.pl mpvcore/lua/osc.lua
./$^ >$@
# ./configure must be rerun if it changed
config.mak: configure
@echo "############################################################"
@echo "####### Please run ./configure again - it's changed! #######"
@echo "############################################################"
version.h .version: version.sh
./$<
# Force version.sh to run to potentially regenerate version.h
-include .version
%$(EXESUF): %.c
$(CC) $(CFLAGS) -o $@ $^
###### dependency declarations / specific CFLAGS ######
mpvcore/version.c osdep/mpv-rc.o: version.h
osdep/mpv-rc.o: osdep/mpv.exe.manifest etc/mpv-icon.ico
DOCS/man/en/mpv.1 DOCS/man/en/mpv.pdf: DOCS/man/en/af.rst \
DOCS/man/en/ao.rst \
DOCS/man/en/changes.rst \
DOCS/man/en/encode.rst \
DOCS/man/en/input.rst \
DOCS/man/en/options.rst \
DOCS/man/en/vf.rst \
DOCS/man/en/vo.rst
###### installation / clean / generic rules #######
install: $(INSTALL_BIN) install-data $(INSTALL_MAN) $(INSTALL_PDF)
install-no-man: $(INSTALL_BIN) install-data
install-strip: $(INSTALL_BIN_STRIP) install-data $(INSTALL_MAN) $(INSTALL_PDF)
install-strip-no-man: $(INSTALL_BIN_STRIP) install-data
install-dirs:
if test ! -d $(BINDIR) ; then $(INSTALL) -d $(BINDIR) ; fi
install-%: %$(EXESUF) install-dirs
$(INSTALL) -m 755 $< $(BINDIR)
install-%-strip: %$(EXESUF) install-dirs
$(INSTALL) -m 755 -s $< $(BINDIR)
install-mpv-man: install-mpv-man-en
install-mpv-man-en: DOCS/man/en/mpv.1
if test ! -d $(MANDIR)/man1 ; then $(INSTALL) -d $(MANDIR)/man1 ; fi
$(INSTALL) -m 644 DOCS/man/en/mpv.1 $(MANDIR)/man1/
install-mpv-pdf: install-mpv-pdf-en
install-mpv-pdf-en: DOCS/man/en/mpv.pdf
if test ! -d $(DOCDIR) ; then $(INSTALL) -d $(DOCDIR) ; fi
$(INSTALL) -m 644 DOCS/man/en/mpv.pdf $(DOCDIR)/
ICONSIZES = 16x16 32x32 64x64
define ICON_INSTALL_RULE
install-mpv-icon-$(size): etc/mpv-icon-8bit-$(size).png
$(INSTALL) -d $(prefix)/share/icons/hicolor/$(size)/apps
$(INSTALL) -m 644 etc/mpv-icon-8bit-$(size).png $(prefix)/share/icons/hicolor/$(size)/apps/mpv.png
endef
$(foreach size,$(ICONSIZES),$(eval $(ICON_INSTALL_RULE)))
install-mpv-icons: $(foreach size,$(ICONSIZES),install-mpv-icon-$(size))
install-mpv-desktop: etc/mpv.desktop
$(INSTALL) -d $(prefix)/share/applications
$(INSTALL) -m 644 etc/mpv.desktop $(prefix)/share/applications/
install-data: install-mpv-icons install-mpv-desktop
uninstall:
$(RM) $(BINDIR)/mpv$(EXESUF)
$(RM) $(MANDIR)/man1/mpv.1
$(RM) $(MANDIR)/en/man1/mpv.1
$(RM) $(DOCDIR)/mpv.pdf
$(RM) $(prefix)/share/applications/mpv.desktop
$(RM) $(foreach size,$(ICONSIZES),$(prefix)/share/icons/hicolor/$(size)/apps/mpv.png)
clean:
-$(RM) $(call ADD_ALL_DIRS,/*.o /*.d /*.a /*.ho /*~)
-$(RM) $(call ADD_ALL_DIRS,/*.o /*.a /*.ho /*~)
-$(RM) $(call ADD_ALL_EXESUFS,mpv)
-$(RM) $(call ADDSUFFIXES,.pdf .tex .log .aux .out .toc,DOCS/man/*/mpv)
-$(RM) DOCS/man/*/mpv.1
-$(RM) version.h
-$(RM) mpvcore/input/input_conf.h
-$(RM) video/out/vdpau_template.c
-$(RM) demux/ebml_types.h demux/ebml_defs.c
-$(RM) video/out/gl_video_shaders.h
-$(RM) video/out/x11_icon.inc
-$(RM) sub/osd_font.h
-$(RM) mpvcore/lua/defaults.inc
-$(RM) mpvcore/lua/assdraw.inc
-$(RM) mpvcore/lua/osc.inc
distclean: clean
-$(RM) config.log config.mak config.h TAGS tags
TAGS:
$(RM) $@; find . -name '*.[chS]' -o -name '*.asm' | xargs etags -a
tags:
$(RM) $@; find . -name '*.[chS]' -o -name '*.asm' | xargs ctags -a
osxbundle:
@TOOLS/osxbundle.py mpv
osxbundle-skip-deps:
@TOOLS/osxbundle.py --skip-deps mpv
-include $(DEP_FILES)
.PHONY: all *install* *clean .version
# Disable suffix rules. Most of the builtin rules are suffix rules,
# so this saves some time on slow systems.
.SUFFIXES:
# If a command returns failure but changed its target file, delete the
# (presumably malformed) file. Otherwise the file would be considered to
# be up to date if make is restarted.
.DELETE_ON_ERROR:
+70 -179
View File
@@ -1,216 +1,107 @@
![mpv logo](https://raw.githubusercontent.com/mpv-player/mpv.io/master/source/images/mpv-logo-128.png)
mpv
===
# mpv
[![Build Status](https://api.travis-ci.org/mpv-player/mpv.png)](https://travis-ci.org/mpv-player/mpv)
Overview
--------
* [External links](#external-links)
* [Overview](#overview)
* [System requirements](#system-requirements)
* [Downloads](#downloads)
* [Changelog](#changelog)
* [Compilation](#compilation)
* [Release cycle](#release-cycle)
* [Bug reports](#bug-reports)
* [Contributing](#contributing)
* [License](#license)
* [Contact](#contact)
**mpv** is a movie player based on MPlayer and mplayer2. It supports a wide
variety of video file formats, audio and video codecs, and subtitle types.
If you are wondering what's different from mplayer2 and MPlayer you can read
more about the [changes][changes].
## External links
* [Wiki](https://github.com/mpv-player/mpv/wiki)
* [FAQ][FAQ]
* [Manual](http://mpv.io/manual/master/)
## Overview
**mpv** is a free (as in freedom) media player for the command line. It supports
a wide variety of media file formats, audio and video codecs, and subtitle types.
There is a [FAQ][FAQ].
Releases can be found on the [release list][releases].
## System requirements
- A not too ancient Linux, Windows 7 or later, or OSX 10.8 or later.
- A somewhat capable CPU. Hardware decoding might help if the CPU is too slow to
decode video in realtime, but must be explicitly enabled with the `--hwdec`
option.
- A not too crappy GPU. mpv's focus is not on power-efficient playback on
embedded or integrated GPUs (for example, hardware decoding is not even
enabled by default). Low power GPUs may cause issues like tearing, stutter,
etc. The main video output uses shaders for video rendering and scaling,
rather than GPU fixed function hardware. On Windows, you might want to make
sure the graphics drivers are current. In some cases, ancient fallback video
output methods can help (such as `--vo=xv` on Linux), but this use is not
recommended or supported.
## Downloads
For semi-official builds and third-party packages please see
[mpv.io/installation](http://mpv.io/installation/).
## Changelog
There is no complete changelog; however, changes to the player core interface
are listed in the [interface changelog][interface-changes].
Changes to the C API are documented in the [client API changelog][api-changes].
The [release list][releases] has a summary of most of the important changes
on every release.
Changes to the default key bindings are indicated in
[restore-old-bindings.conf][restore-old-bindings].
## Compilation
Compilation
-----------
Compiling with full features requires development files for several
external libraries. Below is a list of some important requirements.
The mpv build system uses [waf](https://waf.io/), but we don't store it in the
repository. The `./bootstrap.py` script will download the latest version
of waf that was tested with the build system.
For a list of the available build options use `./waf configure --help`. If
you think you have support for some feature installed but configure fails to
detect it, the file `build/config.log` may contain information about the
reasons for the failure.
NOTE: To avoid cluttering the output with unreadable spam, `--help` only shows
one of the two switches for each option. If the option is autodetected by
default, the `--disable-***` switch is printed; if the option is disabled by
default, the `--enable-***` switch is printed. Either way, you can use
`--enable-***` or `--disable-**` regardless of what is printed by `--help`.
To build the software you can use `./waf build`: the result of the compilation
will be located in `build/mpv`. You can use `./waf install` to install mpv
to the *prefix* after it is compiled.
Example:
./bootstrap.py
./waf configure
./waf
./waf install
external libraries. Below is a list of some important requirements. For
more information see the output of `./configure --help` for a list of options,
or look at the list of enabled and disabled features printed after running
`./configure`. If you think you have support for some feature installed
but configure fails to detect it, the file `config.log` may contain
information about the reasons for the failure.
Essential dependencies (incomplete list):
- gcc or clang
- X development headers (xlib, xrandr, xext, xscrnsaver, xinerama, libvdpau,
libGL, GLX, EGL, xv, ...)
- Audio output development headers (libasound/ALSA, pulseaudio)
- FFmpeg libraries (libavutil libavcodec libavformat libswscale libavfilter
and either libswresample or libavresample)
- zlib
- iconv (normally provided by the system libc)
- libass (OSD, OSC, text subtitles)
- Lua (optional, required for the OSC pseudo-GUI and youtube-dl integration)
- libjpeg (optional, used for screenshots only)
- uchardet (optional, for subtitle charset detection)
- nvdec and vaapi libraries for hardware decoding on Linux (optional)
Libass dependencies (when building libass):
- gcc or clang, yasm on x86 and x86_64
- X development headers (xlib, X extensions, libvdpau, libGL, libXv, ...)
- Audio output development headers (libasound, pulseaudio)
- fribidi, freetype, fontconfig development headers (for libass)
- harfbuzz (optional, required for correct rendering of combining characters,
particularly for correct rendering of non-English text on OSX, and
Arabic/Indic scripts on any platform)
FFmpeg dependencies (when building FFmpeg):
- gcc or clang, yasm on x86 and x86_64
- OpenSSL or GnuTLS (have to be explicitly enabled when compiling FFmpeg)
- libx264/libmp3lame/libfdk-aac if you want to use encoding (have to be
explicitly enabled when compiling FFmpeg)
- For native DASH playback, FFmpeg needs to be built with --enable-libxml2
(although there are security implications, and DASH support has lots of bugs).
- AV1 decoding support requires dav1d.
- For good nvidia support on Linux, make sure nv-codec-headers is installed
and can be found by configure.
- libass
- FFmpeg libraries (libavutil libavcodec libavformat libswscale libpostproc)
- libjpeg
- libquvi if you want to play Youtube videos directly
- libx264/libmp3lame/libfdk-aac if you want to use encoding (has to be
explicitly enabled when compiling ffmpeg)
Most of the above libraries are available in suitable versions on normal
Linux distributions. For ease of compiling the latest git master of everything,
you may wish to use the separately available build wrapper ([mpv-build][mpv-build])
which first compiles FFmpeg libraries and libass, and then compiles the player
statically linked against those.
Linux distributions. However FFmpeg is an exception (distro versions may be
too old to work at all or work well). For that reason you may want to use
the separately available build wrapper ([mpv-build][mpv-build]) that first compiles FFmpeg
libraries and libass, and then compiles the player statically linked against
those.
If you want to build a Windows binary, you either have to use MSYS2 and MinGW,
or cross-compile from Linux with MinGW. See
[Windows compilation][windows_compilation].
If you are running Mac OSX and using homebrew we provide [homebrew-mpv][homebrew-mpv], an up
to date formula that compiles mpv with sensible dependencies and defaults for
OSX.
### configure `--enable-*` parameters
## Release cycle
The `--enable-*` parameters unconditionally force options on, completely
skipping autodetection. This behavior is unlike what you may be used to from
autoconf-based configure scripts that can decide to override you. This greater
level of control comes at a price. You may have to provide the correct compiler
and linker flags yourself.
Every other month, an arbitrary git snapshot is made, and is assigned
a 0.X.0 version number. No further maintenance is done.
If you used one of these options and experience a compilation or
linking failure, make sure you have passed the necessary compiler/linker flags
to configure.
The goal of releases is to make Linux distributions happy. Linux distributions
are also expected to apply their own patches in case of bugs and security
issues.
mpv's configure script is greedy and automatically enables features as a result
of autodetection. The cases where you may want to use `--enable-*` are very
limited.
Releases other than the latest release are unsupported and unmaintained.
FFmpeg vs. Libav
----------------
See the [release policy document][release-policy] for more information.
## Bug reports
Generally, mpv should work with the latest release as well as the git version
of both FFmpeg and Libav. But FFmpeg is preferred, and some mpv features work
with FFmpeg only. See the [wiki article][ffmpeg_vs_libav] about the issue.
Bug reports
-----------
Please use the [issue tracker][issue-tracker] provided by GitHub to send us bug
reports or feature requests. Follow the template's instructions or the issue
will likely be ignored or closed as invalid.
reports or feature requests.
Using the bug tracker as place for simple questions is fine but IRC is
recommended (see [Contact](#Contact) below).
## Contributing
Please read [contribute.md][contribute.md].
Contributing
------------
For small changes you can just send us pull requests through GitHub. For bigger
changes come and talk to us on IRC before you start working on them. It will
make code review easier for both parties later on.
You can check [the wiki](https://github.com/mpv-player/mpv/wiki/Stuff-to-do)
or the [issue tracker](https://github.com/mpv-player/mpv/issues?q=is%3Aopen+is%3Aissue+label%3A%22feature+request%22)
for ideas on what you could contribute with.
Contacts
--------
## License
These forms of contact are meant to ask questions about mpv usage, give
feedback on mpv and discuss it's development.
GPLv2 "or later" by default, LGPLv2.1 "or later" with `--enable-lgpl`.
See [details.](https://github.com/mpv-player/mpv/blob/master/Copyright)
If possible, please avoid posting bugs here and use the [issue tracker][issue-tracker]
instead.
## History
- **Users IRC Channel**: `#mpv-player` on `irc.freenode.net`
- **Users Mailing List**: `mpv-users@googlegroups.com` ([Archive / Subscribe][mpv-users]).
- **Devel Mailing List**: `mpv-devel@googlegroups.com` ([Archive / Subscribe][mpv-devel])
This software is based on the MPlayer project. Before mpv existed as a project,
the code base was briefly developed under the mplayer2 project. For details,
see the [FAQ][FAQ].
To contact the `mpv` team in private write to `mpv-team@googlegroups.com`.
## Contact
Most activity happens on the IRC channel and the github issue tracker.
- **GitHub issue tracker**: [issue tracker][issue-tracker] (report bugs here)
- **User IRC Channel**: `#mpv` on `irc.freenode.net`
- **Developer IRC Channel**: `#mpv-devel` on `irc.freenode.net`
[FAQ]: https://github.com/mpv-player/mpv/wiki/FAQ
[releases]: https://github.com/mpv-player/mpv/releases
[changes]: https://github.com/mpv-player/mpv/blob/master/DOCS/man/en/changes.rst
[mpv-build]: https://github.com/mpv-player/mpv-build
[homebrew-mpv]: https://github.com/mpv-player/homebrew-mpv
[issue-tracker]: https://github.com/mpv-player/mpv/issues
[release-policy]: https://github.com/mpv-player/mpv/blob/master/DOCS/release-policy.md
[windows_compilation]: https://github.com/mpv-player/mpv/blob/master/DOCS/compile-windows.md
[interface-changes]: https://github.com/mpv-player/mpv/blob/master/DOCS/interface-changes.rst
[api-changes]: https://github.com/mpv-player/mpv/blob/master/DOCS/client-api-changes.rst
[restore-old-bindings]: https://github.com/mpv-player/mpv/blob/master/etc/restore-old-bindings.conf
[contribute.md]: https://github.com/mpv-player/mpv/blob/master/DOCS/contribute.md
[mpv-users]: https://groups.google.com/forum/?hl=en#!forum/mpv-users
[mpv-devel]: https://groups.google.com/forum/?hl=en#!forum/mpv-devel
[ffmpeg_vs_libav]: https://github.com/mpv-player/mpv/wiki/FFmpeg-versus-Libav
-158
View File
@@ -1,158 +0,0 @@
Release 0.33.0
==============
This release requires FFmpeg 4.0 or newer.
For packagers: Note that mpv's build system is only supported on Python 3.
If you use the `bootstrap.py` script it will take care of this, otherwise you
need to explicitly invoke the build system using `python3 waf`.
Features
--------
Added
~~~~~
- scripting: load scripts from directories
- mac: activate logging when started from the bundle
- ytdl_hook.lua: delay load subtitles
- sub: add an option to filter subtitles by regex
- scripting: add a way to run subprocesses as "scripts"
- command: implement asynchronous commands and support for named arguments
- player: add optional separate video decoding thread
- vo_gpu: d3d11: add support for exclusive fullscreen
- w32_common: Support HiDPI on Windows
- vo_x11: add 10 bit support
- vo_gpu: add BT.2390 tone-mapping
- client API: add software rendering API
- audio: add scaletempo2 filter based on chromium
- auto_profiles: add this script
- stream: Implement slice:// for reading slices of streams
- player: add automatic loading of external cover art files
- vo_sixel: implement terminal video output using sixel
Changed
~~~~~~~
- sws_utils: use zimg by default if available
- build: pick up Lua 5.2 by default (preferred over 5.1)
- build: disable RPI vendor blob auto-detection in favor of open-source stack
- build: make C11 atomics mandatory
- build: make libass non-optional
- player: stricter filename matching for external subtitle auto-loading
- lua: support Unicode paths in script loading and IO library
- vo_direct3d: rip out texture video rendering path and dumb down OSD rendering
- audio: rewrite internal audio handling and AO API
- build: disable GLX by default
Removed
~~~~~~~
- stream_libarchive: disable tar support due to bugs
- Remove remains of Libav compatibility
- stream_smb: remove due to lack of thread safety and the abundance
of alternatives, FFmpeg still includes SMB support
- command: remove legacy hook API (has been deprecated for a long time)
- client API: remove deprecated qthelper.hpp header
- removed audio outputs: sndio, rsound, oss
- x11: remove xdg-screensaver invocations that supported dbus based idle inhibit
- client API: deactivate the opengl_cb API
- build system: drop Python 2 compatbility
Options and Commands
--------------------
Added
~~~~~
- demux: add option to disable cache "sharing" between back and forward buffers
- player: add ab-loop-count option/property
- ytdl_hook: add a way to use ytdl's default formats
- ytdl_hook: add all_formats option that loads all formats that were found
- demux_mkv: document probe-start-time option and enable it by default
- command: extend osd-overlay command with bounds reporting
- player: a number of new playlist contol commands/properties
- ipc: add --input-ipc-client option
- options: add option to control display-sync factor
- vo_gpu: add better gamut clipping option
- vo_gpu: vulkan: add ability to disable events
- x11: add option to make window appear on a specific workspace
- wayland: expose wayland-app-id as a user option
- player: add --subs-with-matching-audio option
- command: add read-only focused property
- screenshot: option to use software rendering for screenshots
- command: add delete-watch-later-config
- command: new property mouse-pos with current position and hover state
Changed
~~~~~~~
- options: remove deprecation warning for "-foo bar" syntax
- player: make audio hr-seek default
- ad_lavc: disable decoder downmix by default
- command: support save-position-on-quit for "stop" command too
- command: extend subprocess command
- options: do not accept ":" as separator anymore in key/value lists
Deprecated
~~~~~~~~~~
- demux: deprecate --cache-secs
Removed
~~~~~~~
- wayland: remove wayland-frame-wait-offset option
- input: remove deprecated --input-file option
- vo_vdpau: remove deprecated/inactive --vo-vdpau-deint option
Fixes and Minor Enhancements
----------------------------
- options: stop hiding deprecated options from --help output
- lua, js: add mp.get_script_directory() function
- lua: fix security relevant loading order issue with scripts
- player: make screenshot each-frame mode more accurate
- bash completion: complete ao/af/vo/vf options
- zimg: add alpha support
- wayland: make resizing better
- edl: add mechanism for delay loading streams
- stream_file: fix caching-related performance regression on CIFS
- cocoa-cb: fix crashes and issues with UI updates
- sub, demux: improve behavior with negative subtitle delay/muxed subs
- demux: make seek ranges work for static images + audio
- cocoa-cb: support maximize/minimize on startup
- umpv: change from legacy FIFO to socket
- stats: move input speed to cache page, make it a graph
- stats: add fourth page with performance graphs
- command: print edition title to OSD when cycling
- zimg: add support for big endian input and output
- demux_mkv: add png intra support
- build: detect VT_GETMODE on FreeBSD and DragonFly
- win32: use windows 10 native virtual-terminal if available
- vo_gpu: enable frame caching for still frames
- command: add property to return text subtitles in ASS
- vo_gpu: ra_pl: add timers support
- build: allow vo_wlshm on more Wayland platforms (e.g. FreeBSD)
- zimg: add slice threading and use it by default
- command: add a way to access properties of a current track
- vo_gpu: EGL: fix transparency on X11/EGL/Mesa
- vd_lavc: add AV1 to the default allowed hwdec codec list
This listing is not complete. Check DOCS/client-api-changes.rst for a history
of changes to the client API, and DOCS/interface-changes.rst for a history
of changes to other user-visible interfaces.
A complete changelog can be seen by running `git log v0.32.0..v0.33.0`
in the git repository or by visiting either
https://github.com/mpv-player/mpv/compare/v0.32.0...v0.33.0 or
https://git.srsfckn.biz/mpv/log/?qt=range&q=v0.32.0..v0.33.0
View File
Whitespace-only changes.
-24
View File
@@ -1,24 +0,0 @@
#!/usr/bin/bash
set -e
export DEST_OS=win32
export CC=gcc
export PKG_CONFIG=/usr/bin/pkg-config
export PERL=/usr/bin/perl
export PYTHON=/usr/bin/python3
"$PYTHON" bootstrap.py
"$PYTHON" waf configure \
--check-c-compiler=gcc \
--enable-spirv-cross \
--enable-d3d-hwaccel \
--enable-d3d11 \
--enable-jpeg \
--enable-lcms2 \
--enable-libarchive \
--enable-lua \
--enable-rubberband \
--enable-shaderc \
--enable-uchardet \
--enable-vulkan
"$PYTHON" waf build
-72
View File
@@ -1,72 +0,0 @@
#!/usr/bin/bash
set -e
export PYTHON=/usr/bin/python3
# Write an empty fonts.conf to speed up fc-cache
export FONTCONFIG_FILE=/dummy-fonts.conf
cat >"$FONTCONFIG_FILE" <<EOF
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig></fontconfig>
EOF
# Install build dependencies for mpv
pacman -S --noconfirm --needed \
$MINGW_PACKAGE_PREFIX-toolchain \
$MINGW_PACKAGE_PREFIX-cmake \
$MINGW_PACKAGE_PREFIX-lcms2 \
$MINGW_PACKAGE_PREFIX-libarchive \
$MINGW_PACKAGE_PREFIX-libass \
$MINGW_PACKAGE_PREFIX-libjpeg-turbo \
$MINGW_PACKAGE_PREFIX-libplacebo \
$MINGW_PACKAGE_PREFIX-lua51 \
$MINGW_PACKAGE_PREFIX-ninja \
$MINGW_PACKAGE_PREFIX-rubberband \
$MINGW_PACKAGE_PREFIX-uchardet \
$MINGW_PACKAGE_PREFIX-vulkan
# Delete unused packages to reduce space used in the Appveyor cache
pacman -Sc --noconfirm
# Compile ffmpeg
(
git clone --depth=1 https://github.com/FFmpeg/ffmpeg.git && cd ffmpeg
mkdir build && cd build
../configure \
--prefix=$MINGW_PREFIX \
--target-os=mingw32 \
--arch=$MSYSTEM_CARCH \
--disable-static \
--disable-doc \
--disable-asm \
--enable-gpl \
--enable-version3 \
--enable-shared \
--enable-pic \
--enable-d3d11va \
--enable-dxva2 \
--enable-schannel
make -j4 install
)
# Compile shaderc
(
git clone --depth=1 https://github.com/google/shaderc && cd shaderc
"$PYTHON" utils/git-sync-deps
mkdir build && cd build
cmake -GNinja -DCMAKE_BUILD_TYPE=Release -DSHADERC_SKIP_TESTS=ON \
-DCMAKE_INSTALL_PREFIX=$MINGW_PREFIX ..
ninja install
)
# Compile SPIRV-Cross
(
git clone --depth=1 https://github.com/KhronosGroup/SPIRV-Cross && cd SPIRV-Cross
mkdir build && cd build
cmake -GNinja -DSPIRV_CROSS_SHARED=ON -DCMAKE_INSTALL_PREFIX=$MINGW_PREFIX ..
ninja install
)
-130
View File
@@ -1,130 +0,0 @@
#!/usr/bin/env python
import re
import os
import sys
import shutil
import subprocess
from functools import partial
sys_re = re.compile("^/System")
usr_re = re.compile("^/usr/lib/")
exe_re = re.compile("@executable_path")
def is_user_lib(objfile, libname):
return not sys_re.match(libname) and \
not usr_re.match(libname) and \
not exe_re.match(libname) and \
not "libobjc." in libname and \
not "libSystem." in libname and \
not "libc." in libname and \
not "libgcc." in libname and \
not os.path.basename(libname) == 'Python' and \
not os.path.basename(objfile) in libname and \
not "libswift" in libname
def otool(objfile):
command = "otool -L '%s' | grep -e '\t' | awk '{ print $1 }'" % objfile
output = subprocess.check_output(command, shell = True, universal_newlines=True)
return set(filter(partial(is_user_lib, objfile), output.split()))
def get_rpaths_dev_tools(binary):
command = "otool -l '%s' | grep -A2 LC_RPATH | grep path | grep \"Xcode\|CommandLineTools\"" % binary
result = subprocess.check_output(command, shell = True, universal_newlines=True)
pathRe = re.compile("^\s*path (.*) \(offset \d*\)$")
output = []
for line in result.splitlines():
output.append(pathRe.search(line).group(1).strip())
return output
def install_name_tool_change(old, new, objfile):
subprocess.call(["install_name_tool", "-change", old, new, objfile])
def install_name_tool_id(name, objfile):
subprocess.call(["install_name_tool", "-id", name, objfile])
def install_name_tool_add_rpath(rpath, binary):
subprocess.call(["install_name_tool", "-add_rpath", rpath, binary])
def install_name_tool_delete_rpath(rpath, binary):
subprocess.call(["install_name_tool", "-delete_rpath", rpath, binary])
def libraries(objfile, result = dict()):
libs_list = otool(objfile)
result[objfile] = libs_list
for lib in libs_list:
if lib not in result:
libraries(lib, result)
return result
def lib_path(binary):
return os.path.join(os.path.dirname(binary), 'lib')
def lib_name(lib):
return os.path.join("@executable_path", "lib", os.path.basename(lib))
def process_libraries(libs_dict, binary):
libs_set = set(libs_dict)
# Remove binary from libs_set to prevent a duplicate of the binary being
# added to the libs directory.
libs_set.remove(binary)
for src in libs_set:
name = lib_name(src)
dst = os.path.join(lib_path(binary), os.path.basename(src))
shutil.copy(src, dst)
os.chmod(dst, 0o755)
install_name_tool_id(name, dst)
if src in libs_dict[binary]:
install_name_tool_change(src, name, binary)
for p in libs_set:
if p in libs_dict[src]:
install_name_tool_change(p, lib_name(p), dst)
def process_swift_libraries(binary):
command = ['xcrun', '--find', 'swift-stdlib-tool']
swiftStdlibTool = subprocess.check_output(command, universal_newlines=True).strip()
# from xcode11 on the dynamic swift libs reside in a separate directory from
# the std one, might need versioned paths for future swift versions
swiftLibPath = os.path.join(swiftStdlibTool, '../../lib/swift-5.0/macosx')
swiftLibPath = os.path.abspath(swiftLibPath)
command = [swiftStdlibTool, '--copy', '--platform', 'macosx', '--scan-executable', binary, '--destination', lib_path(binary)]
if os.path.exists(swiftLibPath):
command.extend(['--source-libraries', swiftLibPath])
subprocess.check_output(command, universal_newlines=True)
print(">> setting additional rpath for swift libraries")
install_name_tool_add_rpath("@executable_path/lib", binary)
def remove_dev_tools_rapths(binary):
for path in get_rpaths_dev_tools(binary):
install_name_tool_delete_rpath(path, binary)
def main():
binary = os.path.abspath(sys.argv[1])
if not os.path.exists(lib_path(binary)):
os.makedirs(lib_path(binary))
print(">> gathering all linked libraries")
libs = libraries(binary)
print(">> copying and processing all linked libraries")
process_libraries(libs, binary)
print(">> removing rpath definitions towards dev tools")
remove_dev_tools_rapths(binary)
print(">> copying and processing swift libraries")
process_swift_libraries(binary)
if __name__ == "__main__":
main()
+24
View File
@@ -0,0 +1,24 @@
#! /usr/bin/env perl
use strict;
use warnings;
# Convert the contents of a file into a C string constant.
# Note that the compiler will implicitly add an extra 0 byte at the end
# of every string, so code using the string may need to remove that to get
# the exact contents of the original file.
# FIXME: why not a char array?
# treat only alphanumeric and not-" punctuation as safe
my $unsafe_chars = qr{[^][A-Za-z0-9!#%&'()*+,./:;<=>?^_{|}~ -]};
for my $file (@ARGV) {
open my $fh, '<:raw', $file or next;
print "/* Generated from $file */\n";
while (<$fh>) {
# replace unsafe chars with their equivalent octal escapes
s/($unsafe_chars)/\\@{[sprintf '%03o', ord($1)]}/gos;
print "\"$_\"\n"
}
close $fh;
}
-43
View File
@@ -1,43 +0,0 @@
#!/usr/bin/env python3
# Convert the contents of a file into a C string constant.
# Note that the compiler will implicitly add an extra 0 byte at the end
# of every string, so code using the string may need to remove that to get
# the exact contents of the original file.
#
# This file is part of mpv.
#
# mpv is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# mpv is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with mpv. If not, see <http://www.gnu.org/licenses/>.
#
import sys
def file2string(infilename, infile, outfile):
outfile.write("// Generated from %s\n\n" % infilename)
conv = ["\\%03o" % c for c in range(256)]
safe_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" \
"0123456789!#%&'()*+,-./:;<=>[]^_{|}~ "
for c in safe_chars:
conv[ord(c)] = c
for c, esc in ("\nn", "\tt", r"\\", '""'):
conv[ord(c)] = '\\' + esc
for line in infile:
outfile.write('"' + ''.join(conv[c] for c in line) + '"\n')
if __name__ == "__main__":
with open(sys.argv[1], 'rb') as infile:
file2string(sys.argv[1], infile, sys.stdout)
-9
View File
@@ -1,9 +0,0 @@
#!/bin/sh
# This script is expected to be called as TOOLS/gen-osd-font.sh (it will access
# TOOLS/mpv-osd-symbols.sfdir), and it will write sub/osd_font.otf.
# Needs fontforge with python scripting
fontforge -lang=py -c 'f=open(argv[1]); f.generate(argv[2])' \
TOOLS/mpv-osd-symbols.sfdir sub/osd_font.otf
+15
View File
@@ -0,0 +1,15 @@
#!/bin/sh
# This script is expected to be called as TOOLS/gen-x11-icon.sh (it will access
# etc/mpv-icon...), and it will write video/out/x11_icon.bin.
conv() {
echo
identify -format "icon: %w %h" $1
convert $1 -depth 8 rgba:-
}
(echo "# File generated by gen-x11-icon.sh" ;
conv etc/mpv-icon-8bit-16x16.png ;
conv etc/mpv-icon-8bit-32x32.png ;
conv etc/mpv-icon-8bit-64x64.png) | gzip -c > video/out/x11_icon.bin
-158
View File
@@ -1,158 +0,0 @@
#!/bin/sh
: "${MPV:=mpv}"
: "${ILDETECT_MPV:=$MPV}"
: "${ILDETECT_MPVFLAGS:=--start=35% --length=35}"
: "${ILDETECT_DRY_RUN:=}"
: "${ILDETECT_QUIET:=}"
: "${ILDETECT_RUN_INTERLACED_ONLY:=}"
: "${ILDETECT_FORCE_RUN:=}"
# This script uses ffmpeg's "idet" filter for interlace detection. In the
# long run this should replace ildetect.sh+ildetect.so.
# exit status:
# 0 progressive
# 1 telecine
# 2 interlaced
# 8 unknown
# 16 detect fail
# 17+ mpv's status | 16
testfun()
{
$ILDETECT_MPV "$@" \
--vf-add=lavfi="[idet]" --msg-level ffmpeg=v \
--o= --vo=null --no-audio --untimed \
$ILDETECT_MPVFLAGS \
| { if [ -n "$ILDETECT_QUIET" ]; then cat; else tee /dev/stderr; fi } \
| grep "Parsed_idet_0: Multi frame detection: "
}
judge()
{
tff=0
bff=0
progressive=0
undetermined=0
while read -r _ _ _ _ _ _ tff1 _ bff1 _ progressive1 _ undetermined1 _; do
case "$tff1$bff1$progressive1$undetermined1" in
*[!0-9]*)
printf >&2 'ERROR: Unrecognized idet output: %s\n' "$out"
exit 16
;;
esac
tff=$((tff + tff1))
bff=$((bff + bff1))
progressive=$((progressive + progressive1))
undetermined=$((undetermined + undetermined1))
done <<EOF
$(testfun "$@" | sed 's/:/: /g')
EOF
interlaced=$((bff + tff))
determined=$((interlaced + progressive))
if [ "$undetermined" -gt "$determined" ] || [ "$determined" -lt 250 ]; then
echo >&2 "ERROR: Less than 50% or 250 frames are determined."
[ -n "$ILDETECT_FORCE_RUN" ] || exit 8
echo >&2 "Assuming interlacing."
if [ "$tff" -gt $((bff * 10)) ]; then
verdict="interlaced-tff"
elif [ "$bff" -gt $((tff * 10)) ]; then
verdict="interlaced-bff"
else
verdict="interlaced"
fi
elif [ $((interlaced * 20)) -gt "$progressive" ]; then
# At least 5% of the frames are interlaced!
if [ "$tff" -gt $((bff * 10)) ]; then
verdict="interlaced-tff"
elif [ "$bff" -gt $((tff * 10)) ]; then
verdict="interlaced-bff"
else
echo >&2 "ERROR: Content is interlaced, but can't determine field order."
[ -n "$ILDETECT_FORCE_RUN" ] || exit 8
echo >&2 "Assuming interlacing with default field order."
verdict="interlaced"
fi
else
# Likely progressive
verdict="progressive"
fi
printf '%s\n' "$verdict"
}
judge "$@" --vf-clr
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
[ -n "$ILDETECT_RUN_INTERLACED_ONLY" ] || \
$ILDETECT_MPV "$@"
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 0
;;
interlaced-tff)
judge "$@" --vf-clr --vf-pre=lavfi=\[setfield=tff\],pullup
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=lavfi=\[setfield=tff\],pullup
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 1
;;
*)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=lavfi=\[setfield=tff\],yadif
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 2
;;
esac
;;
interlaced-bff)
judge "$@" --vf-clr --vf-pre=lavfi=\[setfield=bff\],pullup
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=lavfi=\[setfield=bff\],pullup
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 1
;;
*)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=lavfi=\[setfield=bff\],yadif
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 2
;;
esac
;;
interlaced)
judge "$@" --vf-clr --vf-pre=pullup
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=pullup
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 1
;;
*)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=yadif
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 2
;;
esac
;;
*)
echo >&2 "ERROR: Internal error."
exit 16
;;
esac
+30
View File
@@ -0,0 +1,30 @@
use 5.008;
use strict;
use warnings;
# ABSTRACT: Module collection to parse Matroska files.
package Parse::Matroska;
=head1 DESCRIPTION
C<use>s L<Parse::Matroska::Reader>. See the documentation
of the modules mentioned in L</"SEE ALSO"> for more information
in how to use this module.
It's intended for this module to contain high-level interfaces
to the other modules in the distribution.
=head1 SOURCE CODE
L<https://github.com/Kovensky/Parse-Matroska>
=head1 SEE ALSO
L<Parse::Matroska::Reader>, L<Parse::Matroska::Element>,
L<Parse::Matroska::Definitions>.
=cut
use Parse::Matroska::Reader;
1;
+351
View File
@@ -0,0 +1,351 @@
use 5.008;
use strict;
use warnings;
# ABSTRACT: internal EBML grammar definitions
package Parse::Matroska::Definitions;
use Parse::Matroska::Utils qw{uniq uncamelize};
use Exporter;
our @ISA = qw{Exporter};
our @EXPORT_OK = qw{elem_by_hexid %EBML_DEFINITION %MATROSKA_DEFINITION};
=head1 SYNOPSIS
use Parse::Matroska::Definitions qw{elem_by_hexid};
my $ebml_id = elem_by_hexid('1a45dfa3');
print "EBML ID $ebml_id->{elid}'s name: $ebml_id->{name}";
=head1 DESCRIPTION
Contains the definition of the EBML grammar as expected in
Matroska files. This module is meant mostly for internal use.
As this was extended from a script in mpv-player, some data
generated is apparently useless for regular module users
but is still relevant to the mpv-player script. Such data
is annotated as being for mpv compatibility.
=head1 NOTE
The API of this module is not yet considered stable.
=head1 GLOBALS
These global variables are considered B<immutable>.
=head2 @Parse::Matroska::Definitions::global_elem_list
A global list of known matroska elements. Useful for
mpv's matroska script, used for generating C headers
that parse matroska.
=head2 %Parse::Matroska::Definitions::global_elem_dict
A global hash of known matroska elements. Used internally
by L</elem_by_hexid($id)>.
=cut
@Parse::Matroska::Definitions::global_elem_list = ();
%Parse::Matroska::Definitions::global_elem_dict = ();
=head2 %EBML_DEFINITION
Optionally-importable hash of known EBML IDs belonging
to the EBML generic grammar.
=head2 %MATROSKA_DEFINITION
Optionally-importable hash of known EBML IDs belonging
to the Matroska-specific grammar.
=cut
our %EBML_DEFINITION = define_ebml();
our %MATROSKA_DEFINITION = define_matroska();
=method elem_by_hexid($id)
Returns an EBML Element Definition corresponding to the provided
hexadecimal string. Returns C<undef> if the element is unknown.
=cut
sub elem_by_hexid {
my ($elid) = @_;
return $Parse::Matroska::Definitions::global_elem_dict{$elid};
}
################################################
### Helper functions for document definition ###
################################################
# used by elem when setting the 'valname' key
use constant TYPE_MAP => {
uint => 'uint64_t',
str => 'struct bstr',
binary => 'struct bstr',
ebml_id => 'uint32_t',
float => 'double',
sint => 'int64_t',
};
# this will be localized to "MATROSKA" or "EBML" on the elem declarations
our $ELEM_DEFINE_TYPE = undef;
=method elem($name,$elid,$valtype)
NOTE: never call this function yourself; it changes data structures
that are considered immutable outside of this package.
Internal API function that generates the EBML Element Definitions.
This API function returns an array which first element is C<$elid>
and the second is a generated hash. The generated hash is stored
in the @global_elem_list and %global_elem_dict.
The generated hash contains:
=for :list
= name
The EBML Element's name, given through C<$name>.
= elid
The EBML Element's hex id, given through C<$elid>. Used for lookups by L</elem_by_hexid($id)>.
= valtype
The EBML Element's type, given through C<$valtype>, except when C<$valtype> is an arrayref.
= multiple
If C<$name> ends with a C<*>, this is set as true and strips the C<*> from L</name>. Used to
mark elements that may be repeated.
= subelements
An arrayref of elements that may be children of this element, given through C<$valtype> if it
is an arrayref. Sets L</valtype> to C<sub> if there are subelements.
= subids
An arrayref listing all the L</elid>s of subelements, C<uniq>ified.
The following elements are for mpv compatibility:
=for :list
= definename
Name used for generating C #defines.
= fieldname
Name used for generating C struct fields.
= structname
Name used for generating C struct names.
= ebmltype
A pre-#defined constant to describe the element's type.
= valname
Typename used when declaring a struct field referring to this element.
=cut
sub elem {
my %e = (name => shift, elid => shift, valtype => shift);
# strip * from name, set 'multiple' if there was one
$e{multiple} = scalar $e{name} =~ s/\*$//;
# ELEM_DEFINE_TYPE is either MATROSKA or EBML
$e{definename} = "${ELEM_DEFINE_TYPE}_ID_".uc($e{name});
$e{fieldname} = uncamelize $e{name};
$e{structname} = "ebml_$e{fieldname}";
if (ref $e{valtype} eq 'HASH') {
$e{subelements} = $e{valtype};
$e{subids} = uniq map { $_->{elid} } values %{$e{subelements}};
$e{valtype} = 'sub';
$e{ebmltype} = 'EBML_TYPE_SUBELEMENTS';
$e{valname} = "struct $e{structname}";
} else {
$e{ebmltype} = "EBML_TYPE_\U$e{valtype}";
die "Unrecognized value type $e{valtype}" unless
defined ($e{valname} = TYPE_MAP->{$e{valtype}});
}
my $e = \%e;
push @Parse::Matroska::Definitions::global_elem_list, $e;
$Parse::Matroska::Definitions::global_elem_dict{$e{elid}} = $e;
return ($e{elid}, $e);
}
#############################################
### EBML and Matroska document definitons ###
#############################################
=method define_ebml
Internal function that defines the EBML generic grammar.
Must not be called from outside the package.
=cut
sub define_ebml {
local $ELEM_DEFINE_TYPE = 'EBML';
return (
elem('EBML', '1a45dfa3', {
elem('EBMLVersion', '4286', 'uint'),
elem('EBMLReadVersion', '42f7', 'uint'),
elem('EBMLMaxIDLength', '42f2', 'uint'),
elem('EBMLMaxSizeLength', '42f3', 'uint'),
elem('DocType', '4282', 'str'),
elem('DocTypeVersion', '4287', 'uint'),
elem('DocTypeReadVersion', '4285', 'uint'),
}),
elem('CRC32', 'bf', 'binary'),
elem('Void', 'ec', 'binary'),
);
}
=method define_matroska
Internal function that defines the Matroska-specific EBML grammar.
Must not be called from outside the package.
=cut
sub define_matroska {
local $ELEM_DEFINE_TYPE = 'MATROSKA';
return (
elem('Segment', '18538067', {
elem('SeekHead*', '114d9b74', {
elem('Seek*', '4dbb', {
elem('SeekID', '53ab', 'ebml_id'),
elem('SeekPosition', '53ac', 'uint'),
}),
}),
elem('Info*', '1549a966', {
elem('SegmentUID', '73a4', 'binary'),
elem('PrevUID', '3cb923', 'binary'),
elem('NextUID', '3eb923', 'binary'),
elem('TimecodeScale', '2ad7b1', 'uint'),
elem('DateUTC', '4461', 'sint'),
elem('Title', '7ba9', 'str'),
elem('MuxingApp', '4d80', 'str'),
elem('WritingApp', '5741', 'str'),
elem('Duration', '4489', 'float'),
}),
elem('Cluster*', '1f43b675', {
elem('Timecode', 'e7', 'uint'),
elem('BlockGroup*', 'a0', {
elem('Block', 'a1', 'binary'),
elem('BlockDuration', '9b', 'uint'),
elem('ReferenceBlock*', 'fb', 'sint'),
}),
elem('SimpleBlock*', 'a3', 'binary'),
}),
elem('Tracks*', '1654ae6b', {
elem('TrackEntry*', 'ae', {
elem('TrackNumber', 'd7', 'uint'),
elem('TrackUID', '73c5', 'uint'),
elem('TrackType', '83', 'uint'),
elem('FlagEnabled', 'b9', 'uint'),
elem('FlagDefault', '88', 'uint'),
elem('FlagForced', '55aa', 'uint'),
elem('FlagLacing', '9c', 'uint'),
elem('MinCache', '6de7', 'uint'),
elem('MaxCache', '6df8', 'uint'),
elem('DefaultDuration', '23e383', 'uint'),
elem('TrackTimecodeScale', '23314f', 'float'),
elem('MaxBlockAdditionID', '55ee', 'uint'),
elem('Name', '536e', 'str'),
elem('Language', '22b59c', 'str'),
elem('CodecID', '86', 'str'),
elem('CodecPrivate', '63a2', 'binary'),
elem('CodecName', '258688', 'str'),
elem('CodecDecodeAll', 'aa', 'uint'),
elem('Video', 'e0', {
elem('FlagInterlaced', '9a', 'uint'),
elem('PixelWidth', 'b0', 'uint'),
elem('PixelHeight', 'ba', 'uint'),
elem('DisplayWidth', '54b0', 'uint'),
elem('DisplayHeight', '54ba', 'uint'),
elem('DisplayUnit', '54b2', 'uint'),
elem('FrameRate', '2383e3', 'float'),
elem('ColourSpace', '2eb524', 'binary'),
}),
elem('Audio', 'e1', {
elem('SamplingFrequency', 'b5', 'float'),
elem('OutputSamplingFrequency', '78b5', 'float'),
elem('Channels', '9f', 'uint'),
elem('BitDepth', '6264', 'uint'),
}),
elem('ContentEncodings', '6d80', {
elem('ContentEncoding*', '6240', {
elem('ContentEncodingOrder', '5031', 'uint'),
elem('ContentEncodingScope', '5032', 'uint'),
elem('ContentEncodingType', '5033', 'uint'),
elem('ContentCompression', '5034', {
elem('ContentCompAlgo', '4254', 'uint'),
elem('ContentCompSettings', '4255', 'binary'),
}),
}),
}),
}),
}),
elem('Cues', '1c53bb6b', {
elem('CuePoint*', 'bb', {
elem('CueTime', 'b3', 'uint'),
elem('CueTrackPositions*', 'b7', {
elem('CueTrack', 'f7', 'uint'),
elem('CueClusterPosition', 'f1', 'uint'),
}),
}),
}),
elem('Attachments', '1941a469', {
elem('AttachedFile*', '61a7', {
elem('FileDescription', '467e', 'str'),
elem('FileName', '466e', 'str'),
elem('FileMimeType', '4660', 'str'),
elem('FileData', '465c', 'binary'),
elem('FileUID', '46ae', 'uint'),
}),
}),
elem('Chapters', '1043a770', {
elem('EditionEntry*', '45b9', {
elem('EditionUID', '45bc', 'uint'),
elem('EditionFlagHidden', '45bd', 'uint'),
elem('EditionFlagDefault', '45db', 'uint'),
elem('EditionFlagOrdered', '45dd', 'uint'),
elem('ChapterAtom*', 'b6', {
elem('ChapterUID', '73c4', 'uint'),
elem('ChapterTimeStart', '91', 'uint'),
elem('ChapterTimeEnd', '92', 'uint'),
elem('ChapterFlagHidden', '98', 'uint'),
elem('ChapterFlagEnabled', '4598', 'uint'),
elem('ChapterSegmentUID', '6e67', 'binary'),
elem('ChapterSegmentEditionUID', '6ebc', 'uint'),
elem('ChapterDisplay*', '80', {
elem('ChapString', '85', 'str'),
elem('ChapLanguage*', '437c', 'str'),
elem('ChapCountry*', '437e', 'str'),
}),
}),
}),
}),
elem('Tags*', '1254c367', {
elem('Tag*', '7373', {
elem('Targets', '63c0', {
elem('TargetTypeValue', '68ca', 'uint'),
elem('TargetTrackUID', '63c5', 'uint'),
elem('TargetEditionUID', '63c9', 'uint'),
elem('TargetChapterUID', '63c4', 'uint'),
elem('TargetAttachmentUID', '63c6', 'uint'),
}),
elem('SimpleTag*', '67c8', {
elem('TagName', '45a3', 'str'),
elem('TagLanguage', '447a', 'str'),
elem('TagString', '4487', 'str'),
}),
}),
}),
}),
);
}
1;
+331
View File
@@ -0,0 +1,331 @@
use 5.008;
use strict;
use warnings;
# ABSTRACT: a mid-level representation of an EBML element
package Parse::Matroska::Element;
use Carp;
use List::Util qw{first};
=head1 SYNOPSIS
use Parse::Matroska::Reader;
my $reader = Parse::Matroska::Reader->new($path);
my $elem = $reader->read_element;
print "ID: $elem->{elid}\n";
print "Name: $elem->{name}\n";
print "Length: $elem->{content_len}\n";
print "Type: $elem->{type}\n";
print "Child count: ", scalar(@{$elem->all_children}), "\n";
if ($elem->{type} eq 'sub') {
while (my $chld = $elem->next_child) {
print "Child Name: $chld->{name}\n";
}
} else {
print "Value: ", $elem->get_value, "\n";
}
=head1 DESCRIPTION
Represents a single Matroska element as decoded by
L<Parse::Matroska::Reader>. This is essentially a hash
augmented with functions for delay-loading of binary
values and children elements.
=head1 NOTE
The API of this module is not yet considered stable.
=attr elid
The EBML Element ID, suitable for passing to
L<Parse::Matroska::Definitions/elem_by_hexid>.
=attr name
The EBML Element's name.
=attr type
The EBML Element's type. Can be C<uint>, C<sint>,
C<float>, C<ebml_id>, C<str> or C<binary>. See L</value>
for details.
Equivalent to
C<elem_by_hexid($elem-E<gt>{value})-E<gt>{valtype}>.
=attr value
The EBML Element's value. Should be obtained through
L</get_value>.
Is an unicode string if the L</type> is C<str>, that is,
the string has already been decoded by L<Encode/decode>.
Is C<undef> if the L</type> is C<binary> and the contents
were delay-loaded and not yet read. L</get_value> will
do the delayed load if needed.
Is an arrayref if the L</type> is C<sub>, containing
the children nodes that were already loaded.
Is a hashref if the L</type> is C<ebml_id>, containing
the referred element's information as defined in
L<Parse::Matroska::Definitions>. Calling
C<elem_by_hexid($elem-E<gt>{value}-E<gt>{elid})> will
return the same object as $elem->{value}.
=attr full_len
The entire length of this EBML Element, including
the header's.
=attr size_len
The length of the size marker. Used when calculating
L</full_len> from L</content_len>
=attr content_len
The length of the contents of this EBML Element,
which excludes the header.
=attr reader
A weakened reference to the associated
L<Parse::Matroska::Reader>.
=method new(%hash)
Creates a new Element initialized with the hash
given as argument.
=cut
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->initialize(@_);
return $self;
}
=method initialize(%hash)
Called by L</new> on initialization.
=cut
sub initialize {
my ($self, %args) = @_;
for (keys %args) {
$self->{$_} = $args{$_};
}
$self->{depth} = 0 unless $self->{depth};
}
=method skip
Called by the user to ignore the contents of this EBML node.
Needed when ignoring the children of a node.
=cut
sub skip {
my ($self) = @_;
my $reader = $self->{reader};
return unless $reader; # we don't have to skip if there's no reader
my $pos = $reader->getpos;
croak "Too late to skip, reads were already done"
if $pos ne $self->{data_pos};
$reader->skip($self->{content_len});
}
=method get_value($keep_bin)
Returns the value contained by this EBML element.
If the element has children, returns an arrayref to
the children elements that were already encountered.
If the element's type is C<binary> and the value was
delay-loaded, does the reading now.
If $keep_bin is true, the delay-loaded data is kept
as the L</value>, otherwise, further calls to
C<get_value> will reread the data from the L</reader>.
=cut
sub get_value {
my ($self, $keep_bin) = @_;
return undef if $self->{type} eq 'skip';
return $self->{value} if $self->{value};
my $reader = $self->{reader} or
croak "The associated Reader has been deleted";
# delay-loaded 'binary'
if ($self->{type} eq 'binary') {
croak "Cannot seek in the current Reader" unless $self->{data_pos};
# seek to the data position...
$reader->setpos($self->{data_pos});
# read the data, keeping it in value if requested
if ($keep_bin) {
$self->{value} = $reader->readlen($self->{content_len});
return $self->{value};
} else {
return $reader->readlen($self->{content_len});
}
}
}
=method next_child($read_bin)
Builtin iterator; reads and returns the next child element.
Always returns undef if the type isn't C<sub>.
Returns undef at the end of the iterator and resets itself to
point to the first element; so calling L</next_child($read_bin)>
after the iterator returned C<undef> will return the first child.
The optional C<$read_bin> parameter has the children elements
not delay-load their value if their type is C<binary>.
If all children elements have already been read, return
each element in-order as would be given by
L</all_children($recurse,$read_bin)>.
=cut
sub next_child {
my ($self, $read_bin) = @_;
return unless $self->{type} eq 'sub';
if ($self->{_all_children_read}) {
my $idx = $self->{_last_child} ||= 0;
if ($idx == @{$self->{value}}) {
# reset the iterator, returning undef once
$self->{_last_child} = 0;
return;
}
my $ret = $self->{value}->[$idx];
++$idx;
$self->{_last_child} = $idx;
return $ret;
}
my $len = defined $self->{remaining_len}
? $self->{remaining_len}
: $self->{content_len};
if ($len == 0) {
# we've read all children; switch into $self->{value} iteration mode
$self->{_all_children_read} = 1;
# return undef since the iterator will reset
return;
}
$self->{pos_offset} ||= 0;
my $pos = $self->{data_pos};
my $reader = $self->{reader} or croak "The associated reader has been deleted";
$reader->setpos($pos);
$reader->{fh}->seek($self->{pos_offset}, 1) if $pos;
my $chld = $reader->read_element($read_bin);
return undef unless defined $chld;
$self->{pos_offset} += $chld->{full_len};
$self->{remaining_len} = $len - $chld->{full_len};
if ($self->{remaining_len} < 0) {
croak "Child elements consumed $self->{remaining_len} more bytes than parent $self->{name} contained";
}
$chld->{depth} = $self->{depth} + 1;
$self->{value} ||= [];
push @{$self->{value}}, $chld;
return $chld;
}
=method all_children($recurse,$read_bin)
Calls L</populate_children($recurse,$read_bin)> on self
and returns an arrayref with the children nodes.
Both C<$recurse> and C<$read_bin> are optional and default
to false.
=cut
sub all_children {
my ($self, $recurse, $read_bin) = @_;
$self->populate_children($recurse, $read_bin);
return $self->{value};
}
=method children_by_name($name)
Searches in the already read children elements for all
elements with the EBML name C<$name>. Returns an array
containing all found elements. On scalar context,
returns only the first element found.
Croaks if the element's C<type> isn't C<sub>.
=cut
sub children_by_name {
my ($self, $name) = @_;
return unless defined wantarray; # don't do work if work isn't wanted
croak "Element can't have children" unless $self->{type} eq 'sub';
my @found = grep { $_->{name} eq $name } @{$self->{value}};
return @found if wantarray; # list
return shift @found if defined wantarray; # scalar
}
=method populate_children($recurse,$read_bin)
Populates the internal array of children elements, that is,
requests that the associated L<Matroska::Parser::Reader> reads
all children elements. Returns itself.
Returns false if the element's C<type> isn't C<sub>.
If C<$recurse> is provided and is true, the method will call
itself in the children elements with the same parameters it
received; this will build a full EBML tree.
If C<$read_bin> is provided and is true, disables delay-loading
of the contents of C<binary>-type nodes, reading the contents
to memory.
If both C<$recurse> and C<$read_bin> are true, entire EBML trees
can be loaded without requiring seeks, thus behaving correctly
on unseekable streams. If C<$read_bin> is false, the entire EBML
tree is still loaded, but calling L</get_value> on C<binary>-type
nodes will produce an error on unseekable streams.
=cut
sub populate_children {
my ($self, $recurse, $read_bin) = @_;
return unless $self->{type} eq 'sub';
if (@{$self->{value}} && $recurse) {
# only recurse
foreach (@{$self->{value}}) {
$_->populate_children($recurse, $read_bin);
}
return $self;
}
while (my $chld = $self->next_child($read_bin)) {
$chld->populate_children($recurse, $read_bin) if $recurse;
}
return $self;
}
1;
+423
View File
@@ -0,0 +1,423 @@
use 5.008;
use strict;
use warnings;
# ABSTRACT: a low-level reader for EBML files
package Parse::Matroska::Reader;
use Parse::Matroska::Definitions qw{elem_by_hexid};
use Parse::Matroska::Element;
use Carp;
use Scalar::Util qw{openhandle weaken};
use IO::Handle;
use IO::File;
use List::Util qw{first};
use Encode;
use constant BIGINT_TRY => 'Pari,GMP,FastCalc';
use Math::BigInt try => BIGINT_TRY;
use Math::BigRat try => BIGINT_TRY;
=head1 SYNOPSIS
use Parse::Matroska::Reader;
my $reader = Parse::Matroska::Reader->new($path);
$reader->close;
$reader->open(\$string_with_matroska_data);
my $elem = $reader->read_element;
print "Element ID: $elem->{elid}\n";
print "Element name: $elem->{name}\n";
if ($elem->{type} ne 'sub') {
print "Element value: $elem->get_value\n";
} else {
while (my $child = $elem->next_child) {
print "Child element: $child->{name}\n";
}
}
$reader->close;
=head1 DESCRIPTION
Reads EBML data, which is used in Matroska files.
This is a low-level reader which is meant to be used as a backend
for higher level readers. TODO: write the high level readers :)
=head1 NOTE
The API of this module is not yet considered stable.
=method new
Creates a new reader.
Calls L</open($arg)> with its arguments if provided.
=cut
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->open(@_) if @_;
return $self;
}
=method open($arg)
Creates the internal filehandle. The argument can be:
=for :list
* An open filehandle or L<IO::Handle> object.
The filehandle is not C<dup()>ed, so calling L</close> in this
object will close the given filehandle as well.
* A scalar containing a path to a file.
* On perl v5.14 or newer, a scalarref pointing to EBML data.
For similar functionality in older perls, give an L<IO::String> object
or the handle to an already C<open>ed scalarref.
=cut
sub open {
my ($self, $arg) = @_;
$self->{fh} = openhandle($arg) || IO::File->new($arg, "<:raw")
or croak "Can't open $arg: $!";
}
=method close
Closes the internal filehandle.
=cut
sub close {
my ($self) = @_;
$self->{fh}->close;
delete $self->{fh};
}
# equivalent to $self->readlen(1), possibly faster
sub _getc {
my ($self) = @_;
my $c = $self->{fh}->getc;
croak "Can't do read of length 1: $!" if !defined $c && $!;
return $c;
}
=method readlen($length)
Reads C<$length> bytes from the internal filehandle.
=cut
sub readlen {
my ($self, $len) = @_;
my $data;
my $readlen = $self->{fh}->read($data, $len);
croak "Can't do read of length $len: $!"
unless defined $readlen;
return $data;
}
# converts a byte string into an integer
# we do so by converting the integer into a hex string (big-endian)
# and then reading the hex-string into an integer
sub _bin2int($) {
my ($bin) = @_;
# if the length is larger than 3
# the resulting integer might be larger than INT_MAX
if (length($bin) > 3) {
return Math::BigInt->from_hex(unpack("H*", $bin));
}
return hex(unpack("H*", $bin));
}
# creates a floating-point number with the given mantissa and exponent
sub _ldexp {
my ($mantissa, $exponent) = @_;
return $mantissa * Math::BigRat->new(2)**$exponent;
}
# NOTE: the read_* functions are hard to read because they're ports
# of even harder to read python functions.
# TODO: make them readable
=method read_id
Reads an EBML ID atom in hexadecimal string format, suitable
for passing to L<Parse::Matroska::Definitions/elem_by_hexid($id)>.
=cut
sub read_id {
my ($self) = @_;
my $t = $self->_getc;
return undef unless defined $t;
my $i = 0;
my $mask = 1<<7;
if (ord($t) == 0) {
croak "Matroska Syntax error: first byte of ID was \\0"
}
until (ord($t) & $mask) {
++$i;
$mask >>= 1;
}
# return hex string of the bytes we just read
return unpack "H*", ($t . $self->readlen($i));
}
=method read_size
Reads an EBML Data Size atom, which immediately follows
an EBML ID atom.
This returns an array consisting of:
=for :list
0. The length of the Data Size atom.
1. The value encoded in the Data Size atom, which is the length of all the data following it.
=cut
sub read_size {
my ($self) = @_;
my $t = $self->_getc;
my $i = 0;
my $mask = 1<<7;
if (ord($t) == 0) {
croak "Matroska Syntax error: first byte of data size was \\0"
}
until (ord($t) & $mask) {
++$i;
$mask >>= 1;
}
$t = $t & chr($mask-1); # strip length bits (keep only significant bits)
return ($i+1, _bin2int $t . $self->readlen($i));
}
=method read_str($length)
Reads a string of length C<$length> bytes from the internal filehandle.
The string is already L<Encode/decode>d from C<UTF-8>, which is the
standard Matroska string encoding.
=cut
{
my $utf8 = find_encoding("UTF-8");
sub read_str {
my ($self, $length) = @_;
return $utf8->decode($self->readlen($length));
}
}
=method read_uint($length)
Reads an unsigned integer of length C<$length> bytes
from the internal filehandle.
Returns a L<Math::BigInt> object if C<$length> is greater
than 4.
=cut
sub read_uint {
my ($self, $length) = @_;
return _bin2int $self->readlen($length);
}
=method read_sint($length)
Reads a signed integer of length C<$length> bytes
from the internal filehandle.
Returns a L<Math::BigInt> object if C<$length> is greater
than 4.
=cut
sub read_sint {
my ($self, $length) = @_;
my $i = $self->read_uint($length);
# Apply 2's complement to the unsigned int
my $mask = int(2 ** ($length * 8 - 1));
# if the most significant bit is set...
if ($i & $mask) {
# subtract the MSB twice
$i -= 2 * $mask;
}
return $i;
}
=method read_float($length)
Reads an IEEE floating point number of length C<$length>
bytes from the internal filehandle.
Only lengths C<4> and C<8> are supported (C C<float> and C<double>).
=cut
sub read_float {
my ($self, $length) = @_;
my $i = $self->read_uint($length);
my $f;
use bigrat try => BIGINT_TRY;
# These evil expressions reinterpret an unsigned int as IEEE binary floats
if ($length == 4) {
$f = _ldexp(($i & (1<<23 - 1)) + (1<<23), ($i>>23 & (1<<8 - 1)) - 150);
$f = -$f if $i & (1<<31);
} elsif ($length == 8) {
$f = _ldexp(($i & (1<<52 - 1)) + (1<<52), ($i>>52 & (1<<12 - 1)) - 1075);
$f = -$f if $i & (1<<63);
} else {
croak "Matroska Syntax error: unsupported IEEE float byte size $length";
}
return $f;
}
=method read_ebml_id($length)
Reads an EBML ID when it's encoded as the data inside another
EBML element, that is, when the enclosing element's C<type> is
C<ebml_id>.
This returns a hashref with the EBML element description as
defined in L<Parse::Matroska::Definitions>.
=cut
sub read_ebml_id {
my ($self, $length) = @_;
return elem_by_hexid(unpack("H*", $self->readlen($length)));
}
=method skip($length)
Skips C<$length> bytes in the internal filehandle.
=cut
sub skip {
my ($self, $len) = @_;
return if $self->{fh}->can('seek') && $self->{fh}->seek($len, 1);
$self->readlen($len);
return;
}
=method getpos
Wrapper for L<IO::Seekable/$io-E<gt>getpos> in the internal filehandle.
Returns undef if the internal filehandle can't C<getpos>.
=cut
sub getpos {
my ($self) = @_;
return undef unless $self->{fh}->can('getpos');
return $self->{fh}->getpos;
}
=method setpos($pos)
Wrapper for L<IO::Seekable/$io-E<gt>setpos> in the internal filehandle.
Returns C<undef> if the internal filehandle can't C<setpos>.
Croaks if C<setpos> does not seek to the requested position,
that is, if calling C<getpos> does not yield the same object
as the C<$pos> argument.
=cut
sub setpos {
my ($self, $pos) = @_;
return undef unless $pos && $self->{fh}->can('setpos');
my $ret = $self->{fh}->setpos($pos);
croak "Cannot seek to correct position"
unless $self->getpos eq $pos;
return $ret;
}
=method read_element($read_bin)
Reads a full EBML element from the internal filehandle.
Returns a L<Parse::Matroska::Element> object initialized with
the read data. If C<read_bin> is not present or is false, will
delay-load the contents of C<binary> type elements, that is,
they will only be loaded when calling C<get_value> on the
returned L<Parse::Matroska::Element> object.
Does not read the children of the element if its type is
C<sub>. Look into the L<Parse::Matroska::Element> interface
for details in how to read children elements.
Pass a true C<$read_bin> if the stream being read is not
seekable (C<getpos> is undef) and the contents of C<binary>
elements is desired, otherwise seeking errors or internal
filehandle corruption might occur.
=cut
sub read_element {
my ($self, $read_bin) = @_;
return undef if $self->{fh}->eof;
my $elem_pos = $self->getpos;
my $elid = $self->read_id;
my $elem_def = elem_by_hexid($elid);
my ($size_len, $content_len) = $self->read_size;
my $full_len = length($elid)/2 + $size_len + $content_len;
my $elem = Parse::Matroska::Element->new(
elid => $elid,
name => $elem_def && $elem_def->{name},
type => $elem_def && $elem_def->{valtype},
size_len => $size_len,
content_len => $content_len,
full_len => $full_len,
reader => $self,
elem_pos => $elem_pos,
data_pos => $self->getpos,
);
weaken($elem->{reader});
if (defined $elem_def) {
if ($elem->{type} eq 'sub') {
$elem->{value} = [];
} elsif ($elem->{type} eq 'str') {
$elem->{value} = $self->read_str($content_len);
} elsif ($elem->{type} eq 'ebml_id') {
$elem->{value} = $self->read_ebml_id($content_len);
} elsif ($elem->{type} eq 'uint') {
$elem->{value} = $self->read_uint($content_len);
} elsif ($elem->{type} eq 'sint') {
$elem->{value} = $self->read_sint($content_len);
} elsif ($elem->{type} eq 'float') {
$elem->{value} = $self->read_float($content_len);
} elsif ($elem->{type} eq 'skip') {
$self->skip($content_len);
} elsif ($elem->{type} eq 'binary') {
if ($read_bin) {
$elem->{value} = $self->readlen($content_len);
} else {
$self->skip($content_len);
}
} else {
die "Matroska Definition error: type $elem->{valtype} unknown"
}
} else {
$self->skip($content_len);
}
return $elem;
}
1;
=head1 CAVEATS
Children elements have to be processed as soon as an element
with children is found, or their children ignored with
L<Parse::Matroska::Element/skip>. Not doing so doesn't cause
errors but results in an invalid structure, with constant C<0>
depth.
To work correctly in unseekable streams, either the contents
of C<binary>-type elements has to be ignored or the C<read_bin>
flag to C<read_element> has to be true.
+37
View File
@@ -0,0 +1,37 @@
use strict;
use warnings;
# ABSTRACT: internally-used helper functions
package Parse::Matroska::Utils;
use Exporter;
our @ISA = qw{Exporter};
our @EXPORT_OK = qw{uniq uncamelize};
=method uniq(@array)
The same as L<List::MoreUtils/"uniq LIST">.
Included to avoid depending on it since it's
not a core module.
=cut
sub uniq(@) {
my %seen;
return grep { !$seen{$_}++ } @_;
}
=method uncamelize($string)
Converts a "StringLikeTHIS" into a
"string_like_this".
=cut
sub uncamelize($) {
local $_ = shift;
# lc followed by UC: lc_UC
s/(?<=[a-z])([A-Z])/_\L$1/g;
# UC followed by two lc: _UClclc
s/([A-Z])(?=[a-z]{2})/_\L$1/g;
# strip leading _ that the second regexp might add; lowercase all
s/^_//; lc
}
-20
View File
@@ -1,20 +0,0 @@
mpv lua scripts
===============
The lua scripts in this folder can be loaded on a one-time basis by
adding the option
--script=/path/to/script.lua
to mpv's command line.
Where appropriate, they may also be placed in ~/.config/mpv/scripts/ from
where they will be automatically loaded when mpv starts.
This is only a small selection of internally maintained scripts. Some of them
are just for testing mpv internals, or serve as examples. An extensive
user-edited list of 3rd party scripts is available here:
https://github.com/mpv-player/mpv/wiki/User-Scripts
(Anyone can add their own scripts to that list.)
-155
View File
@@ -1,155 +0,0 @@
-- This script adds control to the dynamic range compression ffmpeg
-- filter including key bindings for adjusting parameters.
--
-- See https://ffmpeg.org/ffmpeg-filters.html#acompressor for explanation
-- of the parameteres.
local mp = require 'mp'
local options = require 'mp.options'
local o = {
default_enable = false,
show_osd = true,
osd_timeout = 4000,
filter_label = mp.get_script_name(),
key_toggle = 'n',
key_increase_threshold = 'F1',
key_decrease_threshold = 'Shift+F1',
key_increase_ratio = 'F2',
key_decrease_ratio = 'Shift+F2',
key_increase_knee = 'F3',
key_decrease_knee = 'Shift+F3',
key_increase_makeup = 'F4',
key_decrease_makeup = 'Shift+F4',
key_increase_attack = 'F5',
key_decrease_attack = 'Shift+F5',
key_increase_release = 'F6',
key_decrease_release = 'Shift+F6',
default_threshold = -25.0,
default_ratio = 3.0,
default_knee = 2.0,
default_makeup = 8.0,
default_attack = 20.0,
default_release = 250.0,
step_threshold = -2.5,
step_ratio = 1.0,
step_knee = 1.0,
step_makeup = 1.0,
step_attack = 10.0,
step_release = 10.0,
}
options.read_options(o)
local params = {
{ name = 'attack', min=0.01, max=2000, hide_default=true, dB='' },
{ name = 'release', min=0.01, max=9000, hide_default=true, dB='' },
{ name = 'threshold', min= -30, max= 0, hide_default=false, dB='dB' },
{ name = 'ratio', min= 1, max= 20, hide_default=false, dB='' },
{ name = 'knee', min= 1, max= 10, hide_default=true, dB='dB' },
{ name = 'makeup', min= 0, max= 24, hide_default=false, dB='dB' },
}
local function parse_value(value)
-- Using nil here because tonumber differs between lua 5.1 and 5.2 when parsing fractions in combination with explicit base argument set to 10.
-- And we can't omit it because gsub returns 2 values which would get unpacked and cause more problems. Gotta love scripting languages.
return tonumber(value:gsub('dB$', ''), nil)
end
local function format_value(value, dB)
return string.format('%g%s', value, dB)
end
local function show_osd(filter)
if not o.show_osd then
return
end
if not filter.enabled then
mp.commandv('show-text', 'Dynamic range compressor: disabled', o.osd_timeout)
return
end
local pretty = {}
for _,param in ipairs(params) do
local value = parse_value(filter.params[param.name])
if not (param.hide_default and value == o['default_' .. param.name]) then
pretty[#pretty+1] = string.format('%s: %g%s', param.name:gsub("^%l", string.upper), value, param.dB)
end
end
if #pretty == 0 then
pretty = ''
else
pretty = '\n(' .. table.concat(pretty, ', ') .. ')'
end
mp.commandv('show-text', 'Dynamic range compressor: enabled' .. pretty, o.osd_timeout)
end
local function get_filter()
local af = mp.get_property_native('af', {})
for i = 1, #af do
if af[i].label == o.filter_label then
return af, i
end
end
af[#af+1] = {
name = 'acompressor',
label = o.filter_label,
enabled = false,
params = {},
}
for _,param in pairs(params) do
af[#af].params[param.name] = format_value(o['default_' .. param.name], param.dB)
end
return af, #af
end
local function toggle_acompressor()
local af, i = get_filter()
af[i].enabled = not af[i].enabled
mp.set_property_native('af', af)
show_osd(af[i])
end
local function update_param(name, increment)
for _,param in pairs(params) do
if param.name == string.lower(name) then
local af, i = get_filter()
local value = parse_value(af[i].params[param.name])
value = math.max(param.min, math.min(value + increment, param.max))
af[i].params[param.name] = format_value(value, param.dB)
af[i].enabled = true
mp.set_property_native('af', af)
show_osd(af[i])
return
end
end
mp.msg.error('Unknown parameter "' .. name .. '"')
end
mp.add_key_binding(o.key_toggle, "toggle-acompressor", toggle_acompressor)
mp.register_script_message('update-param', update_param)
for _,param in pairs(params) do
for direction,step in pairs({increase=1, decrease=-1}) do
mp.add_key_binding(o['key_' .. direction .. '_' .. param.name],
'acompressor-' .. direction .. '-' .. param.name,
function() update_param(param.name, step*o['step_' .. param.name]); end,
{ repeatable = true })
end
end
if o.default_enable then
local af, i = get_filter()
af[i].enabled = true
mp.set_property_native('af', af)
end
-20
View File
@@ -1,20 +0,0 @@
-- Handles the edge case where previous attempts to init audio have failed, but
-- might start working due to a newly added device. This is required in
-- particular for ao=wasapi, since the internal IMMNotificationClient code that
-- normally triggers ao-reload will not be running in this case.
function do_reload()
mp.command("ao-reload")
reloading = nil
end
function on_audio_device_list_change()
if mp.get_property("current-ao") == "null" and not reloading then
mp.msg.verbose("audio-device-list changed: reloading audio")
-- avoid calling ao-reload too often
reloading = mp.add_timeout(0.5, do_reload)
end
end
mp.set_property("options/audio-fallback-to-null", "yes")
mp.observe_property("audio-device-list", "native", on_audio_device_list_change)
-8
View File
@@ -1,8 +0,0 @@
local utils = require("mp.utils")
mp.observe_property("audio-device-list", "native", function(name, val)
print("Audio device list changed:")
for index, e in ipairs(val) do
print(" - '" .. e.name .. "' (" .. e.description .. ")")
end
end)
-322
View File
@@ -1,322 +0,0 @@
--[[
This script uses the lavfi cropdetect filter to automatically
insert a crop filter with appropriate parameters for the
currently playing video.
It will automatically crop the video, when playback starts.
Also It registers the key-binding "C" (shift+c). You can manually
crop the video by pressing the "C" (shift+c) key.
If the "C" key is pressed again, the crop filter is removed
restoring playback to its original state.
The workflow is as follows: First, it inserts the filter
vf=lavfi=cropdetect. After <detect_seconds> (default is 1)
seconds, it then inserts the filter vf=crop=w:h:x:y, where
w,h,x,y are determined from the vf-metadata gathered by
cropdetect. The cropdetect filter is removed immediately after
the crop filter is inserted as it is no longer needed.
Since the crop parameters are determined from the 1 second of
video between inserting the cropdetect and crop filters, the "C"
key should be pressed at a position in the video where the crop
region is unambiguous (i.e., not a black frame, black background
title card, or dark scene).
The default options can be overridden by adding
script-opts-append=autocrop-<parameter>=<value> into mpv.conf
List of available parameters (For default values, see <options>):
auto: bool - Whether to automatically apply crop at the start of
playback. If you don't want to crop automatically, set it to
false or add "script-opts-append=autocrop-auto=no" into
mpv.conf.
auto_delay: seconds - Delay before starting crop in auto mode.
You can try to increase this value to avoid dark scene or
fade in at beginning. Automatic cropping will not occur if
the value is larger than the remaining playback time.
detect_limit: number[0-255] - Black threshold for cropdetect.
Smaller values will generally result in less cropping.
See limit of https://ffmpeg.org/ffmpeg-filters.html#cropdetect
detect_round: number[2^n] - The value which the width/height
should be divisible by. Smaller values ​​have better detection
accuracy. If you have problems with other filters,
you can try to set it to 4 or 16.
See round of https://ffmpeg.org/ffmpeg-filters.html#cropdetect
detect_min_ratio: number[0.0-1.0] - The ratio of the minimum clip
size to the original. If the picture is over cropped or under
cropped, try adjusting this value.
detect_seconds: seconds - How long to gather cropdetect data.
Increasing this may be desirable to allow cropdetect more
time to collect data.
--]]
require "mp.msg"
require 'mp.options'
local options = {
auto = true,
auto_delay = 4,
detect_limit = "24/255",
detect_round = 2,
detect_min_ratio = 0.5,
detect_seconds = 1
}
read_options(options)
local label_prefix = mp.get_script_name()
local labels = {
crop = string.format("%s-crop", label_prefix),
cropdetect = string.format("%s-cropdetect", label_prefix)
}
timers = {
auto_delay = nil,
detect_crop = nil
}
function is_filter_present(label)
local filters = mp.get_property_native("vf")
for index, filter in pairs(filters) do
if filter["label"] == label then
return true
end
end
return false
end
function is_enough_time(seconds)
-- Plus 1 second for deviation.
local time_needed = seconds + 1
local playtime_remaining = mp.get_property_native("playtime-remaining")
return playtime_remaining and time_needed < playtime_remaining
end
function is_cropable()
local vid = mp.get_property_native("vid")
local is_album = vid and mp.get_property_native(
string.format("track-list/%d/albumart", vid)
) or false
return vid and not is_album
end
function remove_filter(label)
if is_filter_present(label) then
mp.command(string.format('vf remove @%s', label))
return true
end
return false
end
function cleanup()
-- Remove all existing filters.
for key, value in pairs(labels) do
remove_filter(value)
end
-- Kill all timers.
for index, timer in pairs(timers) do
if timer then
timer:kill()
timer = nil
end
end
end
function detect_crop()
-- If it's not cropable, exit.
if not is_cropable() then
mp.msg.warn("autocrop only works for videos.")
return
end
-- Verify if there is enough time to detect crop.
local time_needed = options.detect_seconds
if not is_enough_time(time_needed) then
mp.msg.warn("Not enough time to detect crop.")
return
end
-- Insert the cropdetect filter.
local limit = options.detect_limit
local round = options.detect_round
mp.command(
string.format(
'vf pre @%s:cropdetect=limit=%s:round=%d:reset=0',
labels.cropdetect, limit, round
)
)
-- Wait to gather data.
timers.detect_crop = mp.add_timeout(time_needed, detect_end)
end
function detect_end()
-- Get the metadata and remove the cropdetect filter.
local cropdetect_metadata =
mp.get_property_native(
string.format("vf-metadata/%s",
labels.cropdetect
)
)
remove_filter(labels.cropdetect)
-- Remove the timer of detect crop.
if timers.detect_crop then
timers.detect_crop:kill()
timers.detect_crop = nil
end
local meta = {}
-- Verify the existence of metadata.
if cropdetect_metadata then
meta = {
w = cropdetect_metadata["lavfi.cropdetect.w"],
h = cropdetect_metadata["lavfi.cropdetect.h"],
x = cropdetect_metadata["lavfi.cropdetect.x"],
y = cropdetect_metadata["lavfi.cropdetect.y"],
}
else
mp.msg.error("No crop data.")
mp.msg.info("Was the cropdetect filter successfully inserted?")
mp.msg.info("Does your version of ffmpeg/libav support AVFrame metadata?")
return
end
-- Verify that the metadata meets the requirements and convert it.
if meta.w and meta.h and meta.x and meta.y then
local width = mp.get_property_native("width")
local height = mp.get_property_native("height")
meta = {
w = tonumber(meta.w),
h = tonumber(meta.h),
x = tonumber(meta.x),
y = tonumber(meta.y),
min_w = width * options.detect_min_ratio,
min_h = height * options.detect_min_ratio,
max_w = width,
max_h = height
}
else
mp.msg.error("Got empty crop data.")
mp.msg.info("You might need to increase detect_seconds.")
return
end
apply_crop(meta)
end
function apply_crop(meta)
-- Verify if it is necessary to crop.
local is_effective = meta.x > 0 or meta.y > 0
or meta.w < meta.max_w or meta.h < meta.max_h
if not is_effective then
mp.msg.info("No area detected for cropping.")
return
end
-- Verify it is not over cropped.
local is_excessive = meta.w < meta.min_w and meta.h < meta.min_h
if is_excessive then
mp.msg.info("The area to be cropped is too large.")
mp.msg.info("You might need to decrease detect_min_ratio.")
return
end
-- Remove existing crop.
remove_filter(labels.crop)
-- Apply crop.
mp.command(
string.format("vf pre @%s:lavfi-crop=w=%s:h=%s:x=%s:y=%s",
labels.crop, meta.w, meta.h, meta.x, meta.y
)
)
end
function on_start()
-- Clean up at the beginning.
cleanup()
-- If auto is not true, exit.
if not options.auto then
return
end
-- If it is the beginning, wait for detect_crop
-- after auto_delay seconds, otherwise immediately.
local playback_time = mp.get_property_native("playback-time")
local is_delay_needed = playback_time
and options.auto_delay > playback_time
if is_delay_needed then
-- Verify if there is enough time for autocrop.
local time_needed = options.auto_delay + options.detect_seconds
if not is_enough_time(time_needed) then
mp.msg.warn("Not enough time for autocrop.")
return
end
timers.auto_delay = mp.add_timeout(time_needed,
function()
detect_crop()
-- Remove the timer of auto delay.
timers.auto_delay:kill()
timers.auto_delay = nil
end
)
else
detect_crop()
end
end
function on_toggle()
-- If it is during auto_delay, kill the timer.
if timers.auto_delay then
timers.auto_delay:kill()
timers.auto_delay = nil
end
-- Cropped => Remove it.
if remove_filter(labels.crop) then
return
end
-- Detecting => Leave it.
if timers.detect_crop then
mp.msg.warn("Already cropdetecting!")
return
end
-- Neither => Do delectcrop.
detect_crop()
end
mp.add_key_binding("C", "toggle_crop", on_toggle)
mp.register_event("end-file", cleanup)
mp.register_event("file-loaded", on_start)
-156
View File
@@ -1,156 +0,0 @@
-- This script uses the lavfi idet filter to automatically insert the
-- appropriate deinterlacing filter based on a short section of the
-- currently playing video.
--
-- It registers the key-binding ctrl+d, which when pressed, inserts the filters
-- ``vf=idet,lavfi-pullup,idet``. After 4 seconds, it removes these
-- filters and decides whether the content is progressive, interlaced, or
-- telecined and the interlacing field dominance.
--
-- Based on this information, it may set mpv's ``deinterlace`` property (which
-- usually inserts the yadif filter), or insert the ``pullup`` filter if the
-- content is telecined. It also sets field dominance with lavfi setfield.
--
-- OPTIONS:
-- The default detection time may be overridden by adding
--
-- --script-opts=autodeint.detect_seconds=<number of seconds>
--
-- to mpv's arguments. This may be desirable to allow idet more
-- time to collect data.
--
-- To see counts of the various types of frames for each detection phase,
-- the verbosity can be increased with
--
-- --msg-level=autodeint=v
require "mp.msg"
script_name = mp.get_script_name()
detect_label = string.format("%s-detect", script_name)
pullup_label = string.format("%s", script_name)
dominance_label = string.format("%s-dominance", script_name)
ivtc_detect_label = string.format("%s-ivtc-detect", script_name)
-- number of seconds to gather cropdetect data
detect_seconds = tonumber(mp.get_opt(string.format("%s.detect_seconds", script_name)))
if not detect_seconds then
detect_seconds = 4
end
function del_filter_if_present(label)
-- necessary because mp.command('vf del @label:filter') raises an
-- error if the filter doesn't exist
local vfs = mp.get_property_native("vf")
for i,vf in pairs(vfs) do
if vf["label"] == label then
table.remove(vfs, i)
mp.set_property_native("vf", vfs)
return true
end
end
return false
end
local function add_vf(label, filter)
return mp.command(('vf add @%s:%s'):format(label, filter))
end
function start_detect()
-- exit if detection is already in progress
if timer then
mp.msg.warn("already detecting!")
return
end
mp.set_property("deinterlace","no")
del_filter_if_present(pullup_label)
del_filter_if_present(dominance_label)
-- insert the detection filters
if not (add_vf(detect_label, 'idet') and
add_vf(dominance_label, 'setfield=mode=auto') and
add_vf(pullup_label, 'lavfi-pullup') and
add_vf(ivtc_detect_label, 'idet')) then
mp.msg.error("failed to insert detection filters")
return
end
-- wait to gather data
timer = mp.add_timeout(detect_seconds, select_filter)
end
function stop_detect()
del_filter_if_present(detect_label)
del_filter_if_present(ivtc_detect_label)
timer = nil
end
progressive, interlaced_tff, interlaced_bff, interlaced = 0, 1, 2, 3, 4
function judge(label)
-- get the metadata
local result = mp.get_property_native(string.format("vf-metadata/%s", label))
local num_tff = tonumber(result["lavfi.idet.multiple.tff"])
local num_bff = tonumber(result["lavfi.idet.multiple.bff"])
local num_progressive = tonumber(result["lavfi.idet.multiple.progressive"])
local num_undetermined = tonumber(result["lavfi.idet.multiple.undetermined"])
local num_interlaced = num_tff + num_bff
local num_determined = num_interlaced + num_progressive
mp.msg.verbose(label.." progressive = "..num_progressive)
mp.msg.verbose(label.." interlaced-tff = "..num_tff)
mp.msg.verbose(label.." interlaced-bff = "..num_bff)
mp.msg.verbose(label.." undetermined = "..num_undetermined)
if num_determined < num_undetermined then
mp.msg.warn("majority undetermined frames")
end
if num_progressive > 20*num_interlaced then
return progressive
elseif num_tff > 10*num_bff then
return interlaced_tff
elseif num_bff > 10*num_tff then
return interlaced_bff
else
return interlaced
end
end
function select_filter()
-- handle the first detection filter results
local verdict = judge(detect_label)
local ivtc_verdict = judge(ivtc_detect_label)
local dominance = "auto"
if verdict == progressive then
mp.msg.info("progressive: doing nothing")
stop_detect()
del_filter_if_present(dominance_label)
del_filter_if_present(pullup_label)
return
else
if verdict == interlaced_tff then
dominance = "tff"
add_vf(dominance_label, 'setfield=mode='..dominance)
elseif verdict == interlaced_bff then
dominance = "bff"
add_vf(dominance_label, 'setfield=mode='..dominance)
else
del_filter_if_present(dominance_label)
end
end
-- handle the ivtc detection filter results
if ivtc_verdict == progressive then
mp.msg.info(string.format("telecined with %s field dominance: using pullup", dominance))
stop_detect()
else
mp.msg.info(string.format("interlaced with %s field dominance: setting deinterlace property", dominance))
del_filter_if_present(pullup_label)
mp.set_property("deinterlace","yes")
stop_detect()
end
end
mp.add_key_binding("ctrl+d", script_name, start_detect)
-220
View File
@@ -1,220 +0,0 @@
-- This script automatically loads playlist entries before and after the
-- the currently played file. It does so by scanning the directory a file is
-- located in when starting playback. It sorts the directory entries
-- alphabetically, and adds entries before and after the current file to
-- the internal playlist. (It stops if it would add an already existing
-- playlist entry at the same position - this makes it "stable".)
-- Add at most 5000 * 2 files when starting a file (before + after).
--[[
To configure this script use file autoload.conf in directory script-opts (the "script-opts"
directory must be in the mpv configuration directory, typically ~/.config/mpv/).
Example configuration would be:
disabled=no
images=no
videos=yes
audio=yes
--]]
MAXENTRIES = 5000
local msg = require 'mp.msg'
local options = require 'mp.options'
local utils = require 'mp.utils'
o = {
disabled = false,
images = true,
videos = true,
audio = true
}
options.read_options(o)
function Set (t)
local set = {}
for _, v in pairs(t) do set[v] = true end
return set
end
function SetUnion (a,b)
local res = {}
for k in pairs(a) do res[k] = true end
for k in pairs(b) do res[k] = true end
return res
end
EXTENSIONS_VIDEO = Set {
'mkv', 'avi', 'mp4', 'ogv', 'webm', 'rmvb', 'flv', 'wmv', 'mpeg', 'mpg', 'm4v', '3gp'
}
EXTENSIONS_AUDIO = Set {
'mp3', 'wav', 'ogm', 'flac', 'm4a', 'wma', 'ogg', 'opus'
}
EXTENSIONS_IMAGES = Set {
'jpg', 'jpeg', 'png', 'tif', 'tiff', 'gif', 'webp', 'svg', 'bmp'
}
EXTENSIONS = Set {}
if o.videos then EXTENSIONS = SetUnion(EXTENSIONS, EXTENSIONS_VIDEO) end
if o.audio then EXTENSIONS = SetUnion(EXTENSIONS, EXTENSIONS_AUDIO) end
if o.images then EXTENSIONS = SetUnion(EXTENSIONS, EXTENSIONS_IMAGES) end
function add_files_at(index, files)
index = index - 1
local oldcount = mp.get_property_number("playlist-count", 1)
for i = 1, #files do
mp.commandv("loadfile", files[i], "append")
mp.commandv("playlist-move", oldcount + i - 1, index + i - 1)
end
end
function get_extension(path)
match = string.match(path, "%.([^%.]+)$" )
if match == nil then
return "nomatch"
else
return match
end
end
table.filter = function(t, iter)
for i = #t, 1, -1 do
if not iter(t[i]) then
table.remove(t, i)
end
end
end
-- splitbynum and alnumcomp from alphanum.lua (C) Andre Bogus
-- Released under the MIT License
-- http://www.davekoelle.com/files/alphanum.lua
-- split a string into a table of number and string values
function splitbynum(s)
local result = {}
for x, y in (s or ""):gmatch("(%d*)(%D*)") do
if x ~= "" then table.insert(result, tonumber(x)) end
if y ~= "" then table.insert(result, y) end
end
return result
end
function clean_key(k)
k = (' '..k..' '):gsub("%s+", " "):sub(2, -2):lower()
return splitbynum(k)
end
-- compare two strings
function alnumcomp(x, y)
local xt, yt = clean_key(x), clean_key(y)
for i = 1, math.min(#xt, #yt) do
local xe, ye = xt[i], yt[i]
if type(xe) == "string" then ye = tostring(ye)
elseif type(ye) == "string" then xe = tostring(xe) end
if xe ~= ye then return xe < ye end
end
return #xt < #yt
end
local autoloaded = nil
function find_and_add_entries()
local path = mp.get_property("path", "")
local dir, filename = utils.split_path(path)
msg.trace(("dir: %s, filename: %s"):format(dir, filename))
if o.disabled then
msg.verbose("stopping: autoload disabled")
return
elseif #dir == 0 then
msg.verbose("stopping: not a local path")
return
end
local pl_count = mp.get_property_number("playlist-count", 1)
-- check if this is a manually made playlist
if (pl_count > 1 and autoloaded == nil) or
(pl_count == 1 and EXTENSIONS[string.lower(get_extension(filename))] == nil) then
msg.verbose("stopping: manually made playlist")
return
else
autoloaded = true
end
local pl = mp.get_property_native("playlist", {})
local pl_current = mp.get_property_number("playlist-pos-1", 1)
msg.trace(("playlist-pos-1: %s, playlist: %s"):format(pl_current,
utils.to_string(pl)))
local files = utils.readdir(dir, "files")
if files == nil then
msg.verbose("no other files in directory")
return
end
table.filter(files, function (v, k)
if string.match(v, "^%.") then
return false
end
local ext = get_extension(v)
if ext == nil then
return false
end
return EXTENSIONS[string.lower(ext)]
end)
table.sort(files, alnumcomp)
if dir == "." then
dir = ""
end
-- Find the current pl entry (dir+"/"+filename) in the sorted dir list
local current
for i = 1, #files do
if files[i] == filename then
current = i
break
end
end
if current == nil then
return
end
msg.trace("current file position in files: "..current)
local append = {[-1] = {}, [1] = {}}
for direction = -1, 1, 2 do -- 2 iterations, with direction = -1 and +1
for i = 1, MAXENTRIES do
local file = files[current + i * direction]
local pl_e = pl[pl_current + i * direction]
if file == nil or file[1] == "." then
break
end
local filepath = dir .. file
if pl_e then
-- If there's a playlist entry, and it's the same file, stop.
msg.trace(pl_e.filename.." == "..filepath.." ?")
if pl_e.filename == filepath then
break
end
end
if direction == -1 then
if pl_current == 1 then -- never add additional entries in the middle
msg.info("Prepending " .. file)
table.insert(append[-1], 1, filepath)
end
else
msg.info("Adding " .. file)
table.insert(append[1], filepath)
end
end
end
add_files_at(pl_current + 1, append[1])
add_files_at(pl_current, append[-1])
end
mp.register_event("start-file", find_and_add_entries)
-124
View File
@@ -1,124 +0,0 @@
-- Test script for some command API details.
local utils = require("mp.utils")
function join(sep, arr, count)
local r = ""
if count == nil then
count = #arr
end
for i = 1, count do
if i > 1 then
r = r .. sep
end
r = r .. utils.to_string(arr[i])
end
return r
end
mp.observe_property("vo-configured", "bool", function(_, v)
if v ~= true then
return
end
print("async expand-text")
mp.command_native_async({"expand-text", "hello ${path}!"},
function(res, val, err)
print("done async expand-text: " .. join(" ", {res, val, err}))
end)
-- make screenshot writing very slow
mp.set_property("screenshot-format", "png")
mp.set_property("screenshot-png-compression", "9")
timer = mp.add_periodic_timer(0.1, function() print("I'm alive") end)
timer:resume()
print("Slow screenshot command...")
res, err = mp.command_native({"screenshot"})
print("done, res: " .. utils.to_string(res))
print("Slow screenshot async command...")
res, err = mp.command_native_async({"screenshot"}, function(res)
print("done (async), res: " .. utils.to_string(res))
timer:kill()
end)
print("done (sending), res: " .. utils.to_string(res))
print("Broken screenshot async command...")
mp.command_native_async({"screenshot-to-file", "/nonexistent/bogus.png"},
function(res, val, err)
print("done err scr.: " .. join(" ", {res, val, err}))
end)
mp.command_native_async({name = "subprocess", args = {"sh", "-c", "echo hi && sleep 10s"}, capture_stdout = true},
function(res, val, err)
print("done subprocess: " .. join(" ", {res, val, err}))
end)
local x = mp.command_native_async({name = "subprocess", args = {"sleep", "inf"}},
function(res, val, err)
print("done sleep inf subprocess: " .. join(" ", {res, val, err}))
end)
mp.add_timeout(15, function()
print("aborting sleep inf subprocess after timeout")
mp.abort_async_command(x)
end)
-- (assuming this "freezes")
local y = mp.command_native_async({name = "sub-add", url = "-"},
function(res, val, err)
print("done sub-add stdin: " .. join(" ", {res, val, err}))
end)
mp.add_timeout(20, function()
print("aborting sub-add stdin after timeout")
mp.abort_async_command(y)
end)
mp.command_native_async({name = "subprocess", args = {"wc", "-c"},
stdin_data = "hello", capture_stdout = true},
function(res, val, err)
print("Should be '5': " .. val.stdout)
end)
-- blocking stdin by default
mp.command_native_async({name = "subprocess", args = {"cat"},
capture_stdout = true},
function(res, val, err)
print("Should be 0: " .. #val.stdout)
end)
-- stdin + detached
mp.command_native_async({name = "subprocess",
args = {"bash", "-c", "(sleep 5s ; cat)"},
stdin_data = "this should appear after 5s.\n",
detach = true},
function(res, val, err)
print("5s test: " .. val.status)
end)
-- This should get killed on script exit.
mp.command_native_async({name = "subprocess", playback_only = false,
args = {"sleep", "inf"}}, function()end)
-- Runs detached; should be killed on player exit (forces timeout)
mp.command_native({_flags={"async"}, name = "subprocess",
playback_only = false, args = {"sleep", "inf"}})
end)
function freeze_test(playback_only)
-- This "freezes" the script, should be killed via timeout.
counter = counter and counter + 1 or 0
print("freeze! " .. counter)
local x = mp.command_native({name = "subprocess",
playback_only = playback_only,
args = {"sleep", "inf"}})
print("done, killed=" .. utils.to_string(x.killed_by_us))
end
mp.register_event("shutdown", function()
freeze_test(false)
end)
mp.register_event("idle", function()
freeze_test(true)
end)
-56
View File
@@ -1,56 +0,0 @@
-- This script cycles between deinterlacing, pullup (inverse
-- telecine), and both filters off. It uses the "deinterlace" property
-- so that a hardware deinterlacer will be used if available.
--
-- It overrides the default deinterlace toggle keybinding "D"
-- (shift+d), so that rather than merely cycling the "deinterlace" property
-- between on and off, it adds a "pullup" step to the cycle.
--
-- It provides OSD feedback as to the actual state of the two filters
-- after each cycle step/keypress.
--
-- Note: if hardware decoding is enabled, pullup filter will likely
-- fail to insert.
--
-- TODO: It might make sense to use hardware assisted vdpaupp=pullup,
-- if available, but I don't have hardware to test it. Patch welcome.
script_name = mp.get_script_name()
pullup_label = string.format("%s-pullup", script_name)
function pullup_on()
for i,vf in pairs(mp.get_property_native('vf')) do
if vf['label'] == pullup_label then
return "yes"
end
end
return "no"
end
function do_cycle()
if pullup_on() == "yes" then
-- if pullup is on remove it
mp.command(string.format("vf del @%s:pullup", pullup_label))
return
elseif mp.get_property("deinterlace") == "yes" then
-- if deinterlace is on, turn it off and insert pullup filter
mp.set_property("deinterlace", "no")
mp.command(string.format("vf add @%s:pullup", pullup_label))
return
else
-- if neither is on, turn on deinterlace
mp.set_property("deinterlace", "yes")
return
end
end
function cycle_deinterlace_pullup_handler()
do_cycle()
-- independently determine current state and give user feedback
mp.osd_message(string.format("deinterlace: %s\n"..
"pullup: %s",
mp.get_property("deinterlace"),
pullup_on()))
end
mp.add_key_binding("D", "cycle-deinterlace-pullup", cycle_deinterlace_pullup_handler)
-37
View File
@@ -1,37 +0,0 @@
-- Test a float property which internally uses NaN.
-- Run with --no-config (or just scale-param1 not set).
local utils = require 'mp.utils'
prop_name = "scale-param1"
-- internal NaN, return string "default" instead of NaN
v = mp.get_property_native(prop_name, "fail")
print("Exp:", "string", "\"default\"")
print("Got:", type(v), utils.to_string(v))
v = mp.get_property(prop_name)
print("Exp:", "default")
print("Got:", v)
-- not representable -> return provided fallback value
v = mp.get_property_number(prop_name, -100)
print("Exp:", -100)
print("Got:", v)
mp.set_property_native(prop_name, 123)
v = mp.get_property_number(prop_name, -100)
print("Exp:", "number", 123)
print("Got:", type(v), utils.to_string(v))
-- try to set an actual NaN
st, msg = mp.set_property_number(prop_name, 0.0/0)
print("Exp:", nil, "<message>")
print("Got:", st, msg)
-- set default
mp.set_property(prop_name, "default")
v = mp.get_property(prop_name)
print("Exp:", "default")
print("Got:", v)
-22
View File
@@ -1,22 +0,0 @@
-- Test script for property change notification mechanism.
-- Note that watching/reading some properties can be very expensive, or
-- require the player to synchronously wait on network (when playing
-- remote files), so you should in general only watch properties you
-- are interested in.
local utils = require("mp.utils")
function observe(name)
mp.observe_property(name, "native", function(name, val)
print("property '" .. name .. "' changed to '" ..
utils.to_string(val) .. "'")
end)
end
for i,name in ipairs(mp.get_property_native("property-list")) do
observe(name)
end
for i,name in ipairs(mp.get_property_native("options")) do
observe("options/" .. name)
end
-19
View File
@@ -1,19 +0,0 @@
--makes mpv disable ontop when pausing and re-enable it again when resuming playback
--please note that this won't do anything if ontop was not enabled before pausing
local was_ontop = false
mp.observe_property("pause", "bool", function(name, value)
local ontop = mp.get_property_native("ontop")
if value then
if ontop then
mp.set_property_native("ontop", false)
was_ontop = true
end
else
if was_ontop and not ontop then
mp.set_property_native("ontop", true)
end
was_ontop = false
end
end)
-35
View File
@@ -1,35 +0,0 @@
local assdraw = require 'mp.assdraw'
local utils = require 'mp.utils'
things = {}
for i = 1, 2 do
things[i] = {
osd1 = mp.create_osd_overlay("ass-events"),
osd2 = mp.create_osd_overlay("ass-events")
}
end
things[1].text = "{\\an5}hello\\Nworld"
things[2].text = "{\\pos(400, 200)}something something"
mp.add_periodic_timer(2, function()
for i, thing in ipairs(things) do
thing.osd1.data = thing.text
thing.osd1.compute_bounds = true
--thing.osd1.hidden = true
local res = thing.osd1:update()
print("res " .. i .. ": " .. utils.to_string(res))
thing.osd2.hidden = true
if res ~= nil and res.x0 ~= nil then
local draw = assdraw.ass_new()
draw:append("{\\alpha&H80}")
draw:draw_start()
draw:pos(0, 0)
draw:rect_cw(res.x0, res.y0, res.x1, res.y1)
draw:draw_stop()
thing.osd2.hidden = false
thing.osd2.data = draw.text
end
thing.osd2:update()
end
end)
-20
View File
@@ -1,20 +0,0 @@
-- This script pauses playback when minimizing the window, and resumes playback
-- if it's brought back again. If the player was already paused when minimizing,
-- then try not to mess with the pause state.
local did_minimize = false
mp.observe_property("window-minimized", "bool", function(name, value)
local pause = mp.get_property_native("pause")
if value == true then
if pause == false then
mp.set_property_native("pause", true)
did_minimize = true
end
elseif value == false then
if did_minimize and (pause == true) then
mp.set_property_native("pause", false)
end
did_minimize = false
end
end)
-265
View File
@@ -1,265 +0,0 @@
--[[
Automatically skip in files if video frames with pre-supplied fingerprints are
detected. This will skip ahead by a pre-configured amount of time if a matching
video frame is detected.
This requires the vf_fingerprint video filter to be compiled in. Read the
documentation of this filter for caveats (which will automatically apply to
this script as well), such as no support for zero-copy hardware decoding.
You need to manually gather and provide fingerprints for video frames and add
them to a configuration file in script-opts/skip-logo.conf (the "script-opts"
directory must be in the mpv configuration directory, typically ~/.config/mpv/).
Example script-opts/skip-logo.conf:
cases = {
{
-- Skip ahead 10 seconds if a black frame was detected
-- Note: this is dangerous non-sense. It's just for demonstration.
name = "black frame", -- print if matched
skip = 10, -- number of seconds to skip forward
score = 0.3, -- required score
fingerprint = "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
},
{
-- Skip ahead 20 seconds if a white frame was detected
-- Note: this is dangerous non-sense. It's just for demonstration.
name = "fun2",
skip = 20,
fingerprint = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff",
},
}
This is actually a lua file. Lua was chosen because it seemed less of a pain to
parse. Future versions of this script may change the format.
The fingerprint is a video frame, converted to "gray" (8 bit per pixels), full
range, each pixel concatenated into an array, converted to a hex string. You
can produce these fingerprints by running this manually:
mpv --vf=fingerprint:print yourfile.mkv
This will log the fingerprint of each video frame to the console, along with its
timestamp. You find the fingerprint of a unique-enough looking frame, and add
it as entry to skip-logo.conf.
You can provide a score for "fuzziness". If no score is provided, a default
value of 0.3 is used. The score is inverse: 0 means exactly the same, while a
higher score means a higher difference. Currently, the score is computed as
euclidean distance between the video frame and the pre-provided fingerprint,
thus the highest score is 16. You probably want a score lower than 1 at least.
(This algorithm is very primitive, but also simple and fast to compute.)
There's always the danger of false positives, which might be quite annoying.
It's up to you what you hate more, the logo, or random skips if false positives
are detected. Also, it's always active, and might eat too much CPU with files
that have a high resolution or framerate. To temporarily disable the script,
having a keybind like this in your input.conf will be helpful:
ctrl+k vf toggle @skip-logo
This will disable/enable the fingerprint filter, which the script automatically
adds at start.
Another important caveat is that the script currently disables matching during
seeking or playback initialization, which means it cannot match the first few
frames of a video. This could be fixed, but the author was too lazy to do so.
--]]
local utils = require "mp.utils"
local msg = require "mp.msg"
local label = "skip-logo"
local meta_property = string.format("vf-metadata/%s", label)
local config = {}
local cases = {}
local cur_bmp
local seeking = false
local playback_start_pts = nil
-- Convert a hex string to an array. Convert each byte to a [0,1] float by
-- interpreting it as normalized uint8_t.
-- The data parameter, if not nil, may be used as storage (avoiding garbage).
local function hex_to_norm8(hex, data)
local size = math.floor(#hex / 2)
if #hex ~= size * 2 then
return nil
end
local res
if (data ~= nil) and (#data == size) then
res = data
else
res = {}
end
for i = 1, size do
local num = tonumber(hex:sub(i * 2, i * 2 + 1), 16)
if num == nil then
return nil
end
res[i] = num / 255.0
end
return res
end
local function compare_bmp(a, b)
if #a ~= #b then
return nil -- can't compare
end
local sum = 0
for i = 1, #a do
local diff = a[i] - b[i]
sum = sum + diff * diff
end
return math.sqrt(sum)
end
local function load_config()
local conf_file = mp.find_config_file("script-opts/skip-logo.conf")
local conf_fn
local err = nil
if conf_file then
if setfenv then
conf_fn, err = loadfile(conf_file)
if conf_fn then
setfenv(conf_fn, config)
end
else
conf_fn, err = loadfile(conf_file, "t", config)
end
else
err = "config file not found"
end
if conf_fn and (not err) then
local ok, err2 = pcall(conf_fn)
err = err2
end
if err then
msg.error("Failed to load config file:", err)
end
if config.cases then
for n, case in ipairs(config.cases) do
local err = nil
case.bitmap = hex_to_norm8(case.fingerprint)
if case.bitmap == nil then
err = "invalid or missing fingerprint field"
end
if case.score == nil then
case.score = 0.3
end
if type(case.score) ~= "number" then
err = "score field is not a number"
end
if type(case.skip) ~= "number" then
err = "skip field is not a number or missing"
end
if case.name == nil then
case.name = ("Entry %d"):format(n)
end
if err == nil then
cases[#cases + 1] = case
else
msg.error(("Entry %s: %s, ignoring."):format(case.name, err))
end
end
end
end
load_config()
-- Returns true on match and if something was done.
local function check_fingerprint(hex, pts)
local bmp = hex_to_norm8(hex, cur_bmp)
cur_bmp = bmp
-- If parsing the filter's result failed (well, it shouldn't).
assert(bmp ~= nil, "filter returned nonsense")
for _, case in ipairs(cases) do
local score = compare_bmp(case.bitmap, bmp)
if (score ~= nil) and (score <= case.score) then
msg.warn(("Matching %s: score=%f (required: %f) at %s, skipping %f seconds"):
format(case.name, score, case.score, mp.format_time(pts), case.skip))
mp.commandv("seek", pts + case.skip, "absolute+exact")
return true
end
end
return false
end
local function read_frames()
local result = mp.get_property_native(meta_property)
if result == nil then
return
end
-- Try to get all entries. Out of laziness, assume that there are at most
-- 100 entries. (In fact, vf_fingerprint limits it to 10.)
for i = 0, 99 do
local prefix = string.format("fp%d.", i)
local hex = result[prefix .. "hex"]
local pts = tonumber(result[prefix .. "pts"])
if (hex == nil) or (pts == nil) then
break
end
local skip = false -- blame Lua for not having "continue" or "goto", not me
-- If seeking just stopped, there will be frames before the seek target,
-- ignore them by checking the timestamps.
if playback_start_pts ~= nil then
if pts >= playback_start_pts then
playback_start_pts = nil -- just for robustness
else
skip = true
end
end
if not skip then
if check_fingerprint(hex, pts) then
break
end
end
end
end
mp.observe_property(meta_property, "none", function()
-- Ignore frames that are decoded/filtered during seeking.
if seeking then
return
end
read_frames()
end)
mp.observe_property("seeking", "bool", function(name, val)
seeking = val
if seeking == false then
playback_start_pts = mp.get_property_number("playback-time")
read_frames()
end
end)
local filters = mp.get_property_native("option-info/vf/choices", {})
local found = false
for _, f in ipairs(filters) do
if f == "fingerprint" then
found = true
break
end
end
if found then
mp.command(("no-osd vf add @%s:fingerprint"):format(label, filter))
else
msg.warn("vf_fingerprint not found")
end
-92
View File
@@ -1,92 +0,0 @@
-- Rebuild the terminal status line as a lua script
-- Be aware that this will require more cpu power!
-- Also, this is based on a rather old version of the
-- builtin mpv status line.
-- Add a string to the status line
function atsl(s)
newStatus = newStatus .. s
end
function update_status_line()
-- Reset the status line
newStatus = ""
if mp.get_property_bool("pause") then
atsl("(Paused) ")
elseif mp.get_property_bool("paused-for-cache") then
atsl("(Buffering) ")
end
if mp.get_property("aid") ~= "no" then
atsl("A")
end
if mp.get_property("vid") ~= "no" then
atsl("V")
end
atsl(": ")
atsl(mp.get_property_osd("time-pos"))
atsl(" / ");
atsl(mp.get_property_osd("duration"));
atsl(" (")
atsl(mp.get_property_osd("percent-pos", -1))
atsl("%)")
local r = mp.get_property_number("speed", -1)
if r ~= 1 then
atsl(string.format(" x%4.2f", r))
end
r = mp.get_property_number("avsync", nil)
if r ~= nil then
atsl(string.format(" A-V: %f", r))
end
r = mp.get_property("total-avsync-change", 0)
if math.abs(r) > 0.05 then
atsl(string.format(" ct:%7.3f", r))
end
r = mp.get_property_number("decoder-drop-frame-count", -1)
if r > 0 then
atsl(" Late: ")
atsl(r)
end
r = mp.get_property_osd("video-bitrate")
if r ~= nil and r ~= "" then
atsl(" Vb: ")
atsl(r)
end
r = mp.get_property_osd("audio-bitrate")
if r ~= nil and r ~= "" then
atsl(" Ab: ")
atsl(r)
end
r = mp.get_property_number("cache", 0)
if r > 0 then
atsl(string.format(" Cache: %d%% ", r))
end
-- Set the new status line
mp.set_property("options/term-status-msg", newStatus)
end
timer = mp.add_periodic_timer(1, update_status_line)
function on_pause_change(name, value)
if value == false then
timer:resume()
else
timer:stop()
end
mp.add_timeout(0.1, update_status_line)
end
mp.observe_property("pause", "bool", on_pause_change)
mp.register_event("seek", update_status_line)
-32
View File
@@ -1,32 +0,0 @@
local utils = require("mp.utils")
function hardsleep()
os.execute("sleep 1s")
end
local hooks = {"on_before_start_file", "on_load", "on_load_fail",
"on_preloaded", "on_unload", "on_after_end_file"}
for _, name in ipairs(hooks) do
mp.add_hook(name, 0, function()
print("--- hook: " .. name)
hardsleep()
print(" ... continue")
end)
end
local events = {"start-file", "end-file", "file-loaded", "seek",
"playback-restart", "idle", "shutdown"}
for _, name in ipairs(events) do
mp.register_event(name, function()
print("--- event: " .. name)
end)
end
local props = {"path", "metadata"}
for _, name in ipairs(props) do
mp.observe_property(name, "native", function(name, val)
print("property '" .. name .. "' changed to '" ..
utils.to_string(val) .. "'")
end)
end
+169
View File
@@ -0,0 +1,169 @@
#! /usr/bin/env perl
# Generate C definitions for parsing Matroska files.
use strict;
use warnings;
use FindBin;
use lib "$FindBin::Bin/lib";
use Parse::Matroska::Definitions;
use Parse::Matroska::Reader;
use Getopt::Long;
use List::Util qw{max};
my @global_elem_list = @Parse::Matroska::Definitions::global_elem_list;
Getopt::Long::Configure(qw{auto_version auto_help});
my %opt;
GetOptions(\%opt,
"generate-header",
"generate-definitions",
"full",
);
if ($opt{"generate-header"}) {
generate_c_header();
} elsif ($opt{"generate-definitions"}) {
generate_c_definitions();
} else {
for (@ARGV) {
my $reader = Parse::Matroska::Reader->new($_ eq '-' ? \*STDIN : $_) or die $!;
while (my $elem = $reader->read_element($_ eq '-')) {
process_elem($elem, $_ eq '-');
}
}
}
# Generate declarations for libmpdemux/ebml_types.h
sub generate_c_header {
print "/* Generated by TOOLS/matroska.pl, do not edit manually */\n\n";
# Write a #define for the ElementID of each known element
for my $el (@global_elem_list) {
printf "#define %-40s 0x%s\n", $el->{definename}, $el->{elid};
}
print "\n";
# Define a struct for each ElementID that has child elements
for my $el (@global_elem_list) {
next unless $el->{subelements};
print "\nstruct $el->{structname} {\n";
# Figure out the length of the longest variable name
# Used for pretty-printing in the next step
my $l = max(map { length $_->{valname} } values %{$el->{subelements}});
# Output each variable, with pointers for array (multiple) elements
for my $subel (values %{$el->{subelements}}) {
printf " %-${l}s %s%s;\n",
$subel->{valname}, $subel->{multiple}?'*':' ', $subel->{fieldname};
}
print "\n";
# Output a counter variable for each element
# (presence/absence for scalars, item count for arrays)
for my $subel (values %{$el->{subelements}}) {
print " int n_$subel->{fieldname};\n"
}
print "};\n";
}
print "\n";
# Output extern references for ebml_elem_desc structs for each of the elements
# These are defined by generate_c_definitions
for my $el (@global_elem_list) {
next unless $el->{subelements};
print "extern const struct ebml_elem_desc $el->{structname}_desc;\n";
}
print "\n";
# Output the max number of sub-elements a known element might have
printf "#define MAX_EBML_SUBELEMENTS %d\n",
max(map { scalar keys %{$_->{subelements}} }
grep { $_->{subelements} } @global_elem_list);
}
# Generate definitions for libmpdemux/ebml_defs.c
sub generate_c_definitions {
print "/* Generated by TOOLS/matroska.pl, do not edit manually */\n\n";
# ebml_defs.c uses macros declared in ebml.c
for my $el (@global_elem_list) {
print "\n";
if ($el->{subelements}) {
# set N for the next macros
print "#define N $el->{fieldname}\n";
# define a struct ebml_$N_desc and gets ready to define fields
# this secretly opens two scopes; hence the }}; at the end
print "E_S(\"$el->{name}\", ".scalar(keys %{$el->{subelements}}).")\n";
# define a field for each subelement
# also does lots of macro magic, but doesn't open a scope
for my $subel (values %{$el->{subelements}}) {
print "F($subel->{definename}, $subel->{fieldname}, ".
($subel->{multiple}?'1':'0').")\n";
}
# close the struct
print "}};\n";
# unset N since we've used it
print "#undef N\n";
} else {
print "E(\"$el->{name}\", $el->{fieldname}, $el->{ebmltype})\n";
}
}
}
sub repr {
my @ret;
foreach (@_) {
if (/'/) {
s/"/\\"/g;
push @ret, "\"$_\"";
} else {
push @ret, "'$_'";
}
}
return @ret if wantarray;
return pop @ret if defined wantarray;
return;
}
sub process_elem {
my ($elem, $read_bin) = @_;
unless ($opt{full}) {
if ($elem->{name} eq 'Cluster' || $elem->{name} eq 'Cues') {
$elem->skip;
return;
}
}
die unless $elem;
if ($elem->{type} ne 'skip') {
print "$elem->{depth} $elem->{elid} $elem->{name} size: $elem->{content_len} value: ";
}
if ($elem->{type} eq 'sub') {
print "subelements:\n";
while (my $chld = $elem->next_child($read_bin)) {
process_elem($chld);
}
} elsif ($elem->{type} eq 'binary') {
my $t = "<skipped $elem->{content_len} bytes>";
if ($elem->{content_len} < 20) {
$t = unpack "H*", $elem->get_value;
}
print "binary $t\n";
delete $elem->{value};
} elsif ($elem->{type} eq 'ebml_id') {
print "binary $elem->{value}->{elid} (".($elem->{value}->{name}||"UNKNOWN").")\n";
} elsif ($elem->{type} eq 'skip') {
# skip
} elsif ($elem->{type} eq 'str') {
print "string ". repr($elem->get_value) . "\n";
} else {
print "$elem->{type} ". $elem->get_value ."\n";
}
}
-479
View File
@@ -1,479 +0,0 @@
#!/usr/bin/env python3
"""
Generate C definitions for parsing Matroska files.
Can also be used to directly parse Matroska files and display their contents.
"""
#
# This file is part of mpv.
#
# mpv is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# mpv is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with mpv. If not, see <http://www.gnu.org/licenses/>.
#
# for compatibility with Python 2.x
from __future__ import print_function
elements_ebml = (
'EBML, 1a45dfa3, sub', (
'EBMLVersion, 4286, uint',
'EBMLReadVersion, 42f7, uint',
'EBMLMaxIDLength, 42f2, uint',
'EBMLMaxSizeLength, 42f3, uint',
'DocType, 4282, str',
'DocTypeVersion, 4287, uint',
'DocTypeReadVersion, 4285, uint',
),
'CRC32, bf, binary',
'Void, ec, binary',
)
elements_matroska = (
'Segment, 18538067, sub', (
'SeekHead*, 114d9b74, sub', (
'Seek*, 4dbb, sub', (
'SeekID, 53ab, ebml_id',
'SeekPosition, 53ac, uint',
),
),
'Info*, 1549a966, sub', (
'SegmentUID, 73a4, binary',
'PrevUID, 3cb923, binary',
'NextUID, 3eb923, binary',
'TimecodeScale, 2ad7b1, uint',
'DateUTC, 4461, sint',
'Title, 7ba9, str',
'MuxingApp, 4d80, str',
'WritingApp, 5741, str',
'Duration, 4489, float',
),
'Cluster*, 1f43b675, sub', (
'Timecode, e7, uint',
'BlockGroup*, a0, sub', (
'Block, a1, binary',
'BlockDuration, 9b, uint',
'ReferenceBlock*, fb, sint',
'DiscardPadding, 75A2, sint',
'BlockAdditions, 75A1, sub', (
'BlockMore*, A6, sub', (
'BlockAddID, EE, uint',
'BlockAdditional, A5, binary',
),
),
),
'SimpleBlock*, a3, binary',
),
'Tracks*, 1654ae6b, sub', (
'TrackEntry*, ae, sub', (
'TrackNumber, d7, uint',
'TrackUID, 73c5, uint',
'TrackType, 83, uint',
'FlagEnabled, b9, uint',
'FlagDefault, 88, uint',
'FlagForced, 55aa, uint',
'FlagLacing, 9c, uint',
'MinCache, 6de7, uint',
'MaxCache, 6df8, uint',
'DefaultDuration, 23e383, uint',
'TrackTimecodeScale, 23314f, float',
'MaxBlockAdditionID, 55ee, uint',
'Name, 536e, str',
'Language, 22b59c, str',
'CodecID, 86, str',
'CodecPrivate, 63a2, binary',
'CodecName, 258688, str',
'CodecDecodeAll, aa, uint',
'CodecDelay, 56aa, uint',
'SeekPreRoll, 56bb, uint',
'Video, e0, sub', (
'FlagInterlaced, 9a, uint',
'PixelWidth, b0, uint',
'PixelHeight, ba, uint',
'DisplayWidth, 54b0, uint',
'DisplayHeight, 54ba, uint',
'DisplayUnit, 54b2, uint',
'FrameRate, 2383e3, float',
'ColourSpace, 2eb524, binary',
'StereoMode, 53b8, uint',
'Colour, 55b0, sub', (
'MatrixCoefficients, 55B1, uint',
'BitsPerChannel, 55B2, uint',
'ChromaSubsamplingHorz, 55B3, uint',
'ChromaSubsamplingVert, 55B4, uint',
'CbSubsamplingHorz, 55B5, uint',
'CbSubsamplingVert, 55B6, uint',
'ChromaSitingHorz, 55B7, uint',
'ChromaSitingVert, 55B8, uint',
'Range, 55B9, uint',
'TransferCharacteristics, 55BA, uint',
'Primaries, 55BB, uint',
'MaxCLL, 55BC, uint',
'MaxFALL, 55BD, uint',
'MasteringMetadata, 55D0, sub', (
'PrimaryRChromaticityX, 55D1, float',
'PrimaryRChromaticityY, 55D2, float',
'PrimaryGChromaticityX, 55D3, float',
'PrimaryGChromaticityY, 55D4, float',
'PrimaryBChromaticityX, 55D5, float',
'PrimaryBChromaticityY, 55D6, float',
'WhitePointChromaticityX, 55D7, float',
'WhitePointChromaticityY, 55D8, float',
'LuminanceMax, 55D9, float',
'LuminanceMin, 55DA, float',
),
),
'Projection, 7670, sub', (
'ProjectionType, 7671, uint',
'ProjectionPrivate, 7672, binary',
'ProjectionPoseYaw, 7673, float',
'ProjectionPosePitch, 7674, float',
'ProjectionPoseRoll, 7675, float',
),
),
'Audio, e1, sub', (
'SamplingFrequency, b5, float',
'OutputSamplingFrequency, 78b5, float',
'Channels, 9f, uint',
'BitDepth, 6264, uint',
),
'ContentEncodings, 6d80, sub', (
'ContentEncoding*, 6240, sub', (
'ContentEncodingOrder, 5031, uint',
'ContentEncodingScope, 5032, uint',
'ContentEncodingType, 5033, uint',
'ContentCompression, 5034, sub', (
'ContentCompAlgo, 4254, uint',
'ContentCompSettings, 4255, binary',
),
),
),
),
),
'Cues, 1c53bb6b, sub', (
'CuePoint*, bb, sub', (
'CueTime, b3, uint',
'CueTrackPositions*, b7, sub', (
'CueTrack, f7, uint',
'CueClusterPosition, f1, uint',
'CueRelativePosition, f0, uint',
'CueDuration, b2, uint',
),
),
),
'Attachments, 1941a469, sub', (
'AttachedFile*, 61a7, sub', (
'FileDescription, 467e, str',
'FileName, 466e, str',
'FileMimeType, 4660, str',
'FileData, 465c, binary',
'FileUID, 46ae, uint',
),
),
'Chapters, 1043a770, sub', (
'EditionEntry*, 45b9, sub', (
'EditionUID, 45bc, uint',
'EditionFlagHidden, 45bd, uint',
'EditionFlagDefault, 45db, uint',
'EditionFlagOrdered, 45dd, uint',
'ChapterAtom*, b6, sub', (
'ChapterUID, 73c4, uint',
'ChapterTimeStart, 91, uint',
'ChapterTimeEnd, 92, uint',
'ChapterFlagHidden, 98, uint',
'ChapterFlagEnabled, 4598, uint',
'ChapterSegmentUID, 6e67, binary',
'ChapterSegmentEditionUID, 6ebc, uint',
'ChapterDisplay*, 80, sub', (
'ChapString, 85, str',
'ChapLanguage*, 437c, str',
'ChapCountry*, 437e, str',
),
),
),
),
'Tags*, 1254c367, sub', (
'Tag*, 7373, sub', (
'Targets, 63c0, sub', (
'TargetTypeValue, 68ca, uint',
'TargetType, 63ca, str',
'TargetTrackUID, 63c5, uint',
'TargetEditionUID, 63c9, uint',
'TargetChapterUID, 63c4, uint',
'TargetAttachmentUID, 63c6, uint',
),
'SimpleTag*, 67c8, sub', (
'TagName, 45a3, str',
'TagLanguage, 447a, str',
'TagString, 4487, str',
'TagDefault, 4484, uint',
),
),
),
),
)
import sys
from math import ldexp
from binascii import hexlify
def byte2num(s):
return int(hexlify(s), 16)
class EOF(Exception): pass
def camelcase_to_words(name):
parts = []
start = 0
for i in range(1, len(name)):
if name[i].isupper() and (name[i-1].islower() or
name[i+1:i+2].islower()):
parts.append(name[start:i])
start = i
parts.append(name[start:])
return '_'.join(parts).lower()
class MatroskaElement(object):
def __init__(self, name, elid, valtype, namespace):
self.name = name
self.definename = '{0}_ID_{1}'.format(namespace, name.upper())
self.fieldname = camelcase_to_words(name)
self.structname = 'ebml_' + self.fieldname
self.elid = elid
self.valtype = valtype
if valtype == 'sub':
self.ebmltype = 'EBML_TYPE_SUBELEMENTS'
self.valname = 'struct ' + self.structname
else:
self.ebmltype = 'EBML_TYPE_' + valtype.upper()
try:
self.valname = {'uint': 'uint64_t', 'str': 'char *',
'binary': 'bstr', 'ebml_id': 'uint32_t',
'float': 'double', 'sint': 'int64_t',
}[valtype]
except KeyError:
raise SyntaxError('Unrecognized value type ' + valtype)
self.subelements = ()
def add_subelements(self, subelements):
self.subelements = subelements
self.subids = {x[0].elid for x in subelements}
elementd = {}
elementlist = []
def parse_elems(l, namespace):
subelements = []
for el in l:
if isinstance(el, str):
name, hexid, eltype = [x.strip() for x in el.split(',')]
hexid = hexid.lower()
multiple = name.endswith('*')
name = name.strip('*')
new = MatroskaElement(name, hexid, eltype, namespace)
elementd[hexid] = new
elementlist.append(new)
subelements.append((new, multiple))
else:
new.add_subelements(parse_elems(el, namespace))
return subelements
parse_elems(elements_ebml, 'EBML')
parse_elems(elements_matroska, 'MATROSKA')
def printf(out, *args):
out.write(u' '.join([str(x) for x in args]))
out.write(u'\n')
def generate_C_header(out):
printf(out, '// Generated by TOOLS/matroska.py, do not edit manually')
printf(out)
for el in elementlist:
printf(out, '#define {0.definename:40} 0x{0.elid}'.format(el))
printf(out)
for el in reversed(elementlist):
if not el.subelements:
continue
printf(out)
printf(out, 'struct {0.structname} {{'.format(el))
l = max(len(subel.valname) for subel, multiple in el.subelements)+1
for subel, multiple in el.subelements:
printf(out, ' {e.valname:{l}} {star}{e.fieldname};'.format(
e=subel, l=l, star=' *'[multiple]))
printf(out)
for subel, multiple in el.subelements:
printf(out, ' int n_{0.fieldname};'.format(subel))
printf(out, '};')
for el in elementlist:
if not el.subelements:
continue
printf(out, 'extern const struct ebml_elem_desc {0.structname}_desc;'.format(el))
printf(out)
printf(out, '#define MAX_EBML_SUBELEMENTS', max(len(el.subelements)
for el in elementlist))
def generate_C_definitions(out):
printf(out, '// Generated by TOOLS/matroska.py, do not edit manually')
printf(out)
for el in reversed(elementlist):
printf(out)
if el.subelements:
printf(out, '#define N', el.fieldname)
printf(out, 'E_S("{0}", {1})'.format(el.name, len(el.subelements)))
for subel, multiple in el.subelements:
printf(out, 'F({0.definename}, {0.fieldname}, {1})'.format(
subel, int(multiple)))
printf(out, '}};')
printf(out, '#undef N')
else:
printf(out, 'E("{0.name}", {0.fieldname}, {0.ebmltype})'.format(el))
def read(s, length):
t = s.read(length)
if len(t) != length:
raise EOF
return t
def read_id(s):
t = read(s, 1)
i = 0
mask = 128
if ord(t) == 0:
raise SyntaxError
while not ord(t) & mask:
i += 1
mask >>= 1
t += read(s, i)
return t
def read_vint(s):
t = read(s, 1)
i = 0
mask = 128
if ord(t) == 0:
raise SyntaxError
while not ord(t) & mask:
i += 1
mask >>= 1
t = bytes((ord(t) & (mask - 1),))
t += read(s, i)
return i+1, byte2num(t)
def read_str(s, length):
return read(s, length)
def read_uint(s, length):
t = read(s, length)
return byte2num(t)
def read_sint(s, length):
i = read_uint(s, length)
mask = 1 << (length * 8 - 1)
if i & mask:
i -= 2 * mask
return i
def read_float(s, length):
t = read(s, length)
i = byte2num(t)
if length == 4:
f = ldexp((i & 0x7fffff) + (1 << 23), (i >> 23 & 0xff) - 150)
if i & (1 << 31):
f = -f
elif length == 8:
f = ldexp((i & ((1 << 52) - 1)) + (1 << 52), (i >> 52 & 0x7ff) - 1075)
if i & (1 << 63):
f = -f
else:
raise SyntaxError
return f
def parse_one(s, depth, parent, maxlen):
elid = hexlify(read_id(s)).decode('ascii')
elem = elementd.get(elid)
size, length = read_vint(s)
this_length = len(elid) / 2 + size + length
if elem is not None:
if elem.valtype != 'skip':
print(" " * depth, '[' + elid + ']', elem.name, 'size:', length, 'value:', end=' ')
if elem.valtype == 'sub':
print('subelements:')
while length > 0:
length -= parse_one(s, depth + 1, elem, length)
if length < 0:
raise SyntaxError
elif elem.valtype == 'str':
print('string', repr(read_str(s, length).decode('utf8', 'replace')))
elif elem.valtype in ('binary', 'ebml_id'):
t = read_str(s, length)
dec = ''
if elem.valtype == 'ebml_id':
idelem = elementd.get(hexlify(t).decode('ascii'))
if idelem is None:
dec = '(UNKNOWN)'
else:
dec = '({0.name})'.format(idelem)
if len(t) < 20:
t = hexlify(t).decode('ascii')
else:
t = '<{0} bytes>'.format(len(t))
print('binary', t, dec)
elif elem.valtype == 'uint':
print('uint', read_uint(s, length))
elif elem.valtype == 'sint':
print('sint', read_sint(s, length))
elif elem.valtype == 'float':
print('float', read_float(s, length))
elif elem.valtype == 'skip':
read(s, length)
else:
raise NotImplementedError
else:
print(" " * depth, '[' + elid + '] Unknown element! size:', length)
read(s, length)
return this_length
if __name__ == "__main__":
def parse_toplevel(s):
parse_one(s, 0, None, 1 << 63)
if sys.argv[1] == '--generate-header':
generate_C_header(sys.stdout)
elif sys.argv[1] == '--generate-definitions':
generate_C_definitions(sys.stdout)
else:
if sys.version_info.major < 3:
raise Exception("Dumping requires Python 3.")
s = open(sys.argv[1], "rb")
while 1:
start = s.tell()
try:
parse_toplevel(s)
except EOF:
if s.tell() != start:
raise Exception("Unexpected end of file")
break
Loaded 100 of 1020 files, more files were not shown because too many files have changed in this diff. Show more