summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore12
-rw-r--r--.travis.yml20
-rw-r--r--DOCS/client-api-changes.rst41
-rw-r--r--DOCS/client_api_examples/qtexample.cpp136
-rw-r--r--DOCS/client_api_examples/qtexample.h30
-rw-r--r--DOCS/client_api_examples/qtexample.pro12
-rw-r--r--DOCS/encoding.rst2
-rw-r--r--DOCS/man/ao.rst24
-rw-r--r--DOCS/man/changes.rst28
-rw-r--r--DOCS/man/input.rst39
-rw-r--r--DOCS/man/lua.rst14
-rw-r--r--DOCS/man/mpv.rst93
-rw-r--r--DOCS/man/options.rst3507
-rw-r--r--DOCS/man/vf.rst12
-rw-r--r--DOCS/man/vo.rst2
-rw-r--r--DOCS/release-policy.md14
-rw-r--r--DOCS/tech-overview.txt24
-rw-r--r--RELEASE_NOTES233
-rwxr-xr-xTOOLS/dylib-unhell.py8
-rwxr-xr-xTOOLS/idet.sh10
-rw-r--r--TOOLS/lua/observe-all.lua16
-rw-r--r--TOOLS/lua/status-line.lua (renamed from DOCS/lua_examples/status-line.lua)2
-rw-r--r--TOOLS/osxbundle/mpv.app/Contents/Info.plist84
-rwxr-xr-xTOOLS/zsh.pl77
-rw-r--r--VERSION2
-rw-r--r--audio/decode/ad.h2
-rw-r--r--audio/decode/ad_lavc.c96
-rw-r--r--audio/decode/ad_mpg123.c216
-rw-r--r--audio/decode/ad_spdif.c33
-rw-r--r--audio/decode/dec_audio.c103
-rw-r--r--audio/decode/dec_audio.h15
-rw-r--r--audio/filter/af.c13
-rw-r--r--audio/filter/af.h2
-rw-r--r--audio/filter/af_lavfi.c12
-rw-r--r--audio/filter/af_lavrresample.c10
-rw-r--r--audio/format.h2
-rw-r--r--audio/out/ao.c4
-rw-r--r--audio/out/ao_alsa.c7
-rw-r--r--audio/out/ao_coreaudio.c761
-rw-r--r--audio/out/ao_coreaudio_device.c684
-rw-r--r--audio/out/ao_coreaudio_properties.h1
-rw-r--r--audio/out/ao_coreaudio_utils.c464
-rw-r--r--audio/out/ao_coreaudio_utils.h35
-rw-r--r--audio/out/ao_dsound.c2
-rw-r--r--audio/out/ao_lavc.c22
-rw-r--r--audio/out/ao_null.c2
-rw-r--r--audio/out/ao_oss.c1
-rw-r--r--audio/out/ao_pulse.c68
-rw-r--r--audio/out/push.c9
-rw-r--r--bstr/bstr.c9
-rw-r--r--common/av_common.c46
-rw-r--r--common/av_common.h5
-rw-r--r--common/av_opts.c55
-rw-r--r--common/av_opts.h30
-rw-r--r--common/encode_lavc.c9
-rw-r--r--common/msg.c2
-rw-r--r--common/tags.c19
-rw-r--r--common/tags.h2
-rw-r--r--demux/demux.c1138
-rw-r--r--demux/demux.h98
-rw-r--r--demux/demux_disc.c354
-rw-r--r--demux/demux_lavf.c134
-rw-r--r--demux/demux_mf.c7
-rw-r--r--demux/demux_mkv.c115
-rw-r--r--demux/demux_playlist.c2
-rw-r--r--demux/demux_raw.c4
-rw-r--r--demux/demux_subreader.c54
-rw-r--r--demux/demux_tv.c249
-rw-r--r--demux/ebml.c22
-rw-r--r--demux/ebml.h12
-rw-r--r--demux/mf.c4
-rw-r--r--demux/packet.c122
-rw-r--r--demux/packet.h10
-rw-r--r--demux/stheader.h2
-rw-r--r--etc/example.conf16
-rw-r--r--etc/input.conf95
-rw-r--r--etc/mplayer-input.conf153
-rw-r--r--input/cmd_parse.c2
-rw-r--r--input/input.c85
-rw-r--r--input/input.h10
-rw-r--r--input/keycodes.c1
-rw-r--r--input/keycodes.h3
-rw-r--r--input/lirc.c2
-rw-r--r--libmpv/client.h37
-rw-r--r--libmpv/mpv.def34
-rw-r--r--libmpv/mpv.pc.in1
-rw-r--r--misc/charset_conv.c35
-rw-r--r--misc/ctype.h19
-rw-r--r--misc/rendezvous.c54
-rw-r--r--misc/rendezvous.h8
-rwxr-xr-xold-configure6
-rw-r--r--old-makefile10
-rw-r--r--options/m_config.c1
-rw-r--r--options/m_option.c25
-rw-r--r--options/m_option.h2
-rw-r--r--options/options.c23
-rw-r--r--options/options.h7
-rw-r--r--options/parse_configfile.c29
-rw-r--r--options/path.c220
-rw-r--r--options/path.h12
-rw-r--r--osdep/endian.h31
-rw-r--r--osdep/io.c4
-rw-r--r--osdep/macosx_application.h4
-rw-r--r--osdep/macosx_application.m62
-rw-r--r--osdep/macosx_application_objc.h17
-rw-r--r--osdep/macosx_compat.h5
-rw-r--r--osdep/macosx_events.h4
-rw-r--r--osdep/macosx_events.m140
-rw-r--r--osdep/macosx_events_objc.h37
-rw-r--r--osdep/macosx_versions.h29
-rw-r--r--osdep/path-macosx.m8
-rw-r--r--osdep/path-win.c63
-rw-r--r--osdep/path.h13
-rw-r--r--osdep/terminal-unix.c6
-rw-r--r--osdep/terminal-win.c25
-rw-r--r--osdep/terminal.h3
-rw-r--r--player/audio.c361
-rw-r--r--player/client.c85
-rw-r--r--player/client.h2
-rw-r--r--player/command.c423
-rw-r--r--player/command.h10
-rw-r--r--player/configfiles.c66
-rw-r--r--player/core.h57
-rw-r--r--player/discnav.c33
-rw-r--r--player/loadfile.c279
-rw-r--r--player/lua.c188
-rw-r--r--player/lua/osc.lua45
-rw-r--r--player/main.c24
-rw-r--r--player/main_fn.c4
-rw-r--r--player/misc.c41
-rw-r--r--player/osd.c46
-rw-r--r--player/playloop.c673
-rw-r--r--player/screenshot.c4
-rw-r--r--player/scripting.c10
-rw-r--r--player/sub.c61
-rw-r--r--player/timeline/tl_cue.c1
-rw-r--r--player/timeline/tl_mpv_edl.c5
-rw-r--r--player/video.c466
-rw-r--r--stream/cache.c120
-rw-r--r--stream/cache_file.c2
-rw-r--r--stream/dvb_tune.c1
-rw-r--r--stream/dvbin.h1
-rw-r--r--stream/stream.c21
-rw-r--r--stream/stream.h16
-rw-r--r--stream/stream_bluray.c7
-rw-r--r--stream/stream_cdda.c6
-rw-r--r--stream/stream_dvb.c35
-rw-r--r--stream/stream_dvd.c11
-rw-r--r--stream/stream_dvdnav.c11
-rw-r--r--stream/stream_lavf.c82
-rw-r--r--stream/stream_pvr.c2
-rw-r--r--stream/tv.c261
-rw-r--r--stream/tv.h8
-rw-r--r--stream/tvi_v4l2.c1
-rw-r--r--sub/ass_mp.c8
-rw-r--r--sub/find_subfiles.c9
-rw-r--r--sub/sd_microdvd.c1
-rw-r--r--sub/sd_srt.c13
-rwxr-xr-xtravis-deps69
-rw-r--r--video/csputils.c3
-rw-r--r--video/decode/dec_video.c3
-rw-r--r--video/decode/dec_video.h3
-rw-r--r--video/decode/vaapi.c2
-rw-r--r--video/decode/vd_lavc.c33
-rw-r--r--video/decode/vda.c158
-rw-r--r--video/filter/vf.c42
-rw-r--r--video/filter/vf_buffer.c93
-rw-r--r--video/filter/vf_lavfi.c15
-rw-r--r--video/filter/vf_vapoursynth.c12
-rw-r--r--video/fmt-conversion.c10
-rw-r--r--video/img_format.h3
-rw-r--r--video/img_fourcc.h2
-rw-r--r--video/out/cocoa/window.m1
-rw-r--r--video/out/cocoa_common.h9
-rw-r--r--video/out/cocoa_common.m147
-rw-r--r--video/out/gl_cocoa.c103
-rw-r--r--video/out/gl_common.c7
-rw-r--r--video/out/gl_w32.c179
-rw-r--r--video/out/gl_wayland.c3
-rw-r--r--video/out/pnm_loader.c6
-rw-r--r--video/out/vo.c23
-rw-r--r--video/out/vo.h20
-rw-r--r--video/out/vo_caca.c8
-rw-r--r--video/out/vo_direct3d.c13
-rw-r--r--video/out/vo_opengl.c31
-rw-r--r--video/out/vo_opengl_old.c4
-rw-r--r--video/out/vo_sdl.c12
-rw-r--r--video/out/vo_vaapi.c15
-rw-r--r--video/out/vo_vdpau.c37
-rw-r--r--video/out/vo_wayland.c12
-rw-r--r--video/out/vo_x11.c22
-rw-r--r--video/out/vo_xv.c29
-rw-r--r--video/out/w32_common.c634
-rw-r--r--video/out/w32_common.h43
-rw-r--r--video/out/wayland_common.c75
-rw-r--r--video/out/x11_common.c7
-rw-r--r--video/vdpau.c27
-rw-r--r--video/vdpau.h2
-rw-r--r--waftools/detections/compiler.py6
-rw-r--r--waftools/detections/devices.py2
-rw-r--r--waftools/generators/headers.py8
-rw-r--r--waftools/syms.py97
-rw-r--r--wscript94
-rw-r--r--wscript_build.py50
204 files changed, 9213 insertions, 7312 deletions
diff --git a/.gitignore b/.gitignore
index e9a857b..0411869 100644
--- a/.gitignore
+++ b/.gitignore
@@ -20,12 +20,12 @@
/demux/ebml_types.h
/sub/osd_font.h
/player/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
+/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
/build
diff --git a/.travis.yml b/.travis.yml
index faafe27..c588d05 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,5 +1,8 @@
language: c
+os:
+ - linux
+ - osx
env:
- LIBAV=libav-stable
- LIBAV=libav-git
@@ -7,24 +10,31 @@ env:
- LIBAV=ffmpeg-git
compiler:
- clang
+
branches:
only:
- master
- ci
+matrix:
+ exclude:
+ - os: osx
+ env: LIBAV=libav-stable
+ - os: osx
+ env: LIBAV=libav-git
+ - os: osx
+ env: LIBAV=ffmpeg-git
+
before_install: ./travis-deps libass-stable $LIBAV
script:
- ./bootstrap.py
- ./waf configure
- ./waf build
-notifications-policy: &notifications-policy
- on_success: change
- on_failure: always
-
notifications:
email: false
irc:
channels:
- "irc.freenode.org#mpv-player-dev"
- <<: *notifications-policy
+ on_success: change
+ on_failure: always
diff --git a/DOCS/client-api-changes.rst b/DOCS/client-api-changes.rst
new file mode 100644
index 0000000..e8c5445
--- /dev/null
+++ b/DOCS/client-api-changes.rst
@@ -0,0 +1,41 @@
+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, this list is interesting for other uses of mpv, such as the Lua
+scripting interface, key bindings in ``input.rst``, or plain command line
+usage.
+
+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``.
+
+API changes
+===========
+
+::
+
+ 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 is released ---
+ 1.0 - the API is declared stable
+
diff --git a/DOCS/client_api_examples/qtexample.cpp b/DOCS/client_api_examples/qtexample.cpp
new file mode 100644
index 0000000..354e5d9
--- /dev/null
+++ b/DOCS/client_api_examples/qtexample.cpp
@@ -0,0 +1,136 @@
+// License: pick one of: public domain, WTFPL, ISC, Ms-PL, AGPLv3
+
+// This example can be built with: qmake && make
+
+#include <sstream>
+
+#include <QFileDialog>
+#include <QStatusBar>
+#include <QMenuBar>
+#include <QMenu>
+#include <QGridLayout>
+#include <QApplication>
+
+#include "qtexample.h"
+
+static void wakeup(void *ctx)
+{
+ // This callback is invoked from any mpv thread (but possibly also
+ // recursively from a thread that is calling the mpv API). Just notify
+ // the Qt GUI thread to wake up (so that it can process events with
+ // mpv_wait_event()), and return as quickly as possible.
+ MainWindow *mainwindow = (MainWindow *)ctx;
+ QCoreApplication::postEvent(mainwindow, new QEvent(QEvent::User));
+}
+
+MainWindow::MainWindow(QWidget *parent) :
+ QMainWindow(parent)
+{
+ QMenu *menu = menuBar()->addMenu(tr("&File"));
+ QAction *on_open = new QAction(tr("&Open"), this);
+ on_open->setShortcuts(QKeySequence::Open);
+ on_open->setStatusTip(tr("Open a file"));
+ connect(on_open, SIGNAL(triggered()), this, SLOT(on_file_open()));
+ menu->addAction(on_open);
+
+ statusBar();
+
+ mpv = mpv_create();
+ if (!mpv)
+ throw "can't create mpv instance";
+
+ // Create a video child window. Force Qt to create a native window, and
+ // pass the window ID to the mpv wid option. This doesn't work on OSX,
+ // because Cocoa doesn't support this form of embedding.
+ mpv_container = new QWidget(this);
+ setCentralWidget(mpv_container);
+ mpv_container->setAttribute(Qt::WA_NativeWindow);
+ int64_t wid = mpv_container->winId();
+ mpv_set_option(mpv, "wid", MPV_FORMAT_INT64, &wid);
+
+ // Enable default bindings, because we're lazy. Normally, a player using
+ // mpv as backend would implement its own key bindings.
+ mpv_set_option_string(mpv, "input-default-bindings", "yes");
+
+ // Let us receive property change events with MPV_EVENT_PROPERTY_CHANGE if
+ // this property changes.
+ mpv_observe_property(mpv, 0, "time-pos", MPV_FORMAT_DOUBLE);
+
+ // From this point on, the wakeup function will be called. The callback
+ // can come from any thread, so we use the Qt QEvent mechanism to relay
+ // the wakeup in a thread-safe way.
+ mpv_set_wakeup_callback(mpv, wakeup, this);
+
+ if (mpv_initialize(mpv) < 0)
+ throw "mpv failed to initialize";
+}
+
+void MainWindow::handle_mpv_event(mpv_event *event)
+{
+ switch (event->event_id) {
+ case MPV_EVENT_PROPERTY_CHANGE: {
+ mpv_event_property *prop = (mpv_event_property *)event->data;
+ if (strcmp(prop->name, "time-pos") == 0) {
+ if (prop->format == MPV_FORMAT_DOUBLE) {
+ double time = *(double *)prop->data;
+ std::stringstream ss;
+ ss << "At: " << time;
+ statusBar()->showMessage(QString::fromStdString(ss.str()));
+ } else if (prop->format == MPV_FORMAT_NONE) {
+ // The property is unavailable, which probably means playback
+ // was stopped.
+ statusBar()->showMessage("");
+ }
+ }
+ break;
+ }
+ case MPV_EVENT_SHUTDOWN: {
+ mpv_terminate_destroy(mpv);
+ mpv = NULL;
+ break;
+ }
+ default: ;
+ // Ignore uninteresting or unknown events.
+ }
+}
+
+bool MainWindow::event(QEvent *event)
+{
+ // QEvent::User is sent by wakeup().
+ if (event->type() == QEvent::User) {
+ // Process all events, until the event queue is empty.
+ while (mpv) {
+ mpv_event *event = mpv_wait_event(mpv, 0);
+ if (event->event_id == MPV_EVENT_NONE)
+ break;
+ handle_mpv_event(event);
+ }
+ return true;
+ }
+ return QMainWindow::event(event);
+}
+
+void MainWindow::on_file_open()
+{
+ QString filename = QFileDialog::getOpenFileName(this, "Open file");
+ if (mpv) {
+ const QByteArray c_filename = filename.toUtf8();
+ const char *args[] = {"loadfile", c_filename.data(), NULL};
+ mpv_command_async(mpv, 0, args);
+ }
+}
+
+MainWindow::~MainWindow()
+{
+ if (mpv)
+ mpv_terminate_destroy(mpv);
+}
+
+int main(int argc, char *argv[])
+{
+ QApplication a(argc, argv);
+ MainWindow w;
+ w.show();
+
+ return a.exec();
+}
diff --git a/DOCS/client_api_examples/qtexample.h b/DOCS/client_api_examples/qtexample.h
new file mode 100644
index 0000000..b5b6fe7
--- /dev/null
+++ b/DOCS/client_api_examples/qtexample.h
@@ -0,0 +1,30 @@
+#ifndef QTEXAMPLE_H
+#define QTEXAMPLE_H
+
+#include <QMainWindow>
+
+#include <mpv/client.h>
+
+class MainWindow : public QMainWindow
+{
+ Q_OBJECT
+
+public:
+ explicit MainWindow(QWidget *parent = 0);
+ ~MainWindow();
+
+protected:
+ virtual bool event(QEvent *event);
+
+private slots:
+ void on_file_open();
+
+private:
+ QWidget *mpv_container;
+ mpv_handle *mpv;
+
+ void create_player();
+ void handle_mpv_event(mpv_event *event);
+};
+
+#endif // QTEXAMPLE_H
diff --git a/DOCS/client_api_examples/qtexample.pro b/DOCS/client_api_examples/qtexample.pro
new file mode 100644
index 0000000..03174b8
--- /dev/null
+++ b/DOCS/client_api_examples/qtexample.pro
@@ -0,0 +1,12 @@
+QT += core gui
+
+greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
+
+TARGET = qtexample
+TEMPLATE = app
+
+CONFIG += link_pkgconfig
+PKGCONFIG = mpv
+
+SOURCES += qtexample.cpp
+HEADERS += qtexample.h
diff --git a/DOCS/encoding.rst b/DOCS/encoding.rst
index c82416d..fa3ffb8 100644
--- a/DOCS/encoding.rst
+++ b/DOCS/encoding.rst
@@ -25,7 +25,7 @@ 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 .mpv/config
+Of course, the options can be stored in a profile, like this .config/mpv/mpv.conf
section::
[myencprofile]
diff --git a/DOCS/man/ao.rst b/DOCS/man/ao.rst
index 64c9e30..5bd82cd 100644
--- a/DOCS/man/ao.rst
+++ b/DOCS/man/ao.rst
@@ -53,6 +53,10 @@ Available audio output drivers are:
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.
+ ``non-interleaved``
+ Allow output of non-interleaved formats (if the audio decoder uses
+ this format). Currently disabled by default, because some popular
+ ALSA plugins are utterly broken with non-interleaved formats.
.. note::
@@ -110,7 +114,19 @@ Available audio output drivers are:
with fixed setups.
``coreaudio`` (Mac OS X only)
- Native Mac OS X audio output driver
+ Native Mac OS X audio output driver using the AudioUnits and the CoreAudio
+ sound server.
+
+ ``device_id=<id>``
+ ID of output device to use (0 = default device)
+ ``help``
+ List all available output devices with their IDs.
+
+``coreaudio_device`` (Mac OS X only)
+ Native Mac OS X audio output driver using direct device access and
+ exclusive mode (bypasses the sound server).
+
+ Supports only compressed formats (AC3 and DTS).
``device_id=<id>``
ID of output device to use (0 = default device)
@@ -137,6 +153,12 @@ Available audio output drivers are:
value makes the audio stream react faster, e.g. to playback speed
changes. Default: 250.
+ ``latency-hacks=<yes|no>``
+ Enable hacks to workaround PulseAudio timing bugs (default: yes). 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.
+
``portaudio``
PortAudio audio output driver. This works on all platforms, and has
extensive MS Windows support.
diff --git a/DOCS/man/changes.rst b/DOCS/man/changes.rst
index f1f336a..092256a 100644
--- a/DOCS/man/changes.rst
+++ b/DOCS/man/changes.rst
@@ -308,28 +308,38 @@ input.conf and Slave Commands
Slave mode
~~~~~~~~~~
-* 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
+* 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 **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.
+ 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 already removed (``TOOLS/mpv_identify.sh`` is provided
- instead), and ``--slave-broken`` might be removed in the future.
+ ``--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``.
+
+* A JSON RPC protocol giving access to the client API is planned, but nothing
+ has emerged yet.
* **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.
-* A slave protocol is planned, but nothing has emerged yet.
-
Policy for Removed Features
---------------------------
diff --git a/DOCS/man/input.rst b/DOCS/man/input.rst
index 2ba463a..612c0ca 100644
--- a/DOCS/man/input.rst
+++ b/DOCS/man/input.rst
@@ -4,12 +4,18 @@ INPUT.CONF
The input.conf file consists of a list of key bindings, for example::
s screenshot # take a screenshot with the s key
+ LEFT seek 15 # map the left-arrow key to seeking forward by 15 seconds
Each line maps a key to an input command. Keys are specified with their literal
value (upper case if combined with ``Shift``), or a name for special keys. For
example, ``a`` maps to the ``a`` key without shift, and ``A`` maps to ``a``
with shift.
+The file is normally located in ``~/.config/mpv/input.conf`` (some platforms
+may use different paths). The default bindings are defined here::
+
+ https://github.com/mpv-player/mpv/blob/master/etc/input.conf
+
A list of special keys can be obtained with
``mpv --input-keylist``
@@ -101,7 +107,7 @@ List of Input Commands
``revert_seek`` command itself.
``frame_step``
- Play one frame, then pause.
+ Play one frame, then pause. Does nothing with audio-only playback.
``frame_back_step``
Go back by one frame, then pause. Note that this can be very slow (it tries
@@ -615,11 +621,6 @@ Property list
``stream-end``
Raw end position in bytes in source stream.
-``stream-time-pos`` (RW)
- Time position in source stream. This only works for DVD and Bluray. This
- is probably never different from ``time-pos``, because ``time-pos`` is
- forced to this value anyway.
-
``length``
Length of the current file in seconds. If the length is unknown, the
property is unavailable. Note that the file duration is not always exactly
@@ -660,6 +661,9 @@ Property list
``playtime-remaining``
``time-remaining`` scaled by the the current ``speed``.
+``playback-time``
+ Return the playback time, which is the time difference between start PTS and current PTS.
+
``chapter`` (RW)
Current chapter number. The number of the first chapter is 0.
@@ -793,7 +797,7 @@ Property list
pauses itself due to low network cache.
``cache``
- Network cache fill state (0-100).
+ Network cache fill state (0-100.0).
``cache-size`` (RW)
Total network cache size in KB. This is similar to ``--cache``. This allows
@@ -807,6 +811,16 @@ Property list
Don't use this when playing DVD or Bluray.
+``cache-free`` (R)
+ Total free cache size in KB.
+
+``cache-used`` (R)
+ Total used cache size in KB.
+
+``cache-idle`` (R)
+ Returns ``yes`` if the cache is idle, which means the cache is filled as
+ much as possible, and is currently not reading more data.
+
``paused-for-cache``
Returns ``yes`` when playback is paused because of waiting for the cache.
@@ -817,6 +831,12 @@ Property list
or enter idle mode), and in these cases the ``eof-reached`` property will
logically be cleared immediately after it's set.
+``seeking``
+ Returns ``yes`` if the player is currently seeking, or otherwise trying
+ to restart playback. (It's possible that it returns ``yes`` while a file
+ is loaded, or when switching ordered chapter segments. This is because
+ the same underlying code is used for seeking and resyncing.)
+
``pts-association-mode`` (RW)
See ``--pts-association-mode``.
@@ -980,6 +1000,7 @@ Property list
"par" MPV_FORMAT_DOUBLE
"colormatrix" MPV_FORMAT_STRING
"colorlevels" MPV_FORMAT_STRING
+ "primaries" MPV_FORMAT_STRING
"chroma-location" MPV_FORMAT_STRING
"rotate" MPV_FORMAT_INT64
@@ -1249,8 +1270,8 @@ Property list
require reloading the file for changes to take effect. If there is an
equivalent property, prefer setting the property instead.
-``write_watch_later_config``
- Saves current playback position.
+``property-list``
+ Return the list of top-level properties.
Property Expansion
------------------
diff --git a/DOCS/man/lua.rst b/DOCS/man/lua.rst
index 80467f8..0ab53f0 100644
--- a/DOCS/man/lua.rst
+++ b/DOCS/man/lua.rst
@@ -299,6 +299,20 @@ The ``mp`` module is preloaded, although it can be loaded manually with
with ``add_timeout()``), this starts the timer from the beginning,
using the initially configured timeout.
+ ``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 calback function fn is run).
+
``mp.get_opt(key)``
Return a setting from the ``--lua-opts`` option. It's up to the user and
diff --git a/DOCS/man/mpv.rst b/DOCS/man/mpv.rst
index ec03c4d..80bda76 100644
--- a/DOCS/man/mpv.rst
+++ b/DOCS/man/mpv.rst
@@ -2,7 +2,7 @@ mpv
###
##############
-a movie player
+a media player
##############
:Copyright: GPLv2+
@@ -19,7 +19,7 @@ SYNOPSIS
DESCRIPTION
===========
-**mpv** is a movie player based on MPlayer and mplayer2. It supports a wide variety of video
+**mpv** is a media 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
@@ -40,16 +40,13 @@ Keyboard Control
----------------
LEFT and RIGHT
- Seek backward/forward 10 seconds. Shift+arrow does a 1 second exact seek
+ Seek backward/forward 5 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%.
@@ -69,11 +66,11 @@ p / SPACE
Pause (pressing again unpauses).
\.
- Step forward. Pressing once will pause movie, every consecutive press will
+ Step forward. Pressing once will pause, every consecutive press will
play one frame and then go into pause mode again.
,
- Step backward. Pressing once will pause movie, every consecutive press will
+ Step backward. Pressing once will pause, every consecutive press will
play one frame in reverse and then go into pause mode again.
q / ESC
@@ -83,21 +80,12 @@ 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.
@@ -107,9 +95,6 @@ m
\#
Cycle through the available audio tracks.
-TAB (MPEG-TS and libavformat only)
- Cycle through the available programs.
-
f
Toggle fullscreen (see also ``--fs``).
@@ -119,7 +104,10 @@ T
w and e
Decrease/increase pan-and-scan range.
-o
+o (also P)
+ Show progression bar, elapsed time and total duration on the OSD.
+
+O
Toggle OSD states: none / seek / seek + timer / seek + timer + total time.
d
@@ -132,9 +120,6 @@ v
j and J
Cycle through the available subtitles.
-F
- Toggle displaying "forced subtitles".
-
x and z
Adjust subtitle delay by +/- 0.1 seconds.
@@ -155,23 +140,14 @@ S
I
Show filename on the OSD.
-P
- Show progression bar, elapsed time and total duration on the OSD.
-
-! and @
+PGUP and PGDWN
Seek to the beginning of the previous/next chapter. In most cases,
"previous" will actually go to the beginning of the current chapter; see
``--chapter-seek-threshold``.
-D (``--vo=vdpau``, ``--vf=yadif`` only)
+D
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``).)
@@ -190,21 +166,21 @@ corresponding adjustment, or the software equalizer (``--vf=eq``).)
(The following keys are valid only on OSX.)
command + 0
- Resize movie window to half its original size.
+ Resize video window to half its original size.
(On other platforms, you can bind keys to change the ``window-scale``
property.)
command + 1
- Resize movie window to its original size.
+ Resize video window to its original size.
command + 2
- Resize movie window to double its original size.
+ Resize video window to double its original size.
command + f
Toggle fullscreen (see also ``--fs``).
command + [ and command + ]
- Set movie window alpha.
+ Set video window alpha.
(The following keys are valid if you have a keyboard with multimedia keys.)
@@ -223,12 +199,6 @@ support.)
h and k
Select previous/next channel.
-n
- Change norm.
-
-u
- Change channel list.
-
Mouse Control
-------------
@@ -338,7 +308,7 @@ 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 one is ``~/.config/mpv/mpv.conf``.
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
@@ -373,8 +343,8 @@ 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
+configuration file for a file called 'video.avi', create a file named
+'video.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
@@ -539,15 +509,23 @@ 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``
+``HOME``, ``XDG_CONFIG_HOME``
+ Used to determine mpv config directory. If ``XDG_CONFIG_HOME`` is not set,
+ ``$HOME/.config/mpv`` is used.
+
+ ``$HOME/.mpv`` is always added to the list of config search paths with a
+ lower priority.
+
+``XDG_CONFIG_DIRS``
+ If set, XDG-style system configuration directories are used. Otherwise,
+ the UNIX convention (``PREFIX/etc/mpv/``) is used.
``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``.
+ will try to load the config file as ``$MPV_HOME/mpv.conf``.
``MPV_VERBOSE`` (see also ``-v`` and ``--msg-level``)
Set the initial verbosity level across all message modules (default: 0).
@@ -660,18 +638,23 @@ FILES
``/usr/local/etc/mpv/mpv.conf``
mpv system-wide settings (depends on ``--prefix`` passed to configure)
-``~/.mpv/config``
+``~/.config/mpv/mpv.conf``
mpv user settings
-``~/.mpv/input.conf``
- input bindings (see ``--input-keylist`` for the full list)
+``~/.config/mpv/input.conf``
+ key bindings (see `INPUT.CONF`_ section)
-``~/.mpv/lua/``
+``~/.config/mpv/lua/``
All files in this directly are loaded as if they were passed to the
``--lua`` option. They are loaded in alphabetical order, and sub-directories
and files with no ``.lua`` extension are ignored. The ``--load-scripts=no``
option disables loading these files.
+Note that the environment variables ``$XDG_CONFIG_HOME`` and ``$MPV_HOME`` can
+override the standard directory ``~/.config/mpv/``.
+
+Also, the old config location at ``~/.mpv/`` is still read, and if the XDG
+variant does not exist, will still be preferred.
EXAMPLES OF MPV USAGE
=====================
diff --git a/DOCS/man/options.rst b/DOCS/man/options.rst
index 4d3c586..81da53b 100644
--- a/DOCS/man/options.rst
+++ b/DOCS/man/options.rst
@@ -1,6 +1,737 @@
OPTIONS
=======
+Track Selection
+---------------
+
+``--alang=<languagecode[,languagecode,...]>``
+ Specify a priority list of audio languages to use. Different container
+ formats employ different language codes. DVDs use ISO 639-1 two-letter
+ language codes, Matroska, MPEG-TS and NUT use ISO 639-2 three-letter
+ language codes, while OGM uses a free-form identifier. See also ``--aid``.
+
+ .. admonition:: Examples
+
+ ``mpv dvd://1 --alang=hu,en``
+ Chooses the Hungarian language track on a DVD and falls back on
+ English if Hungarian is not available.
+ ``mpv --alang=jpn example.mkv``
+ Plays a Matroska file in Japanese.
+
+``--slang=<languagecode[,languagecode,...]>``
+ Specify a priority list of subtitle languages to use. Different container
+ formats employ different language codes. DVDs use ISO 639-1 two letter
+ language codes, Matroska uses ISO 639-2 three letter language codes while
+ OGM uses a free-form identifier. See also ``--sid``.
+
+ .. admonition:: Examples
+
+ - ``mpv dvd://1 --slang=hu,en`` chooses the Hungarian subtitle track on
+ a DVD and falls back on English if Hungarian is not available.
+ - ``mpv --slang=jpn example.mkv`` plays a Matroska file with Japanese
+ subtitles.
+
+``--aid=<ID|auto|no>``
+ Select audio track. ``auto`` selects the default, ``no`` disables audio.
+ See also ``--alang``. mpv normally prints available audio tracks on the
+ terminal when starting playback of a file.
+
+``--sid=<ID|auto|no>``
+ Display the subtitle stream specified by ``<ID>``. ``auto`` selects
+ the default, ``no`` disables subtitles.
+
+ See also ``--slang``, ``--no-sub``.
+
+``--vid=<ID|auto|no>``
+ Select video channel. ``auto`` selects the default, ``no`` disables video.
+
+``--edition=<ID|auto>``
+ (Matroska files only)
+ Specify the edition (set of chapters) to use, where 0 is the first. If set
+ to ``auto`` (the default), mpv will choose the first edition declared as a
+ default, or if there is no default, the first edition defined.
+
+
+Playback Control
+----------------
+
+``--start=<relative time>``
+ Seek to given time position.
+
+ The general format for absolute times is ``[[hh:]mm:]ss[.ms]``. If the time
+ is given with a prefix of ``+`` or ``-``, the seek is relative from the start
+ or end of the file.
+
+ ``pp%`` seeks to percent position pp (0-100).
+
+ ``#c`` seeks to chapter number c. (Chapters start from 1.)
+
+ .. admonition:: Examples
+
+ ``--start=+56``, ``--start=+00:56``
+ Seeks to the start time + 56 seconds.
+ ``--start=-56``, ``--start=-00:56``
+ Seeks to the end time - 56 seconds.
+ ``--start=01:10:00``
+ Seeks to 1 hour 10 min.
+ ``--start=50%``
+ Seeks to the middle of the file.
+ ``--start=30 --end=40``
+ Seeks to 30 seconds, plays 10 seconds, and exits.
+ ``--start=-3:20 --length=10``
+ Seeks to 3 minutes and 20 seconds before the end of the file, plays
+ 10 seconds, and exits.
+ ``--start='#2' --end='#4'``
+ Plays chapters 2 and 3, and exits.
+
+``--end=<time>``
+ Stop at given absolute time. Use ``--length`` if the time should be relative
+ to ``--start``. See ``--start`` for valid option values and examples.
+
+``--length=<relative time>``
+ Stop after a given time relative to the start time.
+ See ``--start`` for valid option values and examples.
+
+``--speed=<0.01-100>``
+ Slow down or speed up playback by the factor given as parameter.
+
+``--loop=<N|inf|no>``
+ Loops playback ``N`` times. A value of ``1`` plays it one time (default),
+ ``2`` two times, etc. ``inf`` means forever. ``no`` is the same as ``1`` and
+ disables looping. If several files are specified on command line, the
+ entire playlist is looped.
+
+``--pause``
+ Start the player in paused state.
+
+``--shuffle``
+ Play files in random order.
+
+``--chapter=<start[-end]>``
+ Specify which chapter to start playing at. Optionally specify which
+ chapter to end playing at. Also see ``--start``.
+
+``--playlist=<filename>``
+ Play files according to a playlist file (Supports some common formats.If
+ no format is detected, t will be treated as list of files, separated by
+ newline characters. Note that XML playlist formats are not supported.)
+
+ .. warning::
+
+ The way mpv uses playlist files is not safe against maliciously
+ constructed files. Such files may trigger harmful actions.
+ This has been the case for all mpv and MPlayer versions, but
+ unfortunately this fact was not well documented earlier, and some people
+ have even misguidedly recommended use of ``--playlist`` with untrusted
+ sources. Do NOT use ``--playlist`` with random internet sources or files
+ you do not trust!
+
+ The main problem is that playlists can point to arbitrary network
+ addresses (including local addresses inside of your LAN), and thus
+ can't be considered secure. Playlists also can contain entries using
+ other protocols, such as local files, or (most severely), special
+ protocols like ``avdevice://``, which are inherently unsafe.
+
+``--chapter-merge-threshold=<number>``
+ Threshold for merging almost consecutive ordered chapter parts in
+ milliseconds (default: 100). Some Matroska files with ordered chapters
+ have inaccurate chapter end timestamps, causing a small gap between the
+ end of one chapter and the start of the next one when they should match.
+ If the end of one playback part is less than the given threshold away from
+ the start of the next one then keep playing video normally over the
+ chapter change instead of doing a seek.
+
+``--chapter-seek-threshold=<seconds>``
+ Distance in seconds from the beginning of a chapter within which a backward
+ chapter seek will go to the previous chapter (default: 5.0). Past this
+ threshold, a backward chapter seek will go to the beginning of the current
+ chapter instead. A negative value means always go back to the previous
+ chapter.
+
+``--hr-seek=<no|absolute|yes>``
+ Select when to use precise seeks that are not limited to keyframes. Such
+ seeks require decoding video from the previous keyframe up to the target
+ position and so can take some time depending on decoding performance. For
+ some video formats, precise seeks are disabled. This option selects the
+ default choice to use for seeks; it is possible to explicitly override that
+ default in the definition of key bindings and in slave mode commands.
+
+ :no: Never use precise seeks.
+ :absolute: Use precise seeks if the seek is to an absolute position in the
+ file, such as a chapter seek, but not for relative seeks like
+ the default behavior of arrow keys (default).
+ :yes: Use precise seeks whenever possible.
+
+``--hr-seek-demuxer-offset=<seconds>``
+ This option exists to work around failures to do precise seeks (as in
+ ``--hr-seek``) caused by bugs or limitations in the demuxers for some file
+ formats. Some demuxers fail to seek to a keyframe before the given target
+ position, going to a later position instead. The value of this option is
+ subtracted from the time stamp given to the demuxer. Thus, if you set this
+ option to 1.5 and try to do a precise seek to 60 seconds, the demuxer is
+ told to seek to time 58.5, which hopefully reduces the chance that it
+ erroneously goes to some time later than 60 seconds. The downside of
+ setting this option is that precise seeks become slower, as video between
+ the earlier demuxer position and the real target may be unnecessarily
+ decoded.
+
+``--hr-seek-framedrop=<yes|no>``
+ Allow the video decoder to drop frames during seek, if these frames are
+ before the seek target. If this is enabled, precise seeking can be faster,
+ but if you're using video filters which modify timestamps or add new
+ frames, it can lead to precise seeking skipping the target frame. This
+ e.g. can break frame backstepping when deinterlacing is enabled.
+
+ Default: ``yes``
+
+``--index=<mode>``
+ Controls how to seek in files. Note that if the index is missing from a
+ file, it will be built on the fly by default, so you don't need to change
+ this. But it might help with some broken files.
+
+ :default: use an index if the file has one, or build it if missing
+ :recreate: don't read or use the file's index
+
+ .. note::
+
+ This option only works if the underlying media supports seeking
+ (i.e. not with stdin, pipe, etc).
+
+``--load-unsafe-playlists``
+ Normally, something like ``mpv playlist.m3u`` won't load the playlist. This
+ is because the playlist code is unsafe. (This is the same in all other
+ variations of MPlayer.)
+
+ See ``--playlist`` for details.
+
+ Note: this option will allow opening playlists using the ``playlist``
+ special demuxer. The ``--playlist`` uses different code, and supports more
+ playlist formats than the playlist demuxer. This means that for now, the
+ ``--playlist`` option should always be used if you intend to open playlists.
+ Background: the special demuxer contains newly written code, while the
+ ``--playlist`` option uses the old MPlayer code. Adding support for more
+ playlist formats to the special demuxer is work in progress, and eventually
+ the old code should disappear.
+
+``--loop-file``
+ Loop a single file. The difference to ``--loop=inf`` is that this doesn't
+ loop the playlist, just the file itself. If the playlist contains only a
+ single file, the difference between the two option is that this option
+ performs a seek on loop, instead of reloading the file.
+
+``--ordered-chapters``, ``--no-ordered-chapters``
+ Enabled by default.
+ Disable support for Matroska ordered chapters. mpv will not load or
+ search for video segments from other files, and will also ignore any
+ chapter order specified for the main file.
+
+``--ordered-chapters-files=<playlist-file>``
+ Loads the given file as playlist, and tries to use the files contained in
+ it as reference files when opening a Matroska file that uses ordered
+ chapters. This overrides the normal mechanism for loading referenced
+ files by scanning the same directory the main file is located in.
+
+ Useful for loading ordered chapter files that are not located on the local
+ filesystem, or if the referenced files are in different directories.
+
+ Note: a playlist can be as simple as a text file containing filenames
+ separated by newlines.
+
+``--sstep=<sec>``
+ Skip <sec> seconds after every frame.
+
+ .. note::
+
+ Without ``--hr-seek``, skipping will snap to keyframes.
+
+
+Program Behaviour
+-----------------
+
+``--help``
+ Show short summary of options.
+
+``-v``
+ Increment verbosity level, one level for each ``-v`` found on the command
+ line.
+
+``--version, -V``
+ Print version string and exit.
+
+``--no-config``
+ Do not load default configuration files. This prevents loading of
+ ``~/.config/mpv/mpv.conf`` and ``~/.config/mpv/input.conf``, as well as
+ loading the same files from system wide configuration directories. Other
+ configuration files are blocked as well, such as resume playback files.
+
+ .. note::
+
+ Files explicitly requested by command line options, like
+ ``--include`` or ``--use-filedir-conf``, will still be loaded.
+
+ Also see ``--config-dir``.
+
+``--list-options``
+ Prints all available options.
+
+``--list-properties``
+ Print a list of the available properties.
+
+``--list-protocols``
+ Print a list of the supported protocols.
+
+``--config-dir=<path>``
+ Force a different configuration directory. If this is set, the given
+ directory is used to load configuration files, and all other configuration
+ directories are ignored. This means the global mpv configuration directory
+ as well as per-user directories are ignored, and overrides through
+ environment variables (``MPV_HOME``) are also ignored.
+
+ Note that the ``--no-config`` option takes precedence over this option.
+
+``--save-position-on-quit``
+ Always save the current playback position on quit. When this file is
+ played again later, the player will seek to the old playback position on
+ start. This does not happen if playback of a file is stopped in any other
+ way than quitting. For example, going to the next file in the playlist
+ will not save the position, and start playback at beginning the next time
+ the file is played.
+
+ This behavior is disabled by default, but is always available when quitting
+ the player with Shift+Q.
+
+``--dump-stats=<filename>``
+ Write certain statistics to the given file. The file is truncated on
+ opening. The file will contain raw samples, each with a timestamp. To
+ make this file into a readable, the script ``TOOLS/stats-conv.py`` can be
+ used (which currently displays it as a graph).
+
+ This option is useful for debugging only.
+
+``--idle``
+ Makes mpv wait idly instead of quitting when there is no file to play.
+ Mostly useful in slave mode, where mpv can be controlled through input
+ commands (see also ``--slave-broken``).
+
+``--include=<configuration-file>``
+ Specify configuration file to be parsed after the default ones.
+
+``--load-scripts=<yes|no>``
+ If set to ``no``, don't auto-load scripts from ``~/.mpv/lua/``.
+ (Default: ``yes``)
+
+``--lua=<filename>``
+ Load a Lua script. You can load multiple scripts by separating them with
+ commas (``,``).
+
+``--lua-opts=key1=value1,key2=value2,...``
+ Set options for scripts. A Lua script can query an option by key. If an
+ option is used and what semantics the option value has depends entirely on
+ the loaded Lua scripts. Values not claimed by any scripts are ignored.
+
+``--merge-files``
+ Pretend that all files passed to mpv are concatenated into a single, big
+ file. This uses timeline/EDL support internally. Note that this won't work
+ for ordered chapter files or quvi-resolved URLs (such as youtube links).
+
+ This option is interpreted at program start, and doesn't affect for
+ example files or playlists loaded with the ``loadfile`` or ``loadlist``
+ commands.
+
+``--no-resume-playback``
+ Do not restore playback position from ``~/.mpv/watch_later/``.
+ See ``quit_watch_later`` input command.
+
+``--profile=<profile1,profile2,...>``
+ Use the given profile(s), ``--profile=help`` displays a list of the
+ defined profiles.
+
+``--reset-on-next-file=<all|option1,option2,...>``
+ Normally, mpv will try to keep all settings when playing the next file on
+ the playlist, even if they were changed by the user during playback. (This
+ behavior is the opposite of MPlayer's, which tries to reset all settings
+ when starting next file.)
+
+ Default: Do not reset anything.
+
+ This can be changed with this option. It accepts a list of options, and
+ mpv will reset the value of these options on playback start to the initial
+ value. The initial value is either the default value, or as set by the
+ config file or command line.
+
+ In some cases, this might not work as expected. For example, ``--volume``
+ will only be reset if it is explicitly set in the config file or the
+ command line.
+
+ The special name ``all`` resets as many options as possible.
+
+ .. admonition:: Examples
+
+ - ``--reset-on-next-file=pause``
+ Reset pause mode when switching to the next file.
+ - ``--reset-on-next-file=fullscreen,speed``
+ Reset fullscreen and playback speed settings if they were changed
+ during playback.
+ - ``--reset-on-next-file=all``
+ Try to reset all settings that were changed during playback.
+
+``--write-filename-in-watch-later-config``
+ Prepend the watch later config files with the name of the file they refer
+ to. This is simply written as comment on the top of the file.
+
+ .. warning::
+
+ This option may expose privacy-sensitive information and is thus
+ disabled by default.
+
+``--show-profile=<profile>``
+ Show the description and content of a profile.
+
+``--use-filedir-conf``
+ Look for a file-specific configuration file in the same directory as the
+ file that is being played. See `File-specific Configuration Files`_.
+
+ .. warning::
+
+ May be dangerous if playing from untrusted media.
+
+
+Video
+-----
+
+``--vo=<driver1[:suboption1[=value]:...],driver2,...[,]>``
+ Specify a priority list of video output drivers to be used. For
+ interactive use, one would normally specify a single one to use, but in
+ configuration files, specifying a list of fallbacks may make sense. See
+ `VIDEO OUTPUT DRIVERS`_ for details and descriptions of available drivers.
+
+``--vd=<[+|-]family1:(*|decoder1),[+|-]family2:(*|decoder2),...[-]>``
+ Specify a priority list of video decoders to be used, according to their
+ family and name. See ``--ad`` for further details. Both of these options
+ use the same syntax and semantics; the only difference is that they
+ operate on different codec lists.
+
+ .. note::
+
+ See ``--vd=help`` for a full list of available decoders.
+
+``--vf=<filter1[=parameter1:parameter2:...],filter2,...>``
+ Specify a list of video filters to apply to the video stream. See
+ `VIDEO FILTERS`_ for details and descriptions of the available filters.
+ The option variants ``--vf-add``, ``--vf-pre``, ``--vf-del`` and
+ ``--vf-clr`` exist to modify a previously specified list, but you
+ should not need these for typical use.
+
+``--no-video``
+ Do not play video. With some demuxers this may not work. In those cases
+ you can try ``--vo=null`` instead.
+
+``--untimed``
+ Do not sleep when outputting video frames. Useful for benchmarks when used
+ with ``--no-audio.``
+
+``--framedrop=<no|yes>``
+ Skip displaying some frames to maintain A/V sync on slow systems. Video
+ filters are not applied to such frames. For B-frames even decoding is
+ skipped completely. May produce unwatchably choppy output.
+
+ The ``--vd-lavc-framedrop`` option controls what frames to drop.
+
+ .. note::
+
+ Practical use of this feature is questionable. Disabled by default.
+
+``--hwdec=<api>``
+ Specify the hardware video decoding API that should be used if possible.
+ Whether hardware decoding is actually done depends on the video codec. If
+ hardware decoding is not possible, mpv will fall back on software decoding.
+
+ ``<api>`` can be one of the following:
+
+ :no: always use software decoding (default)
+ :auto: see below
+ :vdpau: requires ``--vo=vdpau`` or ``--vo=opengl`` (Linux only)
+ :vaapi: requires ``--vo=opengl`` or ``--vo=vaapi`` (Linux with Intel GPUs only)
+ :vaapi-copy: copies video back into system RAM (Linux with Intel GPUs only)
+ :vda: requires ``--vo=opengl`` or ``--vo=corevideo`` (OSX only)
+
+ ``auto`` tries to automatically enable hardware decoding using the first
+ available method. This still depends what VO you are using. For example,
+ if you are not using ``--vo=vdpau``, vdpau decoding will never be enabled.
+ Also note that if the first found method doesn't actually work, it will
+ always fall back to software decoding, instead of trying the next method.
+
+ The ``vaapi-copy`` function allows you to use vaapi with any VO. Because
+ this copies the decoded video back to system RAM, it's quite inefficient.
+
+ .. note::
+
+ When using this switch, hardware decoding is still only done for some
+ codecs. See ``--hwdec-codecs`` to enable hardware decoding for more
+ codecs.
+
+``--panscan=<0.0-1.0>``
+ Enables pan-and-scan functionality (cropping the sides of e.g. a 16:9
+ video to make it fit a 4:3 display without black bands). The range
+ controls how much of the image is cropped. May not work with all video
+ output drivers.
+
+``--video-aspect=<ratio>``
+ Override video aspect ratio, in case aspect information is incorrect or
+ missing in the file being played. See also ``--no-video-aspect``.
+
+ Two values have special meaning:
+
+ :0: disable aspect ratio handling, pretend the video has square pixels
+ :-1: use the video stream or container aspect (default)
+
+ But note that handling of these special values might change in the future.
+
+ .. admonition:: Examples
+
+ - ``--video-aspect=4:3`` or ``--video-aspect=1.3333``
+ - ``--video-aspect=16:9`` or ``--video-aspect=1.7777``
+
+``--no-video-aspect``
+ Ignore aspect ratio information from video file and assume the video has
+ square pixels. See also ``--video-aspect``.
+
+``--video-unscaled``
+ Disable scaling of the video. If the window is larger than the video,
+ black bars are added. Otherwise, the video is cropped. The video still
+ can be influenced by the other ``--video-...`` options. (If the
+ ``--video-zoom`` option is set to a value other than ``1``, scaling is
+ enabled, but the video isn't automatically scaled to the window size.)
+
+ The video and monitor aspects aspect will be ignored. Aspect correction
+ would require to scale the video in the X or Y direction, but this option
+ disables scaling, disabling all aspect correction.
+
+ Note that the scaler algorithm may still be used, even if the video isn't
+ scaled. For example, this can influence chroma conversion.
+
+ This option is disabled if the ``--no-keepaspect`` option is used.
+
+``--video-pan-x=<value>``, ``--video-pan-y=<value>``
+ Moves the displayed video rectangle by the given value in the X or Y
+ direction. The unit is in fractions of the size of the scaled video (the
+ full size, even if parts of the video are not visible due to panscan or
+ other options).
+
+ For example, displaying a 1280x720 video fullscreen on a 1680x1050 screen
+ with ``--video-pan-x=-0.1`` would move the video 168 pixels to the left
+ (making 128 pixels of the source video invisible).
+
+ This option is disabled if the ``--no-keepaspect`` option is used.
+
+``--video-rotate=<0-359|no>``
+ Rotate the video clockwise, in degrees. Currently supports 90° steps only.
+ If ``no`` is given, the video is never rotated, even if the file has
+ rotation metadata. (The rotation value is added to the rotation metadata,
+ which means the value ``0`` would rotate the video according to the
+ rotation metadata.)
+
+``--video-zoom=<value>``
+ Adjust the video display scale factor by the given value. The unit is in
+ fractions of the (scaled) window video size.
+
+ For example, given a 1280x720 video shown in a 1280x720 window,
+ ``--video-zoom=-0.1`` would make the video by 128 pixels smaller in
+ X direction, and 72 pixels in Y direction.
+
+ This option is disabled if the ``--no-keepaspect`` option is used.
+
+``--video-align-x=<-1-1>``, ``--video-align-y=<-1-1>``
+ Moves the video rectangle within the black borders, which are usually added
+ to pad the video to screen if video and screen aspect ratios are different.
+ ``--video-align-y=-1`` would move the video to the top of the screen
+ (leaving a border only on the bottom), a value of ``0`` centers it
+ (default), and a value of ``1`` would put the video at the bottom of the
+ screen.
+
+ If video and screen aspect match perfectly, these options do nothing.
+
+ This option is disabled if the ``--no-keepaspect`` option is used.
+
+``--correct-pts``, ``--no-correct-pts``
+ ``--no-correct-pts`` switches mpv to a mode where video timing is
+ determined using a fixed framerate value (either using the ``--fps``
+ option, or using file information). Sometimes, files with very broken
+ timestamps can be played somewhat well in this mode. Note that video
+ filters, subtitle rendering and audio synchronization can be completely
+ broken in this mode.
+
+``--fps=<float>``
+ Override video framerate. Useful if the original value is wrong or missing.
+
+ .. note::
+
+ Works in ``--no-correct-pts`` mode only.
+
+``--deinterlace=<yes|no|auto>``
+ Enable or disable interlacing (default: auto, which usually means no).
+ Interlaced video shows ugly comb-like artifacts, which are visible on
+ fast movement. Enabling this typically inserts the yadif video filter in
+ order to deinterlace the video, or lets the video output apply deinterlacing
+ if supported.
+
+ This behaves exactly like the ``deinterlace`` input property (usually
+ mapped to ``Shift+D``).
+
+ ``auto`` is a technicality. Strictly speaking, the default for this option
+ is deinterlacing disabled, but the ``auto`` case is needed if ``yadif`` was
+ added to the filter chain manually with ``--vf``. Then the core shouldn't
+ disable deinterlacing just because the ``--deinterlace`` was not set.
+
+``--field-dominance=<auto|top|bottom>``
+ Set first field for interlaced content. Useful for deinterlacers that
+ double the framerate: ``--vf=yadif=field`` and ``--vo=vdpau:deint``.
+
+ :auto: (default) If the decoder does not export the appropriate
+ information, it falls back on ``top`` (top field first).
+ :top: top field first
+ :bottom: bottom field first
+
+``--frames=<number>``
+ Play/convert only first ``<number>`` video frames, then quit.
+
+ ``--frames=0`` loads the file, but immediately quits before initializing
+ playback. (Might be useful for scripts which just want to determine some
+ file properties.)
+
+ For audio-only playback, any value greater than 0 will quit playback
+ immediately after initialization. The value 0 works as with video.
+
+``--hwdec-codecs=<codec1,codec2,...|all>``
+ Allow hardware decoding for a given list of codecs only. The special value
+ ``all`` always allows all codecs.
+
+ You can get the list of allowed codecs with ``mpv --vd=help``. Remove the
+ prefix, e.g. instead of ``lavc:h264`` use ``h264``.
+
+ By default this is set to ``h264,vc1,wmv3``. Note that the hardware
+ acceleration special codecs like ``h264_vdpau`` are not relevant anymore,
+ and in fact have been removed from Libav in this form.
+
+ This is usually only needed with broken GPUs, where a codec is reported
+ as supported, but decoding causes more problems than it solves.
+
+ .. admonition:: Example
+
+ ``mpv --hwdec=vdpau --vo=vdpau --hwdec-codecs=h264,mpeg2video``
+ Enable vdpau decoding for h264 and mpeg2 only.
+
+``--quvi-format=<best|default|...>``
+ Video format/quality that is directly passed to libquvi (default: ``best``).
+ This is used when opening links to streaming sites like YouTube. The
+ interpretation of this value is highly specific to the streaming site and
+ the video.
+
+ libquvi 0.4.x:
+
+ The only well-defined values that work on all sites are ``best``
+ (best quality/highest bandwidth, default), and ``default`` (lowest
+ quality).
+
+ The quvi command line tool can be used to find out which formats are
+ supported for a given URL: ``quvi --query-formats URL``.
+
+ libquvi 0.9.x:
+
+ The following explanations are relevant:
+ `<http://quvi.sourceforge.net/r/api/0.9/glossary_termino.html#m_stream_id>`_
+
+ The ``quvi-format`` property can be used at runtime to cycle through the
+ list of formats. Unfortunately, this is slow. On libquvi 0.4.x, this
+ functionality is limited to switching between ``best`` and ``default`` if
+ the ``cycle`` input command is used.
+
+``--vd-lavc-check-hw-profile=<yes|no>``
+ Check hardware decoder profile (default: yes). If ``no`` is set, the
+ highest profile of the hardware decoder is unconditionally selected, and
+ decoding is forced even if the profile of the video is higher than that.
+ The result is most likely broken decoding, but may also help if the
+ detected or reported profiles are somehow incorrect.
+
+``--vd-lavc-bitexact``
+ Only use bit-exact algorithms in all decoding steps (for codec testing).
+
+``--vd-lavc-fast`` (MPEG-2, MPEG-4, and H.264 only)
+ Enable optimizations which do not comply with the format specification and
+ potentially cause problems, like simpler dequantization, simpler motion
+ compensation, assuming use of the default quantization matrix, assuming YUV
+ 4:2:0 and skipping a few checks to detect damaged bitstreams.
+
+``--vd-lavc-o=<key>=<value>[,<key>=<value>[,...]]``
+ Pass AVOptions to libavcodec decoder. Note, a patch to make the ``o=``
+ unneeded and pass all unknown options through the AVOption system is
+ welcome. A full list of AVOptions can be found in the FFmpeg manual.
+
+ Some options which used to be direct options can be set with this
+ mechanism, like ``bug``, ``gray``, ``idct``, ``ec``, ``vismv``,
+ ``skip_top`` (was ``st``), ``skip_bottom`` (was ``sb``), ``debug``.
+
+ .. admonition:: Example
+
+ ``--vd--lavc-o=debug=pict``
+
+``--vd-lavc-show-all=<yes|no>``
+ Show even broken/corrupt frames (default: no). If this option is set to
+ no, libavcodec won't output frames that were either decoded before an
+ initial keyframe was decoded, or frames that are recognized as corrupted.
+
+``--vd-lavc-skiploopfilter=<skipvalue> (H.264 only)``
+ Skips the loop filter (AKA deblocking) during H.264 decoding. Since
+ the filtered frame is supposed to be used as reference for decoding
+ dependent frames, this has a worse effect on quality than not doing
+ deblocking on e.g. MPEG-2 video. But at least for high bitrate HDTV,
+ this provides a big speedup with little visible quality loss.
+
+ ``<skipvalue>`` can be one of the following:
+
+ :none: Never skip.
+ :default: Skip useless processing steps (e.g. 0 size packets in AVI).
+ :nonref: Skip frames that are not referenced (i.e. not used for
+ decoding other frames, the error cannot "build up").
+ :bidir: Skip B-Frames.
+ :nonkey: Skip all frames except keyframes.
+ :all: Skip all frames.
+
+``--vd-lavc-skipidct=<skipvalue> (MPEG-1/2 only)``
+ Skips the IDCT step. This degrades quality a lot in almost all cases
+ (see skiploopfilter for available skip values).
+
+``--vd-lavc-skipframe=<skipvalue>``
+ Skips decoding of frames completely. Big speedup, but jerky motion and
+ sometimes bad artifacts (see skiploopfilter for available skip values).
+
+``--vd-lavc-framedrop=<skipvalue>``
+ Set framedropping mode used with ``--framedrop`` (see skiploopfilter for
+ available skip values).
+
+``--vd-lavc-threads=<0-16>``
+ Number of threads to use for decoding. Whether threading is actually
+ supported depends on codec. 0 means autodetect number of cores on the
+ machine and use that, up to the maximum of 16 (default: 0).
+
+
+
+Audio
+-----
+
+``--ao=<driver1[:suboption1[=value]:...],driver2,...[,]>``
+ Specify a priority list of audio output drivers to be used. For
+ interactive use one would normally specify a single one to use, but in
+ configuration files specifying a list of fallbacks may make sense. See
+ `AUDIO OUTPUT DRIVERS`_ for details and descriptions of available drivers.
+
+``--af=<filter1[=parameter1:parameter2:...],filter2,...>``
+ Specify a list of audio filters to apply to the audio stream. See
+ `AUDIO FILTERS`_ for details and descriptions of the available filters.
+ The option variants ``--af-add``, ``--af-pre``, ``--af-del`` and
+ ``--af-clr`` exist to modify a previously specified list, but you
+ should not need these for typical use.
+
``--ad=<[+|-]family1:(*|decoder1),[+|-]family2:(*|decoder2),...[-]>``
Specify a priority list of audio decoders to be used, according to their
family and decoder name. Entries like ``family:*`` prioritize all decoders
@@ -28,6 +759,42 @@ OPTIONS
``--ad=help``
List all available decoders.
+``--volume=<-1-100>``
+ Set the startup volume. A value of -1 (the default) will not change the
+ volume. See also ``--softvol``.
+
+``--audio-delay=<sec>``
+ Audio delay in seconds (positive or negative float value). Positive values
+ delay the audio, and negative values delay the video.
+
+``--no-audio``
+ Do not play sound. With some demuxers this may not work. In those cases
+ you can try ``--ao=null`` instead.
+
+``--mute=<auto|yes|no>``
+ Set startup audio mute status. ``auto`` (default) will not change the mute
+ status. Also see ``--volume``.
+
+``--softvol=<mode>``
+ Control whether to use the volume controls of the audio output driver or
+ the internal mpv volume filter.
+
+ :no: prefer audio driver controls, use the volume filter only if
+ absolutely needed
+ :yes: always use the volume filter
+ :auto: prefer the volume filter if the audio driver uses the system mixer
+ (default)
+
+ The intention of ``auto`` is to avoid changing system mixer settings from
+ within mpv with default settings. mpv is a video player, not a mixer panel.
+ On the other hand, mixer controls are enabled for sound servers like
+ PulseAudio, which provide per-application volume.
+
+``--audio-demuxer=<[+]name>``
+ Use this audio demuxer type when using ``--audio-file``. Use a '+' before
+ the name to force it; this will skip some checks. Give the demuxer name as
+ printed by ``--audio-demuxer=help``.
+
``--ad-lavc-ac3drc=<level>``
Select the Dynamic Range Compression level for AC-3 audio streams.
``<level>`` is a float value ranging from 0 to 1, where 0 means no
@@ -66,53 +833,217 @@ OPTIONS
``--dtshd`` and ``--no-dtshd`` are deprecated aliases.
-``--af=<filter1[=parameter1:parameter2:...],filter2,...>``
- Specify a list of audio filters to apply to the audio stream. See
- `AUDIO FILTERS`_ for details and descriptions of the available filters.
- The option variants ``--af-add``, ``--af-pre``, ``--af-del`` and
- ``--af-clr`` exist to modify a previously specified list, but you
- should not need these for typical use.
+``--audio-channels=<number|layout>``
+ Request a channel layout for audio output (default: stereo). This will ask
+ the AO to open a device with the given channel layout. It's up to the AO
+ to accept this layout, or to pick a fallback or to error out if the
+ requested layout is not supported.
-``--aid=<ID|auto|no>``
- Select audio channel. ``auto`` selects the default, ``no`` disables audio.
- See also ``--alang``.
+ The ``--audio-channels`` option either takes a channel number or an explicit
+ channel layout. Channel numbers refer to default layouts, e.g. 2 channels
+ refer to stereo, 6 refers to 5.1.
-``--alang=<languagecode[,languagecode,...]>``
- Specify a priority list of audio languages to use. Different container
- formats employ different language codes. DVDs use ISO 639-1 two-letter
- language codes, Matroska, MPEG-TS and NUT use ISO 639-2 three-letter
- language codes, while OGM uses a free-form identifier. See also ``--aid``.
+ See ``--audio-channels=help`` output for defined default layouts. This also
+ lists speaker names, which can be used to express arbitrary channel
+ layouts (e.g. ``fl-fr-lfe`` is 2.1).
- .. admonition:: Examples
+ You can use ``--audio-channels=empty`` to disable this. In this case, the AO
+ use the channel layout as the audio filter chain indicates.
- ``mpv dvd://1 --alang=hu,en``
- Chooses the Hungarian language track on a DVD and falls back on
- English if Hungarian is not available.
- ``mpv --alang=jpn example.mkv``
- Plays a Matroska file in Japanese.
+ This will also request the channel layout from the decoder. If the decoder
+ does not support the layout, it will fall back to its native channel layout.
+ (You can use ``--ad-lavc-downmix=no`` to make the decoder always output
+ its native layout.) Note that only some decoders support remixing audio.
+ Some that do include AC-3, AAC or DTS audio.
-``--ao=<driver1[:suboption1[=value]:...],driver2,...[,]>``
- Specify a priority list of audio output drivers to be used. For
- interactive use one would normally specify a single one to use, but in
- configuration files specifying a list of fallbacks may make sense. See
- `AUDIO OUTPUT DRIVERS`_ for details and descriptions of available drivers.
+ If the channel layout of the media file (i.e. the decoder) and the AO's
+ channel layout don't match, mpv will attempt to insert a conversion filter.
-``--sub-ass``, ``--no-sub-ass``
- Render ASS subtitles natively (enabled by default).
+``--audio-display=<no|attachment>``
+ Setting this option to ``attachment`` (default) will display image
+ attachments when playing audio files. It will display the first image
+ found, and additional images are available as video tracks.
- If ``--no-sub-ass`` is specified, all tags and style declarations are
- stripped and ignored on display. The subtitle renderer uses the font style
- as specified by the ``--sub-text-`` options instead.
+ Setting this option to ``no`` disables display of video entirely when
+ playing audio files.
+
+ This option has no influence on files with normal video tracks.
+
+``--audio-file=<filename>``
+ Play audio from an external file while viewing a video. Each use of this
+ option will add a new audio track. The details are similar to how
+ ``--sub-file`` works.
+
+``--audio-format=<format>``
+ Select the sample format used for output from the audio filter layer to
+ the sound card. The values that ``<format>`` can adopt are listed below in
+ the description of the ``format`` audio filter.
+
+``--audio-samplerate=<Hz>``
+ Select the output sample rate to be used (of course sound cards have
+ limits on this). If the sample frequency selected is different from that
+ of the current media, the lavrresample audio filter will be inserted into
+ the audio filter layer to compensate for the difference.
+
+``--gapless-audio=<no|yes|weak``
+ Try to play consecutive audio files with no silence or disruption at the
+ point of file change. Default: ``weak``.
+
+ :no: Disable gapless audio.
+ :yes: The audio device is opened using parameters chosen according to the
+ first file played and is then kept open for gapless playback. This
+ means that if the first file for example has a low sample rate, then
+ the following files may get resampled to the same low sample rate,
+ resulting in reduced sound quality. If you play files with different
+ parameters, consider using options such as ``--audio-samplerate``
+ and ``--audio-format`` to explicitly select what the shared output
+ format will be.
+ :weak: Normally, the audio device is kept open (using the format it was
+ first initialized with). If the audio format the decoder output
+ changes, the audio device is closed and reopened. This means that
+ you will normally get gapless audio with files that were encoded
+ using the same settings, but might not be gapless in other cases.
+ (Unlike with ``yes``, you don't have to worry about corner cases
+ like the first file setting a very low quality output format, and
+ ruining the playback of higher quality files that follow.)
.. note::
- Using ``--no-sub-ass`` may lead to incorrect or completely broken
- rendering of ASS/SSA subtitles. It can sometimes be useful to forcibly
- override the styling of ASS subtitles, but should be avoided in general.
+ This feature is implemented in a simple manner and relies on audio
+ output device buffering to continue playback while moving from one file
+ to another. If playback of the new file starts slowly, for example
+ because it is played from a remote network location or because you have
+ specified cache settings that require time for the initial cache fill,
+ then the buffered audio may run out before playback of the new file
+ can start.
+
+``--initial-audio-sync``, ``--no-initial-audio-sync``
+ When starting a video file or after events such as seeking, mpv will by
+ default modify the audio stream to make it start from the same timestamp
+ as video, by either inserting silence at the start or cutting away the
+ first samples. Disabling this option makes the player behave like older
+ mpv versions did: video and audio are both started immediately even if
+ their start timestamps differ, and then video timing is gradually adjusted
+ if necessary to reach correct synchronization later.
+
+``--softvol-max=<10.0-10000.0>``
+ Set the maximum amplification level in percent (default: 200). A value of
+ 200 will allow you to adjust the volume up to a maximum of double the
+ current level. With values below 100 the initial volume (which is 100%)
+ will be above the maximum, which e.g. the OSD cannot display correctly.
+
+ .. admonition:: Note
+
+ The maximum value of ``--volume`` as well as the ``volume`` property
+ is always 100. Likewise, the volume OSD bar always goes from 0 to 100.
+ This means that with ``--softvol-max=200``, ``--volume=100`` sets
+ maximum amplification, i.e. amplify by 200%. The default volume (no
+ change in volume) will be ``50`` in this case.
+
+``--volstep=<0-100>``
+ Set the step size of mixer volume changes in percent of the full range
+ (default: 3).
+
+``--volume-restore-data=<string>``
+ Used internally for use by playback resume (e.g. with ``quit_watch_later``).
+ Restoring value has to be done carefully, because different AOs as well as
+ softvol can have different value ranges, and we don't want to restore
+ volume if setting the volume changes it system wide. The normal options
+ (like ``--volume``) would always set the volume. This option was added for
+ restoring volume in a safer way (by storing the method used to set the
+ volume), and is not generally useful. Its semantics are considered private
+ to mpv.
+
+ Do not use.
+
+
+Subtitles
+---------
+
+``--no-sub``
+ Do not select any subtitle when the file is loaded.
+
+``--sub-demuxer=<[+]name>``
+ Force subtitle demuxer type for ``--sub-file``. Give the demuxer name as
+ printed by ``--sub-demuxer=help``.
+
+``--sub-delay=<sec>``
+ Delays subtitles by ``<sec>`` seconds. Can be negative.
+
+``--sub-file=subtitlefile``
+ Add a subtitle file to the list of external subtitles.
+
+ If you use ``--sub-file`` only once, this subtitle file is displayed by
+ default.
+
+ If ``--sub-file`` is used multiple times, the subtitle to use can be
+ switched at runtime by cycling subtitle tracks. It's possible to show
+ two subtitles at once: use ``--sid`` to select the first subtitle index,
+ and ``--secondary-sid`` to select the second index. (The index is printed
+ on the terminal output after the ``--sid=`` in the list of streams.)
+
+``--secondary-sid=<ID|auto|no>``
+ Select a secondary subtitle stream. This is similar to ``--sid``. If a
+ secondary subtitle is selected, it will be rendered as toptitle (i.e. on
+ the top of the screen) alongside the normal subtitle, and provides a way
+ to render two subtitles at once.
+
+ there are some caveats associated with this feature. For example, bitmap
+ subtitles will always be rendered in their usual position, so selecting a
+ bitmap subtitle as secondary subtitle will result in overlapping subtitles.
+ Secondary subtitles are never shown on the terminal if video is disabled.
.. note::
- Try using ``--ass-style-override=force`` instead.
+ Styling and interpretation of any formatting tags is disabled for the
+ secondary subtitle. Internally, the same mechanism as ``--no-sub-ass``
+ is used to strip the styling.
+
+ .. note::
+
+ If the main subtitle stream contains formatting tags which display the
+ subtitle at the top of the screen, it will overlap with the secondary
+ subtitle. To prevent this, you could use ``--no-sub-ass`` to disable
+ styling in the main subtitle stream.
+
+``--sub-scale=<0-100>``
+ Factor for the text subtitle font size (default: 1).
+
+ .. note::
+
+ This affects ASS subtitles as well, and may lead to incorrect subtitle
+ rendering. Use with care, or use ``--sub-text-font-size`` instead.
+
+``--sub-scale-with-window=yes|no``
+ Make the subtitle font size relative to the window, instead of the video.
+ This is useful if you always want the same font size, even if the video
+ doesn't covert the window fully, e.g. because screen aspect and window
+ aspect mismatch (and the player adds black bars).
+
+ Like ``--sub-scale``, this can break ASS subtitles.
+
+``--embeddedfonts``, ``--no-embeddedfonts``
+ Use fonts embedded in Matroska container files and ASS scripts (default:
+ enabled). These fonts can be used for SSA/ASS subtitle rendering.
+
+``--sub-pos=<0-100>``
+ Specify the position of subtitles on the screen. The value is the vertical
+ position of the subtitle in % of the screen height.
+
+ .. note::
+
+ This affects ASS subtitles as well, and may lead to incorrect subtitle
+ rendering. Use with care, or use ``--sub-text-margin-y`` instead.
+
+``--sub-speed=<0.1-10.0>``
+ Multiply the subtitle event timestamps with the given value. Can be used
+ to fix the playback speed for frame-based subtitle formats. Works for
+ external text subtitles only.
+
+ .. admonition:: Example
+
+ `--sub-speed=25/23.976`` plays frame based subtitles which have been
+ loaded assuming a framerate of 23.976 at 25 FPS.
``--ass-force-style=<[Style.]Param=Value[,...]>``
Override some style or script info parameters.
@@ -228,66 +1159,305 @@ OPTIONS
a subtitle script with another video file. The ``--ass-style-override``
option doesn't affect how this option is interpreted.
-``--audio-channels=<number|layout>``
- Request a channel layout for audio output (default: stereo). This will ask
- the AO to open a device with the given channel layout. It's up to the AO
- to accept this layout, or to pick a fallback or to error out if the
- requested layout is not supported.
+``--quvi-fetch-subtitles=<yes|no>``
+ Toggles fetching of subtitles from streaming sites with libquvi. Disabled
+ by default, because it's unreliable and slow. Note that when enabled,
+ subtitles will always be fetched, even if subtitles are explicitly
+ disabled with ``--no-sub`` (because you might want to enable subtitles
+ at runtime).
- The ``--audio-channels`` option either takes a channel number or an explicit
- channel layout. Channel numbers refer to default layouts, e.g. 2 channels
- refer to stereo, 6 refers to 5.1.
+ Supported when using libquvi 0.9.x.
- See ``--audio-channels=help`` output for defined default layouts. This also
- lists speaker names, which can be used to express arbitrary channel
- layouts (e.g. ``fl-fr-lfe`` is 2.1).
+``--stretch-dvd-subs=<yes|no>``
+ Stretch DVD subtitles when playing anamorphic videos for better looking
+ fonts on badly mastered DVDs. This switch has no effect when the
+ video is stored with square pixels - which for DVD input cannot be the case
+ though.
- You can use ``--audio-channels=empty`` to disable this. In this case, the AO
- use the channel layout as the audio filter chain indicates.
+ Many studios tend to use bitmap fonts designed for square pixels when
+ authoring DVDs, causing the fonts to look stretched on playback on DVD
+ players. This option fixes them, however at the price of possibly
+ misaligning sume subtitles (e.g. sign translations).
- This will also request the channel layout from the decoder. If the decoder
- does not support the layout, it will fall back to its native channel layout.
- (You can use ``--ad-lavc-downmix=no`` to make the decoder always output
- its native layout.) Note that only some decoders support remixing audio.
- Some that do include AC-3, AAC or DTS audio.
+ Disabled by default.
- If the channel layout of the media file (i.e. the decoder) and the AO's
- channel layout don't match, mpv will attempt to insert a conversion filter.
+``--sub-ass``, ``--no-sub-ass``
+ Render ASS subtitles natively (enabled by default).
-``--audio-delay=<sec>``
- Audio delay in seconds (positive or negative float value). Positive values
- delay the audio, and negative values delay the video.
+ If ``--no-sub-ass`` is specified, all tags and style declarations are
+ stripped and ignored on display. The subtitle renderer uses the font style
+ as specified by the ``--sub-text-`` options instead.
-``--audio-demuxer=<[+]name>``
- Use this audio demuxer type when using ``--audio-file``. Use a '+' before
- the name to force it; this will skip some checks. Give the demuxer name as
- printed by ``--audio-demuxer=help``.
+ .. note::
-``--audio-display=<no|attachment>``
- Setting this option to ``attachment`` (default) will display image
- attachments when playing audio files. It will display the first image
- found, and additional images are available as video tracks.
+ Using ``--no-sub-ass`` may lead to incorrect or completely broken
+ rendering of ASS/SSA subtitles. It can sometimes be useful to forcibly
+ override the styling of ASS subtitles, but should be avoided in general.
- Setting this option to ``no`` disables display of video entirely when
- playing audio files.
+ .. note::
- This option has no influence on files with normal video tracks.
+ Try using ``--ass-style-override=force`` instead.
-``--audio-file=<filename>``
- Play audio from an external file while viewing a video. Each use of this
- option will add a new audio track. The details are similar to how
- ``--sub-file`` works.
+``--sub-auto=<no|exact|fuzzy|all>``, ``--no-sub-auto``
+ Load additional subtitle files matching the video filename. The parameter
+ specifies how external subtitle files are matched. ``exact`` is enabled by
+ default.
-``--audio-format=<format>``
- Select the sample format used for output from the audio filter layer to
- the sound card. The values that ``<format>`` can adopt are listed below in
- the description of the ``format`` audio filter.
+ :no: Don't automatically load external subtitle files.
+ :exact: Load the media filename with subtitle file extension (default).
+ :fuzzy: Load all subs containing media filename.
+ :all: Load all subs in the current and ``--sub-paths`` directories.
-``--audio-samplerate=<Hz>``
- Select the output sample rate to be used (of course sound cards have
- limits on this). If the sample frequency selected is different from that
- of the current media, the lavrresample audio filter will be inserted into
- the audio filter layer to compensate for the difference.
+``--sub-codepage=<codepage>``
+ If your system supports ``iconv(3)``, you can use this option to specify
+ the subtitle codepage. By default, ENCA will be used to guess the charset.
+ If mpv is not compiled with ENCA, ``UTF-8:UTF-8-BROKEN`` is the default,
+ which means it will try to use UTF-8, otherwise the ``UTF-8-BROKEN``
+ pseudo codepage (see below).
+
+ The default value for this option is ``auto``, whose actual effect depends
+ on whether ENCA is compiled.
+
+ .. admonition:: Warning
+
+ If you force the charset, even subtitles that are known to be
+ UTF-8 will be recoded, which is perhaps not what you expect. Prefix
+ codepages with ``utf8:`` if you want the codepage to be used only if the
+ input is not valid UTF-8.
+
+ .. admonition:: Examples
+
+ - ``--sub-codepage=utf8:latin2`` Use Latin 2 if input is not UTF-8.
+ - ``--sub-codepage=cp1250`` Always force recoding to cp1250.
+
+ The pseudo codepage ``UTF-8-BROKEN`` is used internally. When it
+ is the codepage, subtitles are interpreted as UTF-8 with "Latin 1" as
+ fallback for bytes which are not valid UTF-8 sequences. iconv is
+ never involved in this mode.
+
+ If the player was compiled with ENCA support, you can control it with the
+ following syntax:
+
+ ``--sub-codepage=enca:<language>:<fallback codepage>``
+
+ Language is specified using a two letter code to help ENCA detect
+ the codepage automatically. If an invalid language code is
+ entered, mpv will complain and list valid languages. (Note
+ however that this list will only be printed when the conversion code is actually
+ called, for example when loading an external subtitle). The
+ fallback codepage is used if autodetection fails. If no fallback
+ is specified, ``UTF-8-BROKEN`` is used.
+
+ .. admonition:: Examples
+
+ - ``--sub-codepage=enca:pl:cp1250`` guess the encoding, assuming the subtitles
+ are Polish, fall back on cp1250
+ - ``--sub-codepage=enca:pl`` guess the encoding for Polish, fall back on UTF-8.
+ - ``--sub-codepage=enca`` try universal detection, fall back on UTF-8.
+
+ If the player was compiled with libguess support, you can use it with:
+
+ ``--sub-codepage=guess:<language>:<fallback codepage>``
+
+ libguess always needs a language. There is no universal detection
+ mode. Use ``--sub-codepage=guess:help`` to get a list of
+ languages subject to the same caveat as with ENCA above.
+
+``--sub-fix-timing``, ``--no-sub-fix-timing``
+ By default, external text subtitles are preprocessed to remove minor gaps
+ or overlaps between subtitles (if the difference is smaller than 200 ms,
+ the gap or overlap is removed). This does not affect image subtitles,
+ subtitles muxed with audio/video, or subtitles in the ASS format.
+
+``--sub-forced-only``
+ Display only forced subtitles for the DVD subtitle stream selected by e.g.
+ ``--slang``.
+
+``--sub-fps=<rate>``
+ Specify the framerate of the subtitle file (default: video fps).
+
+ .. note::
+
+ ``<rate>`` > video fps speeds the subtitles up for frame-based
+ subtitle files and slows them down for time-based ones.
+
+ Also see ``--sub-speed`` option.
+
+``--sub-gauss=<0.0-3.0>``
+ Apply gaussian blur to image subtitles (default: 0). This can help making
+ pixelated DVD/Vobsubs look nicer. A value other than 0 also switches to
+ software subtitle scaling. Might be slow.
+
+ .. note::
+
+ Never applied to text subtitles.
+
+``--sub-gray``
+ Convert image subtitles to grayscale. Can help making yellow DVD/Vobsubs
+ look nicer.
+
+ .. note::
+
+ Never applied to text subtitles.
+
+``--sub-paths=<path1:path2:...>``
+ Specify extra directories to search for subtitles matching the video.
+ Multiple directories can be separated by ":" (";" on Windows).
+ Paths can be relative or absolute. Relative paths are interpreted relative
+ to video file directory.
+
+ .. admonition:: Example
+
+ Assuming that ``/path/to/video/video.avi`` is played and
+ ``--sub-paths=sub:subtitles:/tmp/subs`` is specified, mpv searches for
+ subtitle files in these directories:
+
+ - ``/path/to/video/``
+ - ``/path/to/video/sub/``
+ - ``/path/to/video/subtitles/``
+ - ``/tmp/subs/``
+ - ``~/.mpv/sub/``
+
+``--sub-visibility``, ``--no-sub-visibility``
+ Can be used to disable display of subtitles, but still select and decode
+ them.
+
+
+Window
+------
+
+``--title=<string>``
+ Set the window title. Properties are expanded on playback start.
+ (See `Property Expansion`_.)
+
+ .. warning::
+
+ There is a danger of this causing significant CPU usage, depending on
+ the properties used and the window manager. Changing the window title
+ is often a slow operation, and if the title changes every frame,
+ playback can be ruined.
+
+``--screen=<default|0-32>``
+ In multi-monitor configurations (i.e. a single desktop that spans across
+ multiple displays), this option tells mpv which screen to display the
+ video on.
+
+ .. admonition:: Note (X11)
+
+ This option does not work properly with all window managers. In these
+ cases, you can try to use ``--geometry`` to position the window
+ explicitly. It's also possible that the window manager provides native
+ features to control which screens application windows should use.
+
+ See also ``--fs-screen``.
+
+``--fullscreen``, ``--fs``
+ Fullscreen playback.
+
+``--fs-screen=<all|current|0-32>``
+ In multi-monitor configurations (i.e. a single desktop that spans across
+ multiple displays), this option tells mpv which screen to go fullscreen to.
+ If ``default`` is provided mpv will fallback on using the behaviour
+ depending on what the user provided with the ``screen`` option.
+
+ .. admonition:: Note (X11)
+
+ This option does works properly only with window managers which
+ understand the EWMH ``_NET_WM_FULLSCREEN_MONITORS`` hint.
+
+ .. admonition:: Note (OS X)
+
+ ``all`` does not work on OSX and will behave like ``current``.
+
+ See also ``--screen``.
+
+``--keep-open``
+ Do not terminate when playing or seeking beyond the end of the file.
+ Instead, pause the player. When trying to seek beyond end of the file, the
+ player will pause at an arbitrary playback position (or, in corner cases,
+ not redraw the window at all).
+
+ .. note::
+
+ This option is not respected when using ``--frames``, ``--end``,
+ ``--length``, or when passing a chapter range to ``--chapter``.
+ Explicitly skipping to the next file or skipping beyond the last
+ chapter will terminate playback as well, even if ``--keep-open`` is
+ given.
+
+``--force-window``
+ Create a video output window even if there is no video. This can be useful
+ when pretending that mpv is a GUI application. Currently, the window
+ always has the size 640x480, and is subject to ``--geometry``,
+ ``--autofit``, and similar options.
+
+ .. warning::
+
+ The window is created only after initialization (to make sure default
+ window placement still works if the video size is different from the
+ ``--force-window`` default window size). This can be a problem if
+ initialization doesn't work perfectly, such as when opening URLs with
+ bad network connection, or opening broken video files.
+
+``--ontop``
+ Makes the player window stay on top of other windows.
+
+``--border``, ``--no-border``
+ Play video with window border and decorations. Since this is on by
+ default, use ``--no-border`` to disable the standard window decorations.
+
+``--geometry=<[W[xH]][+-x+-y]>``, ``--geometry=<x:y>``
+ Adjust the initial window position or size. ``W`` and ``H`` set the window
+ size in pixels. ``x`` and ``y`` set the window position, measured in pixels
+ from the top-left corner of the screen to the top-left corner of the image
+ being displayed. If a percentage sign (``%``) is given after the argument,
+ it turns the value into a percentage of the screen size in that direction.
+ Positions are specified similar to the standard X11 ``--geometry`` option
+ format, in which e.g. +10-50 means "place 10 pixels from the left border and
+ 50 pixels from the lower border" and "--20+-10" means "place 20 pixels
+ beyond the right and 10 pixels beyond the top border".
+
+ If an external window is specified using the ``--wid`` option, this
+ option is ignored.
+
+ The coordinates are relative to the screen given with ``--screen`` for the
+ video output drivers that fully support ``--screen``.
+
+ .. note::
+
+ Generally only supported by GUI VOs. Ignored for encoding.
+
+ .. admonition: Note (OS X)
+
+ On Mac OSX the origin of the screen coordinate system is located on the
+ bottom-left corner. For instance, ``0:0`` will place the window at the
+ bottom-left of the screen.
+
+ .. admonition:: Note (X11)
+
+ This option does not work properly with all window managers.
+
+ .. admonition:: Examples
+
+ ``50:40``
+ Places the window at x=50, y=40.
+ ``50%:50%``
+ Places the window in the middle of the screen.
+ ``100%:100%``
+ Places the window at the bottom right corner of the screen.
+ ``50%``
+ Sets the window width to half the screen width. Window height is set
+ so that the window has the video aspect ratio.
+ ``50%x50%``
+ Forces the window width and height to half the screen width and
+ height. Will show black borders to compensate for the video aspect
+ ration (with most VOs and without ``--no-keepaspect``).
+ ``50%+10+10``
+ Sets the window to half the screen widths, and positions it 10
+ pixels below/left of the top left corner of the screen.
+
+ See also ``--autofit`` and ``--autofit-larger`` for fitting the window into
+ a given size without changing aspect ratio.
``--autofit=<[W[xH]]>``
Set the initial window size to a maximum size specified by ``WxH``, without
@@ -343,7 +1513,7 @@ OPTIONS
Specifying ``--autosync=0``, the default, will cause frame timing to be
based entirely on audio delay measurements. Specifying ``--autosync=1``
will do the same, but will subtly change the A/V correction algorithm. An
- uneven video framerate in a movie which plays fine with ``--no-audio`` can
+ uneven video framerate in a video which plays fine with ``--no-audio`` can
often be helped by setting this to an integer value greater than 1. The
higher the value, the closer the timing will be to ``--no-audio``. Try
``--autosync=30`` to smooth out problems with sound drivers which do not
@@ -352,106 +1522,191 @@ OPTIONS
out. This delay in reaction time to sudden A/V offsets should be the only
side-effect of turning this option on, for all sound drivers.
-``--untimed``
- Do not sleep when outputting video frames. Useful for benchmarks when used
- with ``--no-audio.``
+``--cursor-autohide=<number|no|always>``
+ Make mouse cursor automatically hide after given number of milliseconds.
+ ``no`` will disable cursor autohide. ``always`` means the cursor will stay
+ hidden.
-``--bluray-angle=<ID>``
- Some Blu-ray discs contain scenes that can be viewed from multiple angles.
- This option tells mpv which angle to use (default: 1).
+``--cursor-autohide-fs-only``
+ If this option is given, the cursor is always visible in windowed mode. In
+ fullscreen mode, the cursor is shown or hidden according to
+ ``--cursor-autohide``.
-``--bluray-device=<path>``
- (Blu-ray only)
- Specify the Blu-ray disc location. Must be a directory with Blu-ray
- structure.
+``--no-fixed-vo``, ``--fixed-vo``
+ ``--no-fixed-vo`` enforces closing and reopening the video window for
+ multiple files (one (un)initialization for each file).
- .. admonition:: Example
+``--force-rgba-osd-rendering``
+ Change how some video outputs render the OSD and text subtitles. This
+ does not change appearance of the subtitles and only has performance
+ implications. For VOs which support native ASS rendering (like ``vdpau``,
+ ``opengl``, ``direct3d``), this can be slightly faster or slower,
+ depending on GPU drivers and hardware. For other VOs, this just makes
+ rendering slower.
- ``mpv bd:// --bluray-device=/path/to/bd/``
+``--fs-missioncontrol``
+ (OS X only)
+ Use OS X Mission Control's fullscreen feature instead of the custom one
+ provided by mpv. This can potentially break a lot of stuff like
+ ``--geometry`` and is disabled by default. On the other hand it provides
+ a more 'OS X-like' user experience.
-``--border``, ``--no-border``
- Play movie with window border and decorations. Since this is on by
- default, use ``--no-border`` to disable the standard window decorations.
+``--cursor-autohide=<number|no|always>``
+ Make mouse cursor automatically hide after given number of milliseconds.
+ ``no`` will disable cursor autohide. ``always`` means the cursor will stay
+ hidden.
-``--brightness=<-100-100>``
- Adjust the brightness of the video signal (default: 0). Not supported by
- all video output drivers.
+``--cursor-autohide-fs-only``
+ If this option is given, the cursor is always visible in windowed mode. In
+ fullscreen mode, the cursor is shown or hidden according to
+ ``--cursor-autohide``.
-``--cache=<kBytes|no|auto>``
- Set the size of the cache in kilobytes, disable it with ``no``, or
- automatically enable it if needed with ``auto`` (default: ``auto``).
- With ``auto``, the cache will usually be enabled for network streams,
- using the size set by ``--cache-default``.
+``--no-fixed-vo``, ``--fixed-vo``
+ ``--no-fixed-vo`` enforces closing and reopening the video window for
+ multiple files (one (un)initialization for each file).
- May be useful when playing files from slow media, but can also have
- negative effects, especially with file formats that require a lot of
- seeking, such as mp4.
+``--force-rgba-osd-rendering``
+ Change how some video outputs render the OSD and text subtitles. This
+ does not change appearance of the subtitles and only has performance
+ implications. For VOs which support native ASS rendering (like ``vdpau``,
+ ``opengl``, ``direct3d``), this can be slightly faster or slower,
+ depending on GPU drivers and hardware. For other VOs, this just makes
+ rendering slower.
- Note that half the cache size will be used to allow fast seeking back. This
- is also the reason why a full cache is usually reported as 50% full. The
- cache fill display does not include the part of the cache reserved for
- seeking back. Likewise, when starting a file the cache will be at 100%,
- because no space is reserved for seeking back yet.
+``--force-window-position``
+ Forcefully move mpv's video output window to default location whenever
+ there is a change in video parameters, video stream or file. This used to
+ be the default behavior. Currently only affects X11 VOs.
-``--cache-default=<kBytes|no>``
- Set the size of the cache in kilobytes (default: 25000 KB). Using ``no``
- will not automatically enable the cache e.g. when playing from a network
- stream. Note that using ``--cache`` will always override this option.
+``--fs-missioncontrol``
+ (OS X only)
+ Use OS X Mission Control's fullscreen feature instead of the custom one
+ provided by mpv. This can potentially break a lot of stuff like
+ ``--geometry`` and is disabled by default. On the other hand it provides
+ a more 'OS X-like' user experience.
-``--cache-pause-below=<kBytes|no>``
- If the cache size goes below the specified value (in KB), pause and wait
- until the size set by ``--cache-pause-restart`` is reached, then resume
- playback (default: 50). If ``no`` is specified, this behavior is disabled.
+``--heartbeat-cmd=<command>``
+ Command that is executed every 30 seconds during playback via *system()* -
+ i.e. using the shell. The time between the commands can be customized with
+ the ``--heartbeat-interval`` option. The command is not run while playback
+ is paused.
- When the player is paused this way, the status line shows ``Buffering``
- instead of ``Paused``, and the OSD uses a clock symbol instead of the
- normal paused symbol.
+ .. note::
-``--cache-pause-restart=<kBytes>``
- If the cache is paused due to the ``--cache-pause-below`` functionality,
- then the player unpauses as soon as the cache has this much data (in KB).
- (Default: 100)
+ mpv uses this command without any checking. It is your responsibility to
+ ensure it does not cause security problems (e.g. make sure to use full
+ paths if "." is in your path like on Windows). It also only works when
+ playing video (i.e. not with ``--no-video`` but works with
+ ``-vo=null``).
-``--cache-initial=<kBytes>``
- Playback will start when the cache has been filled up with this many
- kilobytes of data (default: 0).
+ This can be "misused" to disable screensavers that do not support the
+ proper X API (see also ``--stop-screensaver``). If you think this is too
+ complicated, ask the author of the screensaver program to support the
+ proper X APIs. Note that the ``--stop-screensaver`` does not influence the
+ heartbeat code at all.
-``--cache-seek-min=<kBytes>``
- If a seek is to be made to a position within ``<kBytes>`` of the cache
- size from the current position, mpv will wait for the cache to be
- filled to this position rather than performing a stream seek (default:
- 500).
+ .. admonition:: Example for xscreensaver
- This matters for small forward seeks. With slow streams (especially http
- streams) there is a tradeoff between skipping the data between current
- position and seek destination, or performing an actual seek. Depending
- on the situation, either of these might be slower than the other method.
- This option allows control over this.
+ ``mpv --heartbeat-cmd="xscreensaver-command -deactivate" file``
-``--cache-file=<path>``
- Create a cache file on the filesystem with the given name. The file is
- always overwritten. When the general cache is enabled, this file cache
- will be used to store whatever is read from the source stream.
+ .. admonition:: Example for GNOME screensaver
- This will always overwrite the cache file, and you can't use an existing
- cache file to resume playback of a stream. (Technically, mpv wouldn't
- even know which blocks in the file are valid and which not.)
+ ``mpv --heartbeat-cmd="gnome-screensaver-command -p" file``
- The resulting file will not necessarily contain all data of the source
- stream. For example, if you seek, the parts that were skipped over are
- never read and consequently are not written to the cache. The skipped over
- parts are filled with zeros. This means that the cache file doesn't
- necessarily correspond to a full download of the source stream.
- Both of these issues could be improved if there is any user interest.
+``--heartbeat-interval=<sec>``
+ Time between ``--heartbeat-cmd`` invocations in seconds (default: 30).
- Also see ``--cache-file-size``.
+ .. note::
-``--cache-file-size=<kBytes>``
- Maximum size of the file created with ``--cache-file``. For read accesses
- above this size, the cache is simply not used.
+ This does not affect the normal screensaver operation in any way.
+
+``--no-keepaspect``, ``--keepaspect``
+ ``--no-keepaspect`` will always stretch the video to window size, and will
+ disable the window manager hints that force the window aspect ratio.
+ (Ignored in fullscreen mode.)
- (Default: 1048576, 1 GB.)
+``--monitoraspect=<ratio>``
+ Set the aspect ratio of your monitor or TV screen. A value of 0 disables a
+ previous setting (e.g. in the config file). Overrides the
+ ``--monitorpixelaspect`` setting if enabled.
+
+ See also ``--monitorpixelaspect`` and ``--video-aspect``.
+
+ .. admonition:: Examples
+
+ - ``--monitoraspect=4:3`` or ``--monitoraspect=1.3333``
+ - ``--monitoraspect=16:9`` or ``--monitoraspect=1.7777``
+
+``--monitorpixelaspect=<ratio>``
+ Set the aspect of a single pixel of your monitor or TV screen (default:
+ 1). A value of 1 means square pixels (correct for (almost?) all LCDs). See
+ also ``--monitoraspect`` and ``--video-aspect``.
+
+``--stop-screensaver``, ``--no-stop-screensaver``
+ Turns off the screensaver (or screen blanker and similar mechanisms) at
+ startup and turns it on again on exit (default: yes). The screensaver is
+ always re-enabled when the player is paused.
+
+ This is not supported on all video outputs or platforms. Sometimes it is
+ implemented, but does not work (happens often on GNOME). You might be able
+ to to work this around using ``--heartbeat-cmd`` instead.
+
+``--wid=<ID>``
+ (X11 and Windows only)
+ This tells mpv to attach to an existing window. The ID is interpreted as
+ "Window" on X11, and as HWND on Windows. If a VO is selected that supports
+ this option, a new window will be created and the given window will be set
+ as parent. The window will always be resized to cover the parent window
+ fully, and will add black bars to compensate for the video aspect ratio.
+
+ See also ``--slave-broken``.
+
+``--no-window-dragging``
+ Don't move the window when clicking on it and moving the mouse pointer.
+
+``--x11-name``
+ Set the window class name for X11-based video output methods.
+
+``--x11-netwm=no``
+ (X11 only)
+ Disable use of the NetWM protocol when switching to or from fullscreen.
+ This may or may not help with broken window managers. This provides some
+ functionality that was implemented by the now removed ``--fstype`` option.
+ Actually, it is not known to the developers to which degree this option
+ was needed, so feedback is welcome.
+
+ By default, NetWM support is autodetected, and using this option forces
+ autodetection to fail.
+
+
+Disc Devices
+------------
+
+``--cdrom-device=<path>``
+ Specify the CD-ROM device (default: ``/dev/cdrom``).
+
+``--dvd-device=<path>``
+ Specify the DVD device or .iso filename (default: ``/dev/dvd``). You can
+ also specify a directory that contains files previously copied directly
+ from a DVD (with e.g. vobcopy).
+
+ .. admonition:: Example
+
+ ``mpv dvd:// --dvd-device=/path/to/dvd/``
+
+``--bluray-device=<path>``
+ (Blu-ray only)
+ Specify the Blu-ray disc location. Must be a directory with Blu-ray
+ structure.
+
+ .. admonition:: Example
+
+ ``mpv bd:// --bluray-device=/path/to/bd/``
+
+``--bluray-angle=<ID>``
+ Some Blu-ray discs contain scenes that can be viewed from multiple angles.
+ This option tells mpv which angle to use (default: 1).
``--cdda-...``
These options can be used to tune the CD Audio reading feature of mpv.
@@ -485,28 +1740,48 @@ OPTIONS
``--cdda-skip=<es|no``
(Never) accept imperfect data reconstruction.
-``--cdrom-device=<path>``
- Specify the CD-ROM device (default: ``/dev/cdrom``).
+``--dvd-speed=<speed>``
+ Try to limit DVD speed (default: 0, no change). DVD base speed is 1385
+ kB/s, so an 8x drive can read at speeds up to 11080 kB/s. Slower speeds
+ make the drive more quiet. For watching DVDs, 2700 kB/s should be quiet and
+ fast enough. mpv resets the speed to the drive default value on close.
+ Values of at least 100 mean speed in kB/s. Values less than 100 mean
+ multiples of 1385 kB/s, i.e. ``--dvd-speed=8`` selects 11080 kB/s.
-``--chapter=<start[-end]>``
- Specify which chapter to start playing at. Optionally specify which
- chapter to end playing at. Also see ``--start``.
+ .. note::
-``--chapter-merge-threshold=<number>``
- Threshold for merging almost consecutive ordered chapter parts in
- milliseconds (default: 100). Some Matroska files with ordered chapters
- have inaccurate chapter end timestamps, causing a small gap between the
- end of one chapter and the start of the next one when they should match.
- If the end of one playback part is less than the given threshold away from
- the start of the next one then keep playing video normally over the
- chapter change instead of doing a seek.
+ You need write access to the DVD device to change the speed.
-``--chapter-seek-threshold=<seconds>``
- Distance in seconds from the beginning of a chapter within which a backward
- chapter seek will go to the previous chapter (default: 5.0). Past this
- threshold, a backward chapter seek will go to the beginning of the current
- chapter instead. A negative value means always go back to the previous
- chapter.
+``--dvd-angle=<ID>``
+ Some DVDs contain scenes that can be viewed from multiple angles.
+ This option tells mpv which angle to use (default: 1).
+
+
+
+Equalizer
+---------
+
+``--brightness=<-100-100>``
+ Adjust the brightness of the video signal (default: 0). Not supported by
+ all video output drivers.
+
+``--contrast=<-100-100>``
+ Adjust the contrast of the video signal (default: 0). Not supported by all
+ video output drivers.
+
+``--saturation=<-100-100>``
+ Adjust the saturation of the video signal (default: 0). You can get
+ grayscale output with this option. Not supported by all video output
+ drivers.
+
+``--gamma=<-100-100>``
+ Adjust the gamma of the video signal (default: 0). Not supported by all
+ video output drivers.
+
+``--hue=<-100-100>``
+ Adjust the hue of the video signal (default: 0). You can get a colored
+ negative of the image with this option. Not supported by all video output
+ drivers.
``--colormatrix=<colorspace>``
Controls the YUV to RGB color space conversion when playing video. There
@@ -602,60 +1877,9 @@ OPTIONS
:BT.709: ITU-R BT.709 (HD) (same primaries as sRGB)
:BT.2020: ITU-R BT.2020 (UHD)
-``--config-dir=<path>``
- Force a different configuration directory. If this is set, the given
- directory is used to load configuration files, and all other configuration
- directories are ignored. This means the global mpv configuration directory
- as well as per-user directories are ignored, and overrides through
- environment variables (``MPV_HOME``) are also ignored.
-
- Note that the ``--no-config`` option takes precedence over this option.
-
-``--contrast=<-100-100>``
- Adjust the contrast of the video signal (default: 0). Not supported by all
- video output drivers.
-
-``--cookies``, ``--no-cookies``
- (network only)
- Support cookies when making HTTP requests. Disabled by default.
-``--cookies-file=<filename>``
- (network only)
- Read HTTP cookies from <filename>. The file is assumed to be in Netscape
- format.
-
-``--correct-pts``, ``--no-correct-pts``
- ``--no-correct-pts`` switches mpv to a mode where video timing is
- determined using a fixed framerate value (either using the ``--fps``
- option, or using file information). Sometimes, files with very broken
- timestamps can be played somewhat well in this mode. Note that video
- filters, subtitle rendering and audio synchronization can be completely
- broken in this mode.
-
-``--cursor-autohide=<number|no|always>``
- Make mouse cursor automatically hide after given number of milliseconds.
- ``no`` will disable cursor autohide. ``always`` means the cursor will stay
- hidden.
-
-``--cursor-autohide-fs-only``
- If this option is given, the cursor is always visible in windowed mode. In
- fullscreen mode, the cursor is shown or hidden according to
- ``--cursor-autohide``.
-
-``--deinterlace=<yes|no|auto>``
- Enable or disable interlacing (default: auto, which usually means no).
- Interlaced video shows ugly comb-like artifacts, which are visible on
- fast movement. Enabling this typically inserts the yadif video filter in
- order to deinterlace the video, or lets the video output apply deinterlacing
- if supported.
-
- This behaves exactly like the ``deinterlace`` input property (usually
- mapped to ``Shift+D``).
-
- ``auto`` is a technicality. Strictly speaking, the default for this option
- is deinterlacing disabled, but the ``auto`` case is needed if ``yadif`` was
- added to the filter chain manually with ``--vf``. Then the core shouldn't
- disable deinterlacing just because the ``--deinterlace`` was not set.
+Demuxer
+-------
``--demuxer=<[+]name>``
Force demuxer type. Use a '+' before the name to force it; this will skip
@@ -778,431 +2002,43 @@ OPTIONS
``--demuxer-rawvideo-size=<value>``
Frame size in bytes when using ``--demuxer=rawvideo``.
-``--dump-stats=<filename>``
- Write certain statistics to the given file. The file is truncated on
- opening. The file will contain raw samples, each with a timestamp. To
- make this file into a readable, the script ``TOOLS/stats-conv.py`` can be
- used (which currently displays it as a graph).
-
- This option is useful for debugging only.
-
-``--dvbin-card=<1-4>``
- Specifies using card number 1-4 (default: 1).
-
-``--dvbin-file=<filename>``
- Instructs mpv to read the channels list from ``<filename>``. Default is
- ``~/.mpv/channels.conf.{sat,ter,cbl,atsc}`` (based on your card type) or
- ``~/.mpv/channels.conf`` as a last resort.
-
-``--dvbin-timeout=<1-30>``
- Maximum number of seconds to wait when trying to tune a frequency before
- giving up (default: 30).
-
-``--dvd-device=<path>``
- Specify the DVD device or .iso filename (default: ``/dev/dvd``). You can
- also specify a directory that contains files previously copied directly
- from a DVD (with e.g. vobcopy).
-
- .. admonition:: Example
-
- ``mpv dvd:// --dvd-device=/path/to/dvd/``
-
-``--dvd-speed=<speed>``
- Try to limit DVD speed (default: 0, no change). DVD base speed is 1385
- kB/s, so an 8x drive can read at speeds up to 11080 kB/s. Slower speeds
- make the drive more quiet. For watching DVDs, 2700 kB/s should be quiet and
- fast enough. mpv resets the speed to the drive default value on close.
- Values of at least 100 mean speed in kB/s. Values less than 100 mean
- multiples of 1385 kB/s, i.e. ``--dvd-speed=8`` selects 11080 kB/s.
-
- .. note::
-
- You need write access to the DVD device to change the speed.
-
-``--dvd-angle=<ID>``
- Some DVDs contain scenes that can be viewed from multiple angles.
- This option tells mpv which angle to use (default: 1).
-
-``--edition=<ID|auto>``
- (Matroska files only)
- Specify the edition (set of chapters) to use, where 0 is the first. If set
- to ``auto`` (the default), mpv will choose the first edition declared as a
- default, or if there is no default, the first edition defined.
-
-``--embeddedfonts``, ``--no-embeddedfonts``
- Use fonts embedded in Matroska container files and ASS scripts (default:
- enabled). These fonts can be used for SSA/ASS subtitle rendering.
-
-``--end=<time>``
- Stop at given absolute time. Use ``--length`` if the time should be relative
- to ``--start``. See ``--start`` for valid option values and examples.
-
-``--field-dominance=<auto|top|bottom>``
- Set first field for interlaced content. Useful for deinterlacers that
- double the framerate: ``--vf=yadif=field`` and ``--vo=vdpau:deint``.
-
- :auto: (default) If the decoder does not export the appropriate
- information, it falls back on ``top`` (top field first).
- :top: top field first
- :bottom: bottom field first
-
-``--no-fixed-vo``, ``--fixed-vo``
- ``--no-fixed-vo`` enforces closing and reopening the video window for
- multiple files (one (un)initialization for each file).
-
-``--force-rgba-osd-rendering``
- Change how some video outputs render the OSD and text subtitles. This
- does not change appearance of the subtitles and only has performance
- implications. For VOs which support native ASS rendering (like ``vdpau``,
- ``opengl``, ``direct3d``), this can be slightly faster or slower,
- depending on GPU drivers and hardware. For other VOs, this just makes
- rendering slower.
-
-``--force-window``
- Create a video output window even if there is no video. This can be useful
- when pretending that mpv is a GUI application. Currently, the window
- always has the size 640x480, and is subject to ``--geometry``,
- ``--autofit``, and similar options.
-
- .. warning::
-
- The window is created only after initialization (to make sure default
- window placement still works if the video size is different from the
- ``--force-window`` default window size). This can be a problem if
- initialization doesn't work perfectly, such as when opening URLs with
- bad network connection, or opening broken video files.
-
-``--force-window-position``
- Forcefully move mpv's video output window to default location whenever
- there is a change in video parameters, video stream or file. This used to
- be the default behavior. Currently only affects X11 VOs.
-
-``--sub-forced-only``
- Display only forced subtitles for the DVD subtitle stream selected by e.g.
- ``--slang``.
-
-``--fps=<float>``
- Override video framerate. Useful if the original value is wrong or missing.
-
- .. note::
-
- Works in ``--no-correct-pts`` mode only.
-
-``--framedrop=<no|yes|hard>``
- Skip displaying some frames to maintain A/V sync on slow systems. Video
- filters are not applied to such frames. For B-frames even decoding is
- skipped completely. May produce unwatchably choppy output. With ``hard``,
- decoding and output of any frame can be skipped, and will lead to an even
- worse playback experience.
-
- .. note::
-
- Practical use of this feature is questionable. Disabled by default.
+``--demuxer-thread=<yes|no>``
+ Run the demuxer in a separate thread, and let it prefetch a certain amount
+ of packets (default: no).
-``--frames=<number>``
- Play/convert only first ``<number>`` video frames, then quit. For audio
- only, run ``<number>`` iteration of the playback loop, which is most likely
- not what you want. (This behavior also applies to the corner case when there
- are fewer video frames than ``<number>``, and audio is longer than the
- video.)
+``--demuxer-readahead-packets=N``
+ If ``--demuxer-thread`` is enabled, this controls how much the demuxer
+ should buffer ahead. If the number of packets in the packet queue exceeds
+ ``--demuxer-readahead-packets``, or the total number of bytes exceeds
+ ``--demuxer-readahead-bytes``, the thread stops reading ahead.
-``--fullscreen``, ``--fs``
- Fullscreen playback.
+ Note that if you set these options near the maximum, you might get a
+ packet queue overflow warning.
-``--fs-screen=<all|current|0-32>``
- In multi-monitor configurations (i.e. a single desktop that spans across
- multiple displays), this option tells mpv which screen to go fullscreen to.
- If ``default`` is provided mpv will fallback on using the behaviour
- depending on what the user provided with the ``screen`` option.
+ See ``--list-options`` for defaults and value range.
- .. admonition:: Note (X11)
+``--demuxer-readahead-bytes=N``
+ See ``--demuxer-readahead-packets``.
- This option does works properly only with window managers which
- understand the EWMH ``_NET_WM_FULLSCREEN_MONITORS`` hint.
- .. admonition:: Note (OS X)
+Input
+-----
- ``all`` does not work on OSX and will behave like ``current``.
-
- See also ``--screen``.
-
-``--fs-missioncontrol``
- (OS X only)
- Use OS X Mission Control's fullscreen feature instead of the custom one
- provided by mpv. This can potentially break a lot of stuff like
- ``--geometry`` and is disabled by default. On the other hand it provides
- a more 'OS X-like' user experience.
-
-``--gamma=<-100-100>``
- Adjust the gamma of the video signal (default: 0). Not supported by all
- video output drivers.
-
-``--gapless-audio=<no|yes|weak``
- Try to play consecutive audio files with no silence or disruption at the
- point of file change. Default: ``weak``.
-
- :no: Disable gapless audio.
- :yes: The audio device is opened using parameters chosen according to the
- first file played and is then kept open for gapless playback. This
- means that if the first file for example has a low sample rate, then
- the following files may get resampled to the same low sample rate,
- resulting in reduced sound quality. If you play files with different
- parameters, consider using options such as ``--audio-samplerate``
- and ``--audio-format`` to explicitly select what the shared output
- format will be.
- :weak: Normally, the audio device is kept open (using the format it was
- first initialized with). If the audio format the decoder output
- changes, the audio device is closed and reopened. This means that
- you will normally get gapless audio with files that were encoded
- using the same settings, but might not be gapless in other cases.
- (Unlike with ``yes``, you don't have to worry about corner cases
- like the first file setting a very low quality output format, and
- ruining the playback of higher quality files that follow.)
-
- .. note::
-
- This feature is implemented in a simple manner and relies on audio
- output device buffering to continue playback while moving from one file
- to another. If playback of the new file starts slowly, for example
- because it is played from a remote network location or because you have
- specified cache settings that require time for the initial cache fill,
- then the buffered audio may run out before playback of the new file
- can start.
-
-``--geometry=<[W[xH]][+-x+-y]>``, ``--geometry=<x:y>``
- Adjust the initial window position or size. ``W`` and ``H`` set the window
- size in pixels. ``x`` and ``y`` set the window position, measured in pixels
- from the top-left corner of the screen to the top-left corner of the image
- being displayed. If a percentage sign (``%``) is given after the argument,
- it turns the value into a percentage of the screen size in that direction.
- Positions are specified similar to the standard X11 ``--geometry`` option
- format, in which e.g. +10-50 means "place 10 pixels from the left border and
- 50 pixels from the lower border" and "--20+-10" means "place 20 pixels
- beyond the right and 10 pixels beyond the top border".
-
- If an external window is specified using the ``--wid`` option, this
- option is ignored.
-
- The coordinates are relative to the screen given with ``--screen`` for the
- video output drivers that fully support ``--screen``.
-
- .. note::
-
- Generally only supported by GUI VOs. Ignored for encoding.
-
- .. admonition: Note (OS X)
-
- On Mac OSX the origin of the screen coordinate system is located on the
- bottom-left corner. For instance, ``0:0`` will place the window at the
- bottom-left of the screen.
-
- .. admonition:: Note (X11)
-
- This option does not work properly with all window managers.
-
- .. admonition:: Examples
-
- ``50:40``
- Places the window at x=50, y=40.
- ``50%:50%``
- Places the window in the middle of the screen.
- ``100%:100%``
- Places the window at the bottom right corner of the screen.
- ``50%``
- Sets the window width to half the screen width. Window height is set
- so that the window has the video aspect ratio.
- ``50%x50%``
- Forces the window width and height to half the screen width and
- height. Will show black borders to compensate for the video aspect
- ration (with most VOs and without ``--no-keepaspect``).
- ``50%+10+10``
- Sets the window to half the screen widths, and positions it 10
- pixels below/left of the top left corner of the screen.
-
- See also ``--autofit`` and ``--autofit-larger`` for fitting the window into
- a given size without changing aspect ratio.
-
-``--heartbeat-cmd=<command>``
- Command that is executed every 30 seconds during playback via *system()* -
- i.e. using the shell. The time between the commands can be customized with
- the ``--heartbeat-interval`` option. The command is not run while playback
- is paused.
-
- .. note::
-
- mpv uses this command without any checking. It is your responsibility to
- ensure it does not cause security problems (e.g. make sure to use full
- paths if "." is in your path like on Windows). It also only works when
- playing video (i.e. not with ``--no-video`` but works with
- ``-vo=null``).
-
- This can be "misused" to disable screensavers that do not support the
- proper X API (see also ``--stop-screensaver``). If you think this is too
- complicated, ask the author of the screensaver program to support the
- proper X APIs. Note that the ``--stop-screensaver`` does not influence the
- heartbeat code at all.
-
- .. admonition:: Example for xscreensaver
-
- ``mpv --heartbeat-cmd="xscreensaver-command -deactivate" file``
-
- .. admonition:: Example for GNOME screensaver
-
- ``mpv --heartbeat-cmd="gnome-screensaver-command -p" file``
-
-
-``--heartbeat-interval=<sec>``
- Time between ``--heartbeat-cmd`` invocations in seconds (default: 30).
-
- .. note::
-
- This does not affect the normal screensaver operation in any way.
-
-``--help``
- Show short summary of options.
-
-``--hr-seek=<no|absolute|yes>``
- Select when to use precise seeks that are not limited to keyframes. Such
- seeks require decoding video from the previous keyframe up to the target
- position and so can take some time depending on decoding performance. For
- some video formats, precise seeks are disabled. This option selects the
- default choice to use for seeks; it is possible to explicitly override that
- default in the definition of key bindings and in slave mode commands.
-
- :no: Never use precise seeks.
- :absolute: Use precise seeks if the seek is to an absolute position in the
- file, such as a chapter seek, but not for relative seeks like
- the default behavior of arrow keys (default).
- :yes: Use precise seeks whenever possible.
-
-``--hr-seek-demuxer-offset=<seconds>``
- This option exists to work around failures to do precise seeks (as in
- ``--hr-seek``) caused by bugs or limitations in the demuxers for some file
- formats. Some demuxers fail to seek to a keyframe before the given target
- position, going to a later position instead. The value of this option is
- subtracted from the time stamp given to the demuxer. Thus, if you set this
- option to 1.5 and try to do a precise seek to 60 seconds, the demuxer is
- told to seek to time 58.5, which hopefully reduces the chance that it
- erroneously goes to some time later than 60 seconds. The downside of
- setting this option is that precise seeks become slower, as video between
- the earlier demuxer position and the real target may be unnecessarily
- decoded.
-
-``--hr-seek-framedrop=<yes|no>``
- Allow the video decoder to drop frames during seek, if these frames are
- before the seek target. If this is enabled, precise seeking can be faster,
- but if you're using video filters which modify timestamps or add new
- frames, it can lead to precise seeking skipping the target frame. This
- e.g. can break frame backstepping when deinterlacing is enabled.
-
- Default: ``yes``
-
-``--http-header-fields=<field1,field2>``
- Set custom HTTP fields when accessing HTTP stream.
-
- .. admonition:: Example
-
- ::
-
- mpv --http-header-fields='Field1: value1','Field2: value2' \
- http://localhost:1234
-
- Will generate HTTP request::
-
- GET / HTTP/1.0
- Host: localhost:1234
- User-Agent: MPlayer
- Icy-MetaData: 1
- Field1: value1
- Field2: value2
- Connection: close
-
-``--hue=<-100-100>``
- Adjust the hue of the video signal (default: 0). You can get a colored
- negative of the image with this option. Not supported by all video output
- drivers.
-
-``--hwdec=<api>``
- Specify the hardware video decoding API that should be used if possible.
- Whether hardware decoding is actually done depends on the video codec. If
- hardware decoding is not possible, mpv will fall back on software decoding.
-
- ``<api>`` can be one of the following:
-
- :no: always use software decoding (default)
- :auto: see below
- :vdpau: requires ``--vo=vdpau`` or ``--vo=opengl`` (Linux only)
- :vaapi: requires ``--vo=opengl`` or ``--vo=vaapi`` (Linux with Intel GPUs only)
- :vaapi-copy: copies video back into system RAM (Linux with Intel GPUs only)
- :vda: requires ``--vo=opengl`` or ``--vo=corevideo`` (OSX only)
-
- ``auto`` tries to automatically enable hardware decoding using the first
- available method. This still depends what VO you are using. For example,
- if you are not using ``--vo=vdpau``, vdpau decoding will never be enabled.
- Also note that if the first found method doesn't actually work, it will
- always fall back to software decoding, instead of trying the next method.
-
- The ``vaapi-copy`` function allows you to use vaapi with any VO. Because
- this copies the decoded video back to system RAM, it's quite inefficient.
-
- .. note::
-
- When using this switch, hardware decoding is still only done for some
- codecs. See ``--hwdec-codecs`` to enable hardware decoding for more
- codecs.
-
-``--hwdec-codecs=<codec1,codec2,...|all>``
- Allow hardware decoding for a given list of codecs only. The special value
- ``all`` always allows all codecs.
-
- You can get the list of allowed codecs with ``mpv --vd=help``. Remove the
- prefix, e.g. instead of ``lavc:h264`` use ``h264``.
-
- By default this is set to ``h264,vc1,wmv3``. Note that the hardware
- acceleration special codecs like ``h264_vdpau`` are not relevant anymore,
- and in fact have been removed from Libav in this form.
-
- This is usually only needed with broken GPUs, where a codec is reported
- as supported, but decoding causes more problems than it solves.
-
- .. admonition:: Example
-
- ``mpv --hwdec=vdpau --vo=vdpau --hwdec-codecs=h264,mpeg2video``
- Enable vdpau decoding for h264 and mpeg2 only.
-
-``--idle``
- Makes mpv wait idly instead of quitting when there is no file to play.
- Mostly useful in slave mode, where mpv can be controlled through input
- commands (see also ``--slave-broken``).
-
-``--index=<mode>``
- Controls how to seek in files. Note that if the index is missing from a
- file, it will be built on the fly by default, so you don't need to change
- this. But it might help with some broken files.
-
- :default: use an index if the file has one, or build it if missing
- :recreate: don't read or use the file's index
-
- .. note::
-
- This option only works if the underlying media supports seeking
- (i.e. not with stdin, pipe, etc).
+``--native-keyrepeat``
+ Use system settings for keyrepeat delay and rate, instead of
+ ``--input-ar-delay`` and ``--input-ar-rate``. (Whether this applies
+ depends on the VO backend and how it handles keyboard input. Does not
+ apply to terminal input.)
-``--include=<configuration-file>``
- Specify configuration file to be parsed after the default ones.
+``--input-ar-delay``
+ Delay in milliseconds before we start to autorepeat a key (0 to disable).
-``--initial-audio-sync``, ``--no-initial-audio-sync``
- When starting a video file or after events such as seeking, mpv will by
- default modify the audio stream to make it start from the same timestamp
- as video, by either inserting silence at the start or cutting away the
- first samples. Disabling this option makes the player behave like older
- mpv versions did: video and audio are both started immediately even if
- their start timestamps differ, and then video timing is gradually adjusted
- if necessary to reach correct synchronization later.
+``--input-ar-rate``
+ Number of key presses to generate per second on autorepeat.
``--input-conf=<filename>``
Specify input configuration file other than the default
- ``~/.mpv/input.conf``.
+ ``~/.config/mpv/input.conf``.
``--no-input-default-bindings``
Disable mpv default (builtin) key bindings.
@@ -1252,12 +2088,6 @@ OPTIONS
``--input-appleremote``, ``--no-input-appleremote``
Enable/disable AppleIR remote support. Enabled by default.
-``--input-ar-delay``
- Delay in milliseconds before we start to autorepeat a key (0 to disable).
-
-``--input-ar-rate``
- Number of key presses to generate per second on autorepeat.
-
``--input-cursor``, ``--no-input-cursor``
Permit mpv to receive pointer events reported by the video output
driver. Necessary to use the OSC, or to select the buttons in DVD menus.
@@ -1284,231 +2114,53 @@ OPTIONS
Use the right Alt key as Alt Gr to produce special characters. If disabled,
count the right Alt as an Alt modifier key. Enabled by default.
-``--no-keepaspect``, ``--keepaspect``
- ``--no-keepaspect`` will always stretch the video to window size, and will
- disable the window manager hints that force the window aspect ratio.
- (Ignored in fullscreen mode.)
-
-``--keep-open``
- Do not terminate when playing or seeking beyond the end of the file.
- Instead, pause the player. When trying to seek beyond end of the file, the
- player will pause at an arbitrary playback position (or, in corner cases,
- not redraw the window at all).
-
- .. note::
-
- This option is not respected when using ``--frames``, ``--end``,
- ``--length``, or when passing a chapter range to ``--chapter``.
- Explicitly skipping to the next file or skipping beyond the last
- chapter will terminate playback as well, even if ``--keep-open`` is
- given.
-
-``--length=<relative time>``
- Stop after a given time relative to the start time.
- See ``--start`` for valid option values and examples.
-
-``--list-options``
- Prints all available options.
-
-``--list-properties``
- Print a list of the available properties.
-
-``--load-scripts=<yes|no>``
- If set to ``no``, don't auto-load scripts from ``~/.mpv/lua/``.
- (Default: ``yes``)
-
-``--load-unsafe-playlists``
- Normally, something like ``mpv playlist.m3u`` won't load the playlist. This
- is because the playlist code is unsafe. (This is the same in all other
- variations of MPlayer.)
-
- See ``--playlist`` for details.
-
- Note: this option will allow opening playlists using the ``playlist``
- special demuxer. The ``--playlist`` uses different code, and supports more
- playlist formats than the playlist demuxer. This means that for now, the
- ``--playlist`` option should always be used if you intend to open playlists.
- Background: the special demuxer contains newly written code, while the
- ``--playlist`` option uses the old MPlayer code. Adding support for more
- playlist formats to the special demuxer is work in progress, and eventually
- the old code should disappear.
-
-``--loop=<N|inf|no>``
- Loops playback ``N`` times. A value of ``1`` plays it one time (default),
- ``2`` two times, etc. ``inf`` means forever. ``no`` is the same as ``1`` and
- disables looping. If several files are specified on command line, the
- entire playlist is looped.
-
-``--loop-file``
- Loop a single file. The difference to ``--loop=inf`` is that this doesn't
- loop the playlist, just the file itself. If the playlist contains only a
- single file, the difference between the two option is that this option
- performs a seek on loop, instead of reloading the file.
-
-``--lua=<filename>``
- Load a Lua script. You can load multiple scripts by separating them with
- commas (``,``).
-
-``--lua-opts=key1=value1,key2=value2,...``
- Set options for scripts. A Lua script can query an option by key. If an
- option is used and what semantics the option value has depends entirely on
- the loaded Lua scripts. Values not claimed by any scripts are ignored.
-
-``--mc=<seconds/frame>``
- Maximum A-V sync correction per frame (in seconds)
-``--merge-files``
- Pretend that all files passed to mpv are concatenated into a single, big
- file. This uses timeline/EDL support internally. Note that this won't work
- for ordered chapter files or quvi-resolved URLs (such as youtube links).
+OSD
+---
- This option is interpreted at program start, and doesn't affect for
- example files or playlists loaded with the ``loadfile`` or ``loadlist``
- commands.
+``--osc``, ``--no-osc``
+ Whether to load the on-screen-controller (default: yes).
-``--mf-fps=<value>``
- Framerate used when decoding from multiple PNG or JPEG files with ``mf://``
- (default: 1).
+``--no-osd-bar``, ``--osd-bar``
+ Disable display of the OSD bar. This will make some things (like seeking)
+ use OSD text messages instead of the bar.
-``--mf-type=<value>``
- Input file type for ``mf://`` (available: jpeg, png, tga, sgi). By default,
- this is guessed from the file extension.
+ You can configure this on a per-command basis in input.conf using ``osd-``
+ prefixes, see ``Input command prefixes``. If you want to disable the OSD
+ completely, use ``--osd-level=0``.
-``--monitoraspect=<ratio>``
- Set the aspect ratio of your monitor or TV screen. A value of 0 disables a
- previous setting (e.g. in the config file). Overrides the
- ``--monitorpixelaspect`` setting if enabled.
+``--osd-duration=<time>``
+ Set the duration of the OSD messages in ms (default: 1000).
- See also ``--monitorpixelaspect`` and ``--video-aspect``.
+``--osd-font=<pattern>``, ``--sub-text-font=<pattern>``
+ Specify font to use for OSD and for subtitles that do not themselves
+ specify a particular font. The default is ``sans-serif``.
.. admonition:: Examples
- - ``--monitoraspect=4:3`` or ``--monitoraspect=1.3333``
- - ``--monitoraspect=16:9`` or ``--monitoraspect=1.7777``
-
-``--monitorpixelaspect=<ratio>``
- Set the aspect of a single pixel of your monitor or TV screen (default:
- 1). A value of 1 means square pixels (correct for (almost?) all LCDs). See
- also ``--monitoraspect`` and ``--video-aspect``.
-
-``--no-msg-color``
- Disable colorful console output on terminals.
-
-``--msg-level=<module1=level1:module2=level2:...>``
- Control verbosity directly for each module. The ``all`` module changes the
- verbosity of all the modules not explicitly specified on the command line.
-
- Run mpv with ``--msg-level=all=trace`` to see all messages mpv outputs. You
- can use the module names printed in the output (prefixed to each line in
- ``[...]``) to limit the output to interesting modules.
-
- .. note::
-
- Some messages are printed before the command line is parsed and are
- therefore not affected by ``--msg-level``. To control these messages,
- you have to use the ``MPV_VERBOSE`` environment variable; see
- `ENVIRONMENT VARIABLES`_ for details.
-
- Available levels:
-
- :no: complete silence
- :fatal: fatal messages only
- :error: error messages
- :warn: warning messages
- :info: informational messages
- :status: status messages (default)
- :v: verbose messages
- :debug: debug messages
- :trace: very noisy debug messages
-
-``--msg-module``
- Prepend module name to each console message.
-
-``--msg-time``
- Prepend timing information to each console message.
-
-``--mute=<auto|yes|no>``
- Set startup audio mute status. ``auto`` (default) will not change the mute
- status. Also see ``--volume``.
-
-``--x11-name``
- Set the window class name for X11-based video output methods.
-
-``--native-keyrepeat``
- Use system settings for keyrepeat delay and rate, instead of
- ``--input-ar-delay`` and ``--input-ar-rate``. (Whether this applies
- depends on the VO backend and how it handles keyboard input. Does not
- apply to terminal input.)
-
-``--no-cache``
- Turn off input stream caching. See ``--cache``.
-
-``--no-config``
- Do not load default configuration files. This prevents loading of
- ``~/.mpv/config`` and ``~/.mpv/input.conf``, as well as loading the
- same files from system wide configuration directories. Other configuration
- files are blocked as well, such as resume playback files.
+ - ``--osd-font='Bitstream Vera Sans'``
+ - ``--osd-font='Bitstream Vera Sans:style=Bold'`` (fontconfig pattern)
.. note::
- Files explicitly requested by command line options, like
- ``--include`` or ``--use-filedir-conf``, will still be loaded.
-
- Also see ``--config-dir``.
-
-``--no-idx``
- Do not use index present in the file even if one is present.
-
-``--no-audio``
- Do not play sound. With some demuxers this may not work. In those cases
- you can try ``--ao=null`` instead.
-
-``--no-resume-playback``
- Do not restore playback position from ``~/.mpv/watch_later/``.
- See ``quit_watch_later`` input command.
-
-``--no-sub``
- Do not select any subtitle when the file is loaded.
-
-``--sub-visibility``, ``--no-sub-visibility``
- Can be used to disable display of subtitles, but still select and decode
- them.
-
-``--no-video``
- Do not play video. With some demuxers this may not work. In those cases
- you can try ``--vo=null`` instead.
-
-``--ontop``
- Makes the player window stay on top of other windows.
-
-``--ordered-chapters``, ``--no-ordered-chapters``
- Enabled by default.
- Disable support for Matroska ordered chapters. mpv will not load or
- search for video segments from other files, and will also ignore any
- chapter order specified for the main file.
-
-``--ordered-chapters-files=<playlist-file>``
- Loads the given file as playlist, and tries to use the files contained in
- it as reference files when opening a Matroska file that uses ordered
- chapters. This overrides the normal mechanism for loading referenced
- files by scanning the same directory the main file is located in.
-
- Useful for loading ordered chapter files that are not located on the local
- filesystem, or if the referenced files are in different directories.
-
- Note: a playlist can be as simple as a text file containing filenames
- separated by newlines.
+ The ``--sub-text-font`` option (and most other ``--sub-text-``
+ options) are ignored when ASS-subtitles are rendered, unless the
+ ``--no-sub-ass`` option is specified.
-``--osc``, ``--no-osc``
- Whether to load the on-screen-controller (default: yes).
+``--osd-font-size=<size>``, ``--sub-text-font-size=<size>``
+ Specify the OSD/sub font size. The unit is the size in scaled pixels at a
+ window height of 720. The actual pixel size is scaled with the window
+ height: if the window height is larger or smaller than 720, the actual size
+ of the text increases or decreases as well.
-``--no-osd-bar``, ``--osd-bar``
- Disable display of the OSD bar. This will make some things (like seeking)
- use OSD text messages instead of the bar.
+ Default: 45.
- You can configure this on a per-command basis in input.conf using ``osd-``
- prefixes, see ``Input command prefixes``. If you want to disable the OSD
- completely, use ``--osd-level=0``.
+``--osd-status-msg=<string>``
+ Show a custom string during playback instead of the standard status text.
+ This overrides the status text used for ``--osd-level=3``, when using the
+ ``show_progress`` command (by default mapped to ``P``), or in some
+ non-default cases when seeking. Expands properties. See
+ `Property Expansion`_.
``--osd-bar-align-x=<-1-1>``
Position of the OSD bar. -1 is far left, 0 is centered, 1 is far right.
@@ -1574,32 +2226,6 @@ OPTIONS
- ``--osd-color='#FF0000'`` set OSD to opaque red
- ``--osd-color='#C0808080'`` set OSD to 50% gray with 75% alpha
-``--osd-duration=<time>``
- Set the duration of the OSD messages in ms (default: 1000).
-
-``--osd-font=<pattern>``, ``--sub-text-font=<pattern>``
- Specify font to use for OSD and for subtitles that do not themselves
- specify a particular font. The default is ``sans-serif``.
-
- .. admonition:: Examples
-
- - ``--osd-font='Bitstream Vera Sans'``
- - ``--osd-font='Bitstream Vera Sans:style=Bold'`` (fontconfig pattern)
-
- .. note::
-
- The ``--sub-text-font`` option (and most other ``--sub-text-``
- options) are ignored when ASS-subtitles are rendered, unless the
- ``--no-sub-ass`` option is specified.
-
-``--osd-font-size=<size>``, ``--sub-text-font-size=<size>``
- Specify the OSD/sub font size. The unit is the size in scaled pixels at a
- window height of 720. The actual pixel size is scaled with the window
- height: if the window height is larger or smaller than 720, the actual size
- of the text increases or decreases as well.
-
- Default: 45.
-
``--osd-fractions``
Show OSD times with fractions of seconds.
@@ -1655,259 +2281,9 @@ OPTIONS
Default: 0.
-``--osd-status-msg=<string>``
- Show a custom string during playback instead of the standard status text.
- This overrides the status text used for ``--osd-level=3``, when using the
- ``show_progress`` command (by default mapped to ``P``), or in some
- non-default cases when seeking. Expands properties. See
- `Property Expansion`_.
-
-``--panscan=<0.0-1.0>``
- Enables pan-and-scan functionality (cropping the sides of e.g. a 16:9
- movie to make it fit a 4:3 display without black bands). The range
- controls how much of the image is cropped. May not work with all video
- output drivers.
-``--pause``
- Start the player in paused state.
-
-``--stream-capture=<filename>``
- Allows capturing the primary stream (not additional audio tracks or other
- kind of streams) into the given file. Capturing can also be started and
- stopped by changing the filename with the ``stream-capture`` slave property.
- Generally this will not produce usable results for anything else than MPEG
- or raw streams, unless capturing includes the file headers and is not
- interrupted. Note that, due to cache latencies, captured data may begin and
- end somewhat delayed compared to what you see displayed.
-
-``--stream-dump=<filename>``
- Same as ``--stream-capture``, but do not start playback. Instead, the entire
- file is dumped.
-
-``--playlist=<filename>``
- Play files according to a playlist file (Supports some common formats.If
- no format is detected, t will be treated as list of files, separated by
- newline characters. Note that XML playlist formats are not supported.)
-
- .. warning::
-
- The way mpv uses playlist files is not safe against maliciously
- constructed files. Such files may trigger harmful actions.
- This has been the case for all mpv and MPlayer versions, but
- unfortunately this fact was not well documented earlier, and some people
- have even misguidedly recommended use of ``--playlist`` with untrusted
- sources. Do NOT use ``--playlist`` with random internet sources or files
- you do not trust!
-
- The main problem is that playlists can point to arbitrary network
- addresses (including local addresses inside of your LAN), and thus
- can't be considered secure. Playlists also can contain entries using
- other protocols, such as local files, or (most severely), special
- protocols like ``avdevice://``, which are inherently unsafe.
-
-``--priority=<prio>``
- (Windows only.)
- Set process priority for mpv according to the predefined priorities
- available under Windows.
-
- Possible values of ``<prio>``:
- idle|belownormal|normal|abovenormal|high|realtime
-
- .. warning:: Using realtime priority can cause system lockup.
-
-``--profile=<profile1,profile2,...>``
- Use the given profile(s), ``--profile=help`` displays a list of the
- defined profiles.
-
-``--pts-association-mode=<decode|sort|auto>``
- Select the method used to determine which container packet timestamp
- corresponds to a particular output frame from the video decoder. Normally
- you should not need to change this option.
-
- :decoder: Use decoder reordering functionality. Unlike in classic MPlayer
- and mplayer2, this includes a dTS fallback. (Default.)
- :sort: Maintain a buffer of unused pts values and use the lowest value
- for the frame.
- :auto: Try to pick a working mode from the ones above automatically.
-
- You can also try to use ``--no-correct-pts`` for files with completely
- broken timestamps.
-
-``--pvr-...``
- These options tune various encoding properties of the PVR capture module.
- It has to be used with any hardware MPEG encoder based card supported by
- the V4L2 driver. The Hauppauge WinTV PVR-150/250/350/500 and all IVTV
- based cards are known as PVR capture cards. Be aware that only Linux
- 2.6.18 kernel and above is able to handle MPEG stream through V4L2 layer.
- For hardware capture of an MPEG stream and watching it with mpv, use
- ``pvr://`` as a movie URL.
-
-
-``--pvr-aspect=<0-3>``
- Specify input aspect ratio:
-
- :0: 1:1
- :1: 4:3 (default)
- :2: 16:9
- :3: 2.21:1
-
-``--pvr-arate=<32000-48000>``
- Specify encoding audio rate (default: 48000 Hz, available: 32000,
- 44100 and 48000 Hz).
-
-``--pvr-alayer=<1-3>``
- Specify MPEG audio layer encoding (default: 2).
-
-``--pvr-abitrate=<32-448>``
- Specify audio encoding bitrate in kbps (default: 384).
-
-``--pvr-amode=<value>``
- Specify audio encoding mode. Available preset values are 'stereo',
- 'joint_stereo', 'dual' and 'mono' (default: stereo).
-
-``--pvr-vbitrate=<value>``
- Specify average video bitrate encoding in Mbps (default: 6).
-
-``--pvr-vmode=<value>``
- Specify video encoding mode:
-
- :vbr: Variable BitRate (default)
- :cbr: Constant BitRate
-
-``--pvr-vpeak=<value>``
- Specify peak video bitrate encoding in Mbps (only useful for VBR
- encoding, default: 9.6).
-
-``--pvr-fmt=<value>``
- Choose an MPEG format for encoding:
-
- :ps: MPEG-2 Program Stream (default)
- :ts: MPEG-2 Transport Stream
- :mpeg1: MPEG-1 System Stream
- :vcd: Video CD compatible stream
- :svcd: Super Video CD compatible stream
- :dvd: DVD compatible stream
-
-``--quiet``
- Make console output less verbose; in particular, prevents the status line
- (i.e. AV: 3.4 (00:00:03.37) / 5320.6 ...) from being displayed.
- Particularly useful on slow terminals or broken ones which do not properly
- handle carriage return (i.e. ``\r``).
-
- Also see ``--really-quiet`` and ``--msg-level``.
-
-``--quvi-fetch-subtitles=<yes|no>``
- Toggles fetching of subtitles from streaming sites with libquvi. Disabled
- by default, because it's unreliable and slow. Note that when enabled,
- subtitles will always be fetched, even if subtitles are explicitly
- disabled with ``--no-sub`` (because you might want to enable subtitles
- at runtime).
-
- Supported when using libquvi 0.9.x.
-
-``--quvi-format=<best|default|...>``
- Video format/quality that is directly passed to libquvi (default: ``best``).
- This is used when opening links to streaming sites like YouTube. The
- interpretation of this value is highly specific to the streaming site and
- the video.
-
- libquvi 0.4.x:
-
- The only well-defined values that work on all sites are ``best``
- (best quality/highest bandwidth, default), and ``default`` (lowest
- quality).
-
- The quvi command line tool can be used to find out which formats are
- supported for a given URL: ``quvi --query-formats URL``.
-
- libquvi 0.9.x:
-
- The following explanations are relevant:
- `<http://quvi.sourceforge.net/r/api/0.9/glossary_termino.html#m_stream_id>`_
-
- The ``quvi-format`` property can be used at runtime to cycle through the
- list of formats. Unfortunately, this is slow. On libquvi 0.4.x, this
- functionality is limited to switching between ``best`` and ``default`` if
- the ``cycle`` input command is used.
-
-``--really-quiet``
- Display even less output and status messages than with ``--quiet``.
-
-``--referrer=<string>``
- Specify a referrer path or URL for HTTP requests.
-
-``--reset-on-next-file=<all|option1,option2,...>``
- Normally, mpv will try to keep all settings when playing the next file on
- the playlist, even if they were changed by the user during playback. (This
- behavior is the opposite of MPlayer's, which tries to reset all settings
- when starting next file.)
-
- Default: Do not reset anything.
-
- This can be changed with this option. It accepts a list of options, and
- mpv will reset the value of these options on playback start to the initial
- value. The initial value is either the default value, or as set by the
- config file or command line.
-
- In some cases, this might not work as expected. For example, ``--volume``
- will only be reset if it is explicitly set in the config file or the
- command line.
-
- The special name ``all`` resets as many options as possible.
-
- .. admonition:: Examples
-
- - ``--reset-on-next-file=pause``
- Reset pause mode when switching to the next file.
- - ``--reset-on-next-file=fullscreen,speed``
- Reset fullscreen and playback speed settings if they were changed
- during playback.
- - ``--reset-on-next-file=all``
- Try to reset all settings that were changed during playback.
-
-``--rtsp-transport=<lavf|udp|tcp|http>``
- Select RTSP transport method (default: tcp). This selects the underlying
- network transport when playing ``rtsp://...`` URLs. The value ``lavf``
- leaves the decision to libavformat.
-
-``--saturation=<-100-100>``
- Adjust the saturation of the video signal (default: 0). You can get
- grayscale output with this option. Not supported by all video output
- drivers.
-
-``--save-position-on-quit``
- Always save the current playback position on quit. When this file is
- played again later, the player will seek to the old playback position on
- start. This does not happen if playback of a file is stopped in any other
- way than quitting. For example, going to the next file in the playlist
- will not save the position, and start playback at beginning the next time
- the file is played.
-
- This behavior is disabled by default, but is always available when quitting
- the player with Shift+Q.
-
-``--write-filename-in-watch-later-config``
- Prepend the watch later config files with the name of the file they refer
- to. This is simply written as comment on the top of the file.
-
- .. warning::
-
- This option may expose privacy-sensitive information and is thus
- disabled by default.
-
-``--screen=<default|0-32>``
- In multi-monitor configurations (i.e. a single desktop that spans across
- multiple displays), this option tells mpv which screen to display the
- movie on.
-
- .. admonition:: Note (X11)
-
- This option does not work properly with all window managers. In these
- cases, you can try to use ``--geometry`` to position the window
- explicitly. It's also possible that the window manager provides native
- features to control which screens application windows should use.
-
- See also ``--fs-screen``.
+Screenshot
+----------
``--screenshot-format=<type>``
Set the image file type used for saving screenshots.
@@ -1922,21 +2298,6 @@ OPTIONS
:jpg: JPEG (default)
:jpeg: JPEG (same as jpg, but with .jpeg file ending)
-``--screenshot-jpeg-quality=<0-100>``
- Set the JPEG quality level. Higher means better quality. The default is 90.
-
-``--screenshot-png-compression=<0-9>``
- Set the PNG compression level. Higher means better compression. This will
- affect the file size of the written screenshot file and the time it takes
- to write a screenshot. Too high compression might occupy enough CPU time to
- interrupt playback. The default is 7.
-
-``--screenshot-png-filter=<0-5>``
- Set the filter applied prior to PNG compression. 0 is none, 1 is "sub", 2 is
- "up", 3 is "average", 4 is "Paeth", and 5 is "mixed". This affects the level
- of compression that can be achieved. For most images, "mixed" achieves the
- best compression ratio, hence it is the default.
-
``--screenshot-template=<template>``
Specify the filename template used to save screenshots. The template
specifies the filename without file extension, and can contain format
@@ -2024,332 +2385,24 @@ OPTIONS
``%%``
Replaced with the ``%`` character itself.
-``--secondary-sid=<ID|auto|no>``
- Select a secondary subtitle stream. This is similar to ``--sid``. If a
- secondary subtitle is selected, it will be rendered as toptitle (i.e. on
- the top of the screen) alongside the normal subtitle, and provides a way
- to render two subtitles at once.
-
- there are some caveats associated with this feature. For example, bitmap
- subtitles will always be rendered in their usual position, so selecting a
- bitmap subtitle as secondary subtitle will result in overlapping subtitles.
- Secondary subtitles are never shown on the terminal if video is disabled.
-
- .. note::
-
- Styling and interpretation of any formatting tags is disabled for the
- secondary subtitle. Internally, the same mechanism as ``--no-sub-ass``
- is used to strip the styling.
-
- .. note::
-
- If the main subtitle stream contains formatting tags which display the
- subtitle at the top of the screen, it will overlap with the secondary
- subtitle. To prevent this, you could use ``--no-sub-ass`` to disable
- styling in the main subtitle stream.
-
-``--show-profile=<profile>``
- Show the description and content of a profile.
-
-``--shuffle``
- Play files in random order.
-
-``--sid=<ID|auto|no>``
- Display the subtitle stream specified by ``<ID>``. ``auto`` selects
- the default, ``no`` disables subtitles.
-
- See also ``--slang``, ``--no-sub``.
-
-``--slang=<languagecode[,languagecode,...]>``
- Specify a priority list of subtitle languages to use. Different container
- formats employ different language codes. DVDs use ISO 639-1 two letter
- language codes, Matroska uses ISO 639-2 three letter language codes while
- OGM uses a free-form identifier. See also ``--sid``.
-
- .. admonition:: Examples
-
- - ``mpv dvd://1 --slang=hu,en`` chooses the Hungarian subtitle track on
- a DVD and falls back on English if Hungarian is not available.
- - ``mpv --slang=jpn example.mkv`` plays a Matroska file with Japanese
- subtitles.
-
-``--slave-broken``
- Switches on the old slave mode. This is for testing only, and incompatible
- to the removed ``--slave`` switch.
-
- .. attention::
- Changes incompatible to slave mode applications have been made. In
- particular, the status line output was changed, which is used by some
- applications to determine the current playback position. This switch
- has been renamed to prevent these applications from working with this
- version of mpv, because it would lead to buggy and confusing behavior
- only. Moreover, the slave mode protocol is so horribly bad that it
- should not be used for new programs, nor should existing programs
- attempt to adapt to the changed output and use the ``--slave-broken``
- switch. Instead, a new, saner protocol should be developed (and will be,
- if there is enough interest).
-
- This affects most third-party GUI frontends.
-
-``--softsleep``
- Time frames by repeatedly checking the current time instead of asking
- the kernel to wake up mpv at the correct time. Useful if your kernel
- timing is imprecise and you cannot use the RTC either. Comes at the
- price of higher CPU consumption.
-
-``--softvol=<mode>``
- Control whether to use the volume controls of the audio output driver or
- the internal mpv volume filter.
-
- :no: prefer audio driver controls, use the volume filter only if
- absolutely needed
- :yes: always use the volume filter
- :auto: prefer the volume filter if the audio driver uses the system mixer
- (default)
-
- The intention of ``auto`` is to avoid changing system mixer settings from
- within mpv with default settings. mpv is a video player, not a mixer panel.
- On the other hand, mixer controls are enabled for sound servers like
- PulseAudio, which provide per-application volume.
-
-``--softvol-max=<10.0-10000.0>``
- Set the maximum amplification level in percent (default: 200). A value of
- 200 will allow you to adjust the volume up to a maximum of double the
- current level. With values below 100 the initial volume (which is 100%)
- will be above the maximum, which e.g. the OSD cannot display correctly.
-
- .. admonition:: Note
-
- The maximum value of ``--volume`` as well as the ``volume`` property
- is always 100. Likewise, the volume OSD bar always goes from 0 to 100.
- This means that with ``--softvol-max=200``, ``--volume=100`` sets
- maximum amplification, i.e. amplify by 200%. The default volume (no
- change in volume) will be ``50`` in this case.
-
-``--speed=<0.01-100>``
- Slow down or speed up playback by the factor given as parameter.
-
-``--start=<relative time>``
- Seek to given time position.
-
- The general format for absolute times is ``[[hh:]mm:]ss[.ms]``. If the time
- is negated with ``-``, the seek is relative from the end of the file.
-
- ``pp%`` seeks to percent position pp (0-100).
-
- ``#c`` seeks to chapter number c. (Chapters start from 1.)
-
- .. admonition:: Examples
-
- ``--start=56``
- Seeks to 56 seconds.
- ``--start=01:10:00``
- Seeks to 1 hour 10 min.
- ``--start=50%``
- Seeks to the middle of the file.
- ``--start=30 --end=40``
- Seeks to 30 seconds, plays 10 seconds, and exits.
- ``--start=-3:20 --length=10``
- Seeks to 3 minutes and 20 seconds before the end of the file, plays
- 10 seconds, and exits.
- ``--start='#2' --end='#4'``
- Plays chapters 2 and 3, and exits.
-
-``--stretch-dvd-subs=<yes|no>``
- Stretch DVD subtitles when playing anamorphic videos for better looking
- fonts on badly mastered DVDs. This switch has no effect when the
- video is stored with square pixels - which for DVD input cannot be the case
- though.
-
- Many studios tend to use bitmap fonts designed for square pixels when
- authoring DVDs, causing the fonts to look stretched on playback on DVD
- players. This option fixes them, however at the price of possibly
- misaligning sume subtitles (e.g. sign translations).
-
- Disabled by default.
-
-``--sstep=<sec>``
- Skip <sec> seconds after every frame.
-
- .. note::
-
- Without ``--hr-seek``, skipping will snap to keyframes.
-
-``--stop-screensaver``, ``--no-stop-screensaver``
- Turns off the screensaver (or screen blanker and similar mechanisms) at
- startup and turns it on again on exit (default: yes). The screensaver is
- always re-enabled when the player is paused.
-
- This is not supported on all video outputs or platforms. Sometimes it is
- implemented, but does not work (happens often on GNOME). You might be able
- to to work this around using ``--heartbeat-cmd`` instead.
-
-``--sub-file=subtitlefile``
- Add a subtitle file to the list of external subtitles.
-
- If you use ``--sub-file`` only once, this subtitle file is displayed by
- default.
-
- If ``--sub-file`` is used multiple times, the subtitle to use can be
- switched at runtime by cycling subtitle tracks. It's possible to show
- two subtitles at once: use ``--sid`` to select the first subtitle index,
- and ``--secondary-sid`` to select the second index. (The index is printed
- on the terminal output after the ``--sid=`` in the list of streams.)
-
-``--sub-auto=<no|exact|fuzzy|all>``, ``--no-sub-auto``
- Load additional subtitle files matching the video filename. The parameter
- specifies how external subtitle files are matched. ``exact`` is enabled by
- default.
-
- :no: Don't automatically load external subtitle files.
- :exact: Load the media filename with subtitle file extension (default).
- :fuzzy: Load all subs containing movie name.
- :all: Load all subs in the current and ``--sub-paths`` directories.
-
-``--sub-paths=<path1:path2:...>``
- Specify extra directories to search for subtitles matching the video.
- Multiple directories can be separated by ":" (";" on Windows).
- Paths can be relative or absolute. Relative paths are interpreted relative
- to video file directory.
-
- .. admonition:: Example
-
- Assuming that ``/path/to/movie/movie.avi`` is played and
- ``--sub-paths=sub:subtitles:/tmp/subs`` is specified, mpv searches for
- subtitle files in these directories:
-
- - ``/path/to/movie/``
- - ``/path/to/movie/sub/``
- - ``/path/to/movie/subtitles/``
- - ``/tmp/subs/``
- - ``~/.mpv/sub/``
-
-``--sub-demuxer=<[+]name>``
- Force subtitle demuxer type for ``--sub-file``. Give the demuxer name as
- printed by ``--sub-demuxer=help``.
-
-``--sub-codepage=<codepage>``
- If your system supports ``iconv(3)``, you can use this option to specify
- the subtitle codepage. By default, ENCA will be used to guess the charset.
- If mpv is not compiled with ENCA, ``UTF-8:UTF-8-BROKEN`` is the default,
- which means it will try to use UTF-8, otherwise the ``UTF-8-BROKEN``
- pseudo codepage (see below).
-
- .. admonition:: Warning
-
- If you force the charset, even subtitles that are known to be
- UTF-8 will be recoded, which is perhaps not what you expect. Prefix
- codepages with ``utf8:`` if you want the codepage to be used only if the
- input is not valid UTF-8.
-
- .. admonition:: Examples
-
- - ``--sub-codepage=utf8:latin2`` Use Latin 2 if input is not UTF-8.
- - ``--sub-codepage=cp1250`` Always force recoding to cp1250.
-
- The pseudo codepage ``UTF-8-BROKEN`` is used internally. When it
- is the codepage, subtitles are interpreted as UTF-8 with "Latin 1" as
- fallback for bytes which are not valid UTF-8 sequences. iconv is
- never involved in this mode.
-
- If the player was compiled with ENCA support, you can control it with the
- following syntax:
-
- ``--sub-codepage=enca:<language>:<fallback codepage>``
-
- Language is specified using a two letter code to help ENCA detect
- the codepage automatically. If an invalid language code is
- entered, mpv will complain and list valid languages. (Note
- however that this list will only be printed when the conversion code is actually
- called, for example when loading an external subtitle). The
- fallback codepage is used if autodetection fails. If no fallback
- is specified, ``UTF-8-BROKEN`` is used.
-
- .. admonition:: Examples
-
- - ``--sub-codepage=enca:pl:cp1250`` guess the encoding, assuming the subtitles
- are Polish, fall back on cp1250
- - ``--sub-codepage=enca:pl`` guess the encoding for Polish, fall back on UTF-8.
- - ``--sub-codepage=enca`` try universal detection, fall back on UTF-8.
-
- If the player was compiled with libguess support, you can use it with:
-
- ``--sub-codepage=guess:<language>:<fallback codepage>``
-
- libguess always needs a language. There is no universal detection
- mode. Use ``--sub-codepage=guess:help`` to get a list of
- languages subject to the same caveat as with ENCA above.
-
-``--sub-fix-timing``, ``--no-sub-fix-timing``
- By default, external text subtitles are preprocessed to remove minor gaps
- or overlaps between subtitles (if the difference is smaller than 200 ms,
- the gap or overlap is removed). This does not affect image subtitles,
- subtitles muxed with audio/video, or subtitles in the ASS format.
-
-``--sub-delay=<sec>``
- Delays subtitles by ``<sec>`` seconds. Can be negative.
-
-``--sub-fps=<rate>``
- Specify the framerate of the subtitle file (default: movie fps).
-
- .. note::
-
- ``<rate>`` > movie fps speeds the subtitles up for frame-based
- subtitle files and slows them down for time-based ones.
-
- Also see ``--sub-speed`` option.
-
-``--sub-gauss=<0.0-3.0>``
- Apply gaussian blur to image subtitles (default: 0). This can help making
- pixelated DVD/Vobsubs look nicer. A value other than 0 also switches to
- software subtitle scaling. Might be slow.
-
- .. note::
-
- Never applied to text subtitles.
-
-``--sub-gray``
- Convert image subtitles to grayscale. Can help making yellow DVD/Vobsubs
- look nicer.
-
- .. note::
-
- Never applied to text subtitles.
-
-``--sub-pos=<0-100>``
- Specify the position of subtitles on the screen. The value is the vertical
- position of the subtitle in % of the screen height.
-
- .. note::
-
- This affects ASS subtitles as well, and may lead to incorrect subtitle
- rendering. Use with care, or use ``--sub-text-margin-y`` instead.
-
-``--sub-scale=<0-100>``
- Factor for the text subtitle font size (default: 1).
-
- .. note::
-
- This affects ASS subtitles as well, and may lead to incorrect subtitle
- rendering. Use with care, or use ``--sub-text-font-size`` instead.
-
-``--sub-scale-with-window=yes|no``
- Make the subtitle font size relative to the window, instead of the video.
- This is useful if you always want the same font size, even if the video
- doesn't covert the window fully, e.g. because screen aspect and window
- aspect mismatch (and the player adds black bars).
+``--screenshot-jpeg-quality=<0-100>``
+ Set the JPEG quality level. Higher means better quality. The default is 90.
- Like ``--sub-scale``, this can break ASS subtitles.
+``--screenshot-png-compression=<0-9>``
+ Set the PNG compression level. Higher means better compression. This will
+ affect the file size of the written screenshot file and the time it takes
+ to write a screenshot. Too high compression might occupy enough CPU time to
+ interrupt playback. The default is 7.
-``--sub-speed=<0.1-10.0>``
- Multiply the subtitle event timestamps with the given value. Can be used
- to fix the playback speed for frame-based subtitle formats. Works for
- external text subtitles only.
+``--screenshot-png-filter=<0-5>``
+ Set the filter applied prior to PNG compression. 0 is none, 1 is "sub", 2 is
+ "up", 3 is "average", 4 is "Paeth", and 5 is "mixed". This affects the level
+ of compression that can be achieved. For most images, "mixed" achieves the
+ best compression ratio, hence it is the default.
- .. admonition:: Example
- `--sub-speed=25/23.976`` plays frame based subtitles which have been
- loaded assuming a framerate of 23.976 at 25 FPS.
+Software Scaler
+---------------
``--sws-scaler=<name>``
Specify the software scaler algorithm to be used with ``--vf=scale``. This
@@ -2378,6 +2431,58 @@ OPTIONS
``--sws-cvs=<v>``
Software scaler chroma vertical shifting. See ``--sws-scaler``.
+
+Terminal
+--------
+
+``--quiet``
+ Make console output less verbose; in particular, prevents the status line
+ (i.e. AV: 3.4 (00:00:03.37) / 5320.6 ...) from being displayed.
+ Particularly useful on slow terminals or broken ones which do not properly
+ handle carriage return (i.e. ``\r``).
+
+ Also see ``--really-quiet`` and ``--msg-level``.
+
+``--really-quiet``
+ Display even less output and status messages than with ``--quiet``.
+
+``--no-terminal``, ``--terminal``
+ Disable any use of the terminal and stdin/stdout/stderr. This completely
+ silences any message output.
+
+ Unlike ``--really-quiet``, this disables input and terminal initialization
+ as well.
+
+``--no-msg-color``
+ Disable colorful console output on terminals.
+
+``--msg-level=<module1=level1:module2=level2:...>``
+ Control verbosity directly for each module. The ``all`` module changes the
+ verbosity of all the modules not explicitly specified on the command line.
+
+ Run mpv with ``--msg-level=all=trace`` to see all messages mpv outputs. You
+ can use the module names printed in the output (prefixed to each line in
+ ``[...]``) to limit the output to interesting modules.
+
+ .. note::
+
+ Some messages are printed before the command line is parsed and are
+ therefore not affected by ``--msg-level``. To control these messages,
+ you have to use the ``MPV_VERBOSE`` environment variable; see
+ `ENVIRONMENT VARIABLES`_ for details.
+
+ Available levels:
+
+ :no: complete silence
+ :fatal: fatal messages only
+ :error: error messages
+ :warn: warning messages
+ :info: informational messages
+ :status: status messages (default)
+ :v: verbose messages
+ :debug: debug messages
+ :trace: very noisy debug messages
+
``--term-osd, --no-term-osd``, ``--term-osd=force``
Display OSD messages on the console when no video output is available.
Enabled by default.
@@ -2407,40 +2512,30 @@ OPTIONS
Print out a custom string during playback instead of the standard status
line. Expands properties. See `Property Expansion`_.
-``--no-terminal``, ``--terminal``
- Disable any use of the terminal and stdin/stdout/stderr. This completely
- silences any message output.
-
- Unlike ``--really-quiet``, this disables input and terminal initialization
- as well.
-
-``--title=<string>``
- Set the window title. Properties are expanded on playback start.
- (See `Property Expansion`_.)
+``--msg-module``
+ Prepend module name to each console message.
- .. warning::
+``--msg-time``
+ Prepend timing information to each console message.
- There is a danger of this causing significant CPU usage, depending on
- the properties used and the window manager. Changing the window title
- is often a slow operation, and if the title changes every frame,
- playback can be ruined.
-``--tls-ca-file=<filename>``
- Certificate authority database file for use with TLS. (Silently fails with
- older ffmpeg or libav versions.)
-
-``--tls-verify``
- Verify peer certificates when using TLS (e.g. with ``https://...``).
- (Silently fails with older ffmpeg or libav versions.)
+TV
+--
``--tv-...``
These options tune various properties of the TV capture module. For
watching TV with mpv, use ``tv://`` or ``tv://<channel_number>`` or
even ``tv://<channel_name>`` (see option ``tv-channels`` for ``channel_name``
- below) as a movie URL. You can also use ``tv:///<input_id>`` to start
- watching a movie from a composite or S-Video input (see option ``input`` for
+ below) as a media URL. You can also use ``tv:///<input_id>`` to start
+ watching a video from a composite or S-Video input (see option ``input`` for
details).
+``--tv-device=<value>``
+ Specify TV device (default: ``/dev/video0``).
+
+``--tv-channel=<value>``
+ Set tuner to <value> channel.
+
``--no-tv-audio``
no sound
@@ -2453,9 +2548,6 @@ OPTIONS
See ``--tv=driver=help`` for a list of compiled-in TV input drivers.
available: dummy, v4l2 (default: autodetect)
-``--tv-device=<value>``
- Specify TV device (default: ``/dev/video0``).
-
``--tv-input=<value>``
Specify input (default: 0 (TV), see console output for available
inputs).
@@ -2489,9 +2581,6 @@ OPTIONS
Sets the TV norm to the given numeric ID. The TV norm depends on the
capture card. See the console output for a list of available TV norms.
-``--tv-channel=<value>``
- Set tuner to <value> channel.
-
``--tv-chanlist=<value>``
available: argentina, australia, china-bcast, europe-east,
europe-west, france, ireland, italy, japan-bcast, japan-cable,
@@ -2612,232 +2701,296 @@ OPTIONS
the device (default: 50). A signal strength higher than this value will
indicate that the currently scanning channel is active.
-``--use-filedir-conf``
- Look for a file-specific configuration file in the same directory as the
- file that is being played. See `File-specific Configuration Files`_.
- .. warning::
+Cache
+-----
- May be dangerous if playing from untrusted media.
+``--cache=<kBytes|no|auto>``
+ Set the size of the cache in kilobytes, disable it with ``no``, or
+ automatically enable it if needed with ``auto`` (default: ``auto``).
+ With ``auto``, the cache will usually be enabled for network streams,
+ using the size set by ``--cache-default``.
-``--user-agent=<string>``
- Use ``<string>`` as user agent for HTTP streaming.
+ May be useful when playing files from slow media, but can also have
+ negative effects, especially with file formats that require a lot of
+ seeking, such as mp4.
-``-v``
- Increment verbosity level, one level for each ``-v`` found on the command
- line.
+ Note that half the cache size will be used to allow fast seeking back. This
+ is also the reason why a full cache is usually reported as 50% full. The
+ cache fill display does not include the part of the cache reserved for
+ seeking back. Likewise, when starting a file the cache will be at 100%,
+ because no space is reserved for seeking back yet.
-``--vd=<[+|-]family1:(*|decoder1),[+|-]family2:(*|decoder2),...[-]>``
- Specify a priority list of video decoders to be used, according to their
- family and name. See ``--ad`` for further details. Both of these options
- use the same syntax and semantics; the only difference is that they
- operate on different codec lists.
+``--cache-default=<kBytes|no>``
+ Set the size of the cache in kilobytes (default: 25000 KB). Using ``no``
+ will not automatically enable the cache e.g. when playing from a network
+ stream. Note that using ``--cache`` will always override this option.
- .. note::
+``--cache-pause-below=<kBytes|no>``
+ If the cache size goes below the specified value (in KB), pause and wait
+ until the size set by ``--cache-pause-restart`` is reached, then resume
+ playback (default: 50). If ``no`` is specified, this behavior is disabled.
- See ``--vd=help`` for a full list of available decoders.
+ When the player is paused this way, the status line shows ``Buffering``
+ instead of ``Paused``, and the OSD uses a clock symbol instead of the
+ normal paused symbol.
-``--vd-lavc-check-hw-profile=<yes|no>``
- Check hardware decoder profile (default: yes). If ``no`` is set, the
- highest profile of the hardware decoder is unconditionally selected, and
- decoding is forced even if the profile of the video is higher than that.
- The result is most likely broken decoding, but may also help if the
- detected or reported profiles are somehow incorrect.
+``--cache-pause-restart=<kBytes>``
+ If the cache is paused due to the ``--cache-pause-below`` functionality,
+ then the player unpauses as soon as the cache has this much data (in KB).
+ (Default: 100)
-``--vd-lavc-bitexact``
- Only use bit-exact algorithms in all decoding steps (for codec testing).
+``--cache-initial=<kBytes>``
+ Playback will start when the cache has been filled up with this many
+ kilobytes of data (default: 0).
-``--vd-lavc-fast`` (MPEG-2, MPEG-4, and H.264 only)
- Enable optimizations which do not comply with the format specification and
- potentially cause problems, like simpler dequantization, simpler motion
- compensation, assuming use of the default quantization matrix, assuming YUV
- 4:2:0 and skipping a few checks to detect damaged bitstreams.
+``--cache-seek-min=<kBytes>``
+ If a seek is to be made to a position within ``<kBytes>`` of the cache
+ size from the current position, mpv will wait for the cache to be
+ filled to this position rather than performing a stream seek (default:
+ 500).
-``--vd-lavc-o=<key>=<value>[,<key>=<value>[,...]]``
- Pass AVOptions to libavcodec decoder. Note, a patch to make the ``o=``
- unneeded and pass all unknown options through the AVOption system is
- welcome. A full list of AVOptions can be found in the FFmpeg manual.
+ This matters for small forward seeks. With slow streams (especially http
+ streams) there is a tradeoff between skipping the data between current
+ position and seek destination, or performing an actual seek. Depending
+ on the situation, either of these might be slower than the other method.
+ This option allows control over this.
- Some options which used to be direct options can be set with this
- mechanism, like ``bug``, ``gray``, ``idct``, ``ec``, ``vismv``,
- ``skip_top`` (was ``st``), ``skip_bottom`` (was ``sb``), ``debug``.
+``--cache-file=<path>``
+ Create a cache file on the filesystem with the given name. The file is
+ always overwritten. When the general cache is enabled, this file cache
+ will be used to store whatever is read from the source stream.
+
+ This will always overwrite the cache file, and you can't use an existing
+ cache file to resume playback of a stream. (Technically, mpv wouldn't
+ even know which blocks in the file are valid and which not.)
+
+ The resulting file will not necessarily contain all data of the source
+ stream. For example, if you seek, the parts that were skipped over are
+ never read and consequently are not written to the cache. The skipped over
+ parts are filled with zeros. This means that the cache file doesn't
+ necessarily correspond to a full download of the source stream.
+
+ Both of these issues could be improved if there is any user interest.
+
+ Also see ``--cache-file-size``.
+
+``--cache-file-size=<kBytes>``
+ Maximum size of the file created with ``--cache-file``. For read accesses
+ above this size, the cache is simply not used.
+
+ (Default: 1048576, 1 GB.)
+
+``--no-cache``
+ Turn off input stream caching. See ``--cache``.
+
+
+Network
+-------
+
+``--user-agent=<string>``
+ Use ``<string>`` as user agent for HTTP streaming.
+
+``--cookies``, ``--no-cookies``
+ (network only)
+ Support cookies when making HTTP requests. Disabled by default.
+
+``--cookies-file=<filename>``
+ (network only)
+ Read HTTP cookies from <filename>. The file is assumed to be in Netscape
+ format.
+
+``--http-header-fields=<field1,field2>``
+ Set custom HTTP fields when accessing HTTP stream.
.. admonition:: Example
- ``--vd--lavc-o=debug=pict``
+ ::
-``--vd-lavc-show-all=<yes|no>``
- Show even broken/corrupt frames (default: no). If this option is set to
- no, libavcodec won't output frames that were either decoded before an
- initial keyframe was decoded, or frames that are recognized as corrupted.
+ mpv --http-header-fields='Field1: value1','Field2: value2' \
+ http://localhost:1234
-``--vd-lavc-skiploopfilter=<skipvalue> (H.264 only)``
- Skips the loop filter (AKA deblocking) during H.264 decoding. Since
- the filtered frame is supposed to be used as reference for decoding
- dependent frames, this has a worse effect on quality than not doing
- deblocking on e.g. MPEG-2 video. But at least for high bitrate HDTV,
- this provides a big speedup with little visible quality loss.
+ Will generate HTTP request::
- ``<skipvalue>`` can be one of the following:
+ GET / HTTP/1.0
+ Host: localhost:1234
+ User-Agent: MPlayer
+ Icy-MetaData: 1
+ Field1: value1
+ Field2: value2
+ Connection: close
- :none: Never skip.
- :default: Skip useless processing steps (e.g. 0 size packets in AVI).
- :nonref: Skip frames that are not referenced (i.e. not used for
- decoding other frames, the error cannot "build up").
- :bidir: Skip B-Frames.
- :nonkey: Skip all frames except keyframes.
- :all: Skip all frames.
+``--tls-ca-file=<filename>``
+ Certificate authority database file for use with TLS. (Silently fails with
+ older ffmpeg or libav versions.)
-``--vd-lavc-skipidct=<skipvalue> (MPEG-1/2 only)``
- Skips the IDCT step. This degrades quality a lot in almost all cases
- (see skiploopfilter for available skip values).
+``--tls-verify``
+ Verify peer certificates when using TLS (e.g. with ``https://...``).
+ (Silently fails with older ffmpeg or libav versions.)
-``--vd-lavc-skipframe=<skipvalue>``
- Skips decoding of frames completely. Big speedup, but jerky motion and
- sometimes bad artifacts (see skiploopfilter for available skip values).
+``--referrer=<string>``
+ Specify a referrer path or URL for HTTP requests.
-``--vd-lavc-threads=<0-16>``
- Number of threads to use for decoding. Whether threading is actually
- supported depends on codec. 0 means autodetect number of cores on the
- machine and use that, up to the maximum of 16 (default: 0).
+``--rtsp-transport=<lavf|udp|tcp|http>``
+ Select RTSP transport method (default: tcp). This selects the underlying
+ network transport when playing ``rtsp://...`` URLs. The value ``lavf``
+ leaves the decision to libavformat.
-``--version, -V``
- Print version string and exit.
-``--vf=<filter1[=parameter1:parameter2:...],filter2,...>``
- Specify a list of video filters to apply to the video stream. See
- `VIDEO FILTERS`_ for details and descriptions of the available filters.
- The option variants ``--vf-add``, ``--vf-pre``, ``--vf-del`` and
- ``--vf-clr`` exist to modify a previously specified list, but you
- should not need these for typical use.
+DVB
+---
-``--vid=<ID|auto|no>``
- Select video channel. ``auto`` selects the default, ``no`` disables video.
+``--dvbin-card=<1-4>``
+ Specifies using card number 1-4 (default: 1).
-``--video-align-x=<-1-1>``, ``--video-align-y=<-1-1>``
- Moves the video rectangle within the black borders, which are usually added
- to pad the video to screen if video and screen aspect ratios are different.
- ``--video-align-y=-1`` would move the video to the top of the screen
- (leaving a border only on the bottom), a value of ``0`` centers it
- (default), and a value of ``1`` would put the video at the bottom of the
- screen.
+``--dvbin-file=<filename>``
+ Instructs mpv to read the channels list from ``<filename>``. Default is
+ ``~/.mpv/channels.conf.{sat,ter,cbl,atsc}`` (based on your card type) or
+ ``~/.mpv/channels.conf`` as a last resort.
- If video and screen aspect match perfectly, these options do nothing.
+``--dvbin-timeout=<1-30>``
+ Maximum number of seconds to wait when trying to tune a frequency before
+ giving up (default: 30).
- This option is disabled if the ``--no-keepaspect`` option is used.
-``--video-aspect=<ratio>``
- Override movie aspect ratio, in case aspect information is incorrect or
- missing in the file being played. See also ``--no-video-aspect``.
+PVR
+---
- Two values have special meaning:
+``--pvr-...``
+ These options tune various encoding properties of the PVR capture module.
+ It has to be used with any hardware MPEG encoder based card supported by
+ the V4L2 driver. The Hauppauge WinTV PVR-150/250/350/500 and all IVTV
+ based cards are known as PVR capture cards. Be aware that only Linux
+ 2.6.18 kernel and above is able to handle MPEG stream through V4L2 layer.
+ For hardware capture of an MPEG stream and watching it with mpv, use
+ ``pvr://`` as media URL.
- :0: disable aspect ratio handling, pretend the video has square pixels
- :-1: use the video stream or container aspect (default)
- But note that handling of these special values might change in the future.
+``--pvr-aspect=<0-3>``
+ Specify input aspect ratio:
- .. admonition:: Examples
+ :0: 1:1
+ :1: 4:3 (default)
+ :2: 16:9
+ :3: 2.21:1
- - ``--video-aspect=4:3`` or ``--video-aspect=1.3333``
- - ``--video-aspect=16:9`` or ``--video-aspect=1.7777``
+``--pvr-arate=<32000-48000>``
+ Specify encoding audio rate (default: 48000 Hz, available: 32000,
+ 44100 and 48000 Hz).
-``--no-video-aspect``
- Ignore aspect ratio information from video file and assume the video has
- square pixels. See also ``--video-aspect``.
+``--pvr-alayer=<1-3>``
+ Specify MPEG audio layer encoding (default: 2).
-``--video-pan-x=<value>``, ``--video-pan-y=<value>``
- Moves the displayed video rectangle by the given value in the X or Y
- direction. The unit is in fractions of the size of the scaled video (the
- full size, even if parts of the video are not visible due to panscan or
- other options).
+``--pvr-abitrate=<32-448>``
+ Specify audio encoding bitrate in kbps (default: 384).
- For example, displaying a 1280x720 video fullscreen on a 1680x1050 screen
- with ``--video-pan-x=-0.1`` would move the video 168 pixels to the left
- (making 128 pixels of the source video invisible).
+``--pvr-amode=<value>``
+ Specify audio encoding mode. Available preset values are 'stereo',
+ 'joint_stereo', 'dual' and 'mono' (default: stereo).
- This option is disabled if the ``--no-keepaspect`` option is used.
+``--pvr-vbitrate=<value>``
+ Specify average video bitrate encoding in Mbps (default: 6).
-``--video-rotate=<0-359|no>``
- Rotate the video clockwise, in degrees. Currently supports 90° steps only.
- If ``no`` is given, the video is never rotated, even if the file has
- rotation metadata. (The rotation value is added to the rotation metadata,
- which means the value ``0`` would rotate the video according to the
- rotation metadata.)
+``--pvr-vmode=<value>``
+ Specify video encoding mode:
-``--video-unscaled``
- Disable scaling of the video. If the window is larger than the video,
- black bars are added. Otherwise, the video is cropped. The video still
- can be influenced by the other ``--video-...`` options. (If the
- ``--video-zoom`` option is set to a value other than ``1``, scaling is
- enabled, but the video isn't automatically scaled to the window size.)
+ :vbr: Variable BitRate (default)
+ :cbr: Constant BitRate
- The video and monitor aspects aspect will be ignored. Aspect correction
- would require to scale the video in the X or Y direction, but this option
- disables scaling, disabling all aspect correction.
+``--pvr-vpeak=<value>``
+ Specify peak video bitrate encoding in Mbps (only useful for VBR
+ encoding, default: 9.6).
- Note that the scaler algorithm may still be used, even if the video isn't
- scaled. For example, this can influence chroma conversion.
+``--pvr-fmt=<value>``
+ Choose an MPEG format for encoding:
- This option is disabled if the ``--no-keepaspect`` option is used.
+ :ps: MPEG-2 Program Stream (default)
+ :ts: MPEG-2 Transport Stream
+ :mpeg1: MPEG-1 System Stream
+ :vcd: Video CD compatible stream
+ :svcd: Super Video CD compatible stream
+ :dvd: DVD compatible stream
-``--video-zoom=<value>``
- Adjust the video display scale factor by the given value. The unit is in
- fractions of the (scaled) window video size.
- For example, given a 1280x720 video shown in a 1280x720 window,
- ``--video-zoom=-0.1`` would make the video by 128 pixels smaller in
- X direction, and 72 pixels in Y direction.
+Miscellaneous
+-------------
- This option is disabled if the ``--no-keepaspect`` option is used.
+``--mc=<seconds/frame>``
+ Maximum A-V sync correction per frame (in seconds)
-``--vo=<driver1[:suboption1[=value]:...],driver2,...[,]>``
- Specify a priority list of video output drivers to be used. For
- interactive use, one would normally specify a single one to use, but in
- configuration files, specifying a list of fallbacks may make sense. See
- `VIDEO OUTPUT DRIVERS`_ for details and descriptions of available drivers.
+``--mf-fps=<value>``
+ Framerate used when decoding from multiple PNG or JPEG files with ``mf://``
+ (default: 1).
-``--volstep=<0-100>``
- Set the step size of mixer volume changes in percent of the full range
- (default: 3).
+``--mf-type=<value>``
+ Input file type for ``mf://`` (available: jpeg, png, tga, sgi). By default,
+ this is guessed from the file extension.
-``--volume=<-1-100>``
- Set the startup volume. A value of -1 (the default) will not change the
- volume. See also ``--softvol``.
+``--stream-capture=<filename>``
+ Allows capturing the primary stream (not additional audio tracks or other
+ kind of streams) into the given file. Capturing can also be started and
+ stopped by changing the filename with the ``stream-capture`` slave property.
+ Generally this will not produce usable results for anything else than MPEG
+ or raw streams, unless capturing includes the file headers and is not
+ interrupted. Note that, due to cache latencies, captured data may begin and
+ end somewhat delayed compared to what you see displayed.
-``--volume-restore-data=<string>``
- Used internally for use by playback resume (e.g. with ``quit_watch_later``).
- Restoring value has to be done carefully, because different AOs as well as
- softvol can have different value ranges, and we don't want to restore
- volume if setting the volume changes it system wide. The normal options
- (like ``--volume``) would always set the volume. This option was added for
- restoring volume in a safer way (by storing the method used to set the
- volume), and is not generally useful. Its semantics are considered private
- to mpv.
+``--stream-dump=<filename>``
+ Same as ``--stream-capture``, but do not start playback. Instead, the entire
+ file is dumped.
- Do not use.
+``--stream-lavf-o=opt1=value1,opt2=value2,...``
+ Set AVOptions on streams opened with libavformat. Unknown or misspelled
+ options are silently ignored. (They are mentioned in the terminal output
+ in verbose mode, i.e. ``--v``. In general we can't print errors, because
+ other options such as e.g. user agent are not available with all protocols,
+ and printing errors for unknown options would end up being too noisy.)
-``--wid=<ID>``
- (X11 and Windows only)
- This tells mpv to attach to an existing window. The ID is interpreted as
- "Window" on X11, and as HWND on Windows. If a VO is selected that supports
- this option, a new window will be created and the given window will be set
- as parent. The window will always be resized to cover the parent window
- fully, and will add black bars to compensate for the video aspect ratio.
+``--priority=<prio>``
+ (Windows only.)
+ Set process priority for mpv according to the predefined priorities
+ available under Windows.
- See also ``--slave-broken``.
+ Possible values of ``<prio>``:
+ idle|belownormal|normal|abovenormal|high|realtime
-``--no-window-dragging``
- Don't move the window when clicking on it and moving the mouse pointer.
+ .. warning:: Using realtime priority can cause system lockup.
-``--x11-netwm=no``
- (X11 only)
- Disable use of the NetWM protocol when switching to or from fullscreen.
- This may or may not help with broken window managers. This provides some
- functionality that was implemented by the now removed ``--fstype`` option.
- Actually, it is not known to the developers to which degree this option
- was needed, so feedback is welcome.
+``--pts-association-mode=<decode|sort|auto>``
+ Select the method used to determine which container packet timestamp
+ corresponds to a particular output frame from the video decoder. Normally
+ you should not need to change this option.
- By default, NetWM support is autodetected, and using this option forces
- autodetection to fail.
+ :decoder: Use decoder reordering functionality. Unlike in classic MPlayer
+ and mplayer2, this includes a dTS fallback. (Default.)
+ :sort: Maintain a buffer of unused pts values and use the lowest value
+ for the frame.
+ :auto: Try to pick a working mode from the ones above automatically.
+
+ You can also try to use ``--no-correct-pts`` for files with completely
+ broken timestamps.
+
+``--slave-broken``
+ Switches on the old slave mode. This is for testing only, and incompatible
+ to the removed ``--slave`` switch.
+
+ .. attention::
+ Changes incompatible to slave mode applications have been made. In
+ particular, the status line output was changed, which is used by some
+ applications to determine the current playback position. This switch
+ has been renamed to prevent these applications from working with this
+ version of mpv, because it would lead to buggy and confusing behavior
+ only. Moreover, the slave mode protocol is so horribly bad that it
+ should not be used for new programs, nor should existing programs
+ attempt to adapt to the changed output and use the ``--slave-broken``
+ switch. Instead, a new, saner protocol should be developed (and will be,
+ if there is enough interest).
+
+ This affects most third-party GUI frontends.
+
+``--softsleep``
+ Time frames by repeatedly checking the current time instead of asking
+ the kernel to wake up mpv at the correct time. Useful if your kernel
+ timing is imprecise and you cannot use the RTC either. Comes at the
+ price of higher CPU consumption.
diff --git a/DOCS/man/vf.rst b/DOCS/man/vf.rst
index 7c5c3a0..8adf396 100644
--- a/DOCS/man/vf.rst
+++ b/DOCS/man/vf.rst
@@ -47,7 +47,7 @@ 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.
+ black bands from widescreen videos.
``<w>,<h>``
Cropped width and height, defaults to original width and height.
@@ -55,7 +55,7 @@ Available filters are:
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
+ Expands (not scales) video resolution to the given value and places the
unscaled original at coordinates x, y.
``<w>,<h>``
@@ -617,7 +617,7 @@ Available filters are:
``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
+ The intended use is to fix PAL videos that have been captured with the
opposite field order to the film-to-video transfer. The options are:
``t``
@@ -969,3 +969,9 @@ Available filters are:
Use default VDPAU scaling (default).
1-9
Apply high quality VDPAU scaling (needs capable hardware).
+
+``buffer=<num>``
+ Buffer ``<num>`` frames in the filter chain. This filter is probably pretty
+ useless, except for debugging. (Note that this won't help smoothing out
+ latencies with decoding, because the filter will never output a frame if
+ the buffer isn't full, except on EOF.)
diff --git a/DOCS/man/vo.rst b/DOCS/man/vo.rst
index 587cdd2..f9a22e3 100644
--- a/DOCS/man/vo.rst
+++ b/DOCS/man/vo.rst
@@ -524,7 +524,7 @@ Available video output drivers are:
for mastering instead of the true curve. Most notably, anything in the
Apple ecosystem uses this approximation - including all programs
compatible with it. It's a sound idea to try enabling this flag first
- when watching movies and shows to see if things look better that way.
+ when watching videos and shows to see if things look better that way.
This only affects the output when using either ``icc-profile`` or ``srgb``.
diff --git a/DOCS/release-policy.md b/DOCS/release-policy.md
index ea437dd..4b1a725 100644
--- a/DOCS/release-policy.md
+++ b/DOCS/release-policy.md
@@ -28,7 +28,8 @@ Release procedure
- Push branch and tag to GitHub.
-- Create a new GitHub release using the content of ``RELEASE_NOTES``.
+- Create a new GitHub release using the content of ``RELEASE_NOTES`` related to
+ the new version.
Release notes template
----------------------
@@ -36,6 +37,9 @@ Release notes template
Here is a template that can be used for writing the ``RELEASE_NOTES`` file.
```markdown
+Release 0.X.Y
+=============
+
Changes
-------
@@ -55,3 +59,11 @@ 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.
diff --git a/DOCS/tech-overview.txt b/DOCS/tech-overview.txt
index 981123b..7e60046 100644
--- a/DOCS/tech-overview.txt
+++ b/DOCS/tech-overview.txt
@@ -17,12 +17,12 @@ player/*.c:
* check help options etc. (call handle_help_options()), possibly exit
* 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 (slave mode only)
+ playlist or an exit command was given (only if --idle it set)
* 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 slave command terminates playback
+ done or a 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.)
@@ -82,7 +82,7 @@ talloc.h & talloc.c:
(See ta/README for details.)
player/command.c:
- This contains the implementation for slave commands and properties.
+ 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,
@@ -92,9 +92,10 @@ 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.
- 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.
+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.
options/options.h, options/options.c
options.h contains the global option struct MPOpts. The option declarations
@@ -111,15 +112,14 @@ options/options.h, options/options.c
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
+ as remote control devices like Apple IR or client API 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.
- 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.)
+ 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.
common/msg.h:
All terminal output should go through mp_msg().
@@ -213,7 +213,7 @@ audio/out/:
sub/:
Contains subtitle and OSD rendering.
- sub.c/.h is actually the OSD code. It queries dec_sub.c to retrieve
+ osd.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).
diff --git a/RELEASE_NOTES b/RELEASE_NOTES
index 1596c9e..d27982e 100644
--- a/RELEASE_NOTES
+++ b/RELEASE_NOTES
@@ -1,182 +1,83 @@
-Release 0.4.2
-=============
-
-Bug fixes
----------
-
-- Include changes from point releases in the release notes.
-- Fix --cache-file operation when file size is unknown (e.g. when playing from
- a pipe).
-- Don't sleep if playback is stopped when reconnecting for remote stream.
-- Suspend read on vts change even if the requested title is not found when
- using dvdnav (dvd://) (this fixes a bug where the DVD menu was not shown
- properly after a DVD track ended).
-- Avoid draining if the audio output is paused (this fixes a bug where mpv would
- hang when switching tracks when paused).
-- Drop buffered audio when switching tracks or filters (this fixes a possible
- regression when using gapless audio).
-- Reverse video rotation direction.
-- Fix initialization of the input when playing from a pipe.
-- Fix description of the --mf option in the manpage (the --mf syntax changed a
- while ago, but was not documented).
-- Actually append entries to the end of the playlist instead of after the
- current entry with the "loadlist append" command.
-
-New features
-------------
-
-- Add "append-play" mode for the loadfile command.
-
-This listing is not complete. There are many more bug fixes and changes. The
-complete change log can be viewed by running ``git log bb00774..d50be0a`` in
-the git repository.
-
-Release 0.4.1
-=============
-
-Bug fixes
----------
-
-- Fix af_volume bug that caused negative ReplayGain values to increase volume
- instead of decreasing it in some situations.
-- Actually use "weak" as --gapless-audio default value (as documented in the
- 0.4.0 release notes).
-- Fix cache resizing bug that caused seeking to not work anymore.
-- Escape all colons in the options descriptions in the zsh completion script.
-- Don't consume an extra argument with --ao/af and --vo/vf options in the zsh
- completion script (as side effect, the completion now uses --opt=val instead
- of --opt val).
-- Allow client applications to call mpv_terminate_destroy(NULL).
-- Make sure seeking bounds are within range with dvdnav://.
-- Check the length of the last title too with dvdnav://longest.
-- Properly flush buffers on DVD seek (this fixes some seeking problems when
- playing DVDs).
-- Allow compilation without atomics (for compilers that don't support atomic
- operations).
-- Disable ao_null latency emulation.
-- Restore ability to combine mouse buttons.
-
-This listing is not complete. There are many more bug fixes and changes. The
-complete change log can be viewed by running ``git log 0075f8e..b18c2d9`` in
-the git repository.
-
-Release 0.4.0
+Release 0.5.0
=============
Changes
-------
-- Drop support for Libav 9 and earlier FFmpeg releases. At least FFmpeg 2.1.4 or
- Libav 10 are now required.
-- Change cache options to take kilobytes instead of percentages, and raise the
- default values.
-- Lower --auto-pause/resume defaults values to improve web streams playback.
-- Use dvdnav support instead of the internal dvd implementation for dvd:// URLs
- (the old implementation is available under dvdread://).
-- DVD (dvd://) tracks IDs now start from 0 instead of 1.
-- Play the longest track by default with dvd://.
-- Rename some options to make them more consistent. Here's a partial list of
- renamed options:
-
- + Audio-related:
-
- * --audiofile → --audio-file
- * --audiofile-cache → --audio-file-cache
- * --channels → --audio-channels
- * --format → --audio-format
- * --srate → --audio-samplerate
-
- + Input-related:
-
- * --ar → --input-appleremote
- * --consolecontrols → --input-terminal
- * --media-keys → --input-media-keys
- * --joystick → --input-joystick
- * --lirc → --input-lirc
- * --lircconf → --input-lirc-conf
- * --mouse-movements → --input-cursor
- * --right-alt-gr → --input-right-alt-gr
-
- + Terminal-related:
-
- * --msgcolor → --msg-color
- * --msglevel → --msg-level
- * --msgmodule → --msg-module
- * --msgtime → --msg-time
- * --playing-msg → --term-playing-msg
- * --status-msg → --term-status-msg
-
- + Subtitle-related:
-
- * --ass → --sub-ass
- * --autosub → --sub-auto
- * --autosub-match → --sub-auto-match
- * --sub → --sub-file
- * --subcp → --sub-codepage
- * --subfps → --sub-fps
-
- + Video-related:
-
- * --aspect → --video-aspect
- * --fstype → --x11-fstype
- * --native-fs → --fs-missioncontrol
- * --name → --x11-name
-
-- Remove global options variables for --tv, --pvr, --dvb and --cdda.
-- Move post-processing support to a separate filter (vdpaupp) for the vdpau vo,
- and deprecate the old vdpau post-processing options.
-- Remove radio:// support.
-- Remove support for ASX, SMIL and NSC playlist formats.
-- Re-introduce pretty-printing for module names with --msg-module.
-- Load Lua scripts under `$MPV_HOME/lua/` (default `~/.mpv/lua/`) automatically
- (this can be disabled by using `--load-scripts=no`).
-- Corrupt/broken frames are not shown by default anymore (this can be re-enabled
- by using --vd-lavc-show-all=yes).
-- Automatically copy metadata from the input file to the output when encoding
- (this can be disabled by using --no-ometadata).
-- Change --sub-file semantics: if multiple --sub-file are used, the subtitle
- tracks can be cycled at runtime and used with --sid and --secondary-sid.
-- Make the subtitle font size relative to the window, instead of the video, when
- --sub-scale-with-window=yes is used.
-- Change default ao from wasapi to dsound on Windows.
+- Support setting the start time relative to the start PTS with --start.
+- Use /dev/sr0 as default cdrom/dvd device on Linux.
+- Change "cache" property representation to float.
+- Split the ao_coreaudio audio output into ao_coreaudio (which uses the
+ AudioUnits and the CoreAudio sound server) and ao_coreaudio_device (which uses
+ direct device access).
+- Complete supported URL schemes in the zsh completion script.
+- Enable compiler optimizations (-O2) during build.
+- Allow precise seeking with percent-based seeks too.
+- Do precise seeks when clicking on the OSC seekbar.
+- Remove support for older VDA hwaccel versions on Mac OS X (requires recent
+ versions of ffmpeg/libav).
+- Remove the last remains of slave mode (--slave-broken option). Support for
+ reading input commands from stdin can be emulated using: --input-terminal=no
+ --input-file=/dev/stdin.
+- Some key binding were remapped or removed:
+ + "LEFT" and "RIGHT" have been remapped to seek 5 seconds instead of 10.
+ + "c" for changing the YUV color space was unmapped.
+ + OSD level cycling has been remapped from "o" to "O".
+ + "o" is now mapped to the show_progress command (like "P").
+ + "PGUP" and "PGDWN" have been remapped to chapter-based seeks (the old
+ bindings "@" and "!" are still available). The old behvaiour has been
+ remapped to "Shift+PGUP" and "Shift+PGDWM".
+ + Increasing/decreasing audio delay have been remapped from "+" and "-" to
+ "Ctrl++" and "Ctrl+-".
+ + "(" and ")" for adjusting audio balance have been unmapped.
+ + "F" for toggling the "sub-forced-only" option has been unmapped.
+ + "TAB" for cycling TS programs has been unmapped.
+ + "A" for cycling DVD angle has been unmapped.
+ + "U" for stopping playback has been unmapped.
+ + "l" and "L" for cycling quvi format have been unmapped.
+- Make it possible to build the client API (libmpv) on Mac OS X.
+- Do necessary checks for nested Wayland compositors which only have limited
+ interfaces.
+- The options in the manpage have been re-organized into sections and ordered by
+ usage to make it easier to navigate.
+- The "hard" framedrop mode has been removed (this behaviour is still available
+ via the --vd-lavc-framedrop option).
+- Show the basename of a subtitle file only (without the directory part).
Bug fixes
---------
-- Fix tv:// playback with missing timestamps.
-- Fix display of cover art inside audio files with the vdpau vo.
+- Use a default color space for files with no video (this fixes color managed
+ OSD messages when no video channel is present).
+- Fix key equivalent dispatching for Cocoa on Mac OS X.
+- Disable non-interleaved audio formats by default with ao_alsa, since some
+ ALSA plugins don't cope well with them (non-interleaved formats can still be
+ enabled using the "non-interleaved" ao_alsa option).
+- Fix deadlock in the client API when calling mpv_terminate_destroy() before
+ mpv_initialize().
+- Fix flushing of filter chain (this fixes a bug where the last frames would get
+ dropped on EOF, if buffered by filters).
+- Actually use the channels.conf configuration file for DVB.
+- Restore the --dvbin-file option.
+- Fix off by one error in the command parser which caused a segfault when using
+ the mp.commandv() Lua function with 10 or more arguments.
New features
------------
-- Add client API in the form of the libmpv library, which is intended to be a
- stable API to get some rough control over the player (this is not supported on
- Mac OS X).
-- Add option for approximating BT.709 gamma for the opengl vo (similarly to many
- programs in the Apple ecosystem).
-- Add support for non-BT.709 primaries.
-- Add support for BT.2020 colorspace.
-- Generate and install zsh completion script (disabled by default since it may
- interfere with cross-compilation).
-- Add support for looping a single file (instead of the whole playlist) with the
- --loop-file option.
-- Add VapourSynth video filter (this has various restrictions, which are listed
- in the manpage).
-- Add support for ReplayGain in the volume audio filter.
-- Add a --config-dir option to force config directory.
-- Add support for GPU switching on Mac OS X.
-- Add support for automatic selection of color profiles on Mac OS X.
-- Add support for binding commands to sequences of keys.
-- Add support for passing options to Lua scripts with --lua-opts.
-- Add some filesystem utility functions to the Lua API.
-- Add functions for observing property changes to the Lua API .
-- Add support for creating a cache file on the filesystem with --cache-file.
-- Add support for window dragging by grabbing with the x11 vo.
-- Add option to write file name to watch later file.
-- Add support for a "weak" gapless mode, and make it default (the old mode can
- be enabled with --gapless-audio or --gapless-audio=yes).
-- Automatically detect network filesystems on Linux and Windows.
+- Search for config files in $XDG_CONFIG_HOME and $XDG_CONFIG_DIRS in addition
+ to ~/.mpv. The config file has also been renamed to mpv.conf (although the
+ old file still works and will be loaded even if the new one exists).
+- Add "playback-time" property that returns the current playback time always
+ starting at 0. This is now used to show the playback time in the OSD and the
+ status line, fixing the shown playback time for transport streams that start
+ at a completely random timestamp.
+- Add cache-related "cache-free", "cache-used" and "cache-idle" properties.
+- Add option to list supported protocols (--list-protocols).
+- Allow setting libavformat stream options with the --stream-lavf-o option.
+- Support running the demuxer in a separate thread and prefetch packets (this
+ can be enabled using the --demuxer-thread option).
This listing is not complete. There are many more bug fixes and changes. The
-complete change log can be viewed by running ``git log 56ce2a3..8bb7d42`` in
+complete change log can be viewed by running ``git log cb250d4..52f2f67`` in
the git repository.
diff --git a/TOOLS/dylib-unhell.py b/TOOLS/dylib-unhell.py
index 2f3a6c6..43fd111 100755
--- a/TOOLS/dylib-unhell.py
+++ b/TOOLS/dylib-unhell.py
@@ -15,10 +15,10 @@ 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 "libobjc." in libname and \
+ not "libSystem." in libname and \
+ not "libc." in libname and \
+ not "libgcc." in libname and \
not os.path.basename(objfile) in libname
def otool(objfile):
diff --git a/TOOLS/idet.sh b/TOOLS/idet.sh
index 8e1580c..bfc4f57 100755
--- a/TOOLS/idet.sh
+++ b/TOOLS/idet.sh
@@ -30,7 +30,7 @@ esac
testfun()
{
$ILDETECT_MPV "$@" \
- --vf=lavfi="[idet]" --msg-level ffmpeg=v \
+ --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 } \
@@ -87,7 +87,7 @@ judge()
echo "$verdict"
}
-judge "$@"
+judge "$@" --vf-clr
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
@@ -98,7 +98,7 @@ case "$verdict" in
exit 0
;;
interlaced-tff)
- judge "$@" --vf-pre=pullup --field-dominance=top
+ judge "$@" --vf-clr --vf-pre=pullup --field-dominance=top
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
@@ -117,7 +117,7 @@ case "$verdict" in
esac
;;
interlaced-bff)
- judge "$@" --vf-pre=pullup --field-dominance=bottom
+ judge "$@" --vf-clr --vf-pre=pullup --field-dominance=bottom
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
@@ -136,7 +136,7 @@ case "$verdict" in
esac
;;
interlaced)
- judge "$@" --vf-pre=pullup
+ judge "$@" --vf-clr --vf-pre=pullup
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
diff --git a/TOOLS/lua/observe-all.lua b/TOOLS/lua/observe-all.lua
new file mode 100644
index 0000000..68e0977
--- /dev/null
+++ b/TOOLS/lua/observe-all.lua
@@ -0,0 +1,16 @@
+-- Test script for property change notification mechanism.
+
+function format_property_val(v)
+ if type(v) == "table" then
+ return mp.format_table(v) -- undocumented function; might be removed
+ else
+ return tostring(v)
+ end
+end
+
+for i,name in ipairs(mp.get_property_native("property-list")) do
+ mp.observe_property(name, "native", function(name, val)
+ print("property '" .. name .. "' changed to '" ..
+ format_property_val(val) .. "'")
+ end)
+end
diff --git a/DOCS/lua_examples/status-line.lua b/TOOLS/lua/status-line.lua
index d28bdcc..48597c3 100644
--- a/DOCS/lua_examples/status-line.lua
+++ b/TOOLS/lua/status-line.lua
@@ -1,4 +1,4 @@
--- Rebuild the status line as a lua script
+-- Rebuild the terminal status line as a lua script
-- Be aware that this will require more cpu power!
-- Add a string to the status line
diff --git a/TOOLS/osxbundle/mpv.app/Contents/Info.plist b/TOOLS/osxbundle/mpv.app/Contents/Info.plist
index 4ef1697..572d76c 100644
--- a/TOOLS/osxbundle/mpv.app/Contents/Info.plist
+++ b/TOOLS/osxbundle/mpv.app/Contents/Info.plist
@@ -627,6 +627,90 @@
<dict>
<key>UTTypeConformsTo</key>
<array>
+ <string>public.movie</string>
+ </array>
+ <key>UTTypeDescription</key>
+ <string>AVC raw stream</string>
+ <key>UTTypeIconFile</key>
+ <string>document.icns</string>
+ <key>UTTypeIdentifier</key>
+ <string>io.mpv.h264</string>
+ <key>UTTypeReferenceURL</key>
+ <string>http://www.itu.int/rec/T-REC-H.264</string>
+ <key>UTTypeTagSpecification</key>
+ <dict>
+ <key>public.filename-extension</key>
+ <array>
+ <string>264</string>
+ </array>
+ </dict>
+ </dict>
+ <dict>
+ <key>UTTypeConformsTo</key>
+ <array>
+ <string>public.movie</string>
+ </array>
+ <key>UTTypeDescription</key>
+ <string>HEVC raw stream</string>
+ <key>UTTypeIconFile</key>
+ <string>document.icns</string>
+ <key>UTTypeIdentifier</key>
+ <string>io.mpv.hevc</string>
+ <key>UTTypeReferenceURL</key>
+ <string>http://hevc.info</string>
+ <key>UTTypeTagSpecification</key>
+ <dict>
+ <key>public.filename-extension</key>
+ <array>
+ <string>hevc</string>
+ </array>
+ </dict>
+ </dict>
+ <dict>
+ <key>UTTypeConformsTo</key>
+ <array>
+ <string>public.movie</string>
+ </array>
+ <key>UTTypeDescription</key>
+ <string>YUV stream</string>
+ <key>UTTypeIconFile</key>
+ <string>document.icns</string>
+ <key>UTTypeIdentifier</key>
+ <string>io.mpv.yuv</string>
+ <key>UTTypeReferenceURL</key>
+ <string>http://en.wikipedia.org/wiki/YUV</string>
+ <key>UTTypeTagSpecification</key>
+ <dict>
+ <key>public.filename-extension</key>
+ <array>
+ <string>yuv</string>
+ </array>
+ </dict>
+ </dict>
+ <dict>
+ <key>UTTypeConformsTo</key>
+ <array>
+ <string>public.movie</string>
+ </array>
+ <key>UTTypeDescription</key>
+ <string>YUV4MPEG2 stream</string>
+ <key>UTTypeIconFile</key>
+ <string>document.icns</string>
+ <key>UTTypeIdentifier</key>
+ <string>io.mpv.y4m</string>
+ <key>UTTypeReferenceURL</key>
+ <string>http://wiki.multimedia.cx/index.php?title=YUV4MPEG2</string>
+ <key>UTTypeTagSpecification</key>
+ <dict>
+ <key>public.filename-extension</key>
+ <array>
+ <string>y4m</string>
+ </array>
+ </dict>
+ </dict>
+ <dict>
+ <key>UTTypeConformsTo</key>
+ <array>
<string>public.plain-text</string>
</array>
<key>UTTypeDescription</key>
diff --git a/TOOLS/zsh.pl b/TOOLS/zsh.pl
index 67c0201..15c181f 100755
--- a/TOOLS/zsh.pl
+++ b/TOOLS/zsh.pl
@@ -15,7 +15,9 @@ my @vo = parse_opts("$mpv --vo=help", '^ ([^\s\:]*)\s*: (.*)');
my @af = parse_opts("$mpv --af=help", '^ ([^\s\:]*)\s*: (.*)');
my @vf = parse_opts("$mpv --vf=help", '^ ([^\s\:]*)\s*: (.*)');
-my ($opts_str, $ao_str, $vo_str, $af_str, $vf_str);
+my @protos = parse_opts("$mpv --list-protocols", '^ ([^\s]*)');
+
+my ($opts_str, $ao_str, $vo_str, $af_str, $vf_str, $protos_str);
$opts_str .= qq{ '$_' \\\n} foreach (@opts);
chomp $opts_str;
@@ -32,12 +34,15 @@ chomp $af_str;
$vf_str .= qq{ '$_' \\\n} foreach (@vf);
chomp $vf_str;
+$protos_str .= qq{$_ } foreach (@protos);
+chomp $protos_str;
+
my $tmpl = <<"EOS";
#compdef mpv
# mpv zsh completion
-_x_arguments -C -s \\
+_arguments -C -S \\
$opts_str
'*:files:->mfiles'
@@ -86,7 +91,7 @@ $vf_str
if _requested urls; then
while _next_label urls expl URL; do
_urls "\$expl[@]" && ret=0
- compadd -S '' "\$expl[@]" \{dvd,vcd,cdda,cddb,tv\}:// && ret=0
+ compadd -S '' "\$expl[@]" $protos_str && ret=0
done
fi
(( ret )) || return 0
@@ -98,49 +103,49 @@ EOS
print $tmpl;
sub parse_opts {
- my ($cmd, $regex, $parsing_main_options) = @_;
+ my ($cmd, $regex, $parsing_main_options) = @_;
- my @list;
- my @lines = split /\n/, `$cmd`;
+ my @list;
+ my @lines = split /\n/, `$cmd`;
- foreach my $line (@lines) {
- if ($line !~ /^$regex/) {
- next;
- }
+ foreach my $line (@lines) {
+ if ($line !~ /^$regex/) {
+ next;
+ }
- my $entry = $1;
+ my $entry = $1;
- if ($parsing_main_options) {
- $entry .= '=-';
- }
+ if ($parsing_main_options) {
+ $entry .= '=-';
+ }
- if (defined $2) {
- my $desc = $2;
- $desc =~ s/\:/\\:/g;
+ if (defined $2) {
+ my $desc = $2;
+ $desc =~ s/\:/\\:/g;
- $entry .= ':' . $desc;
- }
+ $entry .= ':' . $desc;
+ }
- if ($parsing_main_options) {
- $entry .= ':';
+ if ($parsing_main_options) {
+ $entry .= ':';
- $entry .= '->ao' if ($1 eq '--ao');
- $entry .= '->vo' if ($1 eq '--vo');
- $entry .= '->af' if ($1 eq '--af');
- $entry .= '->vf' if ($1 eq '--vf');
- }
+ $entry .= '->ao' if ($1 eq '--ao');
+ $entry .= '->vo' if ($1 eq '--vo');
+ $entry .= '->af' if ($1 eq '--af');
+ $entry .= '->vf' if ($1 eq '--vf');
+ }
- push @list, $entry
- }
+ push @list, $entry
+ }
- if ($parsing_main_options) {
- @list = sort {
- $a =~ /(.*?)\:/; my $ma = $1;
- $b =~ /(.*?)\:/; my $mb = $1;
+ if ($parsing_main_options) {
+ @list = sort {
+ $a =~ /(.*?)\:/; my $ma = $1;
+ $b =~ /(.*?)\:/; my $mb = $1;
- length($mb) <=> length($ma)
- } @list;
- }
+ length($mb) <=> length($ma)
+ } @list;
+ }
- return @list;
+ return @list;
}
diff --git a/VERSION b/VERSION
index 2b7c5ae..8f0916f 100644
--- a/VERSION
+++ b/VERSION
@@ -1 +1 @@
-0.4.2
+0.5.0
diff --git a/audio/decode/ad.h b/audio/decode/ad.h
index 2ac9fb2..e09ded2 100644
--- a/audio/decode/ad.h
+++ b/audio/decode/ad.h
@@ -36,7 +36,7 @@ struct ad_functions {
int (*init)(struct dec_audio *da, const char *decoder);
void (*uninit)(struct dec_audio *da);
int (*control)(struct dec_audio *da, int cmd, void *arg);
- int (*decode_audio)(struct dec_audio *da, struct mp_audio *buffer, int maxlen);
+ int (*decode_packet)(struct dec_audio *da);
};
enum ad_ctrl {
diff --git a/audio/decode/ad_lavc.c b/audio/decode/ad_lavc.c
index 404cf19..c4372ba 100644
--- a/audio/decode/ad_lavc.c
+++ b/audio/decode/ad_lavc.c
@@ -33,7 +33,6 @@
#include "common/codecs.h"
#include "common/msg.h"
#include "options/options.h"
-#include "common/av_opts.h"
#include "ad.h"
#include "audio/fmt-conversion.h"
@@ -49,14 +48,13 @@ struct priv {
};
static void uninit(struct dec_audio *da);
-static int decode_new_packet(struct dec_audio *da);
#define OPT_BASE_STRUCT struct ad_lavc_params
struct ad_lavc_params {
float ac3drc;
int downmix;
int threads;
- char *avopt;
+ char **avopts;
};
const struct m_sub_options ad_lavc_conf = {
@@ -64,7 +62,7 @@ const struct m_sub_options ad_lavc_conf = {
OPT_FLOATRANGE("ac3drc", ac3drc, 0, 0, 2),
OPT_FLAG("downmix", downmix, 0),
OPT_INTRANGE("threads", threads, 0, 1, 16),
- OPT_STRING("o", avopt, 0),
+ OPT_KEYVALUELIST("o", avopts, 0),
{0}
},
.size = sizeof(struct ad_lavc_params),
@@ -143,11 +141,10 @@ static const char *find_pcm_decoder(const struct pcm_map *map, int format,
return NULL;
}
-static int setup_format(struct dec_audio *da)
+static void set_data_from_avframe(struct dec_audio *da)
{
struct priv *priv = da->priv;
AVCodecContext *lavc_context = priv->avctx;
- struct sh_audio *sh_audio = da->header->audio;
// Note: invalid parameters are rejected by dec_audio.c
@@ -157,12 +154,6 @@ static int setup_format(struct dec_audio *da)
MP_FATAL(da, "unsupported lavc format %s", av_get_sample_fmt_name(fmt));
da->decoded.rate = lavc_context->sample_rate;
- if (!da->decoded.rate && sh_audio->wf) {
- // If not set, try container samplerate.
- // (Maybe this can't happen, and it's an artifact from the past.)
- da->decoded.rate = sh_audio->wf->nSamplesPerSec;
- MP_WARN(da, "using container rate.\n");
- }
struct mp_chmap lavc_chmap;
mp_chmap_from_lavc(&lavc_chmap, lavc_context->channel_layout);
@@ -170,12 +161,15 @@ static int setup_format(struct dec_audio *da)
if (lavc_chmap.num != lavc_context->channels)
mp_chmap_from_channels(&lavc_chmap, lavc_context->channels);
if (priv->force_channel_map) {
+ struct sh_audio *sh_audio = da->header->audio;
if (lavc_chmap.num == sh_audio->channels.num)
lavc_chmap = sh_audio->channels;
}
mp_audio_set_channels(&da->decoded, &lavc_chmap);
- return 0;
+ da->decoded.samples = priv->avframe->nb_samples;
+ for (int n = 0; n < da->decoded.num_planes; n++)
+ da->decoded.planes[n] = priv->avframe->data[n];
}
static void set_from_wf(AVCodecContext *avctx, MP_WAVEFORMATEX *wf)
@@ -233,13 +227,7 @@ static int init(struct dec_audio *da, const char *decoder)
av_opt_set_double(lavc_context, "drc_scale", opts->ac3drc,
AV_OPT_SEARCH_CHILDREN);
- if (opts->avopt) {
- if (parse_avopts(lavc_context, opts->avopt) < 0) {
- MP_ERR(da, "setting AVOptions '%s' failed.\n", opts->avopt);
- uninit(da);
- return 0;
- }
- }
+ mp_set_avopts(da->log, lavc_context, opts->avopts);
lavc_context->codec_tag = sh->format;
lavc_context->sample_rate = sh_audio->samplerate;
@@ -267,22 +255,6 @@ static int init(struct dec_audio *da, const char *decoder)
uninit(da);
return 0;
}
- MP_VERBOSE(da, "INFO: libavcodec \"%s\" init OK!\n",
- lavc_codec->name);
-
- // Decode at least 1 sample: (to get header filled)
- for (int tries = 1; ; tries++) {
- int x = decode_new_packet(da);
- if (x >= 0 && ctx->frame.samples > 0) {
- MP_VERBOSE(da, "Initial decode succeeded after %d packets.\n", tries);
- break;
- }
- if (tries >= 50) {
- MP_ERR(da, "initial decode failed\n");
- uninit(da);
- return 0;
- }
- }
if (lavc_context->bit_rate != 0)
da->bitrate = lavc_context->bit_rate;
@@ -314,7 +286,7 @@ static int control(struct dec_audio *da, int cmd, void *arg)
switch (cmd) {
case ADCTRL_RESET:
avcodec_flush_buffers(ctx->avctx);
- ctx->frame.samples = 0;
+ mp_audio_set_null_data(&da->decoded);
talloc_free(ctx->packet);
ctx->packet = NULL;
return CONTROL_TRUE;
@@ -322,16 +294,18 @@ static int control(struct dec_audio *da, int cmd, void *arg)
return CONTROL_UNKNOWN;
}
-static int decode_new_packet(struct dec_audio *da)
+static int decode_packet(struct dec_audio *da)
{
struct priv *priv = da->priv;
AVCodecContext *avctx = priv->avctx;
- priv->frame.samples = 0;
+ mp_audio_set_null_data(&da->decoded);
struct demux_packet *mpkt = priv->packet;
- if (!mpkt)
- mpkt = demux_read_packet(da->header);
+ if (!mpkt) {
+ if (demux_read_packet_async(da->header, &mpkt) == 0)
+ return AD_WAIT;
+ }
priv->packet = talloc_steal(priv, mpkt);
@@ -364,22 +338,16 @@ static int decode_new_packet(struct dec_audio *da)
}
// LATM may need many packets to find mux info
if (ret == AVERROR(EAGAIN))
- return 0;
+ return AD_OK;
}
if (ret < 0) {
- MP_VERBOSE(da, "lavc_audio: error\n");
- return -1;
+ MP_ERR(da, "Error decoding audio.\n");
+ return AD_ERR;
}
if (!got_frame)
- return mpkt ? 0 : -1; // -1: eof
+ return mpkt ? AD_OK : AD_EOF;
- if (setup_format(da) < 0)
- return -1;
-
- priv->frame.samples = priv->avframe->nb_samples;
- mp_audio_copy_config(&priv->frame, &da->decoded);
- for (int n = 0; n < priv->frame.num_planes; n++)
- priv->frame.planes[n] = priv->avframe->data[n];
+ set_data_from_avframe(da);
double out_pts = mp_pts_from_av(priv->avframe->pkt_pts, NULL);
if (out_pts != MP_NOPTS_VALUE) {
@@ -387,27 +355,7 @@ static int decode_new_packet(struct dec_audio *da)
da->pts_offset = 0;
}
- MP_DBG(da, "Decoded %d -> %d samples\n", in_len,
- priv->frame.samples);
- return 0;
-}
-
-static int decode_audio(struct dec_audio *da, struct mp_audio *buffer, int maxlen)
-{
- struct priv *priv = da->priv;
-
- if (!priv->frame.samples) {
- if (decode_new_packet(da) < 0)
- return -1;
- }
-
- if (!mp_audio_config_equals(buffer, &priv->frame))
- return 0;
-
- buffer->samples = MPMIN(priv->frame.samples, maxlen);
- mp_audio_copy(buffer, 0, &priv->frame, 0, buffer->samples);
- mp_audio_skip_samples(&priv->frame, buffer->samples);
- da->pts_offset += buffer->samples;
+ MP_DBG(da, "Decoded %d -> %d samples\n", in_len, da->decoded.samples);
return 0;
}
@@ -424,5 +372,5 @@ const struct ad_functions ad_lavc = {
.init = init,
.uninit = uninit,
.control = control,
- .decode_audio = decode_audio,
+ .decode_packet = decode_packet,
};
diff --git a/audio/decode/ad_mpg123.c b/audio/decode/ad_mpg123.c
index ec4dc04..30a4790 100644
--- a/audio/decode/ad_mpg123.c
+++ b/audio/decode/ad_mpg123.c
@@ -35,9 +35,7 @@
struct ad_mpg123_context {
mpg123_handle *handle;
- bool new_format;
int sample_size;
- bool need_data;
/* Running mean for bit rate, stream length estimation. */
float mean_rate;
unsigned int mean_count;
@@ -58,7 +56,7 @@ static void uninit(struct dec_audio *da)
/* This initializes libmpg123 and prepares the handle, including funky
* parameters. */
-static int preinit(struct dec_audio *da)
+static int init(struct dec_audio *da, const char *decoder)
{
int err;
struct ad_mpg123_context *con;
@@ -111,15 +109,18 @@ static int preinit(struct dec_audio *da)
* We need at least 1152 samples. dec_audio.c normally guarantees this. */
mpg123_param(con->handle, MPG123_REMOVE_FLAGS, MPG123_AUTO_RESAMPLE, 0.);
+ err = mpg123_open_feed(con->handle);
+ if (err != MPG123_OK)
+ goto bad_end;
+
return 1;
bad_end:
- if (!con->handle)
- MP_ERR(da, "mpg123 preinit error: %s\n",
- mpg123_plain_strerror(err));
- else
- MP_ERR(da, "mpg123 preinit error: %s\n",
- mpg123_strerror(con->handle));
+ if (!con->handle) {
+ MP_ERR(da, "mpg123 preinit error: %s\n", mpg123_plain_strerror(err));
+ } else {
+ MP_ERR(da, "mpg123 preinit error: %s\n", mpg123_strerror(con->handle));
+ }
uninit(da);
return 0;
@@ -140,111 +141,6 @@ static int mpg123_format_to_af(int mpg123_encoding)
return 0;
}
-/* libmpg123 has a new format ready; query and store, return return value
- of mpg123_getformat() */
-static int set_format(struct dec_audio *da)
-{
- struct ad_mpg123_context *con = da->priv;
- int ret;
- long rate;
- int channels;
- int encoding;
- ret = mpg123_getformat(con->handle, &rate, &channels, &encoding);
- if (ret == MPG123_OK) {
- mp_audio_set_num_channels(&da->decoded, channels);
- da->decoded.rate = rate;
- int af = mpg123_format_to_af(encoding);
- if (!af) {
- /* This means we got a funny custom build of libmpg123 that only supports an unknown format. */
- MP_ERR(da, "Bad encoding from mpg123: %i.\n", encoding);
- return MPG123_ERR;
- }
- mp_audio_set_format(&da->decoded, af);
- con->sample_size = channels * af_fmt2bps(af);
- con->new_format = 0;
- }
- return ret;
-}
-
-static int feed_new_packet(struct dec_audio *da)
-{
- struct ad_mpg123_context *con = da->priv;
- int ret;
-
- struct demux_packet *pkt = demux_read_packet(da->header);
- if (!pkt)
- return -1; /* EOF. */
-
- /* Next bytes from that presentation time. */
- if (pkt->pts != MP_NOPTS_VALUE) {
- da->pts = pkt->pts;
- da->pts_offset = 0;
- }
-
- /* Have to use mpg123_feed() to avoid decoding here. */
- ret = mpg123_feed(con->handle, pkt->buffer, pkt->len);
- talloc_free(pkt);
-
- if (ret == MPG123_ERR)
- return -1;
-
- if (ret == MPG123_NEW_FORMAT)
- con->new_format = 1;
-
- return 0;
-}
-
-/* Now we really start accessing some data and determining file format.
- * Format now is allowed to change on-the-fly. Here is the only point
- * that has MPlayer react to errors. We have to pray that exceptional
- * erros in other places simply cannot occur. */
-static int init(struct dec_audio *da, const char *decoder)
-{
- if (!preinit(da))
- return 0;
-
- struct ad_mpg123_context *con = da->priv;
- int ret;
-
- ret = mpg123_open_feed(con->handle);
- if (ret != MPG123_OK)
- goto fail;
-
- for (int n = 0; ; n++) {
- if (feed_new_packet(da) < 0) {
- ret = MPG123_NEED_MORE;
- goto fail;
- }
- size_t got_now = 0;
- ret = mpg123_decode_frame(con->handle, NULL, NULL, &got_now);
- if (ret == MPG123_OK || ret == MPG123_NEW_FORMAT) {
- ret = set_format(da);
- if (ret == MPG123_OK)
- break;
- }
- if (ret != MPG123_NEED_MORE)
- goto fail;
- // max. 16 retries (randomly chosen number)
- if (n > 16) {
- ret = MPG123_NEED_MORE;
- goto fail;
- }
- }
-
- return 1;
-
-fail:
- if (ret == MPG123_NEED_MORE) {
- MP_ERR(da, "Could not find mp3 stream.\n");
- } else {
- MP_ERR(da, "mpg123 init error: %s\n",
- mpg123_strerror(con->handle));
- }
-
- uninit(da);
- return 0;
-}
-
/* Compute bitrate from frame size. */
static int compute_bitrate(struct mpg123_frameinfo *i)
{
@@ -290,57 +186,86 @@ static void update_info(struct dec_audio *da)
}
}
-static int decode_audio(struct dec_audio *da, struct mp_audio *buffer, int maxlen)
+/* libmpg123 has a new format ready; query and store, return return value
+ of mpg123_getformat() */
+static int set_format(struct dec_audio *da)
{
struct ad_mpg123_context *con = da->priv;
- void *buf = buffer->planes[0];
int ret;
-
- if (con->new_format) {
- ret = set_format(da);
- if (ret == MPG123_OK) {
- return 0; // let caller handle format change
- } else if (ret == MPG123_NEED_MORE) {
- con->need_data = true;
- } else {
- goto mpg123_fail;
+ long rate;
+ int channels;
+ int encoding;
+ ret = mpg123_getformat(con->handle, &rate, &channels, &encoding);
+ if (ret == MPG123_OK) {
+ mp_audio_set_num_channels(&da->decoded, channels);
+ da->decoded.rate = rate;
+ int af = mpg123_format_to_af(encoding);
+ if (!af) {
+ /* This means we got a funny custom build of libmpg123 that only supports an unknown format. */
+ MP_ERR(da, "Bad encoding from mpg123: %i.\n", encoding);
+ return MPG123_ERR;
}
+ mp_audio_set_format(&da->decoded, af);
+ con->sample_size = channels * af_fmt2bps(af);
}
+ return ret;
+}
+
+static int decode_packet(struct dec_audio *da)
+{
+ struct ad_mpg123_context *con = da->priv;
+ int ret;
+
+ mp_audio_set_null_data(&da->decoded);
+
+ struct demux_packet *pkt;
+ if (demux_read_packet_async(da->header, &pkt) == 0)
+ return AD_WAIT;
+ if (!pkt)
+ return AD_EOF;
- if (con->need_data) {
- if (feed_new_packet(da) < 0)
- return -1;
+ /* Next bytes from that presentation time. */
+ if (pkt->pts != MP_NOPTS_VALUE) {
+ da->pts = pkt->pts;
+ da->pts_offset = 0;
}
- if (!mp_audio_config_equals(&da->decoded, buffer))
- return 0;
+ /* Have to use mpg123_feed() to avoid decoding here. */
+ ret = mpg123_feed(con->handle, pkt->buffer, pkt->len);
+ talloc_free(pkt);
- size_t got_now = 0;
- ret = mpg123_replace_buffer(con->handle, buf, maxlen * con->sample_size);
if (ret != MPG123_OK)
goto mpg123_fail;
- ret = mpg123_decode_frame(con->handle, NULL, NULL, &got_now);
+ unsigned char *audio = NULL;
+ size_t bytes = 0;
+ ret = mpg123_decode_frame(con->handle, NULL, &audio, &bytes);
- int got_samples = got_now / con->sample_size;
- buffer->samples += got_samples;
- da->pts_offset += got_samples;
+ if (ret == MPG123_NEED_MORE)
+ return 0;
- if (ret == MPG123_NEW_FORMAT) {
- con->new_format = true;
- } else if (ret == MPG123_NEED_MORE) {
- con->need_data = true;
- } else if (ret != MPG123_OK && ret != MPG123_DONE) {
+ if (ret != MPG123_OK && ret != MPG123_DONE && ret != MPG123_NEW_FORMAT)
goto mpg123_fail;
+
+ ret = set_format(da);
+ if (ret != MPG123_OK)
+ goto mpg123_fail;
+
+ if (con->sample_size < 1) {
+ MP_ERR(da, "no sample size\n");
+ return AD_ERR;
}
+ int got_samples = bytes / con->sample_size;
+ da->decoded.planes[0] = audio;
+ da->decoded.samples = got_samples;
+
update_info(da);
return 0;
mpg123_fail:
- MP_ERR(da, "mpg123 decoding error: %s\n",
- mpg123_strerror(con->handle));
- return -1;
+ MP_ERR(da, "mpg123 decoding error: %s\n", mpg123_strerror(con->handle));
+ return AD_ERR;
}
static int control(struct dec_audio *da, int cmd, void *arg)
@@ -349,6 +274,7 @@ static int control(struct dec_audio *da, int cmd, void *arg)
switch (cmd) {
case ADCTRL_RESET:
+ mp_audio_set_null_data(&da->decoded);
mpg123_close(con->handle);
if (mpg123_open_feed(con->handle) != MPG123_OK) {
@@ -373,5 +299,5 @@ const struct ad_functions ad_mpg123 = {
.init = init,
.uninit = uninit,
.control = control,
- .decode_audio = decode_audio,
+ .decode_packet = decode_packet,
};
diff --git a/audio/decode/ad_spdif.c b/audio/decode/ad_spdif.c
index c055715..528e42f 100644
--- a/audio/decode/ad_spdif.c
+++ b/audio/decode/ad_spdif.c
@@ -38,8 +38,7 @@ struct spdifContext {
AVFormatContext *lavf_ctx;
int iec61937_packet_size;
int out_buffer_len;
- int out_buffer_size;
- uint8_t *out_buffer;
+ uint8_t out_buffer[OUTBUF_SIZE];
bool need_close;
};
@@ -47,7 +46,7 @@ static int write_packet(void *p, uint8_t *buf, int buf_size)
{
struct spdifContext *ctx = p;
- int buffer_left = ctx->out_buffer_size - ctx->out_buffer_len;
+ int buffer_left = OUTBUF_SIZE - ctx->out_buffer_len;
if (buf_size > buffer_left) {
MP_ERR(ctx, "spdif packet too large.\n");
buf_size = buffer_left;
@@ -183,24 +182,21 @@ fail:
return 0;
}
-static int decode_audio(struct dec_audio *da, struct mp_audio *buffer, int maxlen)
+static int decode_packet(struct dec_audio *da)
{
struct spdifContext *spdif_ctx = da->priv;
AVFormatContext *lavf_ctx = spdif_ctx->lavf_ctx;
- int sstride = 2 * da->decoded.channels.num;
- assert(sstride == buffer->sstride);
-
- if (maxlen * sstride < spdif_ctx->iec61937_packet_size)
- return 0;
+ mp_audio_set_null_data(&da->decoded);
spdif_ctx->out_buffer_len = 0;
- spdif_ctx->out_buffer_size = maxlen * sstride;
- spdif_ctx->out_buffer = buffer->planes[0];
- struct demux_packet *mpkt = demux_read_packet(da->header);
+ struct demux_packet *mpkt;
+ if (demux_read_packet_async(da->header, &mpkt) == 0)
+ return AD_WAIT;
+
if (!mpkt)
- return -1;
+ return AD_EOF;
AVPacket pkt;
mp_set_av_packet(&pkt, mpkt, NULL);
@@ -211,12 +207,13 @@ static int decode_audio(struct dec_audio *da, struct mp_audio *buffer, int maxle
da->pts_offset = 0;
}
int ret = av_write_frame(lavf_ctx, &pkt);
- avio_flush(lavf_ctx->pb);
- buffer->samples = spdif_ctx->out_buffer_len / sstride;
- da->pts_offset += buffer->samples;
talloc_free(mpkt);
+ avio_flush(lavf_ctx->pb);
if (ret < 0)
- return -1;
+ return AD_ERR;
+
+ da->decoded.planes[0] = spdif_ctx->out_buffer;
+ da->decoded.samples = spdif_ctx->out_buffer_len / da->decoded.sstride;
return 0;
}
@@ -253,5 +250,5 @@ const struct ad_functions ad_spdif = {
.init = init,
.uninit = uninit,
.control = control,
- .decode_audio = decode_audio,
+ .decode_packet = decode_packet,
};
diff --git a/audio/decode/dec_audio.c b/audio/decode/dec_audio.c
index b8d83e8..c7580a2 100644
--- a/audio/decode/dec_audio.c
+++ b/audio/decode/dec_audio.c
@@ -56,13 +56,6 @@ static const struct ad_functions * const ad_drivers[] = {
NULL
};
-// ad_mpg123 needs to be able to decode 1152 samples at once
-// ad_spdif needs up to 8192
-#define DECODE_MAX_UNIT MPMAX(8192, 1152)
-
-// At least 8192 samples, plus hack for ad_mpg123 and ad_spdif
-#define DECODE_BUFFER_SAMPLES (8192 + DECODE_MAX_UNIT)
-
// Drop audio buffer and reinit it (after format change)
// Returns whether the format was valid at all.
static bool reinit_audio_buffer(struct dec_audio *da)
@@ -73,7 +66,6 @@ static bool reinit_audio_buffer(struct dec_audio *da)
return false;
}
mp_audio_buffer_reinit(da->decode_buffer, &da->decoded);
- mp_audio_buffer_preallocate_min(da->decode_buffer, DECODE_BUFFER_SAMPLES);
return true;
}
@@ -98,11 +90,6 @@ static int init_audio_codec(struct dec_audio *d_audio, const char *decoder)
}
d_audio->decode_buffer = mp_audio_buffer_create(NULL);
- if (!reinit_audio_buffer(d_audio)) {
- uninit_decoder(d_audio);
- return 0;
- }
-
return 1;
}
@@ -164,9 +151,6 @@ int audio_init_best_codec(struct dec_audio *d_audio, char *audio_decoders)
talloc_asprintf(d_audio, "%s [%s:%s]", decoder->desc, decoder->family,
decoder->decoder);
MP_VERBOSE(d_audio, "Selected audio codec: %s\n", d_audio->decoder_desc);
- MP_VERBOSE(d_audio, "AUDIO: %d Hz, %d ch, %s\n",
- d_audio->decoded.rate, d_audio->decoded.channels.num,
- af_fmt_to_str(d_audio->decoded.format));
} else {
MP_ERR(d_audio, "Failed to initialize an audio decoder for codec '%s'.\n",
d_audio->header->codec ? d_audio->header->codec : "<unknown>");
@@ -209,8 +193,6 @@ int audio_init_filters(struct dec_audio *d_audio, int in_samplerate,
mp_audio_set_channels(&afs->output, out_channels);
mp_audio_set_format(&afs->output, *out_format);
- afs->metadata = d_audio->metadata;
-
afs->replaygain_data = d_audio->replaygain_data;
char *s_from = mp_audio_config_to_str(&afs->input);
@@ -233,61 +215,82 @@ int audio_init_filters(struct dec_audio *d_audio, int in_samplerate,
return 1;
}
+/* Decode packets until we know the audio format. Then reinit the buffer.
+ * Returns AD_OK on success, negative AD_* code otherwise.
+ * Also returns AD_OK if already initialized (and does nothing).
+ */
+int initial_audio_decode(struct dec_audio *da)
+{
+ while (!mp_audio_config_valid(&da->decoded)) {
+ if (da->decoded.samples > 0)
+ return AD_ERR; // invalid format, rather than uninitialized
+ int ret = da->ad_driver->decode_packet(da);
+ if (ret < 0)
+ return ret;
+ }
+ if (mp_audio_buffer_samples(da->decode_buffer) > 0) // avoid accidental flush
+ return AD_OK;
+ return reinit_audio_buffer(da) ? AD_OK : AD_ERR;
+}
+
// Filter len bytes of input, put result into outbuf.
static int filter_n_bytes(struct dec_audio *da, struct mp_audio_buffer *outbuf,
int len)
{
+ bool format_change = false;
int error = 0;
- struct mp_audio config;
- mp_audio_buffer_get_format(da->decode_buffer, &config);
+ assert(len > 0); // would break EOF logic below
while (mp_audio_buffer_samples(da->decode_buffer) < len) {
- int maxlen = mp_audio_buffer_get_write_available(da->decode_buffer);
- if (maxlen < DECODE_MAX_UNIT)
+ // Check for a format change
+ struct mp_audio config;
+ mp_audio_buffer_get_format(da->decode_buffer, &config);
+ format_change = !mp_audio_config_equals(&da->decoded, &config);
+ if (format_change) {
+ error = AD_EOF; // drain remaining data left in the current buffer
break;
- struct mp_audio buffer;
- mp_audio_buffer_get_write_buffer(da->decode_buffer, maxlen, &buffer);
- buffer.samples = 0;
- error = da->ad_driver->decode_audio(da, &buffer, maxlen);
+ }
+ if (da->decoded.samples > 0) {
+ int copy = MPMIN(da->decoded.samples, len);
+ struct mp_audio append = da->decoded;
+ append.samples = copy;
+ mp_audio_buffer_append(da->decode_buffer, &append);
+ mp_audio_skip_samples(&da->decoded, copy);
+ da->pts_offset += copy;
+ continue;
+ }
+ error = da->ad_driver->decode_packet(da);
if (error < 0)
break;
- // Commit the data just read as valid data
- mp_audio_buffer_finish_write(da->decode_buffer, buffer.samples);
- // Format change
- if (!mp_audio_config_equals(&da->decoded, &config)) {
- // If there are still samples left in the buffer, let them drain
- // first, and don't signal a format change to the caller yet.
- if (mp_audio_buffer_samples(da->decode_buffer) > 0)
- break;
- error = -2;
- break;
- }
}
+ if (error == AD_WAIT)
+ return error;
+
// Filter
struct mp_audio filter_data;
mp_audio_buffer_peek(da->decode_buffer, &filter_data);
filter_data.rate = da->afilter->input.rate; // due to playback speed change
len = MPMIN(filter_data.samples, len);
filter_data.samples = len;
- bool eof = filter_data.samples == 0 && error < 0;
+ bool eof = error == AD_EOF && filter_data.samples == 0;
if (af_filter(da->afilter, &filter_data, eof ? AF_FILTER_FLAG_EOF : 0) < 0)
- return -1;
+ return AD_ERR;
mp_audio_buffer_append(outbuf, &filter_data);
- if (eof && filter_data.samples > 0)
+ if (error == AD_EOF && filter_data.samples > 0)
error = 0; // don't end playback yet
// remove processed data from decoder buffer:
mp_audio_buffer_skip(da->decode_buffer, len);
- // Assume the filter chain is drained from old data at this point.
- // (If not, the remaining old data is discarded.)
- if (error == -2) {
+ // if format was changed, and all data was drained, execute the format change
+ if (format_change && eof) {
+ error = AD_NEW_FMT;
if (!reinit_audio_buffer(da))
- error = -1; // switch to invalid format
+ error = AD_ERR; // switch to invalid format
}
return error;
@@ -295,17 +298,17 @@ static int filter_n_bytes(struct dec_audio *da, struct mp_audio_buffer *outbuf,
/* Try to get at least minsamples decoded+filtered samples in outbuf
* (total length including possible existing data).
- * Return 0 on success, -1 on error/EOF (not distinguidaed).
+ * Return 0 on success, or negative AD_* error code.
* In the former case outbuf has at least minsamples buffered on return.
* In case of EOF/error it might or might not be. */
int audio_decode(struct dec_audio *d_audio, struct mp_audio_buffer *outbuf,
int minsamples)
{
+ if (!d_audio->afilter)
+ return AD_ERR;
+
// Indicates that a filter seems to be buffering large amounts of data
int huge_filter_buffer = 0;
- // Decoded audio must be cut at boundaries of this many samples
- // (Note: the reason for this is unknown, possibly a refactoring artifact)
- int unitsize = 16;
/* Filter output size will be about filter_multiplier times input size.
* If some filter buffers audio in big blocks this might only hold
@@ -322,8 +325,8 @@ int audio_decode(struct dec_audio *d_audio, struct mp_audio_buffer *outbuf,
prev_buffered = buffered;
int decsamples = (minsamples - buffered) / filter_multiplier;
- // + some extra for possible filter buffering
- decsamples += unitsize << 5;
+ // + some extra for possible filter buffering, and avoid 0
+ decsamples += 512;
if (huge_filter_buffer) {
/* Some filter must be doing significant buffering if the estimated
diff --git a/audio/decode/dec_audio.h b/audio/decode/dec_audio.h
index 9108f6f..b76ff0b 100644
--- a/audio/decode/dec_audio.h
+++ b/audio/decode/dec_audio.h
@@ -36,12 +36,10 @@ struct dec_audio {
struct mp_audio_buffer *decode_buffer;
struct af_stream *afilter;
char *decoder_desc;
- struct mp_tags *metadata;
struct replaygain_data *replaygain_data;
+ int init_retries;
// set by decoder
- struct mp_audio decoded; // format of decoded audio (no data, temporarily
- // different from decode_buffer during format
- // changes)
+ struct mp_audio decoded; // decoded audio set by last decode_packet() call
int bitrate; // input bitrate, can change with VBR sources
// last known pts value in output from decoder
double pts;
@@ -51,10 +49,19 @@ struct dec_audio {
void *priv;
};
+enum {
+ AD_OK = 0,
+ AD_ERR = -1,
+ AD_EOF = -2,
+ AD_NEW_FMT = -3,
+ AD_WAIT = -4,
+};
+
struct mp_decoder_list *audio_decoder_list(void);
int audio_init_best_codec(struct dec_audio *d_audio, char *audio_decoders);
int audio_decode(struct dec_audio *d_audio, struct mp_audio_buffer *outbuf,
int minsamples);
+int initial_audio_decode(struct dec_audio *d_audio);
void audio_reset_decoding(struct dec_audio *d_audio);
void audio_uninit(struct dec_audio *d_audio);
diff --git a/audio/filter/af.c b/audio/filter/af.c
index c69077e..9227c9c 100644
--- a/audio/filter/af.c
+++ b/audio/filter/af.c
@@ -204,7 +204,6 @@ static struct af_instance *af_create(struct af_stream *s, char *name,
.mul = 1,
.data = talloc_zero(af, struct mp_audio),
.log = mp_log_new(af, s->log, name),
- .metadata = s->metadata,
.replaygain_data = s->replaygain_data,
};
struct m_config *config = m_config_from_obj_desc(af, s->log, &desc);
@@ -311,22 +310,22 @@ static void af_print_filter_chain(struct af_stream *s, struct af_instance *at,
struct af_instance *af = s->first;
while (af) {
- MP_MSG(s, msg_level, " [%s] ", af->info->name);
+ char b[128] = {0};
+ mp_snprintf_cat(b, sizeof(b), " [%s] ", af->info->name);
if (af->data) {
char *info = mp_audio_config_to_str(af->data);
- MP_MSG(s, msg_level, "%s", info);
+ mp_snprintf_cat(b, sizeof(b), "%s", info);
talloc_free(info);
}
if (af == at)
- MP_MSG(s, msg_level, " <-");
- MP_MSG(s, msg_level, "\n");
+ mp_snprintf_cat(b, sizeof(b), " <-");
+ MP_MSG(s, msg_level, "%s\n", b);
af = af->next;
}
- MP_MSG(s, msg_level, " [ao] ");
char *info = mp_audio_config_to_str(&s->output);
- MP_MSG(s, msg_level, "%s\n", info);
+ MP_MSG(s, msg_level, " [ao] %s\n", info);
talloc_free(info);
}
diff --git a/audio/filter/af.h b/audio/filter/af.h
index aa49963..bec0e82 100644
--- a/audio/filter/af.h
+++ b/audio/filter/af.h
@@ -59,7 +59,6 @@ struct af_info {
struct af_instance {
const struct af_info *info;
struct mp_log *log;
- struct mp_tags *metadata;
struct replaygain_data *replaygain_data;
int (*control)(struct af_instance *af, int cmd, void *arg);
void (*uninit)(struct af_instance *af);
@@ -92,7 +91,6 @@ struct af_stream {
struct mp_log *log;
struct MPOpts *opts;
- struct mp_tags *metadata;
struct replaygain_data *replaygain_data;
};
diff --git a/audio/filter/af_lavfi.c b/audio/filter/af_lavfi.c
index a565e20..0b7a619 100644
--- a/audio/filter/af_lavfi.c
+++ b/audio/filter/af_lavfi.c
@@ -38,8 +38,9 @@
#include "audio/fmt-conversion.h"
#include "af.h"
+#include "common/av_common.h"
+
#include "options/m_option.h"
-#include "common/av_opts.h"
// FFmpeg and Libav have slightly different APIs, just enough to cause us
// unnecessary pain. <Expletive deleted.>
@@ -62,7 +63,7 @@ struct priv {
// options
char *cfg_graph;
- char *cfg_avopts;
+ char **cfg_avopts;
};
static void destroy_graph(struct af_instance *af)
@@ -90,11 +91,8 @@ static bool recreate_graph(struct af_instance *af, struct mp_audio *config)
if (!graph)
goto error;
- if (parse_avopts(graph, p->cfg_avopts) < 0) {
- MP_FATAL(af, "lavfi: could not set opts: '%s'\n",
- p->cfg_avopts);
+ if (mp_set_avopts(af->log, graph, p->cfg_avopts) < 0)
goto error;
- }
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
@@ -306,7 +304,7 @@ const struct af_info af_info_lavfi = {
.priv_size = sizeof(struct priv),
.options = (const struct m_option[]) {
OPT_STRING("graph", cfg_graph, 0),
- OPT_STRING("o", cfg_avopts, 0),
+ OPT_KEYVALUELIST("o", cfg_avopts, 0),
{0}
},
};
diff --git a/audio/filter/af_lavrresample.c b/audio/filter/af_lavrresample.c
index 8e33f3b..26bbd56 100644
--- a/audio/filter/af_lavrresample.c
+++ b/audio/filter/af_lavrresample.c
@@ -52,9 +52,9 @@
#error "config.h broken or no resampler found"
#endif
+#include "common/av_common.h"
#include "common/msg.h"
#include "options/m_option.h"
-#include "common/av_opts.h"
#include "audio/filter/af.h"
#include "audio/fmt-conversion.h"
@@ -74,7 +74,7 @@ struct af_resample_opts {
struct af_resample {
int allow_detach;
- char *avopts;
+ char **avopts;
struct AVAudioResampleContext *avrctx;
struct AVAudioResampleContext *avrctx_out; // for output channel reordering
struct af_resample_opts ctx; // opts in the context
@@ -164,10 +164,8 @@ static int configure_lavrr(struct af_instance *af, struct mp_audio *in,
av_opt_set_double(s->avrctx, "cutoff", s->ctx.cutoff, 0);
- if (parse_avopts(s->avrctx, s->avopts) < 0) {
- MP_FATAL(af, "af_lavrresample: could not set opts: '%s'\n", s->avopts);
+ if (mp_set_avopts(af->log, s->avrctx, s->avopts) < 0)
return AF_ERROR;
- }
struct mp_chmap map_in = in->channels;
struct mp_chmap map_out = out->channels;
@@ -402,7 +400,7 @@ const struct af_info af_info_lavrresample = {
OPT_FLAG("linear", opts.linear, 0),
OPT_DOUBLE("cutoff", opts.cutoff, M_OPT_RANGE, .min = 0, .max = 1),
OPT_FLAG("detach", allow_detach, 0),
- OPT_STRING("o", avopts, 0),
+ OPT_KEYVALUELIST("o", avopts, 0),
{0}
},
};
diff --git a/audio/format.h b/audio/format.h
index 6821f27..788f4ed 100644
--- a/audio/format.h
+++ b/audio/format.h
@@ -24,8 +24,8 @@
#define MPLAYER_AF_FORMAT_H
#include <stdbool.h>
-#include <sys/types.h>
+#include "osdep/endian.h"
#include "bstr/bstr.h"
#if BYTE_ORDER == BIG_ENDIAN
diff --git a/audio/out/ao.c b/audio/out/ao.c
index 90c66b4..8e1ceb4 100644
--- a/audio/out/ao.c
+++ b/audio/out/ao.c
@@ -37,6 +37,7 @@
extern const struct ao_driver audio_out_oss;
extern const struct ao_driver audio_out_coreaudio;
+extern const struct ao_driver audio_out_coreaudio_exclusive;
extern const struct ao_driver audio_out_rsound;
extern const struct ao_driver audio_out_sndio;
extern const struct ao_driver audio_out_pulse;
@@ -93,6 +94,9 @@ static const struct ao_driver * const audio_out_drivers[] = {
#if HAVE_ENCODING
&audio_out_lavc,
#endif
+#if HAVE_COREAUDIO
+ &audio_out_coreaudio_exclusive,
+#endif
#if HAVE_RSOUND
&audio_out_rsound,
#endif
diff --git a/audio/out/ao_alsa.c b/audio/out/ao_alsa.c
index 25a051f..10580ff 100644
--- a/audio/out/ao_alsa.c
+++ b/audio/out/ao_alsa.c
@@ -31,7 +31,6 @@
#include <sys/time.h>
#include <stdlib.h>
#include <stdarg.h>
-#include <ctype.h>
#include <math.h>
#include <string.h>
@@ -64,6 +63,7 @@ struct priv {
char *cfg_mixer_name;
int cfg_mixer_index;
int cfg_resample;
+ int cfg_ni;
};
#define BUFFER_TIME 250000 // 250ms
@@ -353,6 +353,9 @@ static int init(struct ao *ao)
struct priv *p = ao->priv;
+ if (!p->cfg_ni)
+ ao->format = af_fmt_from_planar(ao->format);
+
/* switch for spdif
* sets opening sequence for SPDIF
* sets also the playback and other switches 'on the fly'
@@ -755,6 +758,7 @@ const struct ao_driver audio_out_alsa = {
.cfg_mixer_device = "default",
.cfg_mixer_name = "Master",
.cfg_mixer_index = 0,
+ .cfg_ni = 0,
},
.options = (const struct m_option[]) {
OPT_STRING("device", cfg_device, 0),
@@ -763,6 +767,7 @@ const struct ao_driver audio_out_alsa = {
OPT_STRING("mixer-device", cfg_mixer_device, 0),
OPT_STRING("mixer-name", cfg_mixer_name, 0),
OPT_INTRANGE("mixer-index", cfg_mixer_index, 0, 0, 99),
+ OPT_FLAG("non-interleaved", cfg_ni, 0),
{0}
},
};
diff --git a/audio/out/ao_coreaudio.c b/audio/out/ao_coreaudio.c
index 1d44c81..7e5b337 100644
--- a/audio/out/ao_coreaudio.c
+++ b/audio/out/ao_coreaudio.c
@@ -1,39 +1,21 @@
/*
- * CoreAudio audio output driver for Mac OS X
+ * This file is part of mpv.
*
- * original copyright (C) Timothy J. Wood - Aug 2000
- * ported to MPlayer libao2 by Dan Christiansen
- *
- * Chris Roccati
- * Stefano Pigozzi
- *
- * The S/PDIF part of the code is based on the auhal audio output
- * module from VideoLAN:
- * Copyright (c) 2006 Derk-Jan Hartman <hartman at videolan dot org>
- *
- * This file is part of MPlayer.
- *
- * MPlayer is free software; you can redistribute it and/or modify
+ * mpv 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,
+ * 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
- * along with MPlayer; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ * with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
-/*
- * The MacOS X CoreAudio framework doesn't mesh as simply as some
- * simpler frameworks do. This is due to the fact that CoreAudio pulls
- * audio samples rather than having them pushed at it (which is nice
- * when you are wanting to do good buffering of audio).
- */
+#include <CoreAudio/HostTime.h>
#include "config.h"
#include "ao.h"
@@ -46,61 +28,64 @@
#include "audio/out/ao_coreaudio_properties.h"
#include "audio/out/ao_coreaudio_utils.h"
-static void audio_pause(struct ao *ao);
-static void audio_resume(struct ao *ao);
-static void reset(struct ao *ao);
-
-static void print_buffer(struct ao *ao, struct mp_ring *buffer)
-{
- void *tctx = talloc_new(NULL);
- MP_VERBOSE(ao, "%s\n", mp_ring_repr(buffer, tctx));
- talloc_free(tctx);
-}
+struct priv {
+ AudioDeviceID device;
+ AudioUnit audio_unit;
-struct priv_d {
- // digital render callback
- AudioDeviceIOProcID render_cb;
+ uint64_t hw_latency_us;
- // pid set for hog mode, (-1) means that hog mode on the device was
- // released. hog mode is exclusive access to a device
- pid_t hog_pid;
+ // options
+ int opt_device_id;
+ int opt_list;
+};
- // stream selected for digital playback by the detection in init
- AudioStreamID stream;
+bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout,
+ struct mp_chmap *chmap);
- // stream index in an AudioBufferList
- int stream_idx;
+static int64_t ca_frames_to_us(struct ao *ao, uint32_t frames)
+{
+ return frames / (float) ao->samplerate * 1e6;
+}
- // format we changed the stream to: for the digital case each application
- // sets the stream format for a device to what it needs
- AudioStreamBasicDescription stream_asbd;
- AudioStreamBasicDescription original_asbd;
+static int64_t ca_get_hardware_latency(struct ao *ao) {
+ struct priv *p = ao->priv;
- bool changed_mixing;
- int stream_asbd_changed;
- bool muted;
-};
+ double audiounit_latency_sec = 0.0;
+ uint32_t size = sizeof(audiounit_latency_sec);
+ OSStatus err = AudioUnitGetProperty(
+ p->audio_unit,
+ kAudioUnitProperty_Latency,
+ kAudioUnitScope_Global,
+ 0,
+ &audiounit_latency_sec,
+ &size);
+ CHECK_CA_ERROR("cannot get audio unit latency");
-struct priv {
- AudioDeviceID device; // selected device
- bool is_digital; // running in digital mode?
+ uint32_t frames = 0;
+ err = CA_GET_O(p->device, kAudioDevicePropertyLatency, &frames);
+ CHECK_CA_ERROR("cannot get device latency");
- AudioUnit audio_unit; // AudioUnit for lpcm output
+ uint64_t audiounit_latency_us = audiounit_latency_sec * 1e6;
+ uint64_t device_latency_us = ca_frames_to_us(ao, frames);
- bool paused;
+ MP_VERBOSE(ao, "audiounit latency [us]: %lld\n", audiounit_latency_us);
+ MP_VERBOSE(ao, "device latency [us]: %lld\n", device_latency_us);
- struct mp_ring *buffer;
- struct priv_d *digital;
+ return audiounit_latency_us + device_latency_us;
- // options
- int opt_device_id;
- int opt_list;
-};
+coreaudio_error:
+ return 0;
+}
-static int get_ring_size(struct ao *ao)
+static int64_t ca_get_latency(const AudioTimeStamp *ts)
{
- return af_fmt_seconds_to_bytes(
- ao->format, 0.5, ao->channels.num, ao->samplerate);
+ uint64_t out = AudioConvertHostTimeToNanos(ts->mHostTime);
+ uint64_t now = AudioConvertHostTimeToNanos(AudioGetCurrentHostTime());
+
+ if (now > out)
+ return 0;
+
+ return (out - now) * 1e-3;
}
static OSStatus render_cb_lpcm(void *ctx, AudioUnitRenderActionFlags *aflags,
@@ -109,259 +94,125 @@ static OSStatus render_cb_lpcm(void *ctx, AudioUnitRenderActionFlags *aflags,
{
struct ao *ao = ctx;
struct priv *p = ao->priv;
-
AudioBuffer buf = buffer_list->mBuffers[0];
- int requested = buf.mDataByteSize;
-
- if (mp_ring_buffered(p->buffer) < requested) {
- MP_VERBOSE(ao, "buffer underrun\n");
- audio_pause(ao);
- memset(buf.mData, 0, requested);
- } else {
- mp_ring_read(p->buffer, buf.mData, requested);
- }
+ int64_t end = mp_time_us();
+ end += p->hw_latency_us + ca_get_latency(ts) + ca_frames_to_us(ao, frames);
+
+ ao_read_data(ao, &buf.mData, frames, end);
return noErr;
}
-static OSStatus render_cb_digital(
- AudioDeviceID device, const AudioTimeStamp *ts,
- const void *in_data, const AudioTimeStamp *in_ts,
- AudioBufferList *out_data, const AudioTimeStamp *out_ts, void *ctx)
-{
- struct ao *ao = ctx;
- struct priv *p = ao->priv;
- struct priv_d *d = p->digital;
- AudioBuffer buf = out_data->mBuffers[d->stream_idx];
- int requested = buf.mDataByteSize;
+static int get_volume(struct ao *ao, struct ao_control_vol *vol) {
+ struct priv *p = ao->priv;
+ float auvol;
+ OSStatus err =
+ AudioUnitGetParameter(p->audio_unit, kHALOutputParam_Volume,
+ kAudioUnitScope_Global, 0, &auvol);
- if (d->muted)
- mp_ring_drain(p->buffer, requested);
- else
- mp_ring_read(p->buffer, buf.mData, requested);
+ CHECK_CA_ERROR("could not get HAL output volume");
+ vol->left = vol->right = auvol * 100.0;
+ return CONTROL_TRUE;
+coreaudio_error:
+ return CONTROL_ERROR;
+}
- return noErr;
+static int set_volume(struct ao *ao, struct ao_control_vol *vol) {
+ struct priv *p = ao->priv;
+ float auvol = (vol->left + vol->right) / 200.0;
+ OSStatus err =
+ AudioUnitSetParameter(p->audio_unit, kHALOutputParam_Volume,
+ kAudioUnitScope_Global, 0, auvol, 0);
+ CHECK_CA_ERROR("could not set HAL output volume");
+ return CONTROL_TRUE;
+coreaudio_error:
+ return CONTROL_ERROR;
}
static int control(struct ao *ao, enum aocontrol cmd, void *arg)
{
- struct priv *p = ao->priv;
- ao_control_vol_t *control_vol;
- OSStatus err;
- Float32 vol;
switch (cmd) {
case AOCONTROL_GET_VOLUME:
- control_vol = (ao_control_vol_t *)arg;
- if (p->is_digital) {
- struct priv_d *d = p->digital;
- // Digital output has no volume adjust.
- int digitalvol = d->muted ? 0 : 100;
- *control_vol = (ao_control_vol_t) {
- .left = digitalvol, .right = digitalvol,
- };
- return CONTROL_TRUE;
- }
-
- err = AudioUnitGetParameter(p->audio_unit, kHALOutputParam_Volume,
- kAudioUnitScope_Global, 0, &vol);
-
- CHECK_CA_ERROR("could not get HAL output volume");
- control_vol->left = control_vol->right = vol * 100.0;
- return CONTROL_TRUE;
-
+ return get_volume(ao, arg);
case AOCONTROL_SET_VOLUME:
- control_vol = (ao_control_vol_t *)arg;
-
- if (p->is_digital) {
- struct priv_d *d = p->digital;
- // Digital output can not set volume. Here we have to return true
- // to make mixer forget it. Else mixer will add a soft filter,
- // that's not we expected and the filter not support ac3 stream
- // will cause mplayer die.
-
- // Although not support set volume, but at least we support mute.
- // MPlayer set mute by set volume to zero, we handle it.
- if (control_vol->left == 0 && control_vol->right == 0)
- d->muted = true;
- else
- d->muted = false;
- return CONTROL_TRUE;
- }
-
- vol = (control_vol->left + control_vol->right) / 200.0;
- err = AudioUnitSetParameter(p->audio_unit, kHALOutputParam_Volume,
- kAudioUnitScope_Global, 0, vol, 0);
-
- CHECK_CA_ERROR("could not set HAL output volume");
- return CONTROL_TRUE;
-
- } // end switch
+ return set_volume(ao, arg);
+ }
return CONTROL_UNKNOWN;
-
-coreaudio_error:
- return CONTROL_ERROR;
}
-static void print_list(struct ao *ao)
+static bool init_chmap(struct ao *ao);
+static bool init_audiounit(struct ao *ao, AudioStreamBasicDescription asbd);
+
+static int init(struct ao *ao)
{
- char *help = talloc_strdup(NULL, "Available output devices:\n");
+ struct priv *p = ao->priv;
- AudioDeviceID *devs;
- size_t n_devs;
+ if (p->opt_list) ca_print_device_list(ao);
- OSStatus err =
- CA_GET_ARY(kAudioObjectSystemObject, kAudioHardwarePropertyDevices,
- &devs, &n_devs);
+ ao->per_application_mixer = true;
+ ao->no_persistent_volume = true;
- CHECK_CA_ERROR("Failed to get list of output devices.");
+ OSStatus err = ca_select_device(ao, p->opt_device_id, &p->device);
+ CHECK_CA_ERROR("failed to select device");
- for (int i = 0; i < n_devs; i++) {
- char *name;
- err = CA_GET_STR(devs[i], kAudioObjectPropertyName, &name);
+ if (!init_chmap(ao))
+ goto coreaudio_error;
- if (err == noErr)
- talloc_steal(devs, name);
- else
- name = "Unknown";
+ ao->format = af_fmt_from_planar(ao->format);
- help = talloc_asprintf_append(
- help, " * %s (id: %" PRIu32 ")\n", name, devs[i]);
- }
+ AudioStreamBasicDescription asbd;
+ ca_fill_asbd(ao, &asbd);
- talloc_free(devs);
+ if (!init_audiounit(ao, asbd))
+ goto coreaudio_error;
+
+ return CONTROL_OK;
coreaudio_error:
- MP_INFO(ao, "%s", help);
- talloc_free(help);
+ return CONTROL_ERROR;
}
-static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd);
-static int init_digital(struct ao *ao, AudioStreamBasicDescription asbd);
-
-static int init(struct ao *ao)
+static bool init_chmap(struct ao *ao)
{
+ struct priv *p = ao->priv;
OSStatus err;
- struct priv *p = ao->priv;
-
- if (p->opt_list) print_list(ao);
-
- struct priv_d *d = talloc_zero(p, struct priv_d);
-
- *d = (struct priv_d) {
- .muted = false,
- .stream_asbd_changed = 0,
- .hog_pid = -1,
- .stream = 0,
- .stream_idx = -1,
- .changed_mixing = false,
- };
-
- p->digital = d;
-
- ao->per_application_mixer = true;
- ao->no_persistent_volume = true;
-
- AudioDeviceID selected_device = 0;
- if (p->opt_device_id < 0) {
- // device not set by user, get the default one
- err = CA_GET(kAudioObjectSystemObject,
- kAudioHardwarePropertyDefaultOutputDevice,
- &selected_device);
- CHECK_CA_ERROR("could not get default audio device");
- } else {
- selected_device = p->opt_device_id;
+ AudioChannelLayout *layouts;
+ size_t n_layouts;
+
+ err = CA_GET_ARY_O(p->device,
+ kAudioDevicePropertyPreferredChannelLayout,
+ &layouts, &n_layouts);
+ CHECK_CA_ERROR("could not get audio device prefered layouts");
+
+ struct mp_chmap_sel chmap_sel = {0};
+ for (int i = 0; i < n_layouts; i++) {
+ struct mp_chmap chmap = {0};
+ if (ca_layout_to_mp_chmap(ao, &layouts[i], &chmap))
+ mp_chmap_sel_add_map(&chmap_sel, &chmap);
}
- if (mp_msg_test(ao->log, MSGL_V)) {
- char *name;
- err = CA_GET_STR(selected_device, kAudioObjectPropertyName, &name);
- CHECK_CA_ERROR("could not get selected audio device name");
-
- MP_VERBOSE(ao, "selected audio output device: %s (%" PRIu32 ")\n",
- name, selected_device);
+ talloc_free(layouts);
- talloc_free(name);
+ if (ao->channels.num < 3) {
+ struct mp_chmap chmap;
+ mp_chmap_from_channels(&chmap, ao->channels.num);
+ mp_chmap_sel_add_map(&chmap_sel, &chmap);
}
- // Save selected device id
- p->device = selected_device;
-
- ao->format = af_fmt_from_planar(ao->format);
-
- bool supports_digital = false;
- /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
- if (AF_FORMAT_IS_AC3(ao->format)) {
- if (ca_device_supports_digital(ao, selected_device))
- supports_digital = true;
+ if (!ao_chmap_sel_adjust(ao, &chmap_sel, &ao->channels)) {
+ MP_ERR(ao, "could not select a suitable channel map among the "
+ "hardware supported ones. Make sure to configure your "
+ "output device correctly in 'Audio MIDI Setup.app'\n");
+ goto coreaudio_error;
}
- if (!supports_digital) {
- AudioChannelLayout *layouts;
- size_t n_layouts;
- err = CA_GET_ARY_O(selected_device,
- kAudioDevicePropertyPreferredChannelLayout,
- &layouts, &n_layouts);
- CHECK_CA_ERROR("could not get audio device prefered layouts");
-
- struct mp_chmap_sel chmap_sel = {0};
- for (int i = 0; i < n_layouts; i++) {
- struct mp_chmap chmap = {0};
- if (ca_layout_to_mp_chmap(ao, &layouts[i], &chmap))
- mp_chmap_sel_add_map(&chmap_sel, &chmap);
- }
-
- talloc_free(layouts);
-
- if (ao->channels.num < 3) {
- struct mp_chmap chmap;
- mp_chmap_from_channels(&chmap, ao->channels.num);
- mp_chmap_sel_add_map(&chmap_sel, &chmap);
- }
-
- if (!ao_chmap_sel_adjust(ao, &chmap_sel, &ao->channels)) {
- MP_ERR(ao, "could not select a suitable channel map among the "
- "hardware supported ones. Make sure to configure your "
- "output device correctly in 'Audio MIDI Setup.app'\n");
- goto coreaudio_error;
- }
-
- } // closes if (!supports_digital)
-
- // Build ASBD for the input format
- AudioStreamBasicDescription asbd;
- asbd.mSampleRate = ao->samplerate;
- asbd.mFormatID = supports_digital ?
- kAudioFormat60958AC3 : kAudioFormatLinearPCM;
- asbd.mChannelsPerFrame = ao->channels.num;
- asbd.mBitsPerChannel = af_fmt2bits(ao->format);
- asbd.mFormatFlags = kAudioFormatFlagIsPacked;
-
- if ((ao->format & AF_FORMAT_POINT_MASK) == AF_FORMAT_F)
- asbd.mFormatFlags |= kAudioFormatFlagIsFloat;
-
- if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_SI)
- asbd.mFormatFlags |= kAudioFormatFlagIsSignedInteger;
-
- if ((ao->format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
- asbd.mFormatFlags |= kAudioFormatFlagIsBigEndian;
-
- asbd.mFramesPerPacket = 1;
- asbd.mBytesPerPacket = asbd.mBytesPerFrame =
- asbd.mFramesPerPacket * asbd.mChannelsPerFrame *
- (asbd.mBitsPerChannel / 8);
-
- ca_print_asbd(ao, "source format:", &asbd);
-
- if (supports_digital)
- return init_digital(ao, asbd);
- else
- return init_lpcm(ao, asbd);
+ return true;
coreaudio_error:
- return CONTROL_ERROR;
+ return false;
}
-static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
+static bool init_audiounit(struct ao *ao, AudioStreamBasicDescription asbd)
{
OSStatus err;
uint32_t size;
@@ -386,7 +237,6 @@ static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
err = AudioComponentInstanceNew(comp, &(p->audio_unit));
CHECK_CA_ERROR("unable to open audio component");
- // Initialize AudioUnit
err = AudioUnitInitialize(p->audio_unit);
CHECK_CA_ERROR_L(coreaudio_error_component,
"unable to initialize audio unit");
@@ -399,7 +249,6 @@ static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
CHECK_CA_ERROR_L(coreaudio_error_audiounit,
"unable to set the input format on the audio unit");
- //Set the Current Device to the Default Output Unit.
err = AudioUnitSetProperty(p->audio_unit,
kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Global, 0, &p->device,
@@ -407,8 +256,7 @@ static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
CHECK_CA_ERROR_L(coreaudio_error_audiounit,
"can't link audio unit to selected device");
- p->buffer = mp_ring_new(p, get_ring_size(ao));
- print_buffer(ao, p->buffer);
+ p->hw_latency_us = ca_get_hardware_latency(ao);
AURenderCallbackStruct render_cb = (AURenderCallbackStruct) {
.inputProc = render_cb_lpcm,
@@ -423,279 +271,174 @@ static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
CHECK_CA_ERROR_L(coreaudio_error_audiounit,
"unable to set render callback on audio unit");
- reset(ao);
- return CONTROL_OK;
+ return true;
coreaudio_error_audiounit:
AudioUnitUninitialize(p->audio_unit);
coreaudio_error_component:
AudioComponentInstanceDispose(p->audio_unit);
coreaudio_error:
- return CONTROL_ERROR;
-}
-
-static int init_digital(struct ao *ao, AudioStreamBasicDescription asbd)
-{
- struct priv *p = ao->priv;
- struct priv_d *d = p->digital;
- OSStatus err = noErr;
-
- uint32_t is_alive = 1;
- err = CA_GET(p->device, kAudioDevicePropertyDeviceIsAlive, &is_alive);
- CHECK_CA_WARN("could not check whether device is alive");
-
- if (!is_alive)
- MP_WARN(ao , "device is not alive\n");
-
- p->is_digital = 1;
-
- err = ca_lock_device(p->device, &d->hog_pid);
- CHECK_CA_WARN("failed to set hogmode");
-
- err = ca_disable_mixing(ao, p->device, &d->changed_mixing);
- CHECK_CA_WARN("failed to disable mixing");
-
- AudioStreamID *streams;
- size_t n_streams;
-
- /* Get a list of all the streams on this device. */
- err = CA_GET_ARY_O(p->device, kAudioDevicePropertyStreams,
- &streams, &n_streams);
-
- CHECK_CA_ERROR("could not get number of streams");
-
- for (int i = 0; i < n_streams && d->stream_idx < 0; i++) {
- bool digital = ca_stream_supports_digital(ao, streams[i]);
-
- if (digital) {
- err = CA_GET(streams[i], kAudioStreamPropertyPhysicalFormat,
- &d->original_asbd);
- if (!CHECK_CA_WARN("could not get stream's physical format to "
- "revert to, getting the next one"))
- continue;
-
- AudioStreamRangedDescription *formats;
- size_t n_formats;
-
- err = CA_GET_ARY(streams[i],
- kAudioStreamPropertyAvailablePhysicalFormats,
- &formats, &n_formats);
-
- if (!CHECK_CA_WARN("could not get number of stream formats"))
- continue; // try next one
-
- int req_rate_format = -1;
- int max_rate_format = -1;
-
- d->stream = streams[i];
- d->stream_idx = i;
-
- for (int j = 0; j < n_formats; j++)
- if (ca_format_is_digital(formats[j].mFormat)) {
- // select the digital format that has exactly the same
- // samplerate. If an exact match cannot be found, select
- // the format with highest samplerate as backup.
- if (formats[j].mFormat.mSampleRate == asbd.mSampleRate) {
- req_rate_format = j;
- break;
- } else if (max_rate_format < 0 ||
- formats[j].mFormat.mSampleRate >
- formats[max_rate_format].mFormat.mSampleRate)
- max_rate_format = j;
- }
-
- if (req_rate_format >= 0)
- d->stream_asbd = formats[req_rate_format].mFormat;
- else
- d->stream_asbd = formats[max_rate_format].mFormat;
-
- talloc_free(formats);
- }
- }
-
- talloc_free(streams);
-
- if (d->stream_idx < 0) {
- MP_WARN(ao , "can't find any digital output stream format\n");
- goto coreaudio_error;
- }
-
- if (!ca_change_format(ao, d->stream, d->stream_asbd))
- goto coreaudio_error;
-
- void *changed = (void *) &(d->stream_asbd_changed);
- err = ca_enable_device_listener(p->device, changed);
- CHECK_CA_ERROR("cannot install format change listener during init");
-
-#if BYTE_ORDER == BIG_ENDIAN
- if (!(p->stream_asdb.mFormatFlags & kAudioFormatFlagIsBigEndian))
-#else
- /* tell mplayer that we need a byteswap on AC3 streams, */
- if (d->stream_asbd.mFormatID & kAudioFormat60958AC3)
- ao->format = AF_FORMAT_AC3_LE;
- else if (d->stream_asbd.mFormatFlags & kAudioFormatFlagIsBigEndian)
-#endif
- MP_WARN(ao, "stream has non-native byte order, output may fail\n");
-
- ao->samplerate = d->stream_asbd.mSampleRate;
- ao->bps = ao->samplerate *
- (d->stream_asbd.mBytesPerPacket /
- d->stream_asbd.mFramesPerPacket);
-
- p->buffer = mp_ring_new(p, get_ring_size(ao));
- print_buffer(ao, p->buffer);
-
- err = AudioDeviceCreateIOProcID(p->device,
- (AudioDeviceIOProc)render_cb_digital,
- (void *)ao,
- &d->render_cb);
-
- CHECK_CA_ERROR("failed to register digital render callback");
-
- reset(ao);
-
- return CONTROL_TRUE;
-
-coreaudio_error:
- err = ca_unlock_device(p->device, &d->hog_pid);
- CHECK_CA_WARN("can't release hog mode");
- return CONTROL_ERROR;
+ return false;
}
-static int play(struct ao *ao, void **data, int samples, int flags)
-{
- struct priv *p = ao->priv;
- struct priv_d *d = p->digital;
- void *output_samples = data[0];
- int num_bytes = samples * ao->sstride;
-
- // Check whether we need to reset the digital output stream.
- if (p->is_digital && d->stream_asbd_changed) {
- d->stream_asbd_changed = 0;
- if (ca_stream_supports_digital(ao, d->stream)) {
- if (!ca_change_format(ao, d->stream, d->stream_asbd)) {
- MP_WARN(ao , "can't restore digital output\n");
- } else {
- MP_WARN(ao, "restoring digital output succeeded.\n");
- reset(ao);
- }
- }
- }
-
- int wrote = mp_ring_write(p->buffer, output_samples, num_bytes);
- audio_resume(ao);
-
- return wrote / ao->sstride;
-}
-
-static void reset(struct ao *ao)
+static void stop(struct ao *ao)
{
struct priv *p = ao->priv;
- audio_pause(ao);
- mp_ring_reset(p->buffer);
+ OSStatus err = AudioOutputUnitStop(p->audio_unit);
+ CHECK_CA_WARN("can't stop audio unit");
}
-static int get_space(struct ao *ao)
+static void start(struct ao *ao)
{
struct priv *p = ao->priv;
- return mp_ring_available(p->buffer) / ao->sstride;
+ OSStatus err = AudioOutputUnitStart(p->audio_unit);
+ CHECK_CA_WARN("can't start audio unit");
}
-static float get_delay(struct ao *ao)
-{
- // FIXME: should also report the delay of coreaudio itself (hardware +
- // internal buffers)
- struct priv *p = ao->priv;
- return mp_ring_buffered(p->buffer) / (float)ao->bps;
-}
static void uninit(struct ao *ao)
{
struct priv *p = ao->priv;
- OSStatus err = noErr;
-
- if (!p->is_digital) {
- AudioOutputUnitStop(p->audio_unit);
- AudioUnitUninitialize(p->audio_unit);
- AudioComponentInstanceDispose(p->audio_unit);
- } else {
- struct priv_d *d = p->digital;
-
- void *changed = (void *) &(d->stream_asbd_changed);
- err = ca_disable_device_listener(p->device, changed);
- CHECK_CA_WARN("can't remove device listener, this may cause a crash");
-
- err = AudioDeviceStop(p->device, d->render_cb);
- CHECK_CA_WARN("failed to stop audio device");
-
- err = AudioDeviceDestroyIOProcID(p->device, d->render_cb);
- CHECK_CA_WARN("failed to remove device render callback");
-
- if (!ca_change_format(ao, d->stream, d->original_asbd))
- MP_WARN(ao, "can't revert to original device format");
+ AudioOutputUnitStop(p->audio_unit);
+ AudioUnitUninitialize(p->audio_unit);
+ AudioComponentInstanceDispose(p->audio_unit);
+}
- err = ca_enable_mixing(ao, p->device, d->changed_mixing);
- CHECK_CA_WARN("can't re-enable mixing");
+// Channel Mapping functions
+static const int speaker_map[][2] = {
+ { kAudioChannelLabel_Left, MP_SPEAKER_ID_FL },
+ { kAudioChannelLabel_Right, MP_SPEAKER_ID_FR },
+ { kAudioChannelLabel_Center, MP_SPEAKER_ID_FC },
+ { kAudioChannelLabel_LFEScreen, MP_SPEAKER_ID_LFE },
+ { kAudioChannelLabel_LeftSurround, MP_SPEAKER_ID_BL },
+ { kAudioChannelLabel_RightSurround, MP_SPEAKER_ID_BR },
+ { kAudioChannelLabel_LeftCenter, MP_SPEAKER_ID_FLC },
+ { kAudioChannelLabel_RightCenter, MP_SPEAKER_ID_FRC },
+ { kAudioChannelLabel_CenterSurround, MP_SPEAKER_ID_BC },
+ { kAudioChannelLabel_LeftSurroundDirect, MP_SPEAKER_ID_SL },
+ { kAudioChannelLabel_RightSurroundDirect, MP_SPEAKER_ID_SR },
+ { kAudioChannelLabel_TopCenterSurround, MP_SPEAKER_ID_TC },
+ { kAudioChannelLabel_VerticalHeightLeft, MP_SPEAKER_ID_TFL },
+ { kAudioChannelLabel_VerticalHeightCenter, MP_SPEAKER_ID_TFC },
+ { kAudioChannelLabel_VerticalHeightRight, MP_SPEAKER_ID_TFR },
+ { kAudioChannelLabel_TopBackLeft, MP_SPEAKER_ID_TBL },
+ { kAudioChannelLabel_TopBackCenter, MP_SPEAKER_ID_TBC },
+ { kAudioChannelLabel_TopBackRight, MP_SPEAKER_ID_TBR },
+
+ // unofficial extensions
+ { kAudioChannelLabel_RearSurroundLeft, MP_SPEAKER_ID_SDL },
+ { kAudioChannelLabel_RearSurroundRight, MP_SPEAKER_ID_SDR },
+ { kAudioChannelLabel_LeftWide, MP_SPEAKER_ID_WL },
+ { kAudioChannelLabel_RightWide, MP_SPEAKER_ID_WR },
+ { kAudioChannelLabel_LFE2, MP_SPEAKER_ID_LFE2 },
+
+ { kAudioChannelLabel_HeadphonesLeft, MP_SPEAKER_ID_DL },
+ { kAudioChannelLabel_HeadphonesRight, MP_SPEAKER_ID_DR },
+
+ { kAudioChannelLabel_Unknown, -1 },
+};
- err = ca_unlock_device(p->device, &d->hog_pid);
- CHECK_CA_WARN("can't release hog mode");
- }
+static int ca_label_to_mp_speaker_id(AudioChannelLabel label)
+{
+ for (int i = 0; speaker_map[i][1] >= 0; i++)
+ if (speaker_map[i][0] == label)
+ return speaker_map[i][1];
+ return -1;
}
-static void audio_pause(struct ao *ao)
+static void ca_log_layout(struct ao *ao, AudioChannelLayout *layout)
{
- struct priv *p = ao->priv;
- OSErr err = noErr;
-
- if (p->paused)
+ if (!mp_msg_test(ao->log, MSGL_V))
return;
- if (!p->is_digital) {
- err = AudioOutputUnitStop(p->audio_unit);
- CHECK_CA_WARN("can't stop audio unit");
- } else {
- struct priv_d *d = p->digital;
- err = AudioDeviceStop(p->device, d->render_cb);
- CHECK_CA_WARN("can't stop digital device");
+ AudioChannelDescription *descs = layout->mChannelDescriptions;
+
+ MP_VERBOSE(ao, "layout: tag: <%d>, bitmap: <%d>, "
+ "descriptions <%d>\n",
+ layout->mChannelLayoutTag,
+ layout->mChannelBitmap,
+ layout->mNumberChannelDescriptions);
+
+ for (int i = 0; i < layout->mNumberChannelDescriptions; i++) {
+ AudioChannelDescription d = descs[i];
+ MP_VERBOSE(ao, " - description %d: label <%d, %d>, flags: <%u>, "
+ "coords: <%f, %f, %f>\n", i,
+ d.mChannelLabel,
+ ca_label_to_mp_speaker_id(d.mChannelLabel),
+ d.mChannelFlags,
+ d.mCoordinates[0],
+ d.mCoordinates[1],
+ d.mCoordinates[2]);
}
-
- p->paused = true;
}
-static void audio_resume(struct ao *ao)
+bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout,
+ struct mp_chmap *chmap)
{
- struct priv *p = ao->priv;
- OSErr err = noErr;
+ AudioChannelLayoutTag tag = layout->mChannelLayoutTag;
+ uint32_t layout_size = sizeof(layout);
+ OSStatus err;
- if (!p->paused)
- return;
+ if (tag == kAudioChannelLayoutTag_UseChannelBitmap) {
+ err = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
+ sizeof(uint32_t),
+ &layout->mChannelBitmap,
+ &layout_size,
+ layout);
+ CHECK_CA_ERROR("failed to convert channel bitmap to descriptions");
+ } else if (tag != kAudioChannelLayoutTag_UseChannelDescriptions) {
+ err = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
+ sizeof(AudioChannelLayoutTag),
+ &layout->mChannelLayoutTag,
+ &layout_size,
+ layout);
+ CHECK_CA_ERROR("failed to convert channel tag to descriptions");
+ }
- if (!p->is_digital) {
- err = AudioOutputUnitStart(p->audio_unit);
- CHECK_CA_WARN("can't start audio unit");
- } else {
- struct priv_d *d = p->digital;
- err = AudioDeviceStart(p->device, d->render_cb);
- CHECK_CA_WARN("can't start digital device");
+ ca_log_layout(ao, layout);
+
+ // If the channel layout uses channel descriptions, from my
+ // experiments there are there three possibile cases:
+ // * The description has a label kAudioChannelLabel_Unknown:
+ // Can't do anything about this (looks like non surround
+ // layouts are like this).
+ // * The description uses positional information: this in
+ // theory could be used but one would have to map spatial
+ // positions to labels which is not really feasible.
+ // * The description has a well known label which can be mapped
+ // to the waveextensible definition: this is the kind of
+ // descriptions we process here.
+
+ for (int n = 0; n < layout->mNumberChannelDescriptions; n++) {
+ AudioChannelLabel label = layout->mChannelDescriptions[n].mChannelLabel;
+ uint8_t speaker = ca_label_to_mp_speaker_id(label);
+ if (label == kAudioChannelLabel_Unknown)
+ continue;
+ if (speaker < 0) {
+ MP_VERBOSE(ao, "channel label=%d unusable to build channel "
+ "bitmap, skipping layout\n", label);
+ } else {
+ chmap->speaker[n] = speaker;
+ chmap->num = n + 1;
+ }
}
- p->paused = false;
+ return chmap->num > 0;
+coreaudio_error:
+ ca_log_layout(ao, layout);
+ return false;
}
#define OPT_BASE_STRUCT struct priv
const struct ao_driver audio_out_coreaudio = {
- .description = "CoreAudio (OS X Audio Output)",
+ .description = "CoreAudio AudioUnit",
.name = "coreaudio",
.uninit = uninit,
.init = init,
- .play = play,
.control = control,
- .get_space = get_space,
- .get_delay = get_delay,
- .reset = reset,
- .pause = audio_pause,
- .resume = audio_resume,
+ .pause = stop,
+ .resume = start,
.priv_size = sizeof(struct priv),
.options = (const struct m_option[]) {
OPT_INT("device_id", opt_device_id, 0, OPTDEF_INT(-1)),
diff --git a/audio/out/ao_coreaudio_device.c b/audio/out/ao_coreaudio_device.c
new file mode 100644
index 0000000..047e094
--- /dev/null
+++ b/audio/out/ao_coreaudio_device.c
@@ -0,0 +1,684 @@
+/*
+ * CoreAudio audio output driver for Mac OS X
+ *
+ * original copyright (C) Timothy J. Wood - Aug 2000
+ * ported to MPlayer libao2 by Dan Christiansen
+ *
+ * Chris Roccati
+ * Stefano Pigozzi
+ *
+ * The S/PDIF part of the code is based on the auhal audio output
+ * module from VideoLAN:
+ * Copyright (c) 2006 Derk-Jan Hartman <hartman at videolan dot org>
+ *
+ * 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
+ * along with MPlayer; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+/*
+ * The MacOS X CoreAudio framework doesn't mesh as simply as some
+ * simpler frameworks do. This is due to the fact that CoreAudio pulls
+ * audio samples rather than having them pushed at it (which is nice
+ * when you are wanting to do good buffering of audio).
+ */
+
+#include "config.h"
+#include "ao.h"
+#include "internal.h"
+#include "audio/format.h"
+#include "osdep/timer.h"
+#include "options/m_option.h"
+#include "misc/ring.h"
+#include "common/msg.h"
+#include "audio/out/ao_coreaudio_properties.h"
+#include "audio/out/ao_coreaudio_utils.h"
+
+static void audio_pause(struct ao *ao);
+static void audio_resume(struct ao *ao);
+static void reset(struct ao *ao);
+
+static bool ca_format_is_digital(AudioStreamBasicDescription asbd)
+{
+ switch (asbd.mFormatID)
+ case 'IAC3':
+ case 'iac3':
+ case kAudioFormat60958AC3:
+ case kAudioFormatAC3:
+ return true;
+ return false;
+}
+
+static bool ca_stream_supports_digital(struct ao *ao, AudioStreamID stream)
+{
+ AudioStreamRangedDescription *formats = NULL;
+ size_t n_formats;
+
+ OSStatus err =
+ CA_GET_ARY(stream, kAudioStreamPropertyAvailablePhysicalFormats,
+ &formats, &n_formats);
+
+ CHECK_CA_ERROR("Could not get number of stream formats.");
+
+ for (int i = 0; i < n_formats; i++) {
+ AudioStreamBasicDescription asbd = formats[i].mFormat;
+ ca_print_asbd(ao, "supported format:", &(asbd));
+ if (ca_format_is_digital(asbd)) {
+ talloc_free(formats);
+ return true;
+ }
+ }
+
+ talloc_free(formats);
+coreaudio_error:
+ return false;
+}
+
+static bool ca_device_supports_digital(struct ao *ao, AudioDeviceID device)
+{
+ AudioStreamID *streams = NULL;
+ size_t n_streams;
+
+ /* Retrieve all the output streams. */
+ OSStatus err =
+ CA_GET_ARY_O(device, kAudioDevicePropertyStreams, &streams, &n_streams);
+
+ CHECK_CA_ERROR("could not get number of streams.");
+
+ for (int i = 0; i < n_streams; i++) {
+ if (ca_stream_supports_digital(ao, streams[i])) {
+ talloc_free(streams);
+ return true;
+ }
+ }
+
+ talloc_free(streams);
+
+coreaudio_error:
+ return false;
+}
+
+static OSStatus ca_property_listener(
+ AudioObjectPropertySelector selector,
+ AudioObjectID object, uint32_t n_addresses,
+ const AudioObjectPropertyAddress addresses[],
+ void *data)
+{
+ void *talloc_ctx = talloc_new(NULL);
+
+ for (int i = 0; i < n_addresses; i++) {
+ if (addresses[i].mSelector == selector) {
+ if (data) *(volatile int *)data = 1;
+ break;
+ }
+ }
+ talloc_free(talloc_ctx);
+ return noErr;
+}
+
+static OSStatus ca_stream_listener(
+ AudioObjectID object, uint32_t n_addresses,
+ const AudioObjectPropertyAddress addresses[],
+ void *data)
+{
+ return ca_property_listener(kAudioStreamPropertyPhysicalFormat,
+ object, n_addresses, addresses, data);
+}
+
+static OSStatus ca_device_listener(
+ AudioObjectID object, uint32_t n_addresses,
+ const AudioObjectPropertyAddress addresses[],
+ void *data)
+{
+ return ca_property_listener(kAudioDevicePropertyDeviceHasChanged,
+ object, n_addresses, addresses, data);
+}
+
+static OSStatus ca_lock_device(AudioDeviceID device, pid_t *pid) {
+ *pid = getpid();
+ OSStatus err = CA_SET(device, kAudioDevicePropertyHogMode, pid);
+ if (err != noErr)
+ *pid = -1;
+
+ return err;
+}
+
+static OSStatus ca_unlock_device(AudioDeviceID device, pid_t *pid) {
+ if (*pid == getpid()) {
+ *pid = -1;
+ return CA_SET(device, kAudioDevicePropertyHogMode, &pid);
+ }
+ return noErr;
+}
+
+static OSStatus ca_change_mixing(struct ao *ao, AudioDeviceID device,
+ uint32_t val, bool *changed) {
+ *changed = false;
+
+ AudioObjectPropertyAddress p_addr = (AudioObjectPropertyAddress) {
+ .mSelector = kAudioDevicePropertySupportsMixing,
+ .mScope = kAudioObjectPropertyScopeGlobal,
+ .mElement = kAudioObjectPropertyElementMaster,
+ };
+
+ if (AudioObjectHasProperty(device, &p_addr)) {
+ OSStatus err;
+ Boolean writeable = 0;
+ err = CA_SETTABLE(device, kAudioDevicePropertySupportsMixing,
+ &writeable);
+
+ if (!CHECK_CA_WARN("can't tell if mixing property is settable")) {
+ return err;
+ }
+
+ if (!writeable)
+ return noErr;
+
+ err = CA_SET(device, kAudioDevicePropertySupportsMixing, &val);
+ if (err != noErr)
+ return err;
+
+ if (!CHECK_CA_WARN("can't set mix mode")) {
+ return err;
+ }
+
+ *changed = true;
+ }
+
+ return noErr;
+}
+
+static OSStatus ca_disable_mixing(struct ao *ao,
+ AudioDeviceID device, bool *changed) {
+ return ca_change_mixing(ao, device, 0, changed);
+}
+
+static OSStatus ca_enable_mixing(struct ao *ao,
+ AudioDeviceID device, bool changed) {
+ if (changed) {
+ bool dont_care = false;
+ return ca_change_mixing(ao, device, 1, &dont_care);
+ }
+
+ return noErr;
+}
+
+static OSStatus ca_change_device_listening(AudioDeviceID device,
+ void *flag, bool enabled)
+{
+ AudioObjectPropertyAddress p_addr = (AudioObjectPropertyAddress) {
+ .mSelector = kAudioDevicePropertyDeviceHasChanged,
+ .mScope = kAudioObjectPropertyScopeGlobal,
+ .mElement = kAudioObjectPropertyElementMaster,
+ };
+
+ if (enabled) {
+ return AudioObjectAddPropertyListener(
+ device, &p_addr, ca_device_listener, flag);
+ } else {
+ return AudioObjectRemovePropertyListener(
+ device, &p_addr, ca_device_listener, flag);
+ }
+}
+
+static OSStatus ca_enable_device_listener(AudioDeviceID device, void *flag) {
+ return ca_change_device_listening(device, flag, true);
+}
+
+static OSStatus ca_disable_device_listener(AudioDeviceID device, void *flag) {
+ return ca_change_device_listening(device, flag, false);
+}
+
+static bool ca_change_format(struct ao *ao, AudioStreamID stream,
+ AudioStreamBasicDescription change_format)
+{
+ OSStatus err = noErr;
+ AudioObjectPropertyAddress p_addr;
+ volatile int stream_format_changed = 0;
+
+ ca_print_asbd(ao, "setting stream format:", &change_format);
+
+ /* Install the callback. */
+ p_addr = (AudioObjectPropertyAddress) {
+ .mSelector = kAudioStreamPropertyPhysicalFormat,
+ .mScope = kAudioObjectPropertyScopeGlobal,
+ .mElement = kAudioObjectPropertyElementMaster,
+ };
+
+ err = AudioObjectAddPropertyListener(stream, &p_addr, ca_stream_listener,
+ (void *)&stream_format_changed);
+ if (!CHECK_CA_WARN("can't add property listener during format change")) {
+ return false;
+ }
+
+ /* Change the format. */
+ err = CA_SET(stream, kAudioStreamPropertyPhysicalFormat, &change_format);
+ if (!CHECK_CA_WARN("error changing physical format")) {
+ return false;
+ }
+
+ /* The AudioStreamSetProperty is not only asynchronious,
+ * it is also not Atomic, in its behaviour.
+ * Therefore we check 5 times before we really give up. */
+ bool format_set = false;
+ for (int i = 0; !format_set && i < 5; i++) {
+ for (int j = 0; !stream_format_changed && j < 50; j++)
+ mp_sleep_us(10000);
+
+ if (stream_format_changed) {
+ stream_format_changed = 0;
+ } else {
+ MP_VERBOSE(ao, "reached timeout\n");
+ }
+
+ AudioStreamBasicDescription actual_format;
+ err = CA_GET(stream, kAudioStreamPropertyPhysicalFormat, &actual_format);
+
+ ca_print_asbd(ao, "actual format in use:", &actual_format);
+ if (actual_format.mSampleRate == change_format.mSampleRate &&
+ actual_format.mFormatID == change_format.mFormatID &&
+ actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
+ format_set = true;
+ }
+ }
+
+ err = AudioObjectRemovePropertyListener(stream, &p_addr, ca_stream_listener,
+ (void *)&stream_format_changed);
+
+ if (!CHECK_CA_WARN("can't remove property listener")) {
+ return false;
+ }
+
+ return format_set;
+}
+
+
+struct priv {
+ AudioDeviceID device; // selected device
+
+ bool paused;
+
+ struct mp_ring *buffer;
+
+ // digital render callback
+ AudioDeviceIOProcID render_cb;
+
+ // pid set for hog mode, (-1) means that hog mode on the device was
+ // released. hog mode is exclusive access to a device
+ pid_t hog_pid;
+
+ // stream selected for digital playback by the detection in init
+ AudioStreamID stream;
+
+ // stream index in an AudioBufferList
+ int stream_idx;
+
+ // format we changed the stream to: for the digital case each application
+ // sets the stream format for a device to what it needs
+ AudioStreamBasicDescription stream_asbd;
+ AudioStreamBasicDescription original_asbd;
+
+ bool changed_mixing;
+ int stream_asbd_changed;
+ bool muted;
+
+ // options
+ int opt_device_id;
+ int opt_list;
+};
+
+static int get_ring_size(struct ao *ao)
+{
+ return af_fmt_seconds_to_bytes(
+ ao->format, 0.5, ao->channels.num, ao->samplerate);
+}
+
+static OSStatus render_cb_digital(
+ AudioDeviceID device, const AudioTimeStamp *ts,
+ const void *in_data, const AudioTimeStamp *in_ts,
+ AudioBufferList *out_data, const AudioTimeStamp *out_ts, void *ctx)
+{
+ struct ao *ao = ctx;
+ struct priv *p = ao->priv;
+ AudioBuffer buf = out_data->mBuffers[p->stream_idx];
+ int requested = buf.mDataByteSize;
+
+ if (p->muted)
+ mp_ring_drain(p->buffer, requested);
+ else
+ mp_ring_read(p->buffer, buf.mData, requested);
+
+ return noErr;
+}
+
+static int control(struct ao *ao, enum aocontrol cmd, void *arg)
+{
+ struct priv *p = ao->priv;
+ ao_control_vol_t *control_vol;
+ switch (cmd) {
+ case AOCONTROL_GET_VOLUME:
+ control_vol = (ao_control_vol_t *)arg;
+ // Digital output has no volume adjust.
+ int digitalvol = p->muted ? 0 : 100;
+ *control_vol = (ao_control_vol_t) {
+ .left = digitalvol, .right = digitalvol,
+ };
+ return CONTROL_TRUE;
+
+ case AOCONTROL_SET_VOLUME:
+ control_vol = (ao_control_vol_t *)arg;
+ // Digital output can not set volume. Here we have to return true
+ // to make mixer forget it. Else mixer will add a soft filter,
+ // that's not we expected and the filter not support ac3 stream
+ // will cause mplayer die.
+
+ // Although not support set volume, but at least we support mute.
+ // MPlayer set mute by set volume to zero, we handle it.
+ if (control_vol->left == 0 && control_vol->right == 0)
+ p->muted = true;
+ else
+ p->muted = false;
+ return CONTROL_TRUE;
+
+ } // end switch
+ return CONTROL_UNKNOWN;
+}
+
+static int init_digital(struct ao *ao, AudioStreamBasicDescription asbd);
+
+static int init(struct ao *ao)
+{
+ struct priv *p = ao->priv;
+
+ if (p->opt_list) ca_print_device_list(ao);
+
+ *p = (struct priv) {
+ .muted = false,
+ .stream_asbd_changed = 0,
+ .hog_pid = -1,
+ .stream = 0,
+ .stream_idx = -1,
+ .changed_mixing = false,
+ };
+
+ OSStatus err = ca_select_device(ao, p->opt_device_id, &p->device);
+ CHECK_CA_ERROR("failed to select device");
+
+ ao->format = af_fmt_from_planar(ao->format);
+
+ bool supports_digital = false;
+ /* Probe whether device support S/PDIF stream output if input is AC3 stream. */
+ if (AF_FORMAT_IS_AC3(ao->format)) {
+ if (ca_device_supports_digital(ao, p->device))
+ supports_digital = true;
+ }
+
+ if (!supports_digital) {
+ MP_ERR(ao, "selected device doesn't support digital formats\n");
+ goto coreaudio_error;
+ } // closes if (!supports_digital)
+
+ // Build ASBD for the input format
+ AudioStreamBasicDescription asbd;
+ ca_fill_asbd(ao, &asbd);
+
+ return init_digital(ao, asbd);
+
+coreaudio_error:
+ return CONTROL_ERROR;
+}
+
+static int init_digital(struct ao *ao, AudioStreamBasicDescription asbd)
+{
+ struct priv *p = ao->priv;
+ OSStatus err = noErr;
+
+ uint32_t is_alive = 1;
+ err = CA_GET(p->device, kAudioDevicePropertyDeviceIsAlive, &is_alive);
+ CHECK_CA_WARN("could not check whether device is alive");
+
+ if (!is_alive)
+ MP_WARN(ao , "device is not alive\n");
+
+ err = ca_lock_device(p->device, &p->hog_pid);
+ CHECK_CA_WARN("failed to set hogmode");
+
+ err = ca_disable_mixing(ao, p->device, &p->changed_mixing);
+ CHECK_CA_WARN("failed to disable mixing");
+
+ AudioStreamID *streams;
+ size_t n_streams;
+
+ /* Get a list of all the streams on this device. */
+ err = CA_GET_ARY_O(p->device, kAudioDevicePropertyStreams,
+ &streams, &n_streams);
+
+ CHECK_CA_ERROR("could not get number of streams");
+
+ for (int i = 0; i < n_streams && p->stream_idx < 0; i++) {
+ bool digital = ca_stream_supports_digital(ao, streams[i]);
+
+ if (digital) {
+ err = CA_GET(streams[i], kAudioStreamPropertyPhysicalFormat,
+ &p->original_asbd);
+ if (!CHECK_CA_WARN("could not get stream's physical format to "
+ "revert to, getting the next one"))
+ continue;
+
+ AudioStreamRangedDescription *formats;
+ size_t n_formats;
+
+ err = CA_GET_ARY(streams[i],
+ kAudioStreamPropertyAvailablePhysicalFormats,
+ &formats, &n_formats);
+
+ if (!CHECK_CA_WARN("could not get number of stream formats"))
+ continue; // try next one
+
+ int req_rate_format = -1;
+ int max_rate_format = -1;
+
+ p->stream = streams[i];
+ p->stream_idx = i;
+
+ for (int j = 0; j < n_formats; j++)
+ if (ca_format_is_digital(formats[j].mFormat)) {
+ // select the digital format that has exactly the same
+ // samplerate. If an exact match cannot be found, select
+ // the format with highest samplerate as backup.
+ if (formats[j].mFormat.mSampleRate == asbd.mSampleRate) {
+ req_rate_format = j;
+ break;
+ } else if (max_rate_format < 0 ||
+ formats[j].mFormat.mSampleRate >
+ formats[max_rate_format].mFormat.mSampleRate)
+ max_rate_format = j;
+ }
+
+ if (req_rate_format >= 0)
+ p->stream_asbd = formats[req_rate_format].mFormat;
+ else
+ p->stream_asbd = formats[max_rate_format].mFormat;
+
+ talloc_free(formats);
+ }
+ }
+
+ talloc_free(streams);
+
+ if (p->stream_idx < 0) {
+ MP_WARN(ao , "can't find any digital output stream format\n");
+ goto coreaudio_error;
+ }
+
+ if (!ca_change_format(ao, p->stream, p->stream_asbd))
+ goto coreaudio_error;
+
+ void *changed = (void *) &(p->stream_asbd_changed);
+ err = ca_enable_device_listener(p->device, changed);
+ CHECK_CA_ERROR("cannot install format change listener during init");
+
+#if BYTE_ORDER == BIG_ENDIAN
+ if (!(p->stream_asdb.mFormatFlags & kAudioFormatFlagIsBigEndian))
+#else
+ /* tell mplayer that we need a byteswap on AC3 streams, */
+ if (p->stream_asbd.mFormatID & kAudioFormat60958AC3)
+ ao->format = AF_FORMAT_AC3_LE;
+ else if (p->stream_asbd.mFormatFlags & kAudioFormatFlagIsBigEndian)
+#endif
+ MP_WARN(ao, "stream has non-native byte order, output may fail\n");
+
+ ao->samplerate = p->stream_asbd.mSampleRate;
+ ao->bps = ao->samplerate *
+ (p->stream_asbd.mBytesPerPacket /
+ p->stream_asbd.mFramesPerPacket);
+
+ p->buffer = mp_ring_new(p, get_ring_size(ao));
+
+ err = AudioDeviceCreateIOProcID(p->device,
+ (AudioDeviceIOProc)render_cb_digital,
+ (void *)ao,
+ &p->render_cb);
+
+ CHECK_CA_ERROR("failed to register digital render callback");
+
+ reset(ao);
+
+ return CONTROL_TRUE;
+
+coreaudio_error:
+ err = ca_unlock_device(p->device, &p->hog_pid);
+ CHECK_CA_WARN("can't release hog mode");
+ return CONTROL_ERROR;
+}
+
+static int play(struct ao *ao, void **data, int samples, int flags)
+{
+ struct priv *p = ao->priv;
+ void *output_samples = data[0];
+ int num_bytes = samples * ao->sstride;
+
+ // Check whether we need to reset the digital output stream.
+ if (p->stream_asbd_changed) {
+ p->stream_asbd_changed = 0;
+ if (ca_stream_supports_digital(ao, p->stream)) {
+ if (!ca_change_format(ao, p->stream, p->stream_asbd)) {
+ MP_WARN(ao , "can't restore digital output\n");
+ } else {
+ MP_WARN(ao, "restoring digital output succeeded.\n");
+ reset(ao);
+ }
+ }
+ }
+
+ int wrote = mp_ring_write(p->buffer, output_samples, num_bytes);
+ audio_resume(ao);
+
+ return wrote / ao->sstride;
+}
+
+static void reset(struct ao *ao)
+{
+ struct priv *p = ao->priv;
+ audio_pause(ao);
+ mp_ring_reset(p->buffer);
+}
+
+static int get_space(struct ao *ao)
+{
+ struct priv *p = ao->priv;
+ return mp_ring_available(p->buffer) / ao->sstride;
+}
+
+static float get_delay(struct ao *ao)
+{
+ // FIXME: should also report the delay of coreaudio itself (hardware +
+ // internal buffers)
+ struct priv *p = ao->priv;
+ return mp_ring_buffered(p->buffer) / (float)ao->bps;
+}
+
+static void uninit(struct ao *ao)
+{
+ struct priv *p = ao->priv;
+ OSStatus err = noErr;
+
+ void *changed = (void *) &(p->stream_asbd_changed);
+ err = ca_disable_device_listener(p->device, changed);
+ CHECK_CA_WARN("can't remove device listener, this may cause a crash");
+
+ err = AudioDeviceStop(p->device, p->render_cb);
+ CHECK_CA_WARN("failed to stop audio device");
+
+ err = AudioDeviceDestroyIOProcID(p->device, p->render_cb);
+ CHECK_CA_WARN("failed to remove device render callback");
+
+ if (!ca_change_format(ao, p->stream, p->original_asbd))
+ MP_WARN(ao, "can't revert to original device format");
+
+ err = ca_enable_mixing(ao, p->device, p->changed_mixing);
+ CHECK_CA_WARN("can't re-enable mixing");
+
+ err = ca_unlock_device(p->device, &p->hog_pid);
+ CHECK_CA_WARN("can't release hog mode");
+}
+
+static void audio_pause(struct ao *ao)
+{
+ struct priv *p = ao->priv;
+
+ if (p->paused)
+ return;
+
+ OSStatus err = AudioDeviceStop(p->device, p->render_cb);
+ CHECK_CA_WARN("can't stop digital device");
+
+ p->paused = true;
+}
+
+static void audio_resume(struct ao *ao)
+{
+ struct priv *p = ao->priv;
+
+ if (!p->paused)
+ return;
+
+ OSStatus err = AudioDeviceStart(p->device, p->render_cb);
+ CHECK_CA_WARN("can't start digital device");
+
+ p->paused = false;
+}
+
+#define OPT_BASE_STRUCT struct priv
+
+const struct ao_driver audio_out_coreaudio_exclusive = {
+ .description = "CoreAudio Exclusive Mode",
+ .name = "coreaudio_exclusive",
+ .uninit = uninit,
+ .init = init,
+ .play = play,
+ .control = control,
+ .get_space = get_space,
+ .get_delay = get_delay,
+ .reset = reset,
+ .pause = audio_pause,
+ .resume = audio_resume,
+ .priv_size = sizeof(struct priv),
+ .options = (const struct m_option[]) {
+ OPT_INT("device_id", opt_device_id, 0, OPTDEF_INT(-1)),
+ OPT_FLAG("list", opt_list, 0),
+ {0}
+ },
+};
diff --git a/audio/out/ao_coreaudio_properties.h b/audio/out/ao_coreaudio_properties.h
index e48b758..8a41944 100644
--- a/audio/out/ao_coreaudio_properties.h
+++ b/audio/out/ao_coreaudio_properties.h
@@ -37,6 +37,7 @@ OSStatus ca_set(AudioObjectID id, ca_scope scope, ca_sel selector,
#define CA_GET(id, sel, data) ca_get(id, CA_GLOBAL, sel, sizeof(*(data)), data)
#define CA_SET(id, sel, data) ca_set(id, CA_GLOBAL, sel, sizeof(*(data)), data)
+#define CA_GET_O(id, sel, data) ca_get(id, CA_OUTPUT, sel, sizeof(*(data)), data)
OSStatus ca_get_ary(AudioObjectID id, ca_scope scope, ca_sel selector,
uint32_t element_size, void **data, size_t *elements);
diff --git a/audio/out/ao_coreaudio_utils.c b/audio/out/ao_coreaudio_utils.c
index 11f8942..da06656 100644
--- a/audio/out/ao_coreaudio_utils.c
+++ b/audio/out/ao_coreaudio_utils.c
@@ -25,12 +25,75 @@
#include "audio/out/ao_coreaudio_utils.h"
#include "audio/out/ao_coreaudio_properties.h"
#include "osdep/timer.h"
+#include "audio/format.h"
+
+void ca_print_device_list(struct ao *ao)
+{
+ char *help = talloc_strdup(NULL, "Available output devices:\n");
+
+ AudioDeviceID *devs;
+ size_t n_devs;
+
+ OSStatus err =
+ CA_GET_ARY(kAudioObjectSystemObject, kAudioHardwarePropertyDevices,
+ &devs, &n_devs);
+
+ CHECK_CA_ERROR("Failed to get list of output devices.");
+
+ for (int i = 0; i < n_devs; i++) {
+ char *name;
+ err = CA_GET_STR(devs[i], kAudioObjectPropertyName, &name);
+
+ if (err == noErr)
+ talloc_steal(devs, name);
+ else
+ name = "Unknown";
+
+ help = talloc_asprintf_append(
+ help, " * %s (id: %" PRIu32 ")\n", name, devs[i]);
+ }
+
+ talloc_free(devs);
+
+coreaudio_error:
+ MP_INFO(ao, "%s", help);
+ talloc_free(help);
+}
+
+OSStatus ca_select_device(struct ao *ao, int selection, AudioDeviceID *device)
+{
+ OSStatus err = noErr;
+ *device = 0;
+ if (selection < 0) {
+ // device not set by user, get the default one
+ err = CA_GET(kAudioObjectSystemObject,
+ kAudioHardwarePropertyDefaultOutputDevice,
+ device);
+ CHECK_CA_ERROR("could not get default audio device");
+ } else {
+ *device = selection;
+ }
+
+ if (mp_msg_test(ao->log, MSGL_V)) {
+ char *name;
+ err = CA_GET_STR(*device, kAudioObjectPropertyName, &name);
+ CHECK_CA_ERROR("could not get selected audio device name");
+
+ MP_VERBOSE(ao, "selected audio output device: %s (%" PRIu32 ")\n",
+ name, *device);
+
+ talloc_free(name);
+ }
+
+coreaudio_error:
+ return err;
+}
char *fourcc_repr(void *talloc_ctx, uint32_t code)
{
// Extract FourCC letters from the uint32_t and finde out if it's a valid
// code that is made of letters.
- char fcc[4] = {
+ unsigned char fcc[4] = {
(code >> 24) & 0xFF,
(code >> 16) & 0xFF,
(code >> 8) & 0xFF,
@@ -39,7 +102,7 @@ char *fourcc_repr(void *talloc_ctx, uint32_t code)
bool valid_fourcc = true;
for (int i = 0; i < 4; i++)
- if (!isprint(fcc[i]))
+ if (fcc[i] >= 32 && fcc[i] < 128)
valid_fourcc = false;
char *repr;
@@ -63,6 +126,31 @@ bool check_ca_st(struct ao *ao, int level, OSStatus code, const char *message)
return false;
}
+void ca_fill_asbd(struct ao *ao, AudioStreamBasicDescription *asbd)
+{
+ asbd->mSampleRate = ao->samplerate;
+ asbd->mFormatID = AF_FORMAT_IS_AC3(ao->format) ?
+ kAudioFormat60958AC3 :
+ kAudioFormatLinearPCM;
+ asbd->mChannelsPerFrame = ao->channels.num;
+ asbd->mBitsPerChannel = af_fmt2bits(ao->format);
+ asbd->mFormatFlags = kAudioFormatFlagIsPacked;
+
+ if ((ao->format & AF_FORMAT_POINT_MASK) == AF_FORMAT_F)
+ asbd->mFormatFlags |= kAudioFormatFlagIsFloat;
+
+ if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_SI)
+ asbd->mFormatFlags |= kAudioFormatFlagIsSignedInteger;
+
+ if ((ao->format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
+ asbd->mFormatFlags |= kAudioFormatFlagIsBigEndian;
+
+ asbd->mFramesPerPacket = 1;
+ asbd->mBytesPerPacket = asbd->mBytesPerFrame =
+ asbd->mFramesPerPacket * asbd->mChannelsPerFrame *
+ (asbd->mBitsPerChannel / 8);
+}
+
void ca_print_asbd(struct ao *ao, const char *description,
const AudioStreamBasicDescription *asbd)
{
@@ -87,375 +175,3 @@ void ca_print_asbd(struct ao *ao, const char *description,
talloc_free(format);
}
-bool ca_format_is_digital(AudioStreamBasicDescription asbd)
-{
- switch (asbd.mFormatID)
- case 'IAC3':
- case 'iac3':
- case kAudioFormat60958AC3:
- case kAudioFormatAC3:
- return true;
- return false;
-}
-
-bool ca_stream_supports_digital(struct ao *ao, AudioStreamID stream)
-{
- AudioStreamRangedDescription *formats = NULL;
- size_t n_formats;
-
- OSStatus err =
- CA_GET_ARY(stream, kAudioStreamPropertyAvailablePhysicalFormats,
- &formats, &n_formats);
-
- CHECK_CA_ERROR("Could not get number of stream formats.");
-
- for (int i = 0; i < n_formats; i++) {
- AudioStreamBasicDescription asbd = formats[i].mFormat;
- ca_print_asbd(ao, "supported format:", &(asbd));
- if (ca_format_is_digital(asbd)) {
- talloc_free(formats);
- return true;
- }
- }
-
- talloc_free(formats);
-coreaudio_error:
- return false;
-}
-
-bool ca_device_supports_digital(struct ao *ao, AudioDeviceID device)
-{
- AudioStreamID *streams = NULL;
- size_t n_streams;
-
- /* Retrieve all the output streams. */
- OSStatus err =
- CA_GET_ARY_O(device, kAudioDevicePropertyStreams, &streams, &n_streams);
-
- CHECK_CA_ERROR("could not get number of streams.");
-
- for (int i = 0; i < n_streams; i++) {
- if (ca_stream_supports_digital(ao, streams[i])) {
- talloc_free(streams);
- return true;
- }
- }
-
- talloc_free(streams);
-
-coreaudio_error:
- return false;
-}
-
-OSStatus ca_property_listener(AudioObjectPropertySelector selector,
- AudioObjectID object, uint32_t n_addresses,
- const AudioObjectPropertyAddress addresses[],
- void *data)
-{
- void *talloc_ctx = talloc_new(NULL);
-
- for (int i = 0; i < n_addresses; i++) {
- if (addresses[i].mSelector == selector) {
- if (data) *(volatile int *)data = 1;
- break;
- }
- }
- talloc_free(talloc_ctx);
- return noErr;
-}
-
-OSStatus ca_stream_listener(AudioObjectID object, uint32_t n_addresses,
- const AudioObjectPropertyAddress addresses[],
- void *data)
-{
- return ca_property_listener(kAudioStreamPropertyPhysicalFormat,
- object, n_addresses, addresses, data);
-}
-
-OSStatus ca_device_listener(AudioObjectID object, uint32_t n_addresses,
- const AudioObjectPropertyAddress addresses[],
- void *data)
-{
- return ca_property_listener(kAudioDevicePropertyDeviceHasChanged,
- object, n_addresses, addresses, data);
-}
-
-OSStatus ca_lock_device(AudioDeviceID device, pid_t *pid) {
- *pid = getpid();
- OSStatus err = CA_SET(device, kAudioDevicePropertyHogMode, pid);
- if (err != noErr)
- *pid = -1;
-
- return err;
-}
-
-OSStatus ca_unlock_device(AudioDeviceID device, pid_t *pid) {
- if (*pid == getpid()) {
- *pid = -1;
- return CA_SET(device, kAudioDevicePropertyHogMode, &pid);
- }
- return noErr;
-}
-
-static OSStatus ca_change_mixing(struct ao *ao, AudioDeviceID device,
- uint32_t val, bool *changed) {
- *changed = false;
-
- AudioObjectPropertyAddress p_addr = (AudioObjectPropertyAddress) {
- .mSelector = kAudioDevicePropertySupportsMixing,
- .mScope = kAudioObjectPropertyScopeGlobal,
- .mElement = kAudioObjectPropertyElementMaster,
- };
-
- if (AudioObjectHasProperty(device, &p_addr)) {
- OSStatus err;
- Boolean writeable = 0;
- err = CA_SETTABLE(device, kAudioDevicePropertySupportsMixing,
- &writeable);
-
- if (!CHECK_CA_WARN("can't tell if mixing property is settable")) {
- return err;
- }
-
- if (!writeable)
- return noErr;
-
- err = CA_SET(device, kAudioDevicePropertySupportsMixing, &val);
- if (err != noErr)
- return err;
-
- if (!CHECK_CA_WARN("can't set mix mode")) {
- return err;
- }
-
- *changed = true;
- }
-
- return noErr;
-}
-
-OSStatus ca_disable_mixing(struct ao *ao, AudioDeviceID device, bool *changed) {
- return ca_change_mixing(ao, device, 0, changed);
-}
-
-OSStatus ca_enable_mixing(struct ao *ao, AudioDeviceID device, bool changed) {
- if (changed) {
- bool dont_care = false;
- return ca_change_mixing(ao, device, 1, &dont_care);
- }
-
- return noErr;
-}
-
-static OSStatus ca_change_device_listening(AudioDeviceID device,
- void *flag, bool enabled)
-{
- AudioObjectPropertyAddress p_addr = (AudioObjectPropertyAddress) {
- .mSelector = kAudioDevicePropertyDeviceHasChanged,
- .mScope = kAudioObjectPropertyScopeGlobal,
- .mElement = kAudioObjectPropertyElementMaster,
- };
-
- if (enabled) {
- return AudioObjectAddPropertyListener(
- device, &p_addr, ca_device_listener, flag);
- } else {
- return AudioObjectRemovePropertyListener(
- device, &p_addr, ca_device_listener, flag);
- }
-}
-
-OSStatus ca_enable_device_listener(AudioDeviceID device, void *flag) {
- return ca_change_device_listening(device, flag, true);
-}
-
-OSStatus ca_disable_device_listener(AudioDeviceID device, void *flag) {
- return ca_change_device_listening(device, flag, false);
-}
-
-bool ca_change_format(struct ao *ao, AudioStreamID stream,
- AudioStreamBasicDescription change_format)
-{
- OSStatus err = noErr;
- AudioObjectPropertyAddress p_addr;
- volatile int stream_format_changed = 0;
-
- ca_print_asbd(ao, "setting stream format:", &change_format);
-
- /* Install the callback. */
- p_addr = (AudioObjectPropertyAddress) {
- .mSelector = kAudioStreamPropertyPhysicalFormat,
- .mScope = kAudioObjectPropertyScopeGlobal,
- .mElement = kAudioObjectPropertyElementMaster,
- };
-
- err = AudioObjectAddPropertyListener(stream, &p_addr, ca_stream_listener,
- (void *)&stream_format_changed);
- if (!CHECK_CA_WARN("can't add property listener during format change")) {
- return false;
- }
-
- /* Change the format. */
- err = CA_SET(stream, kAudioStreamPropertyPhysicalFormat, &change_format);
- if (!CHECK_CA_WARN("error changing physical format")) {
- return false;
- }
-
- /* The AudioStreamSetProperty is not only asynchronious,
- * it is also not Atomic, in its behaviour.
- * Therefore we check 5 times before we really give up. */
- bool format_set = false;
- for (int i = 0; !format_set && i < 5; i++) {
- for (int j = 0; !stream_format_changed && j < 50; j++)
- mp_sleep_us(10000);
-
- if (stream_format_changed) {
- stream_format_changed = 0;
- } else {
- MP_VERBOSE(ao, "reached timeout\n");
- }
-
- AudioStreamBasicDescription actual_format;
- err = CA_GET(stream, kAudioStreamPropertyPhysicalFormat, &actual_format);
-
- ca_print_asbd(ao, "actual format in use:", &actual_format);
- if (actual_format.mSampleRate == change_format.mSampleRate &&
- actual_format.mFormatID == change_format.mFormatID &&
- actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
- format_set = true;
- }
- }
-
- err = AudioObjectRemovePropertyListener(stream, &p_addr, ca_stream_listener,
- (void *)&stream_format_changed);
-
- if (!CHECK_CA_WARN("can't remove property listener")) {
- return false;
- }
-
- return format_set;
-}
-
-static const int speaker_map[][2] = {
- { kAudioChannelLabel_Left, MP_SPEAKER_ID_FL },
- { kAudioChannelLabel_Right, MP_SPEAKER_ID_FR },
- { kAudioChannelLabel_Center, MP_SPEAKER_ID_FC },
- { kAudioChannelLabel_LFEScreen, MP_SPEAKER_ID_LFE },
- { kAudioChannelLabel_LeftSurround, MP_SPEAKER_ID_BL },
- { kAudioChannelLabel_RightSurround, MP_SPEAKER_ID_BR },
- { kAudioChannelLabel_LeftCenter, MP_SPEAKER_ID_FLC },
- { kAudioChannelLabel_RightCenter, MP_SPEAKER_ID_FRC },
- { kAudioChannelLabel_CenterSurround, MP_SPEAKER_ID_BC },
- { kAudioChannelLabel_LeftSurroundDirect, MP_SPEAKER_ID_SL },
- { kAudioChannelLabel_RightSurroundDirect, MP_SPEAKER_ID_SR },
- { kAudioChannelLabel_TopCenterSurround, MP_SPEAKER_ID_TC },
- { kAudioChannelLabel_VerticalHeightLeft, MP_SPEAKER_ID_TFL },
- { kAudioChannelLabel_VerticalHeightCenter, MP_SPEAKER_ID_TFC },
- { kAudioChannelLabel_VerticalHeightRight, MP_SPEAKER_ID_TFR },
- { kAudioChannelLabel_TopBackLeft, MP_SPEAKER_ID_TBL },
- { kAudioChannelLabel_TopBackCenter, MP_SPEAKER_ID_TBC },
- { kAudioChannelLabel_TopBackRight, MP_SPEAKER_ID_TBR },
-
- // unofficial extensions
- { kAudioChannelLabel_RearSurroundLeft, MP_SPEAKER_ID_SDL },
- { kAudioChannelLabel_RearSurroundRight, MP_SPEAKER_ID_SDR },
- { kAudioChannelLabel_LeftWide, MP_SPEAKER_ID_WL },
- { kAudioChannelLabel_RightWide, MP_SPEAKER_ID_WR },
- { kAudioChannelLabel_LFE2, MP_SPEAKER_ID_LFE2 },
-
- { kAudioChannelLabel_HeadphonesLeft, MP_SPEAKER_ID_DL },
- { kAudioChannelLabel_HeadphonesRight, MP_SPEAKER_ID_DR },
-
- { kAudioChannelLabel_Unknown, -1 },
-};
-
-static int ca_label_to_mp_speaker_id(AudioChannelLabel label)
-{
- for (int i = 0; speaker_map[i][1] >= 0; i++)
- if (speaker_map[i][0] == label)
- return speaker_map[i][1];
- return -1;
-}
-
-static void ca_log_layout(struct ao *ao, AudioChannelLayout *layout)
-{
- if (!mp_msg_test(ao->log, MSGL_V))
- return;
-
- AudioChannelDescription *descs = layout->mChannelDescriptions;
-
- MP_VERBOSE(ao, "layout: tag: <%d>, bitmap: <%d>, "
- "descriptions <%d>\n",
- layout->mChannelLayoutTag,
- layout->mChannelBitmap,
- layout->mNumberChannelDescriptions);
-
- for (int i = 0; i < layout->mNumberChannelDescriptions; i++) {
- AudioChannelDescription d = descs[i];
- MP_VERBOSE(ao, " - description %d: label <%d, %d>, flags: <%u>, "
- "coords: <%f, %f, %f>\n", i,
- d.mChannelLabel,
- ca_label_to_mp_speaker_id(d.mChannelLabel),
- d.mChannelFlags,
- d.mCoordinates[0],
- d.mCoordinates[1],
- d.mCoordinates[2]);
- }
-}
-
-bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout,
- struct mp_chmap *chmap)
-{
- AudioChannelLayoutTag tag = layout->mChannelLayoutTag;
- uint32_t layout_size = sizeof(layout);
- OSStatus err;
-
- if (tag == kAudioChannelLayoutTag_UseChannelBitmap) {
- err = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
- sizeof(uint32_t),
- &layout->mChannelBitmap,
- &layout_size,
- layout);
- CHECK_CA_ERROR("failed to convert channel bitmap to descriptions");
- } else if (tag != kAudioChannelLayoutTag_UseChannelDescriptions) {
- err = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
- sizeof(AudioChannelLayoutTag),
- &layout->mChannelLayoutTag,
- &layout_size,
- layout);
- CHECK_CA_ERROR("failed to convert channel tag to descriptions");
- }
-
- ca_log_layout(ao, layout);
-
- // If the channel layout uses channel descriptions, from my
- // experiments there are there three possibile cases:
- // * The description has a label kAudioChannelLabel_Unknown:
- // Can't do anything about this (looks like non surround
- // layouts are like this).
- // * The description uses positional information: this in
- // theory could be used but one would have to map spatial
- // positions to labels which is not really feasible.
- // * The description has a well known label which can be mapped
- // to the waveextensible definition: this is the kind of
- // descriptions we process here.
-
- for (int n = 0; n < layout->mNumberChannelDescriptions; n++) {
- AudioChannelLabel label = layout->mChannelDescriptions[n].mChannelLabel;
- uint8_t speaker = ca_label_to_mp_speaker_id(label);
- if (label == kAudioChannelLabel_Unknown)
- continue;
- if (speaker < 0) {
- MP_VERBOSE(ao, "channel label=%d unusable to build channel "
- "bitmap, skipping layout\n", label);
- } else {
- chmap->speaker[n] = speaker;
- chmap->num = n + 1;
- }
- }
-
- return chmap->num > 0;
-coreaudio_error:
- ca_log_layout(ao, layout);
- return false;
-}
diff --git a/audio/out/ao_coreaudio_utils.h b/audio/out/ao_coreaudio_utils.h
index 9218ccf..2c74619 100644
--- a/audio/out/ao_coreaudio_utils.h
+++ b/audio/out/ao_coreaudio_utils.h
@@ -46,38 +46,11 @@ bool check_ca_st(struct ao *ao, int level, OSStatus code, const char *message);
if (err != noErr) goto label; \
} while (0)
+void ca_print_device_list(struct ao *ao);
+OSStatus ca_select_device(struct ao *ao, int selection, AudioDeviceID *device);
+
+void ca_fill_asbd(struct ao *ao, AudioStreamBasicDescription *asbd);
void ca_print_asbd(struct ao *ao, const char *description,
const AudioStreamBasicDescription *asbd);
-bool ca_format_is_digital(AudioStreamBasicDescription asbd);
-bool ca_stream_supports_digital(struct ao *ao, AudioStreamID stream);
-bool ca_device_supports_digital(struct ao *ao, AudioDeviceID device);
-
-OSStatus ca_property_listener(AudioObjectPropertySelector selector,
- AudioObjectID object, uint32_t n_addresses,
- const AudioObjectPropertyAddress addresses[],
- void *data);
-
-OSStatus ca_stream_listener(AudioObjectID object, uint32_t n_addresses,
- const AudioObjectPropertyAddress addresses[],
- void *data);
-
-OSStatus ca_device_listener(AudioObjectID object, uint32_t n_addresses,
- const AudioObjectPropertyAddress addresses[],
- void *data);
-
-OSStatus ca_lock_device(AudioDeviceID device, pid_t *pid);
-OSStatus ca_unlock_device(AudioDeviceID device, pid_t *pid);
-OSStatus ca_disable_mixing(struct ao *ao, AudioDeviceID device, bool *changed);
-OSStatus ca_enable_mixing(struct ao *ao, AudioDeviceID device, bool changed);
-
-OSStatus ca_enable_device_listener(AudioDeviceID device, void *flag);
-OSStatus ca_disable_device_listener(AudioDeviceID device, void *flag);
-
-bool ca_change_format(struct ao *ao, AudioStreamID stream,
- AudioStreamBasicDescription change_format);
-
-bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout,
- struct mp_chmap *chmap);
-
#endif /* MPV_COREAUDIO_UTILS_H */
diff --git a/audio/out/ao_dsound.c b/audio/out/ao_dsound.c
index e8d37e4..e313c7d 100644
--- a/audio/out/ao_dsound.c
+++ b/audio/out/ao_dsound.c
@@ -403,7 +403,7 @@ static int init(struct ao *ao)
ao->samplerate = rate;
ao->format = format;
ao->bps = ao->channels.num * rate * af_fmt2bps(format);
- int buffersize = ao->bps; // space for 1 sec
+ int buffersize = ao->bps * 0.100; // space for 100ms
MP_VERBOSE(ao, "Samplerate:%iHz Channels:%i Format:%s\n", rate,
ao->channels.num, af_fmt_to_str(format));
MP_VERBOSE(ao, "Buffersize:%d bytes (%d msec)\n",
diff --git a/audio/out/ao_lavc.c b/audio/out/ao_lavc.c
index 32e6fbd..34cf2c2 100644
--- a/audio/out/ao_lavc.c
+++ b/audio/out/ao_lavc.c
@@ -71,7 +71,7 @@ static void select_format(struct ao *ao, AVCodec *codec)
{
int fmt = af_from_avformat(*sampleformat);
if (!fmt) {
- MP_WARN(ao, "unsupported lavc format %s",
+ MP_WARN(ao, "unsupported lavc format %s\n",
av_get_sample_fmt_name(*sampleformat));
continue;
}
@@ -114,12 +114,11 @@ static int init(struct ao *ao)
codec = encode_lavc_get_codec(ao->encode_lavc_ctx, ac->stream);
- // ac->stream->time_base.num = 1;
- // ac->stream->time_base.den = ao->samplerate;
- // doing this breaks mpeg2ts in ffmpeg
- // which doesn't properly force the time base to be 90000
- // furthermore, ffmpeg.c doesn't do this either and works
-
+ // TODO: Remove this redundancy with encode_lavc_alloc_stream also
+ // setting the time base.
+ // Using codec->time_bvase is deprecated, but needed for older lavf.
+ ac->stream->time_base.num = 1;
+ ac->stream->time_base.den = ao->samplerate;
ac->stream->codec->time_base.num = 1;
ac->stream->codec->time_base.den = ao->samplerate;
@@ -342,8 +341,7 @@ static int play(struct ao *ao, void **data, int samples, int flags)
}
double pts = ectx->last_audio_in_pts;
- pts += ectx->samples_since_last_pts / ao->samplerate;
- ectx->samples_since_last_pts += samples;
+ pts += ectx->samples_since_last_pts / (double)ao->samplerate;
size_t num_planes = af_fmt_is_planar(ao->format) ? ao->channels.num : 1;
@@ -451,6 +449,10 @@ static int play(struct ao *ao, void **data, int samples, int flags)
}
talloc_free(tempdata);
+
+ int taken = FFMIN(bufpos, orig_samples);
+ ectx->samples_since_last_pts += taken;
+
pthread_mutex_unlock(&ectx->lock);
if (flags & AOPLAY_FINAL_CHUNK) {
@@ -463,7 +465,7 @@ static int play(struct ao *ao, void **data, int samples, int flags)
}
}
- return FFMIN(bufpos, orig_samples);
+ return taken;
}
static void drain(struct ao *ao)
diff --git a/audio/out/ao_null.c b/audio/out/ao_null.c
index 384343a..2c93cc2 100644
--- a/audio/out/ao_null.c
+++ b/audio/out/ao_null.c
@@ -90,7 +90,7 @@ static int init(struct ao *ao)
struct mp_chmap_sel sel = {0};
mp_chmap_sel_add_any(&sel);
if (!ao_chmap_sel_adjust(ao, &sel, &ao->channels))
- return -1;
+ mp_chmap_from_channels(&ao->channels, 2);
priv->latency = priv->latency_sec * ao->samplerate;
diff --git a/audio/out/ao_oss.c b/audio/out/ao_oss.c
index 7698af4..1d88291 100644
--- a/audio/out/ao_oss.c
+++ b/audio/out/ao_oss.c
@@ -33,6 +33,7 @@
#include <fcntl.h>
#include <errno.h>
#include <string.h>
+#include <strings.h>
#include "config.h"
#include "options/options.h"
diff --git a/audio/out/ao_pulse.c b/audio/out/ao_pulse.c
index dad21fe..14b5161 100644
--- a/audio/out/ao_pulse.c
+++ b/audio/out/ao_pulse.c
@@ -53,7 +53,6 @@ struct priv {
// temporary during control()
struct pa_sink_input_info pi;
- bool broken_pause;
int retval;
// for wakeup handling
@@ -64,6 +63,7 @@ struct priv {
char *cfg_host;
char *cfg_sink;
int cfg_buffer;
+ int cfg_latency_hacks;
};
#define GENERIC_ERR_MSG(str) \
@@ -113,7 +113,7 @@ static void stream_request_cb(pa_stream *s, size_t length, void *userdata)
pa_threaded_mainloop_signal(priv->mainloop, 0);
}
-static int wait(struct ao *ao, pthread_mutex_t *lock)
+static int wait_audio(struct ao *ao, pthread_mutex_t *lock)
{
struct priv *priv = ao->priv;
// We don't use this mutex, because pulse like to call stream_request_cb
@@ -280,26 +280,12 @@ static int init(struct ao *ao)
struct priv *priv = ao->priv;
char *host = priv->cfg_host && priv->cfg_host[0] ? priv->cfg_host : NULL;
char *sink = priv->cfg_sink && priv->cfg_sink[0] ? priv->cfg_sink : NULL;
- const char *version = pa_get_library_version();
pthread_mutex_init(&priv->wakeup_lock, NULL);
pthread_cond_init(&priv->wakeup, NULL);
ao->per_application_mixer = true;
- priv->broken_pause = false;
- /* not sure which versions are affected, assume 0.9.11* to 0.9.14*
- * known bad: 0.9.14, 0.9.13
- * known good: 0.9.9, 0.9.10, 0.9.15
- * To test: pause, wait ca. 5 seconds, framestep and see if MPlayer
- * hangs somewhen. */
- if (strncmp(version, "0.9.1", 5) == 0 && version[5] >= '1'
- && version[5] <= '4') {
- MP_WARN(ao, "working around probably broken pause functionality,\n"
- " see http://www.pulseaudio.org/ticket/440\n");
- priv->broken_pause = true;
- }
-
if (!(priv->mainloop = pa_threaded_mainloop_new())) {
MP_ERR(ao, "Failed to allocate main loop\n");
goto fail;
@@ -357,6 +343,8 @@ static int init(struct ao *ao)
goto unlock_and_fail;
}
(void)pa_proplist_sets(proplist, PA_PROP_MEDIA_ROLE, "video");
+ (void)pa_proplist_sets(proplist, PA_PROP_MEDIA_ICON_NAME,
+ PULSE_CLIENT_NAME);
if (!(priv->stream = pa_stream_new_with_proplist(priv->context,
"audio stream", &ss,
@@ -378,8 +366,13 @@ static int init(struct ao *ao)
.minreq = -1,
.fragsize = -1,
};
+
+ int flags = PA_STREAM_NOT_MONOTONIC;
+ if (!priv->cfg_latency_hacks)
+ flags |= PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_AUTO_TIMING_UPDATE;
+
if (pa_stream_connect_playback(priv->stream, sink, &bufattr,
- PA_STREAM_NOT_MONOTONIC, NULL, NULL) < 0)
+ flags, NULL, NULL) < 0)
goto unlock_and_fail;
/* Wait until the stream is ready */
@@ -463,12 +456,6 @@ static void pause(struct ao *ao)
// Resume the audio stream by uncorking it on the server
static void resume(struct ao *ao)
{
- struct priv *priv = ao->priv;
- /* Without this, certain versions will cause an infinite hang because
- * pa_stream_writable_size returns 0 always.
- * Note that this workaround causes A-V desync after pause. */
- if (priv->broken_pause)
- reset(ao);
cork(ao, false);
}
@@ -482,8 +469,7 @@ static int get_space(struct ao *ao)
return space / ao->sstride;
}
-// Return the current latency in seconds
-static float get_delay(struct ao *ao)
+static float get_delay_hackfixed(struct ao *ao)
{
/* This code basically does what pa_stream_get_latency() _should_
* do, but doesn't due to multiple known bugs in PulseAudio (at
@@ -538,6 +524,34 @@ static float get_delay(struct ao *ao)
return latency / 1e6;
}
+static float get_delay_pulse(struct ao *ao)
+{
+ struct priv *priv = ao->priv;
+ pa_usec_t latency = (pa_usec_t) -1;
+ pa_threaded_mainloop_lock(priv->mainloop);
+ while (pa_stream_get_latency(priv->stream, &latency, NULL) < 0) {
+ if (pa_context_errno(priv->context) != PA_ERR_NODATA) {
+ GENERIC_ERR_MSG("pa_stream_get_latency() failed");
+ break;
+ }
+ /* Wait until latency data is available again */
+ pa_threaded_mainloop_wait(priv->mainloop);
+ }
+ pa_threaded_mainloop_unlock(priv->mainloop);
+ return latency == (pa_usec_t) -1 ? 0 : latency / 1000000.0;
+}
+
+// Return the current latency in seconds
+static float get_delay(struct ao *ao)
+{
+ struct priv *priv = ao->priv;
+ if (priv->cfg_latency_hacks) {
+ return get_delay_hackfixed(ao);
+ } else {
+ return get_delay_pulse(ao);
+ }
+}
+
/* A callback function that is called when the
* pa_context_get_sink_input_info() operation completes. Saves the
* volume field of the specified structure to the global variable volume.
@@ -662,16 +676,18 @@ const struct ao_driver audio_out_pulse = {
.pause = pause,
.resume = resume,
.drain = drain,
- .wait = wait,
+ .wait = wait_audio,
.wakeup = wakeup,
.priv_size = sizeof(struct priv),
.priv_defaults = &(const struct priv) {
.cfg_buffer = 250,
+ .cfg_latency_hacks = 1,
},
.options = (const struct m_option[]) {
OPT_STRING("host", cfg_host, 0),
OPT_STRING("sink", cfg_sink, 0),
OPT_CHOICE_OR_INT("buffer", cfg_buffer, 0, 1, 2000, ({"native", -1})),
+ OPT_FLAG("latency-hacks", cfg_latency_hacks, 0),
{0}
},
};
diff --git a/audio/out/push.c b/audio/out/push.c
index 0ecba19..c825310 100644
--- a/audio/out/push.c
+++ b/audio/out/push.c
@@ -370,11 +370,12 @@ static int init(struct ao *ao)
mp_audio_buffer_reinit_fmt(p->buffer, ao->format,
&ao->channels, ao->samplerate);
mp_audio_buffer_preallocate_min(p->buffer, ao->buffer);
- if (pthread_create(&p->thread, NULL, playthread, ao)) {
- ao->driver->uninit(ao);
- return -1;
- }
+ if (pthread_create(&p->thread, NULL, playthread, ao))
+ goto err;
return 0;
+err:
+ ao->driver->uninit(ao);
+ return -1;
}
const struct ao_driver ao_api_push = {
diff --git a/bstr/bstr.c b/bstr/bstr.c
index 964934a..1aae18c 100644
--- a/bstr/bstr.c
+++ b/bstr/bstr.c
@@ -17,8 +17,8 @@
*/
#include <string.h>
+#include <strings.h>
#include <assert.h>
-#include <ctype.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdlib.h>
@@ -28,6 +28,7 @@
#include "talloc.h"
#include "common/common.h"
+#include "misc/ctype.h"
#include "bstr/bstr.h"
int bstrcmp(struct bstr str1, struct bstr str2)
@@ -104,7 +105,7 @@ int bstr_find(struct bstr haystack, struct bstr needle)
struct bstr bstr_lstrip(struct bstr str)
{
- while (str.len && isspace(*str.start)) {
+ while (str.len && mp_isspace(*str.start)) {
str.start++;
str.len--;
}
@@ -114,7 +115,7 @@ struct bstr bstr_lstrip(struct bstr str)
struct bstr bstr_strip(struct bstr str)
{
str = bstr_lstrip(str);
- while (str.len && isspace(str.start[str.len - 1]))
+ while (str.len && mp_isspace(str.start[str.len - 1]))
str.len--;
return str;
}
@@ -242,7 +243,7 @@ bool bstr_eatstart(struct bstr *s, struct bstr prefix)
void bstr_lower(struct bstr str)
{
for (int i = 0; i < str.len; i++)
- str.start[i] = tolower(str.start[i]);
+ str.start[i] = mp_tolower(str.start[i]);
}
int bstr_sscanf(struct bstr str, const char *format, ...)
diff --git a/common/av_common.c b/common/av_common.c
index 1a162b7..e0a5da7 100644
--- a/common/av_common.c
+++ b/common/av_common.c
@@ -19,6 +19,9 @@
#include <libavutil/common.h>
#include <libavutil/log.h>
+#include <libavutil/dict.h>
+#include <libavutil/opt.h>
+#include <libavutil/error.h>
#include <libavcodec/avcodec.h>
#include "common/common.h"
@@ -64,7 +67,6 @@ void mp_copy_lav_codec_headers(AVCodecContext *avctx, AVCodecContext *st)
avctx->channels = st->channels;
avctx->block_align = st->block_align;
avctx->channel_layout = st->channel_layout;
- avctx->audio_service_type = st->audio_service_type;
avctx->bits_per_coded_sample = st->bits_per_coded_sample;
}
@@ -181,3 +183,45 @@ const char *mp_codec_from_av_codec_id(int codec_id)
}
return name;
}
+
+// kv is in the format as by OPT_KEYVALUELIST(): kv[0]=key0, kv[1]=val0, ...
+// Copy them to the dict.
+void mp_set_avdict(AVDictionary **dict, char **kv)
+{
+ for (int n = 0; kv && kv[n * 2]; n++)
+ av_dict_set(dict, kv[n * 2 + 0], kv[n * 2 + 1], 0);
+}
+
+// For use with libav* APIs that take AVDictionaries of options.
+// Print options remaining in the dict as unset.
+void mp_avdict_print_unset(struct mp_log *log, int msgl, AVDictionary *dict)
+{
+ AVDictionaryEntry *t = NULL;
+ while ((t = av_dict_get(dict, "", t, AV_DICT_IGNORE_SUFFIX)))
+ mp_msg(log, msgl, "Could not set AVOption %s='%s'\n", t->key, t->value);
+}
+
+// kv is in the format as by OPT_KEYVALUELIST(): kv[0]=key0, kv[1]=val0, ...
+// Set these options on given avobj (using av_opt_set..., meaning avobj must
+// point to a struct that has AVClass as first member).
+// Options which fail to set (error or not found) are printed to log.
+// Returns: >=0 success, <0 failed to set an option
+int mp_set_avopts(struct mp_log *log, void *avobj, char **kv)
+{
+ int success = 0;
+ for (int n = 0; kv && kv[n * 2]; n++) {
+ char *k = kv[n * 2 + 0];
+ char *v = kv[n * 2 + 1];
+ int r = av_opt_set(avobj, k, v, AV_OPT_SEARCH_CHILDREN);
+ if (r == AVERROR_OPTION_NOT_FOUND) {
+ mp_err(log, "AVOption '%s' not found.\n", k);
+ success = -1;
+ } else if (r < 0) {
+ char errstr[80];
+ av_strerror(r, errstr, sizeof(errstr));
+ mp_err(log, "Could not set AVOption %s='%s' (%s)\n", k, v, errstr);
+ success = -1;
+ }
+ }
+ return success;
+}
diff --git a/common/av_common.h b/common/av_common.h
index 2e55fe1..3168d53 100644
--- a/common/av_common.h
+++ b/common/av_common.h
@@ -26,6 +26,8 @@
struct mp_decoder_list;
struct demux_packet;
+struct AVDictionary;
+struct mp_log;
int mp_lavc_set_extradata(AVCodecContext *avctx, void *ptr, int size);
void mp_copy_lav_codec_headers(AVCodecContext *avctx, AVCodecContext *st);
@@ -36,5 +38,8 @@ void mp_set_avcodec_threads(AVCodecContext *avctx, int threads);
void mp_add_lavc_decoders(struct mp_decoder_list *list, enum AVMediaType type);
int mp_codec_to_av_codec_id(const char *codec);
const char *mp_codec_from_av_codec_id(int codec_id);
+void mp_set_avdict(struct AVDictionary **dict, char **kv);
+void mp_avdict_print_unset(struct mp_log *log, int msgl, struct AVDictionary *d);
+int mp_set_avopts(struct mp_log *log, void *avobj, char **kv);
#endif
diff --git a/common/av_opts.c b/common/av_opts.c
deleted file mode 100644
index 777a1ee..0000000
--- a/common/av_opts.c
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * AVOption parsing helper
- * Copyright (C) 2008 Michael Niedermayer
- *
- * 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 <stdlib.h>
-#include <string.h>
-
-#include <libavutil/opt.h>
-
-#include "av_opts.h"
-
-int parse_avopts(void *v, char *str){
- char *start;
-
- if (!str)
- return 0;
-
- start= str= strdup(str);
-
- while(str && *str){
- char *next_opt, *arg;
-
- next_opt= strchr(str, ',');
- if(next_opt) *next_opt++= 0;
-
- arg = strchr(str, '=');
- if(arg) *arg++= 0;
-
- if (av_opt_set(v, str, arg, AV_OPT_SEARCH_CHILDREN) < 0) {
- free(start);
- return -1;
- }
- str= next_opt;
- }
-
- free(start);
- return 0;
-}
diff --git a/common/av_opts.h b/common/av_opts.h
deleted file mode 100644
index 640443a..0000000
--- a/common/av_opts.h
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * AVOption parsing helper
- * Copyright (C) 2008 Michael Niedermayer
- *
- * 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.
- */
-
-#ifndef MPLAYER_AV_OPTS_H
-#define MPLAYER_AV_OPTS_H
-
-/**
- * Parses str and sets AVOptions in v accordingly.
- */
-int parse_avopts(void *v, char *str);
-
-#endif /* MPLAYER_AV_OPTS_H */
diff --git a/common/encode_lavc.c b/common/encode_lavc.c
index df5710e..8877033 100644
--- a/common/encode_lavc.c
+++ b/common/encode_lavc.c
@@ -590,11 +590,8 @@ AVStream *encode_lavc_alloc_stream(struct encode_lavc_context *ctx,
}
avcodec_get_context_defaults3(stream->codec, ctx->vc);
- // stream->time_base = ctx->timebase;
- // doing this breaks mpeg2ts in ffmpeg
- // which doesn't properly force the time base to be 90000
- // furthermore, ffmpeg.c doesn't do this either and works
-
+ // Using codec->time_base is deprecated, but needed for older lavf.
+ stream->time_base = ctx->timebase;
stream->codec->time_base = ctx->timebase;
ctx->voptions = NULL;
@@ -626,6 +623,8 @@ AVStream *encode_lavc_alloc_stream(struct encode_lavc_context *ctx,
}
avcodec_get_context_defaults3(stream->codec, ctx->ac);
+ // Using codec->time_base is deprecated, but needed for older lavf.
+ stream->time_base = ctx->timebase;
stream->codec->time_base = ctx->timebase;
ctx->aoptions = NULL;
diff --git a/common/msg.c b/common/msg.c
index 4f9bd88..d1c2530 100644
--- a/common/msg.c
+++ b/common/msg.c
@@ -429,7 +429,7 @@ void mp_msg_update_msglevels(struct mpv_global *global)
root->show_time = opts->msg_time;
if (root->use_terminal) {
root->color = opts->msg_color && isatty(fileno(stdout));
- root->termosd = !opts->slave_mode && isatty(fileno(stderr));
+ root->termosd = isatty(fileno(stderr));
}
talloc_free(root->msglevels);
diff --git a/common/tags.c b/common/tags.c
index f709cf0..c722d5d 100644
--- a/common/tags.c
+++ b/common/tags.c
@@ -61,6 +61,25 @@ void mp_tags_clear(struct mp_tags *tags)
talloc_free_children(tags);
}
+struct mp_tags *mp_tags_dup(void *tparent, struct mp_tags *tags)
+{
+ struct mp_tags *new = talloc_zero(tparent, struct mp_tags);
+ MP_RESIZE_ARRAY(new, new->keys, tags->num_keys);
+ MP_RESIZE_ARRAY(new, new->values, tags->num_keys);
+ new->num_keys = tags->num_keys;
+ for (int n = 0; n < tags->num_keys; n++) {
+ new->keys[n] = talloc_strdup(new, tags->keys[n]);
+ new->values[n] = talloc_strdup(new, tags->values[n]);
+ }
+ return new;
+}
+
+void mp_tags_merge(struct mp_tags *tags, struct mp_tags *src)
+{
+ for (int n = 0; n < src->num_keys; n++)
+ mp_tags_set_str(tags, src->keys[n], src->values[n]);
+}
+
void mp_tags_copy_from_av_dictionary(struct mp_tags *tags,
struct AVDictionary *av_dict)
{
diff --git a/common/tags.h b/common/tags.h
index 3bc0e69..3752896 100644
--- a/common/tags.h
+++ b/common/tags.h
@@ -14,6 +14,8 @@ void mp_tags_set_bstr(struct mp_tags *tags, bstr key, bstr value);
char *mp_tags_get_str(struct mp_tags *tags, const char *key);
char *mp_tags_get_bstr(struct mp_tags *tags, bstr key);
void mp_tags_clear(struct mp_tags *tags);
+struct mp_tags *mp_tags_dup(void *tparent, struct mp_tags *tags);
+void mp_tags_merge(struct mp_tags *tags, struct mp_tags *src);
struct AVDictionary;
void mp_tags_copy_from_av_dictionary(struct mp_tags *tags,
struct AVDictionary *av_dict);
diff --git a/demux/demux.c b/demux/demux.c
index 51a5f4d..56a147e 100644
--- a/demux/demux.c
+++ b/demux/demux.c
@@ -1,6 +1,4 @@
/*
- * DEMUXER v2.5
- *
* This file is part of MPlayer.
*
* MPlayer is free software; you can redistribute it and/or modify
@@ -17,13 +15,13 @@
* with MPlayer; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
-#define DEMUX_PRIV(x) x
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
+#include <pthread.h>
#include <math.h>
@@ -32,7 +30,6 @@
#include "config.h"
#include "options/options.h"
-#include "common/av_common.h"
#include "talloc.h"
#include "common/msg.h"
#include "common/global.h"
@@ -44,8 +41,6 @@
#include "audio/format.h"
-#include <libavcodec/avcodec.h>
-
// Demuxer list
extern const struct demuxer_desc demuxer_desc_edl;
extern const struct demuxer_desc demuxer_desc_cue;
@@ -58,12 +53,14 @@ extern const demuxer_desc_t demuxer_desc_lavf;
extern const demuxer_desc_t demuxer_desc_libass;
extern const demuxer_desc_t demuxer_desc_subreader;
extern const demuxer_desc_t demuxer_desc_playlist;
+extern const demuxer_desc_t demuxer_desc_disc;
/* Please do not add any new demuxers here. If you want to implement a new
* demuxer, add it to libavformat, except for wrappers around external
* libraries and demuxers requiring binary support. */
const demuxer_desc_t *const demuxer_list[] = {
+ &demuxer_desc_disc,
&demuxer_desc_edl,
&demuxer_desc_cue,
&demuxer_desc_rawaudio,
@@ -80,25 +77,76 @@ const demuxer_desc_t *const demuxer_list[] = {
&demuxer_desc_playlist,
// Pretty aggressive, so should be last.
&demuxer_desc_subreader,
- /* Please do not add any new demuxers here. If you want to implement a new
- * demuxer, add it to libavformat, except for wrappers around external
- * libraries and demuxers requiring binary support. */
NULL
};
+struct demux_internal {
+ struct mp_log *log;
+
+ // The demuxer runs potentially in another thread, so we keep two demuxer
+ // structs; the real demuxer can access the shadow struct only.
+ // Since demuxer and user threads both don't use locks, a third demuxer
+ // struct d_buffer is used to copy data between them in a synchronized way.
+ struct demuxer *d_thread; // accessed by demuxer impl. (producer)
+ struct demuxer *d_user; // accessed by player (consumer)
+ struct demuxer *d_buffer; // protected by lock; used to sync d_user/thread
+
+ // The lock protects the packet queues (struct demux_stream), d_buffer,
+ // and some minor fields like thread_paused.
+ pthread_mutex_t lock;
+ pthread_cond_t wakeup;
+ pthread_t thread;
+
+ // -- All the following fields are protected by lock.
+
+ bool thread_paused;
+ int thread_request_pause; // counter, if >0, make demuxer thread pause
+ bool thread_terminate;
+ bool threading;
+ void (*wakeup_cb)(void *ctx);
+ void *wakeup_cb_ctx;
+
+ bool warned_queue_overflow;
+ bool last_eof; // last actual global EOF status
+ bool eof; // whether we're in EOF state (reset for retry)
+ bool autoselect;
+ int min_packs;
+ int min_bytes;
+
+ bool tracks_switched; // thread needs to inform demuxer of this
+
+ bool seeking; // there's a seek queued
+ int seek_flags; // flags for next seek (if seeking==true)
+ double seek_pts;
+
+ // Cached state.
+ double time_length;
+ struct mp_tags *stream_metadata;
+ int64_t stream_size;
+ int64_t stream_cache_size;
+ int64_t stream_cache_fill;
+ int stream_cache_idle;
+};
+
struct demux_stream {
- int selected; // user wants packets from this stream
- int eof; // end of demuxed stream? (true if all buffer empty)
- int packs; // number of packets in buffer
- int bytes; // total bytes of packets in buffer
+ struct demux_internal *in;
+ enum stream_type type;
+ // all fields are protected by in->lock
+ bool selected; // user wants packets from this stream
+ bool active; // try to keep at least 1 packet queued
+ bool eof; // end of demuxed stream? (true if all buffer empty)
+ size_t packs; // number of packets in buffer
+ size_t bytes; // total bytes of packets in buffer
struct demux_packet *head;
struct demux_packet *tail;
};
-static void add_stream_chapters(struct demuxer *demuxer);
-void demuxer_sort_chapters(demuxer_t *demuxer);
+static void demuxer_sort_chapters(demuxer_t *demuxer);
+static void *demux_thread(void *pctx);
+static void update_cache(struct demux_internal *in);
-static void ds_free_packs(struct demux_stream *ds)
+// called locked
+static void ds_flush(struct demux_stream *ds)
{
demux_packet_t *dp = ds->head;
while (dp) {
@@ -107,110 +155,16 @@ static void ds_free_packs(struct demux_stream *ds)
dp = dn;
}
ds->head = ds->tail = NULL;
- ds->packs = 0; // !!!!!
+ ds->packs = 0;
ds->bytes = 0;
- ds->eof = 0;
-}
-
-static void packet_destroy(void *ptr)
-{
- struct demux_packet *dp = ptr;
- talloc_free(dp->avpacket);
- av_free(dp->allocation);
-}
-
-static struct demux_packet *create_packet(size_t len)
-{
- if (len > 1000000000) {
- fprintf(stderr, "Attempt to allocate demux packet over 1 GB!\n");
- abort();
- }
- struct demux_packet *dp = talloc(NULL, struct demux_packet);
- talloc_set_destructor(dp, packet_destroy);
- *dp = (struct demux_packet) {
- .len = len,
- .pts = MP_NOPTS_VALUE,
- .dts = MP_NOPTS_VALUE,
- .duration = -1,
- .stream_pts = MP_NOPTS_VALUE,
- .pos = -1,
- .stream = -1,
- };
- return dp;
-}
-
-struct demux_packet *new_demux_packet(size_t len)
-{
- struct demux_packet *dp = create_packet(len);
- dp->buffer = av_malloc(len + FF_INPUT_BUFFER_PADDING_SIZE);
- if (!dp->buffer) {
- fprintf(stderr, "Memory allocation failure!\n");
- abort();
- }
- memset(dp->buffer + len, 0, FF_INPUT_BUFFER_PADDING_SIZE);
- dp->allocation = dp->buffer;
- return dp;
-}
-
-// data must already have suitable padding, and does not copy the data
-struct demux_packet *new_demux_packet_fromdata(void *data, size_t len)
-{
- struct demux_packet *dp = create_packet(len);
- dp->buffer = data;
- return dp;
-}
-
-struct demux_packet *new_demux_packet_from(void *data, size_t len)
-{
- struct demux_packet *dp = new_demux_packet(len);
- memcpy(dp->buffer, data, len);
- return dp;
-}
-
-void demux_packet_shorten(struct demux_packet *dp, size_t len)
-{
- assert(len <= dp->len);
- dp->len = len;
- memset(dp->buffer + dp->len, 0, FF_INPUT_BUFFER_PADDING_SIZE);
-}
-
-void free_demux_packet(struct demux_packet *dp)
-{
- talloc_free(dp);
-}
-
-static void destroy_avpacket(void *pkt)
-{
- av_free_packet(pkt);
-}
-
-struct demux_packet *demux_copy_packet(struct demux_packet *dp)
-{
- struct demux_packet *new = NULL;
- if (dp->avpacket) {
- assert(dp->buffer == dp->avpacket->data);
- assert(dp->len == dp->avpacket->size);
- AVPacket *newavp = talloc_zero(NULL, AVPacket);
- talloc_set_destructor(newavp, destroy_avpacket);
- av_init_packet(newavp);
- if (av_packet_ref(newavp, dp->avpacket) < 0)
- abort();
- new = new_demux_packet_fromdata(newavp->data, newavp->size);
- new->avpacket = newavp;
- }
- if (!new) {
- new = new_demux_packet(dp->len);
- memcpy(new->buffer, dp->buffer, new->len);
- }
- new->pts = dp->pts;
- new->dts = dp->dts;
- new->duration = dp->duration;
- new->stream_pts = dp->stream_pts;
- return new;
+ ds->eof = false;
+ ds->active = false;
}
struct sh_stream *new_sh_stream(demuxer_t *demuxer, enum stream_type type)
{
+ assert(demuxer == demuxer->in->d_thread);
+
if (demuxer->num_streams > MAX_SH_STREAMS) {
MP_WARN(demuxer, "Too many streams.\n");
return NULL;
@@ -225,33 +179,22 @@ struct sh_stream *new_sh_stream(demuxer_t *demuxer, enum stream_type type)
struct sh_stream *sh = talloc_ptrtype(demuxer, sh);
*sh = (struct sh_stream) {
.type = type,
- .demuxer = demuxer,
.index = demuxer->num_streams,
.demuxer_id = demuxer_id, // may be overwritten by demuxer
- .ds = talloc_zero(sh, struct demux_stream),
+ .ds = talloc(sh, struct demux_stream),
+ };
+ *sh->ds = (struct demux_stream) {
+ .in = demuxer->in,
+ .type = sh->type,
+ .selected = demuxer->in->autoselect,
};
MP_TARRAY_APPEND(demuxer, demuxer->streams, demuxer->num_streams, sh);
switch (sh->type) {
- case STREAM_VIDEO: {
- struct sh_video *sht = talloc_zero(demuxer, struct sh_video);
- sh->video = sht;
- break;
- }
- case STREAM_AUDIO: {
- struct sh_audio *sht = talloc_zero(demuxer, struct sh_audio);
- sh->audio = sht;
- break;
- }
- case STREAM_SUB: {
- struct sh_sub *sht = talloc_zero(demuxer, struct sh_sub);
- sh->sub = sht;
- break;
- }
- default: assert(false);
+ case STREAM_VIDEO: sh->video = talloc_zero(demuxer, struct sh_video); break;
+ case STREAM_AUDIO: sh->audio = talloc_zero(demuxer, struct sh_audio); break;
+ case STREAM_SUB: sh->sub = talloc_zero(demuxer, struct sh_sub); break;
}
- sh->ds->selected = demuxer->stream_autoselect;
-
return sh;
}
@@ -259,56 +202,83 @@ void free_demuxer(demuxer_t *demuxer)
{
if (!demuxer)
return;
+ struct demux_internal *in = demuxer->in;
+ assert(demuxer == in->d_user);
+
+ demux_stop_thread(demuxer);
+
if (demuxer->desc->close)
- demuxer->desc->close(demuxer);
- // free streams:
+ demuxer->desc->close(in->d_thread);
for (int n = 0; n < demuxer->num_streams; n++)
- ds_free_packs(demuxer->streams[n]->ds);
+ ds_flush(demuxer->streams[n]->ds);
+ pthread_mutex_destroy(&in->lock);
+ pthread_cond_destroy(&in->wakeup);
talloc_free(demuxer);
}
-const char *stream_type_name(enum stream_type type)
+// Start the demuxer thread, which reads ahead packets on its own.
+void demux_start_thread(struct demuxer *demuxer)
{
- switch (type) {
- case STREAM_VIDEO: return "video";
- case STREAM_AUDIO: return "audio";
- case STREAM_SUB: return "sub";
- default: return "unknown";
+ struct demux_internal *in = demuxer->in;
+ assert(demuxer == in->d_user);
+
+ if (!in->threading) {
+ in->threading = true;
+ if (pthread_create(&in->thread, NULL, demux_thread, in))
+ in->threading = false;
}
}
-static int count_packs(struct demuxer *demux, enum stream_type type)
+void demux_stop_thread(struct demuxer *demuxer)
{
- int c = 0;
- for (int n = 0; n < demux->num_streams; n++)
- c += demux->streams[n]->type == type ? demux->streams[n]->ds->packs : 0;
- return c;
+ struct demux_internal *in = demuxer->in;
+ assert(demuxer == in->d_user);
+
+ if (in->threading) {
+ pthread_mutex_lock(&in->lock);
+ in->thread_terminate = true;
+ pthread_cond_signal(&in->wakeup);
+ pthread_mutex_unlock(&in->lock);
+ pthread_join(in->thread, NULL);
+ in->threading = false;
+ in->thread_terminate = false;
+ }
}
-static int count_bytes(struct demuxer *demux, enum stream_type type)
+// The demuxer thread will call cb(ctx) if there's a new packet, or EOF is reached.
+void demux_set_wakeup_cb(struct demuxer *demuxer, void (*cb)(void *ctx), void *ctx)
+{
+ struct demux_internal *in = demuxer->in;
+ pthread_mutex_lock(&in->lock);
+ in->wakeup_cb = cb;
+ in->wakeup_cb_ctx = ctx;
+ pthread_mutex_unlock(&in->lock);
+}
+
+const char *stream_type_name(enum stream_type type)
{
- int c = 0;
- for (int n = 0; n < demux->num_streams; n++)
- c += demux->streams[n]->type == type ? demux->streams[n]->ds->bytes : 0;
- return c;
+ switch (type) {
+ case STREAM_VIDEO: return "video";
+ case STREAM_AUDIO: return "audio";
+ case STREAM_SUB: return "sub";
+ default: return "unknown";
+ }
}
// Returns the same value as demuxer->fill_buffer: 1 ok, 0 EOF/not selected.
-int demuxer_add_packet(demuxer_t *demuxer, struct sh_stream *stream,
- demux_packet_t *dp)
+int demux_add_packet(struct sh_stream *stream, demux_packet_t *dp)
{
struct demux_stream *ds = stream ? stream->ds : NULL;
- if (!dp || !ds || !ds->selected) {
+ if (!dp || !ds) {
talloc_free(dp);
return 0;
}
-
- if (stream->type == STREAM_VIDEO && !dp->len) {
- /* Video packets with size 0 are assumed to not correspond to frames,
- * but to indicate the absence of a frame in formats like AVI
- * that must have packets at fixed timestamp intervals. */
+ struct demux_internal *in = ds->in;
+ pthread_mutex_lock(&in->lock);
+ if (!ds->selected || in->seeking) {
+ pthread_mutex_unlock(&in->lock);
talloc_free(dp);
- return 1;
+ return 0;
}
dp->stream = stream->index;
@@ -324,82 +294,192 @@ int demuxer_add_packet(demuxer_t *demuxer, struct sh_stream *stream,
// first packet in stream
ds->head = ds->tail = dp;
}
- /* ds_get_packets() can set ds->eof to 1 when another stream runs out of
- * buffer space. That makes sense because in that situation the calling
- * code should not count on being able to demux more packets from this
- * stream. (Can happen with e.g. badly interleaved files.)
- * In this case, we didn't necessarily reach EOF, and new packet can
- * appear. */
- ds->eof = 0;
-
- if (dp->pos >= 0)
- demuxer->filepos = dp->pos;
+ // obviously not true anymore
+ ds->eof = false;
+ in->last_eof = in->eof = false;
// For video, PTS determination is not trivial, but for other media types
// distinguishing PTS and DTS is not useful.
if (stream->type != STREAM_VIDEO && dp->pts == MP_NOPTS_VALUE)
dp->pts = dp->dts;
- MP_DBG(demuxer, "DEMUX: Append packet to %s, len=%d pts=%5.3f pos=%"PRIi64" "
- "[packs: A=%d V=%d S=%d]\n", stream_type_name(stream->type),
- dp->len, dp->pts, dp->pos, count_packs(demuxer, STREAM_AUDIO),
- count_packs(demuxer, STREAM_VIDEO), count_packs(demuxer, STREAM_SUB));
+ MP_DBG(in, "append packet to %s: size=%d pts=%f dts=%f pos=%"PRIi64" "
+ "[num=%zd size=%zd]\n", stream_type_name(stream->type),
+ dp->len, dp->pts, dp->dts, dp->pos, ds->packs, ds->bytes);
+
+ if (ds->in->wakeup_cb)
+ ds->in->wakeup_cb(ds->in->wakeup_cb_ctx);
+ pthread_cond_signal(&in->wakeup);
+ pthread_mutex_unlock(&in->lock);
return 1;
}
-static bool demux_check_queue_full(demuxer_t *demux)
+// Returns true if there was "progress" (lock was released temporarily).
+static bool read_packet(struct demux_internal *in)
{
- for (int n = 0; n < demux->num_streams; n++) {
- struct sh_stream *sh = demux->streams[n];
- if (sh->ds->packs > MAX_PACKS || sh->ds->bytes > MAX_PACK_BYTES)
- goto overflow;
+ in->eof = false;
+
+ // Check if we need to read a new packet. We do this if all queues are below
+ // the minimum, or if a stream explicitly needs new packets. Also includes
+ // safe-guards against packet queue overflow.
+ bool active = false, read_more = false;
+ size_t packs = 0, bytes = 0;
+ for (int n = 0; n < in->d_buffer->num_streams; n++) {
+ struct demux_stream *ds = in->d_buffer->streams[n]->ds;
+ active |= ds->selected && ds->active;
+ read_more |= ds->active && !ds->head;
+ packs += ds->packs;
+ bytes += ds->bytes;
+ }
+ MP_DBG(in, "packets=%zd, bytes=%zd, active=%d, more=%d\n",
+ packs, bytes, active, read_more);
+ if (packs >= MAX_PACKS || bytes >= MAX_PACK_BYTES) {
+ if (!in->warned_queue_overflow) {
+ in->warned_queue_overflow = true;
+ MP_ERR(in, "Too many packets in the demuxer packet queues:\n");
+ for (int n = 0; n < in->d_buffer->num_streams; n++) {
+ struct demux_stream *ds = in->d_buffer->streams[n]->ds;
+ if (ds->selected) {
+ MP_ERR(in, " %s/%d: %zd packets, %zd bytes\n",
+ stream_type_name(ds->type), n, ds->packs, ds->bytes);
+ }
+ }
+ }
+ for (int n = 0; n < in->d_buffer->num_streams; n++) {
+ struct demux_stream *ds = in->d_buffer->streams[n]->ds;
+ ds->eof |= !ds->head;
+ }
+ pthread_cond_signal(&in->wakeup);
+ return false;
}
- return false;
-
-overflow:
-
- if (!demux->warned_queue_overflow) {
- MP_ERR(demux, "Too many packets in the demuxer "
- "packet queue (video: %d packets in %d bytes, audio: %d "
- "packets in %d bytes, sub: %d packets in %d bytes).\n",
- count_packs(demux, STREAM_VIDEO), count_bytes(demux, STREAM_VIDEO),
- count_packs(demux, STREAM_AUDIO), count_bytes(demux, STREAM_AUDIO),
- count_packs(demux, STREAM_SUB), count_bytes(demux, STREAM_SUB));
- MP_INFO(demux, "Maybe you are playing a non-"
- "interleaved stream/file or the codec failed?\n");
+ if (packs < in->min_packs && bytes < in->min_bytes)
+ read_more |= active;
+
+ if (!read_more)
+ return false;
+
+ // Actually read a packet. Drop the lock while doing so, because waiting
+ // for disk or network I/O can take time.
+ pthread_mutex_unlock(&in->lock);
+ struct demuxer *demux = in->d_thread;
+ bool eof = !demux->desc->fill_buffer || demux->desc->fill_buffer(demux) <= 0;
+ pthread_mutex_lock(&in->lock);
+
+ update_cache(in);
+
+ if (eof) {
+ for (int n = 0; n < in->d_buffer->num_streams; n++) {
+ struct demux_stream *ds = in->d_buffer->streams[n]->ds;
+ ds->eof = true;
+ ds->active = false;
+ }
+ // If we had EOF previously, then don't wakeup (avoids wakeup loop)
+ if (!in->last_eof) {
+ if (in->wakeup_cb)
+ in->wakeup_cb(in->wakeup_cb_ctx);
+ pthread_cond_signal(&in->wakeup);
+ MP_VERBOSE(in, "EOF reached.\n");
+ }
}
- demux->warned_queue_overflow = true;
+ in->eof = in->last_eof = eof;
return true;
}
-// return value:
-// 0 = EOF or no stream found or invalid type
-// 1 = successfully read a packet
+// must be called locked; may temporarily unlock
+static void ds_get_packets(struct demux_stream *ds)
+{
+ const char *t = stream_type_name(ds->type);
+ struct demux_internal *in = ds->in;
+ MP_DBG(in, "reading packet for %s\n", t);
+ in->eof = false; // force retry
+ ds->eof = false;
+ while (ds->selected && !ds->head && !ds->eof) {
+ ds->active = true;
+ // Note: the following code marks EOF if it can't continue
+ if (in->threading) {
+ MP_VERBOSE(in, "waiting for demux thread (%s)\n", t);
+ pthread_cond_signal(&in->wakeup);
+ pthread_cond_wait(&in->wakeup, &in->lock);
+ } else {
+ read_packet(in);
+ }
+ }
+}
-static int demux_fill_buffer(demuxer_t *demux)
+static void execute_trackswitch(struct demux_internal *in)
{
- return demux->desc->fill_buffer ? demux->desc->fill_buffer(demux) : 0;
+ in->tracks_switched = false;
+
+ pthread_mutex_unlock(&in->lock);
+
+ if (in->d_thread->desc->control)
+ in->d_thread->desc->control(in->d_thread, DEMUXER_CTRL_SWITCHED_TRACKS, 0);
+
+ pthread_mutex_lock(&in->lock);
}
-static void ds_get_packets(struct sh_stream *sh)
+static void execute_seek(struct demux_internal *in)
{
- struct demux_stream *ds = sh->ds;
- demuxer_t *demux = sh->demuxer;
- MP_TRACE(demux, "ds_get_packets (%s) called\n",
- stream_type_name(sh->type));
- while (1) {
- if (ds->head)
- return;
-
- if (demux_check_queue_full(demux))
- break;
+ int flags = in->seek_flags;
+ double pts = in->seek_pts;
+ in->seeking = false;
+
+ pthread_mutex_unlock(&in->lock);
+
+ if (in->d_thread->desc->seek)
+ in->d_thread->desc->seek(in->d_thread, pts, flags);
- if (!demux_fill_buffer(demux))
- break; // EOF
+ pthread_mutex_lock(&in->lock);
+}
+
+static void *demux_thread(void *pctx)
+{
+ struct demux_internal *in = pctx;
+ pthread_mutex_lock(&in->lock);
+ while (!in->thread_terminate) {
+ in->thread_paused = in->thread_request_pause > 0;
+ if (in->thread_paused) {
+ pthread_cond_signal(&in->wakeup);
+ pthread_cond_wait(&in->wakeup, &in->lock);
+ continue;
+ }
+ if (in->tracks_switched) {
+ execute_trackswitch(in);
+ continue;
+ }
+ if (in->seeking) {
+ execute_seek(in);
+ continue;
+ }
+ if (!in->eof) {
+ if (read_packet(in))
+ continue; // read_packet unlocked, so recheck conditions
+ }
+ update_cache(in);
+ pthread_cond_signal(&in->wakeup);
+ pthread_cond_wait(&in->wakeup, &in->lock);
}
- MP_VERBOSE(demux, "ds_get_packets: EOF reached (stream: %s)\n",
- stream_type_name(sh->type));
- ds->eof = 1;
+ pthread_mutex_unlock(&in->lock);
+ return NULL;
+}
+
+static struct demux_packet *dequeue_packet(struct demux_stream *ds)
+{
+ if (!ds->head)
+ return NULL;
+ struct demux_packet *pkt = ds->head;
+ ds->head = pkt->next;
+ pkt->next = NULL;
+ if (!ds->head)
+ ds->tail = NULL;
+ ds->bytes -= pkt->len;
+ ds->packs--;
+
+ // This implies this function is actually called from "the" user thread.
+ if (pkt && pkt->pos >= 0)
+ ds->in->d_user->filepos = pkt->pos;
+
+ return pkt;
}
// Read a packet from the given stream. The returned packet belongs to the
@@ -408,24 +488,46 @@ static void ds_get_packets(struct sh_stream *sh)
struct demux_packet *demux_read_packet(struct sh_stream *sh)
{
struct demux_stream *ds = sh ? sh->ds : NULL;
+ struct demux_packet *pkt = NULL;
+ if (ds) {
+ pthread_mutex_lock(&ds->in->lock);
+ ds_get_packets(ds);
+ pkt = dequeue_packet(ds);
+ pthread_cond_signal(&ds->in->wakeup); // possibly read more
+ pthread_mutex_unlock(&ds->in->lock);
+ }
+ return pkt;
+}
+
+// Poll the demuxer queue, and if there's a packet, return it. Otherwise, just
+// make the demuxer thread read packets for this stream, and if there's at
+// least one packet, call the wakeup callback.
+// Unlike demux_read_packet(), this always enables readahead (which means you
+// must not use it on interleaved subtitle streams).
+// Returns:
+// < 0: EOF was reached, *out_pkt=NULL
+// == 0: no new packet yet, but maybe later, *out_pkt=NULL
+// > 0: new packet read, *out_pkt is set
+int demux_read_packet_async(struct sh_stream *sh, struct demux_packet **out_pkt)
+{
+ struct demux_stream *ds = sh ? sh->ds : NULL;
+ int r = -1;
+ *out_pkt = NULL;
if (ds) {
- ds_get_packets(sh);
- struct demux_packet *pkt = ds->head;
- if (pkt) {
- ds->head = pkt->next;
- pkt->next = NULL;
- if (!ds->head)
- ds->tail = NULL;
- ds->bytes -= pkt->len;
- ds->packs--;
-
- if (pkt->stream_pts != MP_NOPTS_VALUE)
- sh->demuxer->stream_pts = pkt->stream_pts;
-
- return pkt;
+ if (ds->in->threading) {
+ pthread_mutex_lock(&ds->in->lock);
+ *out_pkt = dequeue_packet(ds);
+ r = *out_pkt ? 1 : (ds->eof ? -1 : 0);
+ ds->active = ds->selected; // enable readahead
+ ds->in->eof = false; // force retry
+ pthread_cond_signal(&ds->in->wakeup); // possibly read more
+ pthread_mutex_unlock(&ds->in->lock);
+ } else {
+ *out_pkt = demux_read_packet(sh);
+ r = *out_pkt ? 1 : -1;
}
}
- return NULL;
+ return r;
}
// Return the pts of the next packet that demux_read_packet() would return.
@@ -433,31 +535,61 @@ struct demux_packet *demux_read_packet(struct sh_stream *sh)
// packets from the queue.
double demux_get_next_pts(struct sh_stream *sh)
{
- if (sh && sh->ds->selected) {
- ds_get_packets(sh);
+ double res = MP_NOPTS_VALUE;
+ if (sh) {
+ pthread_mutex_lock(&sh->ds->in->lock);
+ ds_get_packets(sh->ds);
if (sh->ds->head)
- return sh->ds->head->pts;
+ res = sh->ds->head->pts;
+ pthread_mutex_unlock(&sh->ds->in->lock);
}
- return MP_NOPTS_VALUE;
+ return res;
}
// Return whether a packet is queued. Never blocks, never forces any reads.
bool demux_has_packet(struct sh_stream *sh)
{
- return sh && sh->ds->head;
+ bool has_packet = false;
+ if (sh) {
+ pthread_mutex_lock(&sh->ds->in->lock);
+ has_packet = sh->ds->head;
+ pthread_mutex_unlock(&sh->ds->in->lock);
+ }
+ return has_packet;
}
-// Same as demux_has_packet, but to be called internally by demuxers, as
-// opposed to the user of the demuxer.
-bool demuxer_stream_has_packets_queued(struct demuxer *d, struct sh_stream *stream)
+// Return whether EOF was returned with an earlier packet read.
+bool demux_stream_eof(struct sh_stream *sh)
{
- return demux_has_packet(stream);
+ bool eof = false;
+ if (sh) {
+ pthread_mutex_lock(&sh->ds->in->lock);
+ eof = sh->ds->eof && !sh->ds->head;
+ pthread_mutex_unlock(&sh->ds->in->lock);
+ }
+ return eof;
}
-// Return whether EOF was returned with an earlier packet read.
-bool demux_stream_eof(struct sh_stream *sh)
+// Read and return any packet we find.
+struct demux_packet *demux_read_any_packet(struct demuxer *demuxer)
{
- return !sh || sh->ds->eof;
+ assert(!demuxer->in->threading); // doesn't work with threading
+ bool read_more = true;
+ while (read_more) {
+ for (int n = 0; n < demuxer->num_streams; n++) {
+ struct sh_stream *sh = demuxer->streams[n];
+ sh->ds->active = sh->ds->selected; // force read_packet() to read
+ struct demux_packet *pkt = dequeue_packet(sh->ds);
+ if (pkt)
+ return pkt;
+ }
+ // retry after calling this
+ pthread_mutex_lock(&demuxer->in->lock);
+ read_more = read_packet(demuxer->in);
+ read_more &= !demuxer->in->eof;
+ pthread_mutex_unlock(&demuxer->in->lock);
+ }
+ return NULL;
}
// ====================================================================
@@ -543,8 +675,7 @@ static void demux_export_replaygain(demuxer_t *demuxer)
{
float tg, tp, ag, ap;
- if (!demuxer->replaygain_data &&
- !decode_gain(demuxer, "REPLAYGAIN_TRACK_GAIN", &tg) &&
+ if (!decode_gain(demuxer, "REPLAYGAIN_TRACK_GAIN", &tg) &&
!decode_peak(demuxer, "REPLAYGAIN_TRACK_PEAK", &tp) &&
!decode_gain(demuxer, "REPLAYGAIN_ALBUM_GAIN", &ag) &&
!decode_peak(demuxer, "REPLAYGAIN_ALBUM_PEAK", &ap))
@@ -556,8 +687,88 @@ static void demux_export_replaygain(demuxer_t *demuxer)
rgain->album_gain = ag;
rgain->album_peak = ap;
- demuxer->replaygain_data = rgain;
+ for (int n = 0; n < demuxer->num_streams; n++) {
+ struct sh_stream *sh = demuxer->streams[n];
+ if (sh->audio && !sh->audio->replaygain_data)
+ sh->audio->replaygain_data = rgain;
+ }
+ }
+}
+
+// Copy all fields from src to dst, depending on event flags.
+static void demux_copy(struct demuxer *dst, struct demuxer *src)
+{
+ if (src->events & DEMUX_EVENT_INIT) {
+ // Note that we do as shallow copies as possible. We expect the date
+ // that is not-copied (only referenced) to be immutable.
+ // This implies e.g. that no chapters are added after initialization.
+ dst->chapters = src->chapters;
+ dst->num_chapters = src->num_chapters;
+ dst->editions = src->editions;
+ dst->num_editions = src->num_editions;
+ dst->edition = src->edition;
+ dst->attachments = src->attachments;
+ dst->num_attachments = src->num_attachments;
+ dst->matroska_data = src->matroska_data;
+ dst->file_contents = src->file_contents;
+ dst->playlist = src->playlist;
+ dst->seekable = src->seekable;
+ dst->filetype = src->filetype;
+ dst->ts_resets_possible = src->ts_resets_possible;
+ dst->start_time = src->start_time;
}
+ if (src->events & DEMUX_EVENT_STREAMS) {
+ // The stream structs themselves are immutable.
+ for (int n = dst->num_streams; n < src->num_streams; n++)
+ MP_TARRAY_APPEND(dst, dst->streams, dst->num_streams, src->streams[n]);
+ }
+ if (src->events & DEMUX_EVENT_METADATA) {
+ talloc_free(dst->metadata);
+ dst->metadata = mp_tags_dup(dst, src->metadata);
+ }
+ dst->events |= src->events;
+ src->events = 0;
+}
+
+// This is called by demuxer implementations if certain parameters change
+// at runtime.
+// events is one of DEMUX_EVENT_*
+// The code will copy the fields references by the events to the user-thread.
+void demux_changed(demuxer_t *demuxer, int events)
+{
+ assert(demuxer == demuxer->in->d_thread); // call from demuxer impl. only
+ struct demux_internal *in = demuxer->in;
+
+ demuxer->events |= events;
+
+ pthread_mutex_lock(&in->lock);
+
+ update_cache(in);
+
+ if (demuxer->events & DEMUX_EVENT_INIT)
+ demuxer_sort_chapters(demuxer);
+ if (demuxer->events & (DEMUX_EVENT_METADATA | DEMUX_EVENT_STREAMS))
+ demux_export_replaygain(demuxer);
+
+ demux_copy(in->d_buffer, demuxer);
+
+ pthread_mutex_unlock(&in->lock);
+}
+
+// Called by the user thread (i.e. player) to update metadata and other things
+// from the demuxer thread.
+void demux_update(demuxer_t *demuxer)
+{
+ assert(demuxer == demuxer->in->d_user);
+ struct demux_internal *in = demuxer->in;
+
+ pthread_mutex_lock(&in->lock);
+ if (!in->threading)
+ update_cache(in);
+ demux_copy(demuxer, in->d_buffer);
+ if (in->stream_metadata && (demuxer->events & DEMUX_EVENT_METADATA))
+ mp_tags_merge(demuxer->metadata, in->stream_metadata);
+ pthread_mutex_unlock(&in->lock);
}
static struct demuxer *open_given_type(struct mpv_global *global,
@@ -572,54 +783,62 @@ static struct demuxer *open_given_type(struct mpv_global *global,
.desc = desc,
.type = desc->type,
.stream = stream,
- .stream_pts = MP_NOPTS_VALUE,
.seekable = stream->seekable,
- .accurate_seek = true,
.filepos = -1,
.opts = global->opts,
.global = global,
.log = mp_log_new(demuxer, log, desc->name),
.glog = log,
.filename = talloc_strdup(demuxer, stream->url),
- .metadata = talloc_zero(demuxer, struct mp_tags),
+ .events = DEMUX_EVENT_ALL,
};
demuxer->seekable = stream->seekable;
if (demuxer->stream->uncached_stream &&
!demuxer->stream->uncached_stream->seekable)
demuxer->seekable = false;
- demuxer->params = params; // temporary during open()
+ struct demux_internal *in = demuxer->in = talloc_ptrtype(demuxer, in);
+ *in = (struct demux_internal){
+ .log = demuxer->log,
+ .d_thread = talloc(demuxer, struct demuxer),
+ .d_buffer = talloc(demuxer, struct demuxer),
+ .d_user = demuxer,
+ .min_packs = demuxer->opts->demuxer_min_packs,
+ .min_bytes = demuxer->opts->demuxer_min_bytes,
+ };
+ pthread_mutex_init(&in->lock, NULL);
+ pthread_cond_init(&in->wakeup, NULL);
+
+ *in->d_thread = *demuxer;
+ *in->d_buffer = *demuxer;
+
+ in->d_thread->metadata = talloc_zero(in->d_thread, struct mp_tags);
+ in->d_user->metadata = talloc_zero(in->d_user, struct mp_tags);
+ in->d_buffer->metadata = talloc_zero(in->d_buffer, struct mp_tags);
+
int64_t start_pos = stream_tell(stream);
mp_verbose(log, "Trying demuxer: %s (force-level: %s)\n",
desc->name, d_level(check));
- int ret = demuxer->desc->open(demuxer, check);
+ in->d_thread->params = params; // temporary during open()
+
+ int ret = demuxer->desc->open(in->d_thread, check);
if (ret >= 0) {
- demuxer->params = NULL;
- if (demuxer->filetype)
+ in->d_thread->params = NULL;
+ if (in->d_thread->filetype)
mp_verbose(log, "Detected file format: %s (%s)\n",
- demuxer->filetype, desc->desc);
+ in->d_thread->filetype, desc->desc);
else
mp_verbose(log, "Detected file format: %s\n", desc->desc);
- if (stream_manages_timeline(demuxer->stream)) {
- // Incorrect, but fixes some behavior with DVD/BD
- demuxer->ts_resets_possible = false;
- // Doesn't work, because stream_pts is a "guess".
- demuxer->accurate_seek = false;
- // Can be seekable even if the stream isn't.
- demuxer->seekable = true;
- }
- add_stream_chapters(demuxer);
- demuxer_sort_chapters(demuxer);
- demux_info_update(demuxer);
- demux_export_replaygain(demuxer);
// Pretend we can seek if we can't seek, but there's a cache.
- if (!demuxer->seekable && stream->uncached_stream) {
+ if (!in->d_thread->seekable && stream->uncached_stream) {
mp_warn(log,
"File is not seekable, but there's a cache: enabling seeking.\n");
- demuxer->seekable = true;
+ in->d_thread->seekable = true;
}
+ demux_changed(in->d_thread, DEMUX_EVENT_ALL);
+ demux_update(demuxer);
return demuxer;
}
@@ -685,15 +904,28 @@ done:
return demuxer;
}
-void demux_flush(demuxer_t *demuxer)
+static void flush_locked(demuxer_t *demuxer)
{
for (int n = 0; n < demuxer->num_streams; n++)
- ds_free_packs(demuxer->streams[n]->ds);
- demuxer->warned_queue_overflow = false;
+ ds_flush(demuxer->streams[n]->ds);
+ demuxer->in->warned_queue_overflow = false;
+ demuxer->in->eof = false;
+ demuxer->in->last_eof = false;
+}
+
+// clear the packet queues
+void demux_flush(demuxer_t *demuxer)
+{
+ pthread_mutex_lock(&demuxer->in->lock);
+ flush_locked(demuxer);
+ pthread_mutex_unlock(&demuxer->in->lock);
}
int demux_seek(demuxer_t *demuxer, float rel_seek_secs, int flags)
{
+ struct demux_internal *in = demuxer->in;
+ assert(demuxer == in->d_user);
+
if (!demuxer->seekable) {
MP_WARN(demuxer, "Cannot seek in this file.\n");
return 0;
@@ -702,107 +934,27 @@ int demux_seek(demuxer_t *demuxer, float rel_seek_secs, int flags)
if (rel_seek_secs == MP_NOPTS_VALUE && (flags & SEEK_ABSOLUTE))
return 0;
- // clear demux buffers:
- demux_flush(demuxer);
+ pthread_mutex_lock(&in->lock);
- /* Note: this is for DVD and BD playback. The stream layer has to do these
- * seeks, and the demuxer has to react to DEMUXER_CTRL_RESYNC in order to
- * deal with the suddenly changing stream position.
- */
- struct stream *stream = demuxer->stream;
- if (stream_manages_timeline(stream)) {
- double pts;
-
- if (flags & SEEK_ABSOLUTE)
- pts = 0.0f;
- else {
- if (demuxer->stream_pts == MP_NOPTS_VALUE)
- goto dmx_seek;
- pts = demuxer->stream_pts;
- }
+ flush_locked(demuxer);
+ in->seeking = true;
+ in->seek_flags = flags;
+ in->seek_pts = rel_seek_secs;
- if (flags & SEEK_FACTOR) {
- double tmp = 0;
- if (stream_control(demuxer->stream, STREAM_CTRL_GET_TIME_LENGTH,
- &tmp) == STREAM_UNSUPPORTED)
- goto dmx_seek;
- pts += tmp * rel_seek_secs;
- } else
- pts += rel_seek_secs;
-
- if (stream_control(demuxer->stream, STREAM_CTRL_SEEK_TO_TIME, &pts)
- != STREAM_UNSUPPORTED) {
- demux_control(demuxer, DEMUXER_CTRL_RESYNC, NULL);
- return 1;
- }
- }
+ if (!in->threading)
+ execute_seek(in);
- dmx_seek:
- if (demuxer->desc->seek)
- demuxer->desc->seek(demuxer, rel_seek_secs, flags);
+ pthread_cond_signal(&in->wakeup);
+ pthread_mutex_unlock(&in->lock);
return 1;
}
-static int demux_info_print(demuxer_t *demuxer)
-{
- struct mp_tags *info = demuxer->metadata;
- int n;
-
- if (!info || !info->num_keys)
- return 0;
-
- mp_info(demuxer->glog, "File tags:\n");
- for (n = 0; n < info->num_keys; n++) {
- mp_info(demuxer->glog, " %s: %s\n", info->keys[n], info->values[n]);
- }
-
- return 0;
-}
-
char *demux_info_get(demuxer_t *demuxer, const char *opt)
{
return mp_tags_get_str(demuxer->metadata, opt);
}
-bool demux_info_update(struct demuxer *demuxer)
-{
- struct mp_tags *tags = demuxer->metadata;
- // Take care of stream metadata as well
- char **meta;
- if (stream_control(demuxer->stream, STREAM_CTRL_GET_METADATA, &meta) > 0) {
- for (int n = 0; meta[n + 0]; n += 2)
- mp_tags_set_str(tags, meta[n + 0], meta[n + 1]);
- talloc_free(meta);
- }
- // Check for metadata changes the hard way.
- char *data = talloc_strdup(demuxer, "");
- for (int n = 0; n < tags->num_keys; n++) {
- data = talloc_asprintf_append_buffer(data, "%s=%s\n", tags->keys[n],
- tags->values[n]);
- }
- if (!demuxer->previous_metadata ||
- strcmp(demuxer->previous_metadata, data) != 0)
- {
- talloc_free(demuxer->previous_metadata);
- demuxer->previous_metadata = data;
- demux_info_print(demuxer);
- return true;
- } else {
- talloc_free(data);
- return false;
- }
-}
-
-int demux_control(demuxer_t *demuxer, int cmd, void *arg)
-{
-
- if (demuxer->desc->control)
- return demuxer->desc->control(demuxer, cmd, arg);
-
- return DEMUXER_CTRL_NOTIMPL;
-}
-
struct sh_stream *demuxer_stream_by_demuxer_id(struct demuxer *d,
enum stream_type t, int id)
{
@@ -830,21 +982,34 @@ void demuxer_select_track(struct demuxer *demuxer, struct sh_stream *stream,
bool selected)
{
// don't flush buffers if stream is already selected / unselected
+ pthread_mutex_lock(&demuxer->in->lock);
+ bool update = false;
if (stream->ds->selected != selected) {
stream->ds->selected = selected;
- ds_free_packs(stream->ds);
- demux_control(demuxer, DEMUXER_CTRL_SWITCHED_TRACKS, NULL);
+ stream->ds->active = false;
+ ds_flush(stream->ds);
+ update = true;
}
+ pthread_mutex_unlock(&demuxer->in->lock);
+ if (update)
+ demux_control(demuxer, DEMUXER_CTRL_SWITCHED_TRACKS, NULL);
}
-void demuxer_enable_autoselect(struct demuxer *demuxer)
+void demux_set_stream_autoselect(struct demuxer *demuxer, bool autoselect)
{
- demuxer->stream_autoselect = true;
+ assert(!demuxer->in->threading); // laziness
+ demuxer->in->autoselect = autoselect;
}
-bool demuxer_stream_is_selected(struct demuxer *d, struct sh_stream *stream)
+bool demux_stream_is_selected(struct sh_stream *stream)
{
- return stream && stream->ds->selected;
+ if (!stream)
+ return false;
+ bool r = false;
+ pthread_mutex_lock(&stream->ds->in->lock);
+ r = stream->ds->selected;
+ pthread_mutex_unlock(&stream->ds->in->lock);
+ return r;
}
int demuxer_add_attachment(demuxer_t *demuxer, struct bstr name,
@@ -878,7 +1043,7 @@ static int chapter_compare(const void *p1, const void *p2)
return c1->original_index > c2->original_index ? 1 :-1; // never equal
}
-void demuxer_sort_chapters(demuxer_t *demuxer)
+static void demuxer_sort_chapters(demuxer_t *demuxer)
{
qsort(demuxer->chapters, demuxer->num_chapters,
sizeof(struct demux_chapter), chapter_compare);
@@ -900,145 +1065,168 @@ int demuxer_add_chapter(demuxer_t *demuxer, struct bstr name,
return demuxer->num_chapters - 1;
}
-static void add_stream_chapters(struct demuxer *demuxer)
-{
- if (demuxer->num_chapters)
- return;
- int num_chapters = 0;
- if (stream_control(demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS,
- &num_chapters) != STREAM_OK)
- return;
- for (int n = 0; n < num_chapters; n++) {
- double p = n;
- if (stream_control(demuxer->stream, STREAM_CTRL_GET_CHAPTER_TIME, &p)
- != STREAM_OK)
- return;
- demuxer_add_chapter(demuxer, bstr0(""), p * 1e9, 0, 0);
- }
-}
-
double demuxer_get_time_length(struct demuxer *demuxer)
{
double len;
- if (stream_control(demuxer->stream, STREAM_CTRL_GET_TIME_LENGTH, &len) > 0)
- return len;
- // <= 0 means DEMUXER_CTRL_NOTIMPL or DEMUXER_CTRL_DONTKNOW
if (demux_control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH, &len) > 0)
return len;
return -1;
}
-double demuxer_get_start_time(struct demuxer *demuxer)
+// must be called locked
+static void update_cache(struct demux_internal *in)
{
- double time;
- if (stream_control(demuxer->stream, STREAM_CTRL_GET_START_TIME, &time) > 0)
- return time;
- if (demux_control(demuxer, DEMUXER_CTRL_GET_START_TIME, &time) > 0)
- return time;
- return 0;
-}
+ struct demuxer *demuxer = in->d_thread;
+ struct stream *stream = demuxer->stream;
-int demuxer_angles_count(demuxer_t *demuxer)
-{
- int ris, angles = -1;
+ in->time_length = -1;
+ if (demuxer->desc->control) {
+ demuxer->desc->control(demuxer, DEMUXER_CTRL_GET_TIME_LENGTH,
+ &in->time_length);
+ }
- ris = stream_control(demuxer->stream, STREAM_CTRL_GET_NUM_ANGLES, &angles);
- if (ris == STREAM_UNSUPPORTED)
- return -1;
- return angles;
+ struct mp_tags *s_meta = NULL;
+ stream_control(stream, STREAM_CTRL_GET_METADATA, &s_meta);
+ if (s_meta) {
+ talloc_free(in->stream_metadata);
+ in->stream_metadata = talloc_steal(in, s_meta);
+ in->d_buffer->events |= DEMUX_EVENT_METADATA;
+ }
+
+ in->stream_size = -1;
+ stream_control(stream, STREAM_CTRL_GET_SIZE, &in->stream_size);
+ in->stream_cache_size = -1;
+ stream_control(stream, STREAM_CTRL_GET_CACHE_SIZE, &in->stream_cache_size);
+ in->stream_cache_fill = -1;
+ stream_control(stream, STREAM_CTRL_GET_CACHE_FILL, &in->stream_cache_fill);
+ in->stream_cache_idle = -1;
+ stream_control(stream, STREAM_CTRL_GET_CACHE_IDLE, &in->stream_cache_idle);
}
-int demuxer_get_current_angle(demuxer_t *demuxer)
+// must be called locked
+static int cached_stream_control(struct demux_internal *in, int cmd, void *arg)
{
- int ris, curr_angle = -1;
- ris = stream_control(demuxer->stream, STREAM_CTRL_GET_ANGLE, &curr_angle);
- if (ris == STREAM_UNSUPPORTED)
- return -1;
- return curr_angle;
+ switch (cmd) {
+ case STREAM_CTRL_GET_CACHE_SIZE:
+ if (in->stream_cache_size < 0)
+ return STREAM_UNSUPPORTED;
+ *(int64_t *)arg = in->stream_cache_size;
+ return STREAM_OK;
+ case STREAM_CTRL_GET_CACHE_FILL:
+ if (in->stream_cache_fill < 0)
+ return STREAM_UNSUPPORTED;
+ *(int64_t *)arg = in->stream_cache_fill;
+ return STREAM_OK;
+ case STREAM_CTRL_GET_CACHE_IDLE:
+ if (in->stream_cache_idle < 0)
+ return STREAM_UNSUPPORTED;
+ *(int *)arg = in->stream_cache_idle;
+ return STREAM_OK;
+ case STREAM_CTRL_GET_SIZE:
+ if (in->stream_size < 0)
+ return STREAM_UNSUPPORTED;
+ *(int64_t *)arg = in->stream_size;
+ return STREAM_OK;
+ }
+ return STREAM_ERROR;
}
-
-int demuxer_set_angle(demuxer_t *demuxer, int angle)
+// must be called locked
+static int cached_demux_control(struct demux_internal *in, int cmd, void *arg)
{
- int ris, angles = -1;
-
- angles = demuxer_angles_count(demuxer);
- if ((angles < 1) || (angle > angles))
- return -1;
-
- demux_flush(demuxer);
-
- ris = stream_control(demuxer->stream, STREAM_CTRL_SET_ANGLE, &angle);
- if (ris == STREAM_UNSUPPORTED)
- return -1;
-
- demux_control(demuxer, DEMUXER_CTRL_RESYNC, NULL);
-
- return angle;
+ switch (cmd) {
+ case DEMUXER_CTRL_GET_TIME_LENGTH:
+ if (in->time_length < 0)
+ return DEMUXER_CTRL_NOTIMPL;
+ *(double *)arg = in->time_length;
+ return DEMUXER_CTRL_OK;
+ case DEMUXER_CTRL_STREAM_CTRL: {
+ struct demux_ctrl_stream_ctrl *c = arg;
+ int r = cached_stream_control(in, c->ctrl, c->arg);
+ if (r == STREAM_ERROR)
+ break;
+ c->res = r;
+ return DEMUXER_CTRL_OK;
+ }
+ case DEMUXER_CTRL_SWITCHED_TRACKS:
+ in->tracks_switched = true;
+ return DEMUXER_CTRL_OK;
+ }
+ return DEMUXER_CTRL_DONTKNOW;
}
-static int packet_sort_compare(const void *p1, const void *p2)
+int demux_control(demuxer_t *demuxer, int cmd, void *arg)
{
- struct demux_packet *c1 = *(struct demux_packet **)p1;
- struct demux_packet *c2 = *(struct demux_packet **)p2;
+ struct demux_internal *in = demuxer->in;
+
+ if (in->threading) {
+ pthread_mutex_lock(&in->lock);
+ pthread_cond_signal(&in->wakeup);
+ int cr = cached_demux_control(in, cmd, arg);
+ pthread_mutex_unlock(&in->lock);
+ if (cr != DEMUXER_CTRL_DONTKNOW)
+ return cr;
+ }
- if (c1->pts > c2->pts)
- return 1;
- else if (c1->pts < c2->pts)
- return -1;
- return 0;
+ int r = DEMUXER_CTRL_NOTIMPL;
+ demux_pause(demuxer);
+ if (cmd == DEMUXER_CTRL_STREAM_CTRL) {
+ struct demux_ctrl_stream_ctrl *c = arg;
+ if (in->threading)
+ MP_VERBOSE(demuxer, "blocking for STREAM_CTRL %d\n", c->ctrl);
+ c->res = stream_control(demuxer->stream, c->ctrl, c->arg);
+ if (c->res != STREAM_UNSUPPORTED)
+ r = DEMUXER_CTRL_OK;
+ }
+ if (r != DEMUXER_CTRL_OK) {
+ if (in->threading)
+ MP_VERBOSE(demuxer, "blocking for DEMUXER_CTRL %d\n", cmd);
+ if (demuxer->desc->control)
+ r = demuxer->desc->control(demuxer->in->d_thread, cmd, arg);
+ }
+ demux_unpause(demuxer);
+ return r;
}
-void demux_packet_list_sort(struct demux_packet **pkts, int num_pkts)
+int demux_stream_control(demuxer_t *demuxer, int ctrl, void *arg)
{
- qsort(pkts, num_pkts, sizeof(struct demux_packet *), packet_sort_compare);
+ struct demux_ctrl_stream_ctrl c = {ctrl, arg, STREAM_UNSUPPORTED};
+ demux_control(demuxer, DEMUXER_CTRL_STREAM_CTRL, &c);
+ return c.res;
}
-void demux_packet_list_seek(struct demux_packet **pkts, int num_pkts,
- int *current, float rel_seek_secs, int flags)
+// Make the demuxer thread stop doing anything.
+// demux_unpause() wakes up the thread again.
+// Can be nested with other calls, but trying to read packets may deadlock.
+void demux_pause(demuxer_t *demuxer)
{
- double ref_time = 0;
- if (*current >= 0 && *current < num_pkts) {
- ref_time = pkts[*current]->pts;
- } else if (*current == num_pkts && num_pkts > 0) {
- ref_time = pkts[num_pkts - 1]->pts + pkts[num_pkts - 1]->duration;
- }
+ struct demux_internal *in = demuxer->in;
+ assert(demuxer == in->d_user);
- if (flags & SEEK_ABSOLUTE)
- ref_time = 0;
+ if (!in->threading)
+ return;
- if (flags & SEEK_FACTOR) {
- ref_time += demux_packet_list_duration(pkts, num_pkts) * rel_seek_secs;
- } else {
- ref_time += rel_seek_secs;
- }
+ MP_VERBOSE(in, "pause demux thread\n");
- // Could do binary search, but it's probably not worth the complexity.
- int last_index = 0;
- for (int n = 0; n < num_pkts; n++) {
- if (pkts[n]->pts > ref_time)
- break;
- last_index = n;
- }
- *current = last_index;
+ pthread_mutex_lock(&in->lock);
+ in->thread_request_pause++;
+ pthread_cond_signal(&in->wakeup);
+ while (!in->thread_paused)
+ pthread_cond_wait(&in->wakeup, &in->lock);
+ pthread_mutex_unlock(&in->lock);
}
-double demux_packet_list_duration(struct demux_packet **pkts, int num_pkts)
+void demux_unpause(demuxer_t *demuxer)
{
- if (num_pkts > 0)
- return pkts[num_pkts - 1]->pts + pkts[num_pkts - 1]->duration;
- return 0;
-}
+ struct demux_internal *in = demuxer->in;
+ assert(demuxer == in->d_user);
-struct demux_packet *demux_packet_list_fill(struct demux_packet **pkts,
- int num_pkts, int *current)
-{
- if (*current < 0)
- *current = 0;
- if (*current >= num_pkts)
- return NULL;
- struct demux_packet *new = talloc(NULL, struct demux_packet);
- *new = *pkts[*current];
- *current += 1;
- return new;
+ if (!in->threading)
+ return;
+
+ pthread_mutex_lock(&in->lock);
+ assert(in->thread_request_pause > 0);
+ in->thread_request_pause--;
+ pthread_cond_signal(&in->wakeup);
+ pthread_mutex_unlock(&in->lock);
}
diff --git a/demux/demux.h b/demux/demux.h
index 222d3b8..701c353 100644
--- a/demux/demux.h
+++ b/demux/demux.h
@@ -31,14 +31,18 @@
#include "packet.h"
#include "stheader.h"
-struct MPOpts;
-
-#define MAX_PACKS 4096
-#define MAX_PACK_BYTES 0x8000000 // 128 MiB
+// Maximum total size of packets queued - if larger, no new packets are read,
+// and the demuxer pretends EOF was reached.
+#define MAX_PACKS 16000
+#define MAX_PACK_BYTES (400 * 1024 * 1024)
+// Minimum total size of packets queued - the demuxer thread will read more
+// packets, until either number or total size of the packets exceed the minimum.
+// This can actually be configured with command line options.
+#define MIN_PACKS 64
+#define MIN_PACK_BYTES (5 * 1024 * 1024)
enum demuxer_type {
DEMUXER_TYPE_GENERIC = 0,
- DEMUXER_TYPE_TV,
DEMUXER_TYPE_MATROSKA,
DEMUXER_TYPE_EDL,
DEMUXER_TYPE_CUE,
@@ -48,15 +52,13 @@ enum demuxer_type {
#define DEMUXER_CTRL_NOTIMPL -1
#define DEMUXER_CTRL_DONTKNOW 0
#define DEMUXER_CTRL_OK 1
-#define DEMUXER_CTRL_GUESS 2
enum demux_ctrl {
DEMUXER_CTRL_SWITCHED_TRACKS = 1,
DEMUXER_CTRL_GET_TIME_LENGTH,
- DEMUXER_CTRL_GET_START_TIME,
DEMUXER_CTRL_RESYNC,
DEMUXER_CTRL_IDENTIFY_PROGRAM,
- DEMUXER_CTRL_STREAM_CTRL, // stupid workaround for legacy TV code
+ DEMUXER_CTRL_STREAM_CTRL,
};
struct demux_ctrl_stream_ctrl {
@@ -87,6 +89,13 @@ enum demux_check {
DEMUX_CHECK_NORMAL, // normal, safe detection
};
+enum demux_event {
+ DEMUX_EVENT_INIT = 1 << 0, // complete (re-)initialization
+ DEMUX_EVENT_STREAMS = 1 << 1, // a stream was added
+ DEMUX_EVENT_METADATA = 1 << 2, // metadata or stream_metadata changed
+ DEMUX_EVENT_ALL = 0xFFFF,
+};
+
#define MAX_SH_STREAMS 256
struct demuxer;
@@ -105,7 +114,7 @@ typedef struct demuxer_desc {
// The following functions are all optional
int (*fill_buffer)(struct demuxer *demuxer); // 0 on EOF, otherwise 1
void (*close)(struct demuxer *demuxer);
- void (*seek)(struct demuxer *demuxer, float rel_seek_secs, int flags);
+ void (*seek)(struct demuxer *demuxer, double rel_seek_secs, int flags);
int (*control)(struct demuxer *demuxer, int cmd, void *arg);
} demuxer_desc_t;
@@ -169,21 +178,18 @@ typedef struct demuxer {
const demuxer_desc_t *desc; ///< Demuxer description structure
const char *filetype; // format name when not identified by demuxer (libavformat)
int64_t filepos; // input stream current pos.
- struct stream *stream;
- double stream_pts; // current stream pts, if applicable (e.g. dvd)
char *filename; // same as stream->url
enum demuxer_type type;
int seekable; // flag
- /* Set if using absolute seeks for small movements is OK (no pts resets
- * that would make pts ambigious, preferably supports back/forward flags */
- bool accurate_seek;
+ double start_time;
// File format allows PTS resets (even if the current file is without)
bool ts_resets_possible;
- bool warned_queue_overflow;
+
+ // Bitmask of DEMUX_EVENT_*
+ int events;
struct sh_stream **streams;
int num_streams;
- bool stream_autoselect;
struct demux_edition *editions;
int num_editions;
@@ -199,19 +205,24 @@ typedef struct demuxer {
// for trivial demuxers which just read the whole file for codec to use
struct bstr file_contents;
- struct replaygain_data *replaygain_data;
-
// If the file is a playlist file
struct playlist *playlist;
struct mp_tags *metadata;
- char *previous_metadata;
void *priv; // demuxer-specific internal data
struct MPOpts *opts;
struct mpv_global *global;
struct mp_log *log, *glog;
struct demuxer_params *params;
+
+ struct demux_internal *in; // internal to demux.c
+
+ // Since the demuxer can run in its own thread, and the stream is not
+ // thread-safe, only the demuxer is allowed to access the stream directly.
+ // You can freely use demux_stream_control() to send STREAM_CTRLs, or use
+ // demux_pause() to get exclusive access to the stream.
+ struct stream *stream;
} demuxer_t;
typedef struct {
@@ -219,27 +230,17 @@ typedef struct {
int aid, vid, sid; //audio, video and subtitle id
} demux_program_t;
-struct demux_packet *new_demux_packet(size_t len);
-// data must already have suitable padding
-struct demux_packet *new_demux_packet_fromdata(void *data, size_t len);
-struct demux_packet *new_demux_packet_from(void *data, size_t len);
-void demux_packet_shorten(struct demux_packet *dp, size_t len);
-void free_demux_packet(struct demux_packet *dp);
-struct demux_packet *demux_copy_packet(struct demux_packet *dp);
-
-#ifndef SIZE_MAX
-#define SIZE_MAX ((size_t)-1)
-#endif
-
void free_demuxer(struct demuxer *demuxer);
-int demuxer_add_packet(demuxer_t *demuxer, struct sh_stream *stream,
- demux_packet_t *dp);
+int demux_add_packet(struct sh_stream *stream, demux_packet_t *dp);
struct demux_packet *demux_read_packet(struct sh_stream *sh);
+int demux_read_packet_async(struct sh_stream *sh, struct demux_packet **out_pkt);
+bool demux_stream_is_selected(struct sh_stream *stream);
double demux_get_next_pts(struct sh_stream *sh);
bool demux_has_packet(struct sh_stream *sh);
bool demux_stream_eof(struct sh_stream *sh);
+struct demux_packet *demux_read_any_packet(struct demuxer *demuxer);
struct sh_stream *new_sh_stream(struct demuxer *demuxer, enum stream_type type);
@@ -247,11 +248,14 @@ struct demuxer *demux_open(struct stream *stream, char *force_format,
struct demuxer_params *params,
struct mpv_global *global);
+void demux_start_thread(struct demuxer *demuxer);
+void demux_stop_thread(struct demuxer *demuxer);
+void demux_set_wakeup_cb(struct demuxer *demuxer, void (*cb)(void *ctx), void *ctx);
+
void demux_flush(struct demuxer *demuxer);
int demux_seek(struct demuxer *demuxer, float rel_seek_secs, int flags);
char *demux_info_get(struct demuxer *demuxer, const char *opt);
-bool demux_info_update(struct demuxer *demuxer);
int demux_control(struct demuxer *demuxer, int cmd, void *arg);
@@ -259,7 +263,7 @@ void demuxer_switch_track(struct demuxer *demuxer, enum stream_type type,
struct sh_stream *stream);
void demuxer_select_track(struct demuxer *demuxer, struct sh_stream *stream,
bool selected);
-void demuxer_enable_autoselect(struct demuxer *demuxer);
+void demux_set_stream_autoselect(struct demuxer *demuxer, bool autoselect);
void demuxer_help(struct mp_log *log);
@@ -269,27 +273,17 @@ int demuxer_add_chapter(struct demuxer *demuxer, struct bstr name,
uint64_t start, uint64_t end, uint64_t demuxer_id);
double demuxer_get_time_length(struct demuxer *demuxer);
-double demuxer_get_start_time(struct demuxer *demuxer);
-/// Get current angle index.
-int demuxer_get_current_angle(struct demuxer *demuxer);
-/// Set angle.
-int demuxer_set_angle(struct demuxer *demuxer, int angle);
-/// Get number of angles.
-int demuxer_angles_count(struct demuxer *demuxer);
+int demux_stream_control(demuxer_t *demuxer, int ctrl, void *arg);
-struct sh_stream *demuxer_stream_by_demuxer_id(struct demuxer *d,
- enum stream_type t, int id);
+void demux_pause(demuxer_t *demuxer);
+void demux_unpause(demuxer_t *demuxer);
-bool demuxer_stream_is_selected(struct demuxer *d, struct sh_stream *stream);
-bool demuxer_stream_has_packets_queued(struct demuxer *d, struct sh_stream *stream);
+void demux_changed(demuxer_t *demuxer, int events);
+void demux_update(demuxer_t *demuxer);
-void demux_packet_list_sort(struct demux_packet **pkts, int num_pkts);
-void demux_packet_list_seek(struct demux_packet **pkts, int num_pkts,
- int *current, float rel_seek_secs, int flags);
-double demux_packet_list_duration(struct demux_packet **pkts, int num_pkts);
-struct demux_packet *demux_packet_list_fill(struct demux_packet **pkts,
- int num_pkts, int *current);
+struct sh_stream *demuxer_stream_by_demuxer_id(struct demuxer *d,
+ enum stream_type t, int id);
bool demux_matroska_uid_cmp(struct matroska_segment_uid *a,
struct matroska_segment_uid *b);
diff --git a/demux/demux_disc.c b/demux/demux_disc.c
new file mode 100644
index 0000000..b3d4db3
--- /dev/null
+++ b/demux/demux_disc.c
@@ -0,0 +1,354 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv 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.
+ *
+ * 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#include <string.h>
+#include <math.h>
+#include <assert.h>
+
+#include "common/common.h"
+#include "common/msg.h"
+
+#include "stream/stream.h"
+#include "demux.h"
+#include "stheader.h"
+
+#include "video/csputils.h"
+
+struct priv {
+ struct demuxer *slave;
+ // streams[slave_stream_index] == our_stream
+ struct sh_stream **streams;
+ int num_streams;
+ // This contains each DVD sub stream, or NULL. Needed because DVD packets
+ // can come arbitrarily late in the MPEG stream, so the slave demuxer
+ // might add the streams only later.
+ struct sh_stream *dvd_subs[32];
+ // Used to rewrite the raw MPEG timestamps to playback time.
+ double base_time; // playback display start time of current segment
+ double base_dts; // packet DTS that maps to base_time
+ double last_dts; // DTS of previously demuxed packet
+ double seek_pts;
+ bool seek_reinit; // needs reinit after seek
+};
+
+// If the timestamp difference between subsequent packets is this big, assume
+// a reset. It should be big enough to account for 1. low video framerates and
+// large audio frames, and 2. bad interleaving.
+#define DTS_RESET_THRESHOLD 5.0
+
+static void reselect_streams(demuxer_t *demuxer)
+{
+ struct priv *p = demuxer->priv;
+ for (int n = 0; n < MPMIN(p->slave->num_streams, p->num_streams); n++) {
+ if (p->streams[n]) {
+ demuxer_select_track(p->slave, p->slave->streams[n],
+ demux_stream_is_selected(p->streams[n]));
+ }
+ }
+}
+
+static void get_disc_lang(struct stream *stream, struct sh_stream *sh)
+{
+ struct stream_lang_req req = {.type = sh->type, .id = sh->demuxer_id};
+ if (stream->uncached_type == STREAMTYPE_DVD && sh->type == STREAM_SUB)
+ req.id = req.id & 0x1F; // mpeg ID to index
+ stream_control(stream, STREAM_CTRL_GET_LANG, &req);
+ if (req.name[0])
+ sh->lang = talloc_strdup(sh, req.name);
+}
+
+static void add_dvd_streams(demuxer_t *demuxer)
+{
+ struct priv *p = demuxer->priv;
+ struct stream *stream = demuxer->stream;
+ if (stream->uncached_type != STREAMTYPE_DVD)
+ return;
+ struct stream_dvd_info_req info;
+ if (stream_control(stream, STREAM_CTRL_GET_DVD_INFO, &info) > 0) {
+ for (int n = 0; n < MPMIN(32, info.num_subs); n++) {
+ struct sh_stream *sh = new_sh_stream(demuxer, STREAM_SUB);
+ if (!sh)
+ break;
+ sh->demuxer_id = n + 0x20;
+ sh->codec = "dvd_subtitle";
+ get_disc_lang(stream, sh);
+ // p->streams _must_ match with p->slave->streams, so we can't add
+ // it yet - it has to be done when the real stream appears, which
+ // could be right on start, or any time later.
+ p->dvd_subs[n] = sh;
+
+ // emulate the extradata
+ struct mp_csp_params csp = MP_CSP_PARAMS_DEFAULTS;
+ csp.int_bits_in = 8;
+ csp.int_bits_out = 8;
+ float cmatrix[3][4];
+ mp_get_yuv2rgb_coeffs(&csp, cmatrix);
+
+ char *s = talloc_strdup(sh, "");
+ s = talloc_asprintf_append(s, "palette: ");
+ for (int i = 0; i < 16; i++) {
+ int color = info.palette[i];
+ int c[3] = {(color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff};
+ mp_map_int_color(cmatrix, 8, c);
+ color = (c[2] << 16) | (c[1] << 8) | c[0];
+
+ if (i != 0)
+ s = talloc_asprintf_append(s, ", ");
+ s = talloc_asprintf_append(s, "%06x", color);
+ }
+ s = talloc_asprintf_append(s, "\n");
+
+ sh->sub->extradata = s;
+ sh->sub->extradata_len = strlen(s);
+ }
+ }
+}
+
+static void add_streams(demuxer_t *demuxer)
+{
+ struct priv *p = demuxer->priv;
+
+ for (int n = p->num_streams; n < p->slave->num_streams; n++) {
+ struct sh_stream *src = p->slave->streams[n];
+ if (src->sub) {
+ struct sh_stream *sub = NULL;
+ if (src->demuxer_id >= 0x20 && src->demuxer_id <= 0x3F)
+ sub = p->dvd_subs[src->demuxer_id - 0x20];
+ if (sub) {
+ assert(p->num_streams == n); // directly mapped
+ MP_TARRAY_APPEND(p, p->streams, p->num_streams, sub);
+ continue;
+ }
+ }
+ struct sh_stream *sh = new_sh_stream(demuxer, src->type);
+ assert(p->num_streams == n); // directly mapped
+ MP_TARRAY_APPEND(p, p->streams, p->num_streams, sh);
+ // Copy all stream fields that might be relevant
+ sh->codec = talloc_strdup(sh, src->codec);
+ sh->format = src->format;
+ sh->lav_headers = src->lav_headers;
+ if (sh && src->video) {
+ double ar;
+ if (stream_control(demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar)
+ == STREAM_OK)
+ sh->video->aspect = ar;
+ }
+ if (sh && src->audio)
+ sh->audio = src->audio;
+ }
+ reselect_streams(demuxer);
+}
+
+static void d_seek(demuxer_t *demuxer, double rel_seek_secs, int flags)
+{
+ struct priv *p = demuxer->priv;
+
+ if (demuxer->stream->uncached_type == STREAMTYPE_CDDA) {
+ demux_seek(p->slave, rel_seek_secs, flags);
+ return;
+ }
+
+ double pts = p->seek_pts;
+ if (flags & SEEK_ABSOLUTE)
+ pts = 0.0f;
+
+ if (flags & SEEK_FACTOR) {
+ double tmp = 0;
+ stream_control(demuxer->stream, STREAM_CTRL_GET_TIME_LENGTH, &tmp);
+ pts += tmp * rel_seek_secs;
+ } else {
+ pts += rel_seek_secs;
+ }
+
+ MP_VERBOSE(demuxer, "seek to: %f\n", pts);
+
+ stream_control(demuxer->stream, STREAM_CTRL_SEEK_TO_TIME, &pts);
+ demux_control(p->slave, DEMUXER_CTRL_RESYNC, NULL);
+
+ p->seek_pts = pts;
+ p->seek_reinit = true;
+}
+
+static void reset_pts(demuxer_t *demuxer)
+{
+ struct priv *p = demuxer->priv;
+
+ double base;
+ if (stream_control(demuxer->stream, STREAM_CTRL_GET_CURRENT_TIME, &base) < 1)
+ base = 0;
+
+ MP_VERBOSE(demuxer, "reset to time: %f\n", base);
+
+ p->base_dts = p->last_dts = MP_NOPTS_VALUE;
+ p->base_time = base;
+ p->seek_reinit = false;
+}
+
+static int d_fill_buffer(demuxer_t *demuxer)
+{
+ struct priv *p = demuxer->priv;
+
+ struct demux_packet *pkt = demux_read_any_packet(p->slave);
+ if (!pkt)
+ return 0;
+
+ demux_update(p->slave);
+
+ if (p->seek_reinit)
+ reset_pts(demuxer);
+
+ add_streams(demuxer);
+ if (pkt->stream >= p->num_streams) { // out of memory?
+ talloc_free(pkt);
+ return 0;
+ }
+
+ struct sh_stream *sh = p->streams[pkt->stream];
+ if (!demux_stream_is_selected(sh)) {
+ talloc_free(pkt);
+ return 1;
+ }
+
+ MP_TRACE(demuxer, "ipts: %d %f %f\n", sh->type, pkt->pts, pkt->dts);
+
+ if (sh->type == STREAM_SUB) {
+ if (p->base_dts == MP_NOPTS_VALUE)
+ MP_WARN(demuxer, "subtitle packet along PTS reset\n");
+ } else if (pkt->dts != MP_NOPTS_VALUE) {
+ // Use the very first DTS to rebase the start time of the MPEG stream
+ // to the playback time.
+ if (p->base_dts == MP_NOPTS_VALUE)
+ p->base_dts = pkt->dts;
+
+ if (p->last_dts == MP_NOPTS_VALUE)
+ p->last_dts = pkt->dts;
+
+ if (fabs(p->last_dts - pkt->dts) >= DTS_RESET_THRESHOLD) {
+ MP_WARN(demuxer, "PTS discontinuity: %f->%f\n", p->last_dts, pkt->dts);
+ p->base_time += p->last_dts - p->base_dts;
+ p->base_dts = pkt->dts - pkt->duration;
+ }
+ p->last_dts = pkt->dts;
+ }
+
+ if (p->base_dts != MP_NOPTS_VALUE) {
+ double delta = -p->base_dts + p->base_time;
+ if (pkt->pts != MP_NOPTS_VALUE)
+ pkt->pts += delta;
+ if (pkt->dts != MP_NOPTS_VALUE)
+ pkt->dts += delta;
+ }
+
+ MP_TRACE(demuxer, "opts: %d %f %f\n", sh->type, pkt->pts, pkt->dts);
+
+ if (pkt->pts != MP_NOPTS_VALUE)
+ p->seek_pts = pkt->pts;
+
+ demux_add_packet(sh, pkt);
+ return 1;
+}
+
+static void add_stream_chapters(struct demuxer *demuxer)
+{
+ int num = 0;
+ if (stream_control(demuxer->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &num) < 1)
+ return;
+ for (int n = 0; n < num; n++) {
+ double p = n;
+ if (stream_control(demuxer->stream, STREAM_CTRL_GET_CHAPTER_TIME, &p) < 1)
+ continue;
+ demuxer_add_chapter(demuxer, bstr0(""), p * 1e9, 0, 0);
+ }
+}
+
+static int d_open(demuxer_t *demuxer, enum demux_check check)
+{
+ struct priv *p = demuxer->priv = talloc_zero(demuxer, struct priv);
+
+ if (check != DEMUX_CHECK_FORCE)
+ return -1;
+
+ char *demux = "+lavf";
+ if (demuxer->stream->uncached_type == STREAMTYPE_CDDA)
+ demux = "+rawaudio";
+
+ char *t = NULL;
+ stream_control(demuxer->stream, STREAM_CTRL_GET_DISC_NAME, &t);
+ if (t) {
+ mp_tags_set_bstr(demuxer->metadata, bstr0("TITLE"), bstr0(t));
+ talloc_free(t);
+ }
+
+ // Initialize the playback time. We need to read _some_ data to get the
+ // correct stream-layer time (at least with libdvdnav).
+ stream_peek(demuxer->stream, 1);
+ reset_pts(demuxer);
+
+ p->slave = demux_open(demuxer->stream, demux, NULL, demuxer->global);
+ if (!p->slave)
+ return -1;
+
+ // So that we don't miss initial packets of delayed subtitle streams.
+ demux_set_stream_autoselect(p->slave, true);
+
+ // Can be seekable even if the stream isn't.
+ demuxer->seekable = true;
+
+ add_dvd_streams(demuxer);
+ add_streams(demuxer);
+ add_stream_chapters(demuxer);
+
+ return 0;
+}
+
+static void d_close(demuxer_t *demuxer)
+{
+ struct priv *p = demuxer->priv;
+ free_demuxer(p->slave);
+}
+
+static int d_control(demuxer_t *demuxer, int cmd, void *arg)
+{
+ struct priv *p = demuxer->priv;
+
+ switch (cmd) {
+ case DEMUXER_CTRL_GET_TIME_LENGTH: {
+ double len;
+ if (stream_control(demuxer->stream, STREAM_CTRL_GET_TIME_LENGTH, &len) < 1)
+ break;
+ *(double *)arg = len;
+ return DEMUXER_CTRL_OK;
+ }
+ case DEMUXER_CTRL_RESYNC:
+ demux_flush(p->slave);
+ break; // relay to slave demuxer
+ case DEMUXER_CTRL_SWITCHED_TRACKS:
+ reselect_streams(demuxer);
+ return DEMUXER_CTRL_OK;
+ }
+ return demux_control(p->slave, cmd, arg);
+}
+
+const demuxer_desc_t demuxer_desc_disc = {
+ .name = "disc",
+ .desc = "CD/DVD/BD wrapper",
+ .fill_buffer = d_fill_buffer,
+ .open = d_open,
+ .close = d_close,
+ .seek = d_seek,
+ .control = d_control,
+};
diff --git a/demux/demux_lavf.c b/demux/demux_lavf.c
index c3c5650..0987508 100644
--- a/demux/demux_lavf.c
+++ b/demux/demux_lavf.c
@@ -18,12 +18,11 @@
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
-// #include <stdio.h>
#include <stdlib.h>
-// #include <unistd.h>
#include <limits.h>
#include <stdbool.h>
#include <string.h>
+#include <strings.h>
#include <assert.h>
#include "config.h"
@@ -45,7 +44,6 @@
#include "options/options.h"
#include "common/msg.h"
#include "common/tags.h"
-#include "common/av_opts.h"
#include "common/av_common.h"
#include "bstr/bstr.h"
@@ -54,6 +52,7 @@
#include "stheader.h"
#include "options/m_option.h"
+
#define INITIAL_PROBE_SIZE STREAM_BUFFER_SIZE
#define PROBE_BUF_SIZE FFMIN(STREAM_MAX_BUFFER_SIZE, 2 * 1024 * 1024)
@@ -71,7 +70,7 @@ struct demux_lavf_opts {
int allow_mimetype;
char *format;
char *cryptokey;
- char *avopt;
+ char **avopts;
int genptsmode;
};
@@ -87,7 +86,7 @@ const struct m_sub_options demux_lavf_conf = {
OPT_STRING("cryptokey", cryptokey, 0),
OPT_CHOICE("genpts-mode", genptsmode, 0,
({"lavf", 1}, {"no", 0})),
- OPT_STRING("o", avopt, 0),
+ OPT_KEYVALUELIST("o", avopts, 0),
{0}
},
.size = sizeof(struct demux_lavf_opts),
@@ -107,6 +106,7 @@ typedef struct lavf_priv {
int num_streams;
int cur_program;
char *mime_type;
+ bool merge_track_metadata;
} lavf_priv_t;
struct format_hack {
@@ -143,8 +143,8 @@ static int mp_read(void *opaque, uint8_t *buf, int size)
ret = stream_read(stream, buf, size);
- MP_DBG(demuxer, "%d=mp_read(%p, %p, %d), pos: %"PRId64", eof:%d\n",
- ret, stream, buf, size, stream_tell(stream), stream->eof);
+ MP_TRACE(demuxer, "%d=mp_read(%p, %p, %d), pos: %"PRId64", eof:%d\n",
+ ret, stream, buf, size, stream_tell(stream), stream->eof);
return ret;
}
@@ -153,10 +153,7 @@ static int64_t mp_seek(void *opaque, int64_t pos, int whence)
struct demuxer *demuxer = opaque;
struct stream *stream = demuxer->stream;
int64_t current_pos;
- if (stream_manages_timeline(stream))
- return -1;
- MP_DBG(demuxer, "mp_seek(%p, %"PRId64", %d)\n",
- stream, pos, whence);
+ MP_TRACE(demuxer, "mp_seek(%p, %"PRId64", %d)\n", stream, pos, whence);
if (whence == SEEK_END || whence == AVSEEK_SIZE) {
int64_t end;
if (stream_control(stream, STREAM_CTRL_GET_SIZE, &end) != STREAM_OK)
@@ -185,14 +182,15 @@ static int64_t mp_read_seek(void *opaque, int stream_idx, int64_t ts, int flags)
{
struct demuxer *demuxer = opaque;
struct stream *stream = demuxer->stream;
- struct lavf_priv *priv = demuxer->priv;
- AVStream *st = priv->avfc->streams[stream_idx];
- double pts = (double)ts * st->time_base.num / st->time_base.den;
- int ret = stream_control(stream, STREAM_CTRL_SEEK_TO_TIME, &pts);
- if (ret < 0)
- ret = AVERROR(ENOSYS);
- return ret;
+ struct stream_avseek cmd = {
+ .stream_index = stream_idx,
+ .timestamp = ts,
+ .flags = flags,
+ };
+
+ int ret = stream_control(stream, STREAM_CTRL_AVSEEK, &cmd);
+ return ret < 1 ? AVERROR(ENOSYS) : 0;
}
static void list_formats(struct demuxer *demuxer)
@@ -267,8 +265,7 @@ static int lavf_check_file(demuxer_t *demuxer, enum demux_check check)
MP_FATAL(demuxer, "Unknown lavf format %s\n", format);
return -1;
}
- MP_INFO(demuxer, "Forced lavf %s demuxer\n",
- priv->avif->long_name);
+ MP_VERBOSE(demuxer, "Forced lavf %s demuxer\n", priv->avif->long_name);
goto success;
}
@@ -396,13 +393,13 @@ static void select_tracks(struct demuxer *demuxer, int start)
for (int n = start; n < priv->num_streams; n++) {
struct sh_stream *stream = priv->streams[n];
AVStream *st = priv->avfc->streams[n];
- bool selected = stream && demuxer_stream_is_selected(demuxer, stream) &&
+ bool selected = stream && demux_stream_is_selected(stream) &&
!stream->attached_picture;
st->discard = selected ? AVDISCARD_DEFAULT : AVDISCARD_ALL;
}
}
-static void export_replaygain(demuxer_t *demuxer, AVStream *st)
+static void export_replaygain(demuxer_t *demuxer, sh_audio_t *sh, AVStream *st)
{
#if HAVE_AVCODEC_REPLAYGAIN_SIDE_DATA
for (int i = 0; i < st->nb_side_data; i++) {
@@ -428,7 +425,7 @@ static void export_replaygain(demuxer_t *demuxer, AVStream *st)
rgain->album_peak = (av_rgain->album_peak != 0.0) ?
av_rgain->album_peak / 100000.0f : 1.0;
- demuxer->replaygain_data = rgain;
+ sh->replaygain_data = rgain;
}
#endif
}
@@ -457,7 +454,7 @@ static void handle_stream(demuxer_t *demuxer, int i)
sh_audio->samplerate = codec->sample_rate;
sh_audio->bitrate = codec->bit_rate;
- export_replaygain(demuxer, st);
+ export_replaygain(demuxer, sh_audio, st);
break;
}
@@ -522,9 +519,6 @@ static void handle_stream(demuxer_t *demuxer, int i)
// This also applies to vfw-muxed mkv, but we can't detect these easily.
sh_video->avi_dts = matches_avinputformat_name(priv, "avi");
- MP_DBG(demuxer, "aspect= %d*%d/(%d*%d)\n",
- codec->width, codec->sample_aspect_ratio.num,
- codec->height, codec->sample_aspect_ratio.den);
break;
}
case AVMEDIA_TYPE_SUBTITLE: {
@@ -561,11 +555,18 @@ static void handle_stream(demuxer_t *demuxer, int i)
AVDictionaryEntry *ftag = av_dict_get(st->metadata, "filename",
NULL, 0);
char *filename = ftag ? ftag->value : NULL;
- if (st->codec->codec_id == AV_CODEC_ID_TTF)
- demuxer_add_attachment(demuxer, bstr0(filename),
- bstr0("application/x-truetype-font"),
+ char *mimetype = NULL;
+ switch (st->codec->codec_id) {
+ case AV_CODEC_ID_TTF: mimetype = "application/x-truetype-font"; break;
+#if LIBAVFORMAT_VERSION_MICRO >= 100
+ case AV_CODEC_ID_OTF: mimetype = "application/vnd.ms-opentype"; break;
+#endif
+ }
+ if (mimetype) {
+ demuxer_add_attachment(demuxer, bstr0(filename), bstr0(mimetype),
(struct bstr){codec->extradata,
codec->extradata_size});
+ }
break;
}
default: ;
@@ -592,6 +593,7 @@ static void handle_stream(demuxer_t *demuxer, int i)
}
select_tracks(demuxer, i);
+ demux_changed(demuxer, DEMUX_EVENT_STREAMS);
}
// Add any new streams that might have been added
@@ -605,16 +607,18 @@ static void add_new_streams(demuxer_t *demuxer)
static void update_metadata(demuxer_t *demuxer, AVPacket *pkt)
{
#if HAVE_AVCODEC_METADATA_UPDATE_SIDE_DATA
+ lavf_priv_t *priv = demuxer->priv;
int md_size;
const uint8_t *md;
md = av_packet_get_side_data(pkt, AV_PKT_DATA_METADATA_UPDATE, &md_size);
- if (md) {
+ if (md && priv->merge_track_metadata) {
AVDictionary *dict = NULL;
av_packet_unpack_dictionary(md, md_size, &dict);
if (dict) {
mp_tags_clear(demuxer->metadata);
mp_tags_copy_from_av_dictionary(demuxer->metadata, dict);
av_dict_free(&dict);
+ demux_changed(demuxer, DEMUX_EVENT_METADATA);
}
}
#endif
@@ -654,7 +658,7 @@ static int demux_open_lavf(demuxer_t *demuxer, enum demux_check check)
if (lavfdopts->probesize) {
if (av_opt_set_int(avfc, "probesize", lavfdopts->probesize, 0) < 0)
- MP_ERR(demuxer, "demux_lavf, couldn't set option probesize to %u\n",
+ MP_ERR(demuxer, "couldn't set option probesize to %u\n",
lavfdopts->probesize);
}
@@ -669,14 +673,6 @@ static int demux_open_lavf(demuxer_t *demuxer, enum demux_check check)
"analyzeduration to %f\n", analyze_duration);
}
- if (lavfdopts->avopt) {
- if (parse_avopts(avfc, lavfdopts->avopt) < 0) {
- MP_ERR(demuxer, "Your options /%s/ look like gibberish to me pal\n",
- lavfdopts->avopt);
- return -1;
- }
- }
-
if ((priv->avif->flags & AVFMT_NOFILE) ||
demuxer->stream->type == STREAMTYPE_AVDEVICE)
{
@@ -710,27 +706,25 @@ static int demux_open_lavf(demuxer_t *demuxer, enum demux_check check)
av_dict_set(&dopts, "rtsp_transport", transport, 0);
}
+ mp_set_avdict(&dopts, lavfdopts->avopts);
+
if (avformat_open_input(&avfc, priv->filename, priv->avif, &dopts) < 0) {
- MP_ERR(demuxer, "LAVF_header: avformat_open_input() failed\n");
+ MP_ERR(demuxer, "avformat_open_input() failed\n");
av_dict_free(&dopts);
return -1;
}
- t = NULL;
- while ((t = av_dict_get(dopts, "", t, AV_DICT_IGNORE_SUFFIX))) {
- MP_VERBOSE(demuxer, "[lavf] Could not set demux option %s=%s\n",
- t->key, t->value);
- }
+ mp_avdict_print_unset(demuxer->log, MSGL_V, dopts);
av_dict_free(&dopts);
priv->avfc = avfc;
if (avformat_find_stream_info(avfc, NULL) < 0) {
- MP_ERR(demuxer, "LAVF_header: av_find_stream_info() failed\n");
+ MP_ERR(demuxer, "av_find_stream_info() failed\n");
return -1;
}
- MP_VERBOSE(demuxer, "demux_lavf: avformat_find_stream_info() "
- "finished after %"PRId64" bytes.\n", stream_tell(demuxer->stream));
+ MP_VERBOSE(demuxer, "avformat_find_stream_info() finished after %"PRId64
+ " bytes.\n", stream_tell(demuxer->stream));
for (i = 0; i < avfc->nb_chapters; i++) {
AVChapter *c = avfc->chapters[i];
@@ -751,27 +745,18 @@ static int demux_open_lavf(demuxer_t *demuxer, enum demux_check check)
// Often useful with OGG audio-only files, which have metadata in the audio
// track metadata instead of the main metadata.
if (demuxer->num_streams == 1) {
+ priv->merge_track_metadata = true;
for (int n = 0; n < priv->num_streams; n++) {
if (priv->streams[n])
mp_tags_copy_from_av_dictionary(demuxer->metadata, avfc->streams[n]->metadata);
}
}
- if (avfc->nb_programs) {
- int p;
- for (p = 0; p < avfc->nb_programs; p++) {
- AVProgram *program = avfc->programs[p];
- t = av_dict_get(program->metadata, "title", NULL, 0);
- MP_INFO(demuxer, "LAVF: Program %d %s\n",
- program->id, t ? t->value : "");
- MP_VERBOSE(demuxer, "PROGRAM_ID=%d\n", program->id);
- }
- }
-
- MP_VERBOSE(demuxer, "LAVF: build %d\n", LIBAVFORMAT_BUILD);
-
demuxer->ts_resets_possible = priv->avif->flags & AVFMT_TS_DISCONT;
+ demuxer->start_time = priv->avfc->start_time == AV_NOPTS_VALUE ?
+ 0 : (double)priv->avfc->start_time / AV_TIME_BASE;
+
return 0;
}
@@ -784,12 +769,12 @@ static int demux_lavf_fill_buffer(demuxer_t *demux)
{
lavf_priv_t *priv = demux->priv;
demux_packet_t *dp;
- MP_DBG(demux, "demux_lavf_fill_buffer()\n");
AVPacket *pkt = talloc(NULL, AVPacket);
- if (av_read_frame(priv->avfc, pkt) < 0) {
+ int r = av_read_frame(priv->avfc, pkt);
+ if (r < 0) {
talloc_free(pkt);
- return 0; // eof
+ return r == AVERROR(EAGAIN) ? 1 : -1; // eof
}
talloc_set_destructor(pkt, destroy_avpacket);
@@ -800,7 +785,7 @@ static int demux_lavf_fill_buffer(demuxer_t *demux)
struct sh_stream *stream = priv->streams[pkt->stream_index];
AVStream *st = priv->avfc->streams[pkt->stream_index];
- if (!demuxer_stream_is_selected(demux, stream)) {
+ if (!demux_stream_is_selected(stream)) {
talloc_free(pkt);
return 1; // don't signal EOF if skipping a packet
}
@@ -823,27 +808,19 @@ static int demux_lavf_fill_buffer(demuxer_t *demux)
dp->duration = pkt->convergence_duration * av_q2d(st->time_base);
dp->pos = pkt->pos;
dp->keyframe = pkt->flags & AV_PKT_FLAG_KEY;
- // Use only one stream for stream_pts, otherwise PTS might be jumpy.
- if (stream->type == STREAM_VIDEO) {
- double pts;
- if (stream_control(demux->stream, STREAM_CTRL_GET_CURRENT_TIME, &pts) > 0)
- dp->stream_pts = pts;
- }
if (dp->pts != MP_NOPTS_VALUE) {
priv->last_pts = dp->pts * AV_TIME_BASE;
} else if (dp->dts != MP_NOPTS_VALUE) {
priv->last_pts = dp->dts * AV_TIME_BASE;
}
- demuxer_add_packet(demux, stream, dp);
+ demux_add_packet(stream, dp);
return 1;
}
-static void demux_seek_lavf(demuxer_t *demuxer, float rel_seek_secs, int flags)
+static void demux_seek_lavf(demuxer_t *demuxer, double rel_seek_secs, int flags)
{
lavf_priv_t *priv = demuxer->priv;
int avsflags = 0;
- MP_DBG(demuxer, "demux_seek_lavf(%p, %f, %d)\n",
- demuxer, rel_seek_secs, flags);
if (flags & SEEK_ABSOLUTE)
priv->last_pts = 0;
@@ -929,11 +906,6 @@ static int demux_lavf_control(demuxer_t *demuxer, int cmd, void *arg)
*((double *)arg) = (double)priv->avfc->duration / AV_TIME_BASE;
return DEMUXER_CTRL_OK;
- case DEMUXER_CTRL_GET_START_TIME:
- *((double *)arg) = priv->avfc->start_time == AV_NOPTS_VALUE ?
- 0 : (double)priv->avfc->start_time / AV_TIME_BASE;
- return DEMUXER_CTRL_OK;
-
case DEMUXER_CTRL_SWITCHED_TRACKS:
{
select_tracks(demuxer, 0);
diff --git a/demux/demux_mf.c b/demux/demux_mf.c
index fa5908c..c0e4cd7 100644
--- a/demux/demux_mf.c
+++ b/demux/demux_mf.c
@@ -18,6 +18,7 @@
#include <stdio.h>
#include <stdlib.h>
+#include <strings.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
@@ -36,7 +37,7 @@
#define MF_MAX_FILE_SIZE (1024 * 1024 * 256)
-static void demux_seek_mf(demuxer_t *demuxer, float rel_seek_secs, int flags)
+static void demux_seek_mf(demuxer_t *demuxer, double rel_seek_secs, int flags)
{
mf_t *mf = demuxer->priv;
int newpos = (flags & SEEK_ABSOLUTE) ? 0 : mf->curr_frame - 1;
@@ -48,7 +49,7 @@ static void demux_seek_mf(demuxer_t *demuxer, float rel_seek_secs, int flags)
if (newpos < 0)
newpos = 0;
if (newpos >= mf->nr_of_files)
- newpos = mf->nr_of_files - 1;
+ newpos = mf->nr_of_files;
mf->curr_frame = newpos;
}
@@ -79,7 +80,7 @@ static int demux_mf_fill_buffer(demuxer_t *demuxer)
memcpy(dp->buffer, data.start, data.len);
dp->pts = mf->curr_frame / mf->sh->fps;
dp->keyframe = true;
- demuxer_add_packet(demuxer, demuxer->streams[0], dp);
+ demux_add_packet(demuxer->streams[0], dp);
}
talloc_free(data.start);
}
diff --git a/demux/demux_mkv.c b/demux/demux_mkv.c
index 5ebfab4..dff08ec 100644
--- a/demux/demux_mkv.c
+++ b/demux/demux_mkv.c
@@ -23,7 +23,6 @@
#include <stdlib.h>
#include <stdio.h>
-#include <ctype.h>
#include <inttypes.h>
#include <stdbool.h>
#include <assert.h>
@@ -462,13 +461,11 @@ static void parse_trackaudio(struct demuxer *demuxer, struct mkv_track *track,
}
if (audio->n_bit_depth) {
track->a_bps = audio->bit_depth;
- MP_VERBOSE(demuxer, "| + Bit depth: %u\n",
- track->a_bps);
+ MP_VERBOSE(demuxer, "| + Bit depth: %u\n", track->a_bps);
}
if (audio->n_channels) {
track->a_channels = audio->channels;
- MP_VERBOSE(demuxer, "| + Channels: %u\n",
- track->a_channels);
+ MP_VERBOSE(demuxer, "| + Channels: %u\n", track->a_channels);
} else {
track->a_channels = 1;
}
@@ -479,38 +476,33 @@ static void parse_trackvideo(struct demuxer *demuxer, struct mkv_track *track,
{
if (video->n_frame_rate) {
track->v_frate = video->frame_rate;
- MP_VERBOSE(demuxer, "| + Frame rate: %f\n",
- track->v_frate);
+ MP_VERBOSE(demuxer, "| + Frame rate: %f\n", track->v_frate);
if (track->v_frate > 0)
track->default_duration = 1 / track->v_frate;
}
if (video->n_display_width) {
track->v_dwidth = video->display_width;
track->v_dwidth_set = true;
- MP_VERBOSE(demuxer, "| + Display width: %u\n",
- track->v_dwidth);
+ MP_VERBOSE(demuxer, "| + Display width: %u\n", track->v_dwidth);
}
if (video->n_display_height) {
track->v_dheight = video->display_height;
track->v_dheight_set = true;
- MP_VERBOSE(demuxer, "| + Display height: %u\n",
- track->v_dheight);
+ MP_VERBOSE(demuxer, "| + Display height: %u\n", track->v_dheight);
}
if (video->n_pixel_width) {
track->v_width = video->pixel_width;
- MP_VERBOSE(demuxer, "| + Pixel width: %u\n",
- track->v_width);
+ MP_VERBOSE(demuxer, "| + Pixel width: %u\n", track->v_width);
}
if (video->n_pixel_height) {
track->v_height = video->pixel_height;
- MP_VERBOSE(demuxer, "| + Pixel height: %u\n",
- track->v_height);
+ MP_VERBOSE(demuxer, "| + Pixel height: %u\n", track->v_height);
}
if (video->n_colour_space && video->colour_space.len == 4) {
uint8_t *d = (uint8_t *)&video->colour_space.start[0];
track->colorspace = d[0] | (d[1] << 8) | (d[2] << 16) | (d[3] << 24);
MP_VERBOSE(demuxer, "| + Colorspace: %#x\n",
- (unsigned int)track->colorspace);
+ (unsigned int)track->colorspace);
}
}
@@ -534,8 +526,7 @@ static void parse_trackentry(struct demuxer *demuxer,
track->tnum = entry->track_number;
if (track->tnum) {
- MP_VERBOSE(demuxer, "| + Track number: %u\n",
- track->tnum);
+ MP_VERBOSE(demuxer, "| + Track number: %u\n", track->tnum);
} else {
MP_ERR(demuxer, "Missing track number!\n");
}
@@ -543,8 +534,7 @@ static void parse_trackentry(struct demuxer *demuxer,
if (entry->n_name) {
track->name = talloc_strndup(track, entry->name.start,
entry->name.len);
- MP_VERBOSE(demuxer, "| + Name: %s\n",
- track->name);
+ MP_VERBOSE(demuxer, "| + Name: %s\n", track->name);
}
track->type = entry->track_type;
@@ -580,8 +570,7 @@ static void parse_trackentry(struct demuxer *demuxer,
if (!strcmp(track->codec_id, MKV_V_MSCOMP)
|| !strcmp(track->codec_id, MKV_A_ACM))
track->ms_compat = 1;
- MP_VERBOSE(demuxer, "| + Codec ID: %s\n",
- track->codec_id);
+ MP_VERBOSE(demuxer, "| + Codec ID: %s\n", track->codec_id);
} else {
MP_ERR(demuxer, "Missing codec ID!\n");
track->codec_id = "";
@@ -592,23 +581,20 @@ static void parse_trackentry(struct demuxer *demuxer,
track->private_data = talloc_size(track, len + AV_LZO_INPUT_PADDING);
memcpy(track->private_data, entry->codec_private.start, len);
track->private_size = len;
- MP_VERBOSE(demuxer, "| + CodecPrivate, length %u\n",
- track->private_size);
+ MP_VERBOSE(demuxer, "| + CodecPrivate, length %u\n", track->private_size);
}
if (entry->n_language) {
track->language = talloc_strndup(track, entry->language.start,
entry->language.len);
- MP_VERBOSE(demuxer, "| + Language: %s\n",
- track->language);
+ MP_VERBOSE(demuxer, "| + Language: %s\n", track->language);
} else {
track->language = talloc_strdup(track, "eng");
}
if (entry->n_flag_default) {
track->default_track = entry->flag_default;
- MP_VERBOSE(demuxer, "| + Default flag: %u\n",
- track->default_track);
+ MP_VERBOSE(demuxer, "| + Default flag: %u\n", track->default_track);
} else {
track->default_track = 1;
}
@@ -621,7 +607,7 @@ static void parse_trackentry(struct demuxer *demuxer,
if (!track->v_frate)
track->v_frate = 1e9 / entry->default_duration;
MP_VERBOSE(demuxer, "| + Default duration: %.3fms ( = %.3f fps)\n",
- entry->default_duration / 1000000.0, track->v_frate);
+ entry->default_duration / 1000000.0, track->v_frate);
}
}
@@ -784,8 +770,7 @@ static int demux_mkv_read_chapters(struct demuxer *demuxer)
}
if (wanted_edition >= 0 && wanted_edition < num_editions) {
selected_edition = wanted_edition;
- MP_VERBOSE(demuxer, "User-specified edition: %d\n",
- selected_edition);
+ MP_VERBOSE(demuxer, "User-specified edition: %d\n", selected_edition);
} else {
for (int i = 0; i < num_editions; i++) {
if (wanted_edition_uid &&
@@ -814,10 +799,10 @@ static int demux_mkv_read_chapters(struct demuxer *demuxer)
int warn_level = idx == selected_edition ? MSGL_WARN : MSGL_V;
if (editions[idx].n_edition_flag_default)
MP_VERBOSE(demuxer, "Default edition flag: %"PRIu64
- "\n", editions[idx].edition_flag_default);
+ "\n", editions[idx].edition_flag_default);
if (editions[idx].n_edition_flag_ordered)
MP_VERBOSE(demuxer, "Ordered chapter flag: %"PRIu64
- "\n", editions[idx].edition_flag_ordered);
+ "\n", editions[idx].edition_flag_ordered);
int chapter_count = editions[idx].n_chapter_atom;
@@ -834,8 +819,7 @@ static int demux_mkv_read_chapters(struct demuxer *demuxer)
struct bstr name = { "(unnamed)", 9 };
if (!ca->n_chapter_time_start)
- MP_MSG(demuxer, warn_level,
- "Chapter lacks start time\n");
+ MP_MSG(demuxer, warn_level, "Chapter lacks start time\n");
chapter.start = ca->chapter_time_start;
chapter.end = ca->chapter_time_end;
@@ -844,8 +828,7 @@ static int demux_mkv_read_chapters(struct demuxer *demuxer)
MP_MSG(demuxer, warn_level, "Multiple chapter "
"names not supported, picking first\n");
if (!ca->chapter_display[0].n_chap_string)
- MP_MSG(demuxer, warn_level, "Malformed chapter "
- "name entry\n");
+ MP_MSG(demuxer, warn_level, "Malformed chapter name entry\n");
else
name = ca->chapter_display[0].chap_string;
}
@@ -986,7 +969,7 @@ static int demux_mkv_read_attachments(demuxer_t *demuxer)
struct bstr mime = attachment->file_mime_type;
demuxer_add_attachment(demuxer, name, mime, attachment->file_data);
MP_VERBOSE(demuxer, "Attachment: %.*s, %.*s, %zu bytes\n",
- BSTR_P(name), BSTR_P(mime), attachment->file_data.len);
+ BSTR_P(name), BSTR_P(mime), attachment->file_data.len);
}
talloc_free(parse_ctx.talloc_ctx);
@@ -1675,10 +1658,8 @@ static int demux_mkv_open_sub(demuxer_t *demuxer, mkv_track_t *track)
sh->title = talloc_strdup(sh, track->name);
sh->default_track = track->default_track;
- if (!subtitle_type) {
- MP_ERR(demuxer, "Subtitle type '%s' is not supported.\n",
- track->codec_id);
- }
+ if (!subtitle_type)
+ MP_ERR(demuxer, "Subtitle type '%s' is not supported.\n", track->codec_id);
return 0;
}
@@ -1695,7 +1676,7 @@ static int read_ebml_header(demuxer_t *demuxer)
return 0;
if (ebml_master.doc_type.start == NULL) {
MP_VERBOSE(demuxer, "File has EBML header but no doctype."
- " Assuming \"matroska\".\n");
+ " Assuming \"matroska\".\n");
} else if (bstrcmp(ebml_master.doc_type, bstr0("matroska")) != 0
&& bstrcmp(ebml_master.doc_type, bstr0("webm")) != 0) {
MP_DBG(demuxer, "no head found\n");
@@ -1704,8 +1685,8 @@ static int read_ebml_header(demuxer_t *demuxer)
}
if (ebml_master.doc_type_read_version > 2) {
MP_WARN(demuxer, "This looks like a Matroska file, "
- "but we don't support format version %"PRIu64"\n",
- ebml_master.doc_type_read_version);
+ "but we don't support format version %"PRIu64"\n",
+ ebml_master.doc_type_read_version);
talloc_free(parse_ctx.talloc_ctx);
return 0;
}
@@ -1717,7 +1698,7 @@ static int read_ebml_header(demuxer_t *demuxer)
&& ebml_master.ebml_max_id_length != 4))
{
MP_WARN(demuxer, "This looks like a Matroska file, "
- "but the header has bad parameters\n");
+ "but the header has bad parameters\n");
talloc_free(parse_ctx.talloc_ctx);
return 0;
}
@@ -2003,7 +1984,7 @@ static void handle_realvideo(demuxer_t *demuxer, mkv_track_t *track,
dp->pos = mkv_d->last_filepos;
dp->keyframe = keyframe;
- demuxer_add_packet(demuxer, track->stream, dp);
+ demux_add_packet(track->stream, dp);
}
static void handle_realaudio(demuxer_t *demuxer, mkv_track_t *track,
@@ -2061,30 +2042,30 @@ static void handle_realaudio(demuxer_t *demuxer, mkv_track_t *track,
int bs = sph * w * 2 / 96; // nibbles per subpacket
// Perform reordering
for (n = 0; n < 38; n++) {
- int i = bs * sipr_swaps[n][0]; // 77 max
- int o = bs * sipr_swaps[n][1]; // 95 max
+ unsigned int i = bs * sipr_swaps[n][0]; // 77 max
+ unsigned int o = bs * sipr_swaps[n][1]; // 95 max
// swap nibbles of block 'i' with 'o'
for (int j = 0; j < bs; j++) {
if (i / 2 >= audiobuf_size || o / 2 >= audiobuf_size)
goto error;
int x = (i & 1) ?
- (track->audio_buf[i >> 1] >> 4) :
- (track->audio_buf[i >> 1] & 0x0F);
+ (track->audio_buf[i / 2] >> 4) :
+ (track->audio_buf[i / 2] & 0x0F);
int y = (o & 1) ?
- (track->audio_buf[o >> 1] >> 4) :
- (track->audio_buf[o >> 1] & 0x0F);
+ (track->audio_buf[o / 2] >> 4) :
+ (track->audio_buf[o / 2] & 0x0F);
if (o & 1)
- track->audio_buf[o >> 1] =
- (track->audio_buf[o >> 1] & 0x0F) | (x << 4);
+ track->audio_buf[o / 2] =
+ (track->audio_buf[o / 2] & 0x0F) | (x << 4);
else
- track->audio_buf[o >> 1] =
- (track->audio_buf[o >> 1] & 0xF0) | x;
+ track->audio_buf[o / 2] =
+ (track->audio_buf[o / 2] & 0xF0) | x;
if (i & 1)
- track->audio_buf[i >> 1] =
- (track->audio_buf[i >> 1] & 0x0F) | (y << 4);
+ track->audio_buf[i / 2] =
+ (track->audio_buf[i / 2] & 0x0F) | (y << 4);
else
- track->audio_buf[i >> 1] =
- (track->audio_buf[i >> 1] & 0xF0) | y;
+ track->audio_buf[i / 2] =
+ (track->audio_buf[i / 2] & 0xF0) | y;
++i;
++o;
}
@@ -2113,7 +2094,7 @@ static void handle_realaudio(demuxer_t *demuxer, mkv_track_t *track,
track->audio_timestamp[x * apk_usize / w];
dp->pos = track->audio_filepos; // all equal
dp->keyframe = !x; // Mark first packet as keyframe
- demuxer_add_packet(demuxer, track->stream, dp);
+ demux_add_packet(track->stream, dp);
}
}
} else { // Not a codec that requires reordering
@@ -2126,7 +2107,7 @@ static void handle_realaudio(demuxer_t *demuxer, mkv_track_t *track,
dp->pos = mkv_d->last_filepos;
dp->keyframe = keyframe;
- demuxer_add_packet(demuxer, track->stream, dp);
+ demux_add_packet(track->stream, dp);
}
return;
error:
@@ -2381,7 +2362,7 @@ static int handle_block(demuxer_t *demuxer, struct block_info *block_info)
uint32_t lace_size[MAX_NUM_LACES];
bool use_this_block = tc >= mkv_d->skip_to_timecode;
- if (!demuxer_stream_is_selected(demuxer, stream))
+ if (!demux_stream_is_selected(stream))
return 0;
if (demux_mkv_read_block_lacing(&data, &laces, lace_size)) {
@@ -2445,7 +2426,7 @@ static int handle_block(demuxer_t *demuxer, struct block_info *block_info)
if (track->ms_compat)
MPSWAP(double, dp->pts, dp->dts);
dp->duration = block_duration / 1e9;
- demuxer_add_packet(demuxer, stream, dp);
+ demux_add_packet(stream, dp);
}
talloc_free_children(track->parser_tmp);
}
@@ -2725,7 +2706,7 @@ static struct mkv_index *seek_with_cues(struct demuxer *demuxer, int seek_id,
return index;
}
-static void demux_mkv_seek(demuxer_t *demuxer, float rel_seek_secs, int flags)
+static void demux_mkv_seek(demuxer_t *demuxer, double rel_seek_secs, int flags)
{
mkv_demuxer_t *mkv_d = demuxer->priv;
int64_t old_pos = stream_tell(demuxer->stream);
@@ -2735,7 +2716,7 @@ static void demux_mkv_seek(demuxer_t *demuxer, float rel_seek_secs, int flags)
mkv_seek_reset(demuxer);
for (int i = 0; i < mkv_d->num_tracks; i++) {
mkv_track_t *track = mkv_d->tracks[i];
- if (demuxer_stream_is_selected(demuxer, track->stream)) {
+ if (demux_stream_is_selected(track->stream)) {
st_active[track->stream->type] = true;
if (track->type == MATROSKA_TRACK_VIDEO)
v_tnum = track->tnum;
diff --git a/demux/demux_playlist.c b/demux/demux_playlist.c
index b2344b5..9f533e1 100644
--- a/demux/demux_playlist.c
+++ b/demux/demux_playlist.c
@@ -15,6 +15,8 @@
* with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
+#include <strings.h>
+
#include "common/common.h"
#include "options/options.h"
#include "common/msg.h"
diff --git a/demux/demux_raw.c b/demux/demux_raw.c
index 888b7ec..4388900 100644
--- a/demux/demux_raw.c
+++ b/demux/demux_raw.c
@@ -232,12 +232,12 @@ static int raw_fill_buffer(demuxer_t *demuxer)
int len = stream_read(demuxer->stream, dp->buffer, dp->len);
demux_packet_shorten(dp, len);
- demuxer_add_packet(demuxer, demuxer->streams[0], dp);
+ demux_add_packet(demuxer->streams[0], dp);
return 1;
}
-static void raw_seek(demuxer_t *demuxer, float rel_seek_secs, int flags)
+static void raw_seek(demuxer_t *demuxer, double rel_seek_secs, int flags)
{
struct priv *p = demuxer->priv;
stream_t *s = demuxer->stream;
diff --git a/demux/demux_subreader.c b/demux/demux_subreader.c
index d3a792c..f6454aa 100644
--- a/demux/demux_subreader.c
+++ b/demux/demux_subreader.c
@@ -26,7 +26,6 @@
#include <string.h>
#include <sys/types.h>
#include <dirent.h>
-#include <ctype.h>
#include <libavutil/common.h>
#include <libavutil/avstring.h>
@@ -112,6 +111,55 @@ struct readline_args {
/* Maximal length of line of a subtitle */
#define LINE_LEN 1000
+static double demux_packet_list_duration(struct demux_packet **pkts, int num_pkts)
+{
+ if (num_pkts > 0)
+ return pkts[num_pkts - 1]->pts + pkts[num_pkts - 1]->duration;
+ return 0;
+}
+
+static void demux_packet_list_seek(struct demux_packet **pkts, int num_pkts,
+ int *current, double rel_seek_secs, int flags)
+{
+ double ref_time = 0;
+ if (*current >= 0 && *current < num_pkts) {
+ ref_time = pkts[*current]->pts;
+ } else if (*current == num_pkts && num_pkts > 0) {
+ ref_time = pkts[num_pkts - 1]->pts + pkts[num_pkts - 1]->duration;
+ }
+
+ if (flags & SEEK_ABSOLUTE)
+ ref_time = 0;
+
+ if (flags & SEEK_FACTOR) {
+ ref_time += demux_packet_list_duration(pkts, num_pkts) * rel_seek_secs;
+ } else {
+ ref_time += rel_seek_secs;
+ }
+
+ // Could do binary search, but it's probably not worth the complexity.
+ int last_index = 0;
+ for (int n = 0; n < num_pkts; n++) {
+ if (pkts[n]->pts > ref_time)
+ break;
+ last_index = n;
+ }
+ *current = last_index;
+}
+
+static struct demux_packet *demux_packet_list_fill(struct demux_packet **pkts,
+ int num_pkts, int *current)
+{
+ if (*current < 0)
+ *current = 0;
+ if (*current >= num_pkts)
+ return NULL;
+ struct demux_packet *new = talloc(NULL, struct demux_packet);
+ *new = *pkts[*current];
+ *current += 1;
+ return new;
+}
+
static int eol(char p) {
return p=='\r' || p=='\n' || p=='\0';
}
@@ -752,10 +800,10 @@ static int d_fill_buffer(struct demuxer *demuxer)
struct priv *p = demuxer->priv;
struct demux_packet *dp = demux_packet_list_fill(p->pkts, p->num_pkts,
&p->current);
- return demuxer_add_packet(demuxer, p->sh, dp);
+ return demux_add_packet(p->sh, dp);
}
-static void d_seek(struct demuxer *demuxer, float secs, int flags)
+static void d_seek(struct demuxer *demuxer, double secs, int flags)
{
struct priv *p = demuxer->priv;
demux_packet_list_seek(p->pkts, p->num_pkts, &p->current, secs, flags);
diff --git a/demux/demux_tv.c b/demux/demux_tv.c
new file mode 100644
index 0000000..f0ee979
--- /dev/null
+++ b/demux/demux_tv.c
@@ -0,0 +1,249 @@
+#include <assert.h>
+
+#include "common/common.h"
+#include "common/msg.h"
+
+#include "options/m_option.h"
+#include "options/m_config.h"
+#include "options/options.h"
+
+#include "demux.h"
+
+#include "audio/format.h"
+#include "video/img_fourcc.h"
+
+#include "stream/stream.h"
+#include "stream/tv.h"
+
+static int demux_open_tv(demuxer_t *demuxer, enum demux_check check)
+{
+ tvi_handle_t *tvh;
+ sh_video_t *sh_video;
+ sh_audio_t *sh_audio = NULL;
+ const tvi_functions_t *funcs;
+
+ if (check > DEMUX_CHECK_REQUEST || demuxer->stream->type != STREAMTYPE_TV)
+ return -1;
+
+ tv_param_t *params = m_sub_options_copy(demuxer, &tv_params_conf,
+ demuxer->opts->tv_params);
+ struct tv_stream_params *sparams = demuxer->stream->priv;
+ if (sparams->channel && sparams->channel[0]) {
+ talloc_free(params->channel);
+ params->channel = talloc_strdup(NULL, sparams->channel);
+ }
+ if (sparams->input >= 0)
+ params->input = sparams->input;
+
+ assert(demuxer->priv==NULL);
+ if(!(tvh=tv_begin(params, demuxer->log))) return -1;
+ if (!tvh->functions->init(tvh->priv)) return -1;
+
+ tvh->demuxer = demuxer;
+
+ if (!open_tv(tvh)){
+ tv_uninit(tvh);
+ return -1;
+ }
+ funcs = tvh->functions;
+ demuxer->priv=tvh;
+
+ struct sh_stream *sh_v = new_sh_stream(demuxer, STREAM_VIDEO);
+ sh_video = sh_v->video;
+
+ /* get IMAGE FORMAT */
+ int fourcc;
+ funcs->control(tvh->priv, TVI_CONTROL_VID_GET_FORMAT, &fourcc);
+ if (fourcc == MP_FOURCC_MJPEG) {
+ sh_v->codec = "mjpeg";
+ } else {
+ sh_v->codec = "rawvideo";
+ sh_v->format = fourcc;
+ }
+
+ /* set FPS and FRAMETIME */
+
+ if(!sh_video->fps)
+ {
+ float tmp;
+ if (funcs->control(tvh->priv, TVI_CONTROL_VID_GET_FPS, &tmp) != TVI_CONTROL_TRUE)
+ sh_video->fps = 25.0f; /* on PAL */
+ else sh_video->fps = tmp;
+ }
+
+ if (tvh->tv_param->fps != -1.0f)
+ sh_video->fps = tvh->tv_param->fps;
+
+ /* If playback only mode, go to immediate mode, fail silently */
+ if(tvh->tv_param->immediate == 1)
+ {
+ funcs->control(tvh->priv, TVI_CONTROL_IMMEDIATE, 0);
+ tvh->tv_param->audio = 0;
+ }
+
+ /* set width */
+ funcs->control(tvh->priv, TVI_CONTROL_VID_GET_WIDTH, &sh_video->disp_w);
+
+ /* set height */
+ funcs->control(tvh->priv, TVI_CONTROL_VID_GET_HEIGHT, &sh_video->disp_h);
+
+ demuxer->seekable = 0;
+
+ /* here comes audio init */
+ if (tvh->tv_param->audio && funcs->control(tvh->priv, TVI_CONTROL_IS_AUDIO, 0) == TVI_CONTROL_TRUE)
+ {
+ int audio_format;
+
+ /* yeah, audio is present */
+
+ funcs->control(tvh->priv, TVI_CONTROL_AUD_SET_SAMPLERATE,
+ &tvh->tv_param->audiorate);
+
+ if (funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_FORMAT, &audio_format) != TVI_CONTROL_TRUE)
+ goto no_audio;
+
+ switch(audio_format)
+ {
+ case AF_FORMAT_U8:
+ case AF_FORMAT_S8:
+ case AF_FORMAT_U16_LE:
+ case AF_FORMAT_U16_BE:
+ case AF_FORMAT_S16_LE:
+ case AF_FORMAT_S16_BE:
+ case AF_FORMAT_S32_LE:
+ case AF_FORMAT_S32_BE:
+ break;
+ case AF_FORMAT_MPEG2:
+ default:
+ MP_ERR(tvh, "Audio type '%s' unsupported!\n",
+ af_fmt_to_str(audio_format));
+ goto no_audio;
+ }
+
+ struct sh_stream *sh_a = new_sh_stream(demuxer, STREAM_AUDIO);
+ sh_audio = sh_a->audio;
+
+ funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_SAMPLERATE,
+ &sh_audio->samplerate);
+ int nchannels = sh_audio->channels.num;
+ funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_CHANNELS,
+ &nchannels);
+ mp_chmap_from_channels(&sh_audio->channels, nchannels);
+
+ sh_a->codec = "mp-pcm";
+ sh_a->format = audio_format;
+
+ int samplesize = af_fmt2bps(audio_format);
+ int block_align = samplesize * sh_audio->channels.num;
+ int bytes_per_second = sh_audio->samplerate * block_align;
+
+ sh_audio->bitrate = bytes_per_second * 8;
+
+ // emulate WF for win32 codecs:
+ sh_audio->wf = talloc_zero(sh_audio, MP_WAVEFORMATEX);
+ sh_audio->wf->wFormatTag = sh_a->format;
+ sh_audio->wf->nChannels = sh_audio->channels.num;
+ sh_audio->wf->wBitsPerSample = samplesize * 8;
+ sh_audio->wf->nSamplesPerSec = sh_audio->samplerate;
+ sh_audio->wf->nBlockAlign = block_align;
+ sh_audio->wf->nAvgBytesPerSec = bytes_per_second;
+
+ MP_VERBOSE(tvh, " TV audio: %d channels, %d bits, %d Hz\n",
+ sh_audio->wf->nChannels, sh_audio->wf->wBitsPerSample,
+ sh_audio->wf->nSamplesPerSec);
+ }
+no_audio:
+
+ if(!(funcs->start(tvh->priv))){
+ // start failed :(
+ tv_uninit(tvh);
+ return -1;
+ }
+
+ /* set color eq */
+ tv_set_color_options(tvh, TV_COLOR_BRIGHTNESS, tvh->tv_param->brightness);
+ tv_set_color_options(tvh, TV_COLOR_HUE, tvh->tv_param->hue);
+ tv_set_color_options(tvh, TV_COLOR_SATURATION, tvh->tv_param->saturation);
+ tv_set_color_options(tvh, TV_COLOR_CONTRAST, tvh->tv_param->contrast);
+
+ if(tvh->tv_param->gain!=-1)
+ if(funcs->control(tvh->priv,TVI_CONTROL_VID_SET_GAIN,&tvh->tv_param->gain)!=TVI_CONTROL_TRUE)
+ MP_WARN(tvh, "Unable to set gain control!\n");
+
+ return 0;
+}
+
+static void demux_close_tv(demuxer_t *demuxer)
+{
+ tvi_handle_t *tvh=(tvi_handle_t*)(demuxer->priv);
+ if (!tvh) return;
+ tv_uninit(tvh);
+ free(tvh);
+ demuxer->priv=NULL;
+}
+
+static int demux_tv_fill_buffer(demuxer_t *demux)
+{
+ tvi_handle_t *tvh=(tvi_handle_t*)(demux->priv);
+ demux_packet_t* dp;
+ unsigned int len=0;
+ struct sh_stream *want_audio = NULL, *want_video = NULL;
+
+ for (int n = 0; n < demux->num_streams; n++) {
+ struct sh_stream *sh = demux->streams[n];
+ if (!demux_has_packet(sh) && demux_stream_is_selected(sh)) {
+ if (sh->type == STREAM_AUDIO)
+ want_audio = sh;
+ if (sh->type == STREAM_VIDEO)
+ want_video = sh;
+ }
+ }
+
+ /* ================== ADD AUDIO PACKET =================== */
+
+ if (want_audio && tvh->tv_param->audio &&
+ tvh->functions->control(tvh->priv,
+ TVI_CONTROL_IS_AUDIO, 0) == TVI_CONTROL_TRUE)
+ {
+ len = tvh->functions->get_audio_framesize(tvh->priv);
+
+ dp=new_demux_packet(len);
+ dp->keyframe = true;
+ dp->pts=tvh->functions->grab_audio_frame(tvh->priv, dp->buffer,len);
+ demux_add_packet(want_audio, dp);
+ }
+
+ /* ================== ADD VIDEO PACKET =================== */
+
+ if (want_video && tvh->functions->control(tvh->priv,
+ TVI_CONTROL_IS_VIDEO, 0) == TVI_CONTROL_TRUE)
+ {
+ len = tvh->functions->get_video_framesize(tvh->priv);
+ dp=new_demux_packet(len);
+ dp->keyframe = true;
+ dp->pts=tvh->functions->grab_video_frame(tvh->priv, dp->buffer, len);
+ demux_add_packet(want_video, dp);
+ }
+
+ if (tvh->tv_param->scan) tv_scan(tvh);
+ return 1;
+}
+
+static int demux_tv_control(demuxer_t *demuxer, int cmd, void *arg)
+{
+ tvi_handle_t *tvh=(tvi_handle_t*)(demuxer->priv);
+ if (cmd != DEMUXER_CTRL_STREAM_CTRL)
+ return DEMUXER_CTRL_NOTIMPL;
+ struct demux_ctrl_stream_ctrl *ctrl = arg;
+ ctrl->res = tv_stream_control(tvh, ctrl->ctrl, ctrl->arg);
+ return DEMUXER_CTRL_OK;
+}
+
+const demuxer_desc_t demuxer_desc_tv = {
+ .name = "tv",
+ .desc = "TV card demuxer",
+ .fill_buffer = demux_tv_fill_buffer,
+ .control = demux_tv_control,
+ .open = demux_open_tv,
+ .close = demux_close_tv,
+};
diff --git a/demux/ebml.c b/demux/ebml.c
index 1d0473a..7e79ee0 100644
--- a/demux/ebml.c
+++ b/demux/ebml.c
@@ -37,10 +37,6 @@
#include "compat/mpbswap.h"
#include "common/msg.h"
-#ifndef SIZE_MAX
-#define SIZE_MAX ((size_t)-1)
-#endif
-
// Whether the id is a known Matroska level 1 element (allowed as element on
// global file level, after the level 0 MATROSKA_ID_SEGMENT).
// This (intentionally) doesn't include "global" elements.
@@ -413,8 +409,7 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target,
continue;
past_end_error:
- MP_DBG(ctx, "Subelement headers go "
- "past end of containing element\n");
+ MP_DBG(ctx, "Subelement headers go past end of containing element\n");
other_error:
ctx->has_errors = true;
end = startp;
@@ -536,8 +531,7 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target,
subelptr = (fieldtype *) fieldptr
GETPTR(uintptr, uint64_t);
if (length < 1 || length > 8) {
- MP_DBG(ctx, "uint invalid length %"PRIu64
- "\n", length);
+ MP_DBG(ctx, "uint invalid length %"PRIu64"\n", length);
goto error;
}
*uintptr = ebml_parse_uint(data, length);
@@ -548,8 +542,7 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target,
int64_t *sintptr;
GETPTR(sintptr, int64_t);
if (length < 1 || length > 8) {
- MP_DBG(ctx, "sint invalid length %"PRIu64
- "\n", length);
+ MP_DBG(ctx, "sint invalid length %"PRIu64"\n", length);
goto error;
}
*sintptr = ebml_parse_sint(data, length);
@@ -560,8 +553,7 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target,
double *floatptr;
GETPTR(floatptr, double);
if (length != 4 && length != 8) {
- MP_DBG(ctx, "float invalid length %"PRIu64
- "\n", length);
+ MP_DBG(ctx, "float invalid length %"PRIu64"\n", length);
goto error;
}
*floatptr = ebml_parse_float(data, length);
@@ -579,11 +571,9 @@ static void ebml_parse_element(struct ebml_parse_ctx *ctx, void *target,
strptr->start = data;
strptr->len = length;
if (ed->type == EBML_TYPE_STR)
- MP_DBG(ctx, "string \"%.*s\"\n",
- BSTR_P(*strptr));
+ MP_DBG(ctx, "string \"%.*s\"\n", BSTR_P(*strptr));
else
- MP_DBG(ctx, "binary %zd bytes\n",
- strptr->len);
+ MP_DBG(ctx, "binary %zd bytes\n", strptr->len);
break;
case EBML_TYPE_EBML_ID:;
diff --git a/demux/ebml.h b/demux/ebml.h
index 5a0af48..a544ad4 100644
--- a/demux/ebml.h
+++ b/demux/ebml.h
@@ -28,7 +28,6 @@
struct mp_log;
-
/* EBML version supported */
#define EBML_VERSION 1
@@ -69,7 +68,6 @@ struct ebml_parse_ctx {
#define EBML_ID_INVALID 0xffffffff
-
/* matroska track types */
#define MATROSKA_TRACK_VIDEO 0x01 /* rectangle-shaped pictures aka video */
#define MATROSKA_TRACK_AUDIO 0x02 /* anything you can hear */
@@ -78,18 +76,8 @@ struct ebml_parse_ctx {
#define MATROSKA_TRACK_SUBTITLE 0x11 /* text-subtitles */
#define MATROSKA_TRACK_CONTROL 0x20 /* control-codes for menu or other stuff*/
-#ifndef UINT64_MAX
-#define UINT64_MAX 18446744073709551615ULL
-#endif
-
-#ifndef INT64_MAX
-#define INT64_MAX 9223372036854775807LL
-#endif
-
#define EBML_UINT_INVALID UINT64_MAX
#define EBML_INT_INVALID INT64_MAX
-#define EBML_FLOAT_INVALID -1000000000.0
-
bool ebml_is_mkv_level1_id(uint32_t id);
uint32_t ebml_read_id (stream_t *s);
diff --git a/demux/mf.c b/demux/mf.c
index 5edc980..d687c3c 100644
--- a/demux/mf.c
+++ b/demux/mf.c
@@ -16,7 +16,6 @@
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
-#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -30,6 +29,7 @@
#include "talloc.h"
#include "common/msg.h"
#include "stream/stream.h"
+#include "misc/ctype.h"
#include "options/path.h"
#include "mf.h"
@@ -55,7 +55,7 @@ mf_t *open_mf_pattern(void *talloc_ctx, struct mp_log *log, char *filename)
while (fgets(fname, 512, lst_f)) {
/* remove spaces from end of fname */
char *t = fname + strlen(fname) - 1;
- while (t > fname && isspace((unsigned char)*t))
+ while (t > fname && mp_isspace(*t))
*(t--) = 0;
if (!mp_path_exists(fname)) {
mp_verbose(log, "file not found: '%s'\n", fname);
diff --git a/demux/packet.c b/demux/packet.c
new file mode 100644
index 0000000..77ea78f
--- /dev/null
+++ b/demux/packet.c
@@ -0,0 +1,122 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv 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.
+ *
+ * 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+#include <stdlib.h>
+#include <stdio.h>
+#include <string.h>
+#include <assert.h>
+
+#include <libavcodec/avcodec.h>
+
+#include "common/av_common.h"
+#include "common/common.h"
+
+#include "packet.h"
+
+static void packet_destroy(void *ptr)
+{
+ struct demux_packet *dp = ptr;
+ talloc_free(dp->avpacket);
+ av_free(dp->allocation);
+}
+
+static struct demux_packet *create_packet(size_t len)
+{
+ if (len > 1000000000) {
+ fprintf(stderr, "Attempt to allocate demux packet over 1 GB!\n");
+ abort();
+ }
+ struct demux_packet *dp = talloc(NULL, struct demux_packet);
+ talloc_set_destructor(dp, packet_destroy);
+ *dp = (struct demux_packet) {
+ .len = len,
+ .pts = MP_NOPTS_VALUE,
+ .dts = MP_NOPTS_VALUE,
+ .duration = -1,
+ .pos = -1,
+ .stream = -1,
+ };
+ return dp;
+}
+
+struct demux_packet *new_demux_packet(size_t len)
+{
+ struct demux_packet *dp = create_packet(len);
+ dp->buffer = av_malloc(len + FF_INPUT_BUFFER_PADDING_SIZE);
+ if (!dp->buffer) {
+ fprintf(stderr, "Memory allocation failure!\n");
+ abort();
+ }
+ memset(dp->buffer + len, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+ dp->allocation = dp->buffer;
+ return dp;
+}
+
+// data must already have suitable padding, and does not copy the data
+struct demux_packet *new_demux_packet_fromdata(void *data, size_t len)
+{
+ struct demux_packet *dp = create_packet(len);
+ dp->buffer = data;
+ return dp;
+}
+
+struct demux_packet *new_demux_packet_from(void *data, size_t len)
+{
+ struct demux_packet *dp = new_demux_packet(len);
+ memcpy(dp->buffer, data, len);
+ return dp;
+}
+
+void demux_packet_shorten(struct demux_packet *dp, size_t len)
+{
+ assert(len <= dp->len);
+ dp->len = len;
+ memset(dp->buffer + dp->len, 0, FF_INPUT_BUFFER_PADDING_SIZE);
+}
+
+void free_demux_packet(struct demux_packet *dp)
+{
+ talloc_free(dp);
+}
+
+static void destroy_avpacket(void *pkt)
+{
+ av_free_packet(pkt);
+}
+
+struct demux_packet *demux_copy_packet(struct demux_packet *dp)
+{
+ struct demux_packet *new = NULL;
+ if (dp->avpacket) {
+ assert(dp->buffer == dp->avpacket->data);
+ assert(dp->len == dp->avpacket->size);
+ AVPacket *newavp = talloc_zero(NULL, AVPacket);
+ talloc_set_destructor(newavp, destroy_avpacket);
+ av_init_packet(newavp);
+ if (av_packet_ref(newavp, dp->avpacket) < 0)
+ abort();
+ new = new_demux_packet_fromdata(newavp->data, newavp->size);
+ new->avpacket = newavp;
+ }
+ if (!new) {
+ new = new_demux_packet(dp->len);
+ memcpy(new->buffer, dp->buffer, new->len);
+ }
+ new->pts = dp->pts;
+ new->dts = dp->dts;
+ new->duration = dp->duration;
+ return new;
+}
diff --git a/demux/packet.h b/demux/packet.h
index ca57179..21c0a6d 100644
--- a/demux/packet.h
+++ b/demux/packet.h
@@ -20,6 +20,7 @@
#define MPLAYER_DEMUX_PACKET_H
#include <stdbool.h>
+#include <stddef.h>
#include <inttypes.h>
// Holds one packet/frame/whatever
@@ -28,7 +29,6 @@ typedef struct demux_packet {
double pts;
double dts;
double duration;
- double stream_pts;
int64_t pos; // position in source file byte stream
unsigned char *buffer;
bool keyframe;
@@ -38,4 +38,12 @@ typedef struct demux_packet {
struct AVPacket *avpacket; // original libavformat packet (demux_lavf)
} demux_packet_t;
+struct demux_packet *new_demux_packet(size_t len);
+// data must already have suitable padding
+struct demux_packet *new_demux_packet_fromdata(void *data, size_t len);
+struct demux_packet *new_demux_packet_from(void *data, size_t len);
+void demux_packet_shorten(struct demux_packet *dp, size_t len);
+void free_demux_packet(struct demux_packet *dp);
+struct demux_packet *demux_copy_packet(struct demux_packet *dp);
+
#endif /* MPLAYER_DEMUX_PACKET_H */
diff --git a/demux/stheader.h b/demux/stheader.h
index 101c75e..082fffa 100644
--- a/demux/stheader.h
+++ b/demux/stheader.h
@@ -31,7 +31,6 @@ struct demuxer;
struct sh_stream {
enum stream_type type;
- struct demuxer *demuxer;
// Index into demuxer->streams.
int index;
// Demuxer/format specific ID. Corresponds to the stream IDs as encoded in
@@ -73,6 +72,7 @@ typedef struct sh_audio {
// note codec extradata may be either under "wf" or "codecdata"
unsigned char *codecdata;
int codecdata_len;
+ struct replaygain_data *replaygain_data;
} sh_audio_t;
typedef struct sh_video {
diff --git a/etc/example.conf b/etc/example.conf
index dfdbd08..cf9089f 100644
--- a/etc/example.conf
+++ b/etc/example.conf
@@ -2,7 +2,7 @@
# mpv configuration file
#
# Configuration files are read system-wide from /usr/local/etc/mpv.conf
-# and per-user from ~/.mpv/config, where per-user settings override
+# and per-user from ~/.config/mpv/mpv.conf, where per-user settings override
# system-wide settings, all of which are overridden by the command line.
#
# Configuration file settings and the command line options use the same
@@ -80,11 +80,17 @@
# Use 8MB input cache for everything, even local files.
#cache=8192
#
-# Prefill 20% of the cache before starting playback.
-#cache-min=20.0
+# If a seek is issued, and the target is 1024KB past the cached range, then
+# keep reading until the seek target is hit, instead of doing a real seek.
+#cache-seek-min=1024
#
-# Prefill 50% of the cache before restarting playback after the cache emptied.
-#cache-seek-min=50
+# Disable the behavior that the player will pause if the cache goes below a
+# certain fill size.
+#cache-pause-below=no
+#
+# Enable demuxer-based cache. This reads ahead a number of packets, and the
+# player won't freeze completely if network is slow during playback.
+#demuxer-thread=yes
# Display English subtitles if available.
#slang=en
diff --git a/etc/input.conf b/etc/input.conf
index 08988a2..a602179 100644
--- a/etc/input.conf
+++ b/etc/input.conf
@@ -1,43 +1,29 @@
-# mpv input control file
+# mpv keybindings
#
-# You are able to redefine default keyboard/joystick/mouse/LIRC bindings, or
-# add new ones here.
-# See DOCS/man/input.rst for possible commands that can be bound.
-# Also see mpv --input-cmdlist for other possible options.
-# The file should be placed in the $HOME/.mpv directory.
+# Location of user-defined bindings: ~/.config/mpv/input.conf
#
-# mpv --input-test --force-window --idle can be used to test which commands
-# keys are bound to.
-#
-# If you wish to unbind a key, bind it to the 'ignore' command:
-# KEY ignore
+# Lines starting with # are comments. Use SHARP to assign the # key.
+# Copy this file and uncomment and edit the bindings you want to change.
#
-# Note that merely removing default key bindings from this file won't remove
-# the default bindings mpv was compiled with, unless
-# --no-input-default-bindings
-# is specified.
+# List of commands and further details: DOCS/man/input.rst
+# List of special keys: --input-keylist
+# Keybindings testing mode: mpv --input-test --force-window --idle
#
-# Lines starting with # are comments. Use SHARP to assign the # key.
+# Use 'ignore' to unbind a key fully (e.g. 'ctrl+a ignore').
#
# Strings need to be quoted and escaped:
# KEY show_text "This is a single backslash: \\ and a quote: \" !"
#
# You can use modifier-key combinations like Shift+Left or Ctrl+Alt+x with
-# modifiers Shift, Ctrl, Alt and Meta, but note that currently reading
-# key combinations is only supported through the video windows of certain
-# output drivers (not in output windows of other drivers or in a terminal).
-
-# All lines in this file are commented. If you want to remap a key, copy the
-# file to ~/.mpv/input.conf, and uncomment and edit the binding you want to
-# change.
+# the modifiers Shift, Ctrl, Alt and Meta (may not work on the terminal).
+#
+# The default keybindings are hardcoded into the mpv binary.
+# You can disable them completely with: --no-input-default-bindings
# Developer note:
-# etc/input.conf from the mpv source tree is baked into the mpv binary, with
-# all entries magically uncommented and parsed on initialization. Thus, this
-# file defines the mpv default key bindings. If this file is read as normal
-# config file, all lines starting with '#' are treated as comments (and this
-# file, if unedited, doesn't define any bindings).
-# Lines that have a space after the '#' are always ignored as real comments.
+# On compilation, this file is baked into the mpv binary, and all lines are
+# uncommented (unless '#' is followed by a space) - thus this file defines the
+# default key bindings.
# If this is enabled, treat all the following bindings as default.
#default-bindings start
@@ -59,8 +45,8 @@
#AXIS_RIGHT seek -5
## Seek units are in seconds, but note that these are limited by keyframes
-#RIGHT seek 10
-#LEFT seek -10
+#RIGHT seek 5
+#LEFT seek -5
#UP seek 60
#DOWN seek -60
# Do smaller, always exact (non-keyframe-limited), seeks with shift.
@@ -69,10 +55,10 @@
#Shift+LEFT no-osd seek -1 - exact
#Shift+UP no-osd seek 5 - exact
#Shift+DOWN no-osd seek -5 - exact
-#PGUP seek 600
-#PGDWN seek -600
-#+ add audio-delay 0.100 # this changes audio/video sync
-#- add audio-delay -0.100
+#PGUP add chapter 1 # skip to next chapter
+#PGDWN add chapter -1 # skip to previous chapter
+#Shift+PGUP seek 600
+#Shift+PGDWN seek -600
#[ multiply speed 0.9091 # scale playback speed
#] multiply speed 1.1
#{ multiply speed 0.5
@@ -90,17 +76,18 @@
#> playlist_next # skip to next file
#ENTER playlist_next force # skip to next file or quit
#< playlist_prev # skip to previous file
-#o osd # cycle through OSD mode
-#I show_text "${filename}" # display filename in osd
+#O osd # cycle through OSD mode
+#o show_progress
#P show_progress
+#I show_text "${filename}" # display filename in osd
#z add sub-delay -0.1 # subtract 100 ms delay from subs
#x add sub-delay +0.1 # add
+#ctrl++ add audio-delay 0.100 # this changes audio/video sync
+#ctrl+- add audio-delay -0.100
#9 add volume -1
#/ add volume -1
#0 add volume 1
#* add volume 1
-#( add balance -0.1 # adjust audio balance in favor of left
-#) add balance 0.1 # right
#m cycle mute
#1 add contrast -1
#2 add contrast 1
@@ -111,10 +98,8 @@
#7 add saturation -1
#8 add saturation 1
#d cycle framedrop # cycle through framedrop modes
-# toggle deinterlacer; requires either vdpau output, -vf yadif or kerndeint
+# toggle deinterlacer (automatically inserts or removes required filter)
#D cycle deinterlace
-#c cycle colormatrix
-# Next 3 currently only work with --no-ass
#r add sub-pos -1 # move subtitles up
#t add sub-pos +1 # down
#v cycle sub-visibility
@@ -122,10 +107,8 @@
#V cycle ass-vsfilter-aspect-compat
#j cycle sub # cycle through subtitles
#J cycle sub down # ...backwards
-#F cycle sub-forced-only
#SHARP cycle audio # switch audio streams
#_ cycle video
-#TAB cycle program
#T cycle ontop # toggle video window ontop of other windows
#f cycle fullscreen # toggle fullscreen
#s screenshot # take a screenshot
@@ -148,14 +131,7 @@
#MUTE cycle mute
#CLOSE_WIN quit
#CLOSE_WIN {encode} quit
-#! add chapter -1 # skip to previous chapter
-#@ add chapter 1 # next
#E cycle edition # next edition
-#A cycle angle
-#U stop
-
-#l cycle quvi-format 1
-#L cycle quvi-format -1
# Apple Remote section
#AR_PLAY cycle pause
@@ -206,6 +182,12 @@
#k cycle tv-channel +1 # next channel
#
+# Legacy bindings (may or may not be removed in the future)
+#
+#! add chapter -1 # skip to previous chapter
+#@ add chapter 1 # next
+
+#
# Not assigned by default
# (not an exhaustive list of unbound commands)
#
@@ -215,3 +197,14 @@
# ? sub_step -1 # immediately display next subtitle
# ? sub_step +1 # previous
# ? cycle_values window-scale 0.5 2 1 # switch between 1/2, 2x, unresized window size
+# ? cycle colormatrix
+# ? add audio-delay 0.100 # this changes audio/video sync
+# ? add audio-delay -0.100
+# ? cycle angle # switch DVD/Bluray angle
+# ? add balance -0.1 # adjust audio balance in favor of left
+# ? add balance 0.1 # right
+# ? cycle sub-forced-only # toggle DVD forced subs
+# ? cycle program # cycle transport stream programs
+# ? stop # stop playback (quit or enter idle mode)
+# ? cycle quvi-format 1 # cycle streaming video quality (semi-broken)
+# ? cycle quvi-format -1
diff --git a/etc/mplayer-input.conf b/etc/mplayer-input.conf
new file mode 100644
index 0000000..c898ccb
--- /dev/null
+++ b/etc/mplayer-input.conf
@@ -0,0 +1,153 @@
+##
+## MPlayer-style key bindings
+##
+## Save it as ~/.config/input.conf to use it.
+##
+## Generally, it's recommended to use this as reference-only.
+##
+
+RIGHT seek +10
+LEFT seek -10
+DOWN seek -60
+UP seek +60
+PGUP seek 600
+PGDWN seek -600
+m cycle mute
+# cycle audio # switch audio streams
++ add audio-delay 0.100
+= add audio-delay 0.100
+- add audio-delay -0.100
+[ multiply speed 0.9091 # scale playback speed
+] multiply speed 1.1
+{ multiply speed 0.5
+} multiply speed 2.0
+BS set speed 1.0 # reset speed to normal
+q quit
+ESC quit
+ENTER playlist_next force # skip to next file
+p cycle pause
+. frame_step # advance one frame and pause
+SPACE cycle pause
+HOME set playlist-pos 1 # not the same as MPlayer
+#END pt_up_step -1
+> playlist_next # skip to next file
+< playlist_prev # previous
+#INS alt_src_step 1
+#DEL alt_src_step -1
+o osd
+I show_text "${filename}" # display filename in osd
+P show_progress
+z add sub-delay -0.1 # subtract 100 ms delay from subs
+x add sub-delay +0.1 # add
+9 add volume -1
+/ add volume -1
+0 add volume 1
+* add volume 1
+1 add contrast -1
+2 add contrast 1
+3 add brightness -1
+4 add brightness 1
+5 add hue -1
+6 add hue 1
+7 add saturation -1
+8 add saturation 1
+( add balance -0.1 # adjust audio balance in favor of left
+) add balance +0.1 # right
+d cycle framedrop
+D cycle deinterlace # toggle deinterlacer (auto-inserted filter)
+r add sub-pos -1 # move subtitles up
+t add sub-pos +1 # down
+#? sub_step +1 # immediately display next subtitle
+#? sub_step -1 # previous
+#? add sub-scale +0.1 # increase subtitle font size
+#? add sub-scale -0.1 # decrease subtitle font size
+f cycle fullscreen
+T cycle ontop # toggle video window ontop of other windows
+w add panscan -0.1 # zoom out with -panscan 0 -fs
+e add panscan +0.1 # in
+c cycle stream-capture # save (and append) file/stream to stream.dump with -capture
+s screenshot # take a screenshot (if you want PNG, use "--screenshot-format=png")
+S screenshot - each-frame # S will take a png screenshot of every frame
+
+h cycle tv-channel 1
+l cycle tv-channel -1
+n cycle tv-norm
+#b tv_step_chanlist
+
+##
+## Joystick section
+## WARNING: joystick support has to be explicitly enabled at
+## compiletime with --enable-joystick
+##
+
+JOY_RIGHT seek 10
+JOY_LEFT seek -10
+JOY_UP seek 60
+JOY_DOWN seek -60
+JOY_BTN0 cycle pause
+JOY_BTN1 osd
+JOY_BTN2 add volume 1
+JOY_BTN3 add volume -1
+#JOY_BTN4 set_menu main
+
+##
+## Apple Remote section
+##
+## To use OSD menu with Apple Remote, set key AR_MENU to any OSD menu command,
+## or just comment out the 'AR_MENU osd' line and uncomment the line after it.
+##
+
+AR_PLAY cycle pause
+AR_PLAY_HOLD quit
+AR_NEXT seek 30
+AR_NEXT_HOLD seek 120
+AR_PREV seek -10
+AR_PREV_HOLD seek -120
+#AR_MENU menu up
+#AR_MENU menu cancel
+AR_MENU_HOLD cycle mute
+AR_VUP add volume 1
+AR_VDOWN add volume -1
+
+##
+## DVD and Bluray menus
+##
+## Unlike MPlayer, input doesn't require blocking normal keys when no menu
+## is active. The "discnav-menu" input section is active only when a menu
+## is shown, while "discnav" is always active when a DVD/Bluray is played.
+##
+## The bindings were adjusted according to this.
+##
+
+UP {discnav-menu} discnav up # DVDNav UP
+DOWN {discnav-menu} discnav down # DVDNav DOWN
+LEFT {discnav-menu} discnav left # DVDNav LEFT
+RIGHT {discnav-menu} discnav right # DVDNav RIGHT
+ESC {discnav} discnav menu # DVDNav MENU
+ENTER {discnav-menu} discnav select # DVDNav SELECT (ok)
+BS {discnav-menu} discnav prev # DVDNav PREVIOUS menu (in the order chapter->title->root)
+
+AR_VUP {discnav-menu} discnav up # DVDNav UP
+AR_VDOWN {discnav-menu} discnav down # DVDNav DOWN
+AR_PREV {discnav-menu} discnav left # DVDNav LEFT
+AR_NEXT {discnav-menu} discnav right # DVDNav RIGHT
+AR_MENU {discnav} discnav menu # DVDNav MENU
+AR_PLAY {discnav-menu} discnav select # DVDNav SELECT (ok)
+
+#? add chapter -1 # skip to previous dvd chapter
+#? add chapter +1 # next
+
+##
+## Advanced seek
+## Uncomment the following lines to be able to seek to n% of the media with
+## the Fx keys.
+##
+#F1 seek 10 absolute-percent
+#F2 seek 20 absolute-percent
+#F3 seek 30 absolute-percent
+#F4 seek 40 absolute-percent
+#F5 seek 50 absolute-percent
+#F6 seek 60 absolute-percent
+#F7 seek 70 absolute-percent
+#F8 seek 80 absolute-percent
+#F9 seek 90 absolute-percent
diff --git a/input/cmd_parse.c b/input/cmd_parse.c
index fd7e178..db44cca 100644
--- a/input/cmd_parse.c
+++ b/input/cmd_parse.c
@@ -306,7 +306,7 @@ struct mp_cmd *mp_input_parse_cmd_strv(struct mp_log *log, int def_flags,
bstr args[MP_CMD_MAX_ARGS];
int num = 0;
for (; argv[num]; num++) {
- if (num > MP_CMD_MAX_ARGS) {
+ if (num >= MP_CMD_MAX_ARGS) {
mp_err(log, "%s: too many arguments.\n", location);
return NULL;
}
diff --git a/input/input.c b/input/input.c
index ffe1703..18ef20b 100644
--- a/input/input.c
+++ b/input/input.c
@@ -28,7 +28,6 @@
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
-#include <ctype.h>
#include <pthread.h>
#include <assert.h>
@@ -123,6 +122,7 @@ struct input_ctx {
bool mainthread_set;
struct mp_log *log;
struct mpv_global *global;
+ struct input_opts *opts;
bool using_alt_gr;
bool using_ar;
@@ -160,6 +160,9 @@ struct input_ctx {
// Unlike mouse_x/y, this can be used to resolve mouse click bindings.
int mouse_vo_x, mouse_vo_y;
+ bool mouse_mangle, mouse_src_mangle;
+ struct mp_rect mouse_src, mouse_dst;
+
bool test;
bool default_bindings;
@@ -170,10 +173,6 @@ struct input_ctx {
struct active_section active_sections[MAX_ACTIVE_SECTIONS];
int num_active_sections;
- // Used to track whether we managed to read something while checking
- // events sources. If yes, the sources may have more queued.
- bool got_new_events;
-
unsigned int mouse_event_counter;
struct input_fd fds[MP_MAX_FDS];
@@ -181,6 +180,7 @@ struct input_ctx {
struct cmd_queue cmd_queue;
+ bool need_wakeup;
bool in_select;
int wakeup_pipe[2];
};
@@ -207,6 +207,7 @@ struct input_opts {
int use_appleremote;
int use_media_keys;
int default_bindings;
+ int enable_mouse_movements;
int test;
};
@@ -226,6 +227,7 @@ const struct m_sub_options input_config = {
OPT_FLAG("lirc", use_lirc, CONF_GLOBAL),
OPT_FLAG("right-alt-gr", use_alt_gr, CONF_GLOBAL),
OPT_INTRANGE("key-fifo-size", key_fifo_size, CONF_GLOBAL, 2, 65000),
+ OPT_FLAG("cursor", enable_mouse_movements, CONF_GLOBAL),
#if HAVE_LIRC
OPT_STRING("lirc-conf", lirc_configfile, CONF_GLOBAL),
#endif
@@ -243,6 +245,7 @@ const struct m_sub_options input_config = {
.ar_rate = 40,
.use_lirc = 1,
.use_alt_gr = 1,
+ .enable_mouse_movements = 1,
#if HAVE_COCOA
.use_appleremote = 1,
.use_media_keys = 1,
@@ -539,7 +542,7 @@ static void update_mouse_section(struct input_ctx *ictx)
struct mp_cmd *cmd = get_cmd_from_keys(ictx, old, MP_KEY_MOUSE_LEAVE);
if (cmd)
queue_add_tail(&ictx->cmd_queue, cmd);
- ictx->got_new_events = true;
+ mp_input_wakeup(ictx);
}
}
@@ -560,7 +563,7 @@ static void release_down_cmd(struct input_ctx *ictx, bool drop_current)
memset(ictx->key_history, 0, sizeof(ictx->key_history));
ictx->current_down_cmd->key_up_follows = false;
queue_add_tail(&ictx->cmd_queue, ictx->current_down_cmd);
- ictx->got_new_events = true;
+ mp_input_wakeup(ictx);
} else {
talloc_free(ictx->current_down_cmd);
}
@@ -628,7 +631,7 @@ static void interpret_key(struct input_ctx *ictx, int code, double scale)
if (MP_KEY_DEPENDS_ON_MOUSE_POS(unmod))
ictx->mouse_event_counter++;
- ictx->got_new_events = true;
+ mp_input_wakeup(ictx);
struct mp_cmd *cmd = NULL;
@@ -686,12 +689,14 @@ static void mp_input_feed_key(struct input_ctx *ictx, int code, double scale)
release_down_cmd(ictx, false);
return;
}
+ if (!ictx->opts->enable_mouse_movements && MP_KEY_IS_MOUSE(unmod))
+ return;
if (unmod == MP_KEY_MOUSE_LEAVE) {
update_mouse_section(ictx);
struct mp_cmd *cmd = get_cmd_from_keys(ictx, NULL, code);
if (cmd)
queue_add_tail(&ictx->cmd_queue, cmd);
- ictx->got_new_events = true;
+ mp_input_wakeup(ictx);
return;
}
double now = mp_time_sec();
@@ -739,11 +744,50 @@ void mp_input_put_axis(struct input_ctx *ictx, int direction, double value)
input_unlock(ictx);
}
+void mp_input_set_mouse_transform(struct input_ctx *ictx, struct mp_rect *dst,
+ struct mp_rect *src)
+{
+ input_lock(ictx);
+ ictx->mouse_mangle = dst || src;
+ if (ictx->mouse_mangle) {
+ ictx->mouse_dst = *dst;
+ ictx->mouse_src_mangle = !!src;
+ if (ictx->mouse_src_mangle)
+ ictx->mouse_src = *src;
+ }
+ input_unlock(ictx);
+}
+
+bool mp_input_mouse_enabled(struct input_ctx *ictx)
+{
+ input_lock(ictx);
+ bool r = ictx->opts->enable_mouse_movements;
+ input_unlock(ictx);
+ return r;
+}
+
void mp_input_set_mouse_pos(struct input_ctx *ictx, int x, int y)
{
input_lock(ictx);
MP_DBG(ictx, "mouse move %d/%d\n", x, y);
+ if (!ictx->opts->enable_mouse_movements) {
+ input_unlock(ictx);
+ return;
+ }
+
+ if (ictx->mouse_mangle) {
+ struct mp_rect *src = &ictx->mouse_src;
+ struct mp_rect *dst = &ictx->mouse_dst;
+ x = MPCLAMP(x, dst->x0, dst->x1) - dst->x0;
+ y = MPCLAMP(y, dst->y0, dst->y1) - dst->y0;
+ if (ictx->mouse_src_mangle) {
+ x = x * 1.0 / (dst->x1 - dst->x0) * (src->x1 - src->x0) + src->x0;
+ y = y * 1.0 / (dst->y1 - dst->y0) * (src->y1 - src->y0) + src->y0;
+ }
+ MP_DBG(ictx, "-> %d/%d\n", x, y);
+ }
+
ictx->mouse_event_counter++;
ictx->mouse_vo_x = x;
ictx->mouse_vo_y = y;
@@ -767,7 +811,7 @@ void mp_input_set_mouse_pos(struct input_ctx *ictx, int x, int y)
talloc_free(tail);
}
queue_add_tail(&ictx->cmd_queue, cmd);
- ictx->got_new_events = true;
+ mp_input_wakeup(ictx);
}
}
input_unlock(ictx);
@@ -949,7 +993,7 @@ static void read_cmd_fd(struct input_ctx *ictx, struct input_fd *cmd_fd)
int r;
char *text;
while ((r = read_cmd(cmd_fd, &text)) >= 0) {
- ictx->got_new_events = true;
+ mp_input_wakeup(ictx);
struct mp_cmd *cmd = mp_input_parse_cmd(ictx, bstr0(text), "<pipe>");
talloc_free(text);
if (cmd)
@@ -1057,9 +1101,9 @@ static void read_events(struct input_ctx *ictx, int time)
time = FFMAX(time, 0);
while (1) {
- if (ictx->got_new_events)
+ if (ictx->need_wakeup)
time = 0;
- ictx->got_new_events = false;
+ ictx->need_wakeup = false;
remove_dead_fds(ictx);
@@ -1070,13 +1114,13 @@ static void read_events(struct input_ctx *ictx, int time)
}
}
- if (ictx->got_new_events)
+ if (ictx->need_wakeup)
time = 0;
input_wait_read(ictx, time);
- // Read until all input FDs are empty
- if (!ictx->got_new_events)
+ // Read until no new wakeups happen.
+ if (!ictx->need_wakeup)
break;
}
}
@@ -1084,7 +1128,6 @@ static void read_events(struct input_ctx *ictx, int time)
int mp_input_queue_cmd(struct input_ctx *ictx, mp_cmd_t *cmd)
{
input_lock(ictx);
- ictx->got_new_events = true;
if (cmd)
queue_add_tail(&ictx->cmd_queue, cmd);
input_unlock(ictx);
@@ -1451,6 +1494,7 @@ static int parse_config_file(struct input_ctx *ictx, char *file, bool warn)
MP_ERR(ictx, "Can't open input config file %s.\n", file);
goto done;
}
+ stream_skip_bom(s);
bstr data = stream_read_complete(s, tmp, 1000000);
if (data.start) {
MP_VERBOSE(ictx, "Parsing input config file %s\n", file);
@@ -1488,6 +1532,7 @@ struct input_ctx *mp_input_init(struct mpv_global *global)
struct input_ctx *ictx = talloc_ptrtype(NULL, ictx);
*ictx = (struct input_ctx){
.global = global,
+ .opts = input_conf,
.log = mp_log_new(ictx, global->log, "input"),
.key_fifo_size = input_conf->key_fifo_size,
.doubleclick_time = input_conf->doubleclick_time,
@@ -1521,7 +1566,7 @@ struct input_ctx *mp_input_init(struct mpv_global *global)
#ifndef __MINGW32__
int ret = mp_make_wakeup_pipe(ictx->wakeup_pipe);
if (ret < 0)
- MP_ERR(ictx, "Failed to initialize wakeup pipe: %s\n", strerror(-ret));
+ MP_ERR(ictx, "Failed to initialize wakeup pipe.\n");
else
mp_input_add_fd(ictx, ictx->wakeup_pipe[0], true, NULL, read_wakeup,
NULL, NULL);
@@ -1633,7 +1678,7 @@ void mp_input_wakeup(struct input_ctx *ictx)
{
input_lock(ictx);
bool send_wakeup = ictx->in_select;
- ictx->got_new_events = true;
+ ictx->need_wakeup = true;
pthread_cond_signal(&ictx->wakeup);
input_unlock(ictx);
// Safe without locking
@@ -1647,7 +1692,7 @@ void mp_input_wakeup_nolock(struct input_ctx *ictx)
write(ictx->wakeup_pipe[1], &(char){0}, 1);
} else {
// Not race condition free. Done for the sake of jackaudio+windows.
- ictx->got_new_events = true;
+ ictx->need_wakeup = true;
pthread_cond_signal(&ictx->wakeup);
}
}
diff --git a/input/input.h b/input/input.h
index 2dc7b4b..de363cf 100644
--- a/input/input.h
+++ b/input/input.h
@@ -133,6 +133,16 @@ void mp_input_set_mouse_pos(struct input_ctx *ictx, int x, int y);
void mp_input_get_mouse_pos(struct input_ctx *ictx, int *x, int *y);
+// Return whether we want/accept mouse input.
+bool mp_input_mouse_enabled(struct input_ctx *ictx);
+
+/* Make mp_input_set_mouse_pos() mangle the mouse coordinates. Hack for certain
+ * VOs. dst=NULL, src=NULL reset it. src can be NULL.
+ */
+struct mp_rect;
+void mp_input_set_mouse_transform(struct input_ctx *ictx, struct mp_rect *dst,
+ struct mp_rect *src);
+
// As for the cmd one you usually don't need this function.
void mp_input_rm_key_fd(struct input_ctx *ictx, int fd);
diff --git a/input/keycodes.c b/input/keycodes.c
index 7d9c9be..078e29f 100644
--- a/input/keycodes.c
+++ b/input/keycodes.c
@@ -18,6 +18,7 @@
#include <stddef.h>
#include <string.h>
+#include <strings.h>
#include "bstr/bstr.h"
#include "common/common.h"
diff --git a/input/keycodes.h b/input/keycodes.h
index 9e890fc..49a7f8d 100644
--- a/input/keycodes.h
+++ b/input/keycodes.h
@@ -222,6 +222,9 @@
(MP_KEY_IS_MOUSE_BTN_SINGLE(code) || MP_KEY_IS_MOUSE_BTN_DBL(code) || \
(code) == MP_KEY_MOUSE_MOVE)
+#define MP_KEY_IS_MOUSE(code) \
+ (MP_KEY_DEPENDS_ON_MOUSE_POS(code) || (code) == MP_KEY_MOUSE_LEAVE)
+
// Emit a command even on key-up (normally key-up is ignored). This means by
// default they binding will be triggered on key-up instead of key-down.
// This is a fixed part of the keycode, not a modifier than can change.
diff --git a/input/lirc.c b/input/lirc.c
index 06036b8..e764929 100644
--- a/input/lirc.c
+++ b/input/lirc.c
@@ -71,7 +71,7 @@ int mp_input_lirc_init(struct input_ctx *ictx, struct mp_log *log,
.log = log,
.lirc_config = lirc_config,
};
- mp_input_add_fd(ictx, lirc_sock, 0, mp_input_lirc_read, NULL, mp_input_lirc_close, ctx);
+ mp_input_add_fd(ictx, lirc_sock, 1, mp_input_lirc_read, NULL, mp_input_lirc_close, ctx);
return lirc_sock;
}
diff --git a/libmpv/client.h b/libmpv/client.h
index b2b48f3..4a65396 100644
--- a/libmpv/client.h
+++ b/libmpv/client.h
@@ -114,7 +114,7 @@ extern "C" {
* handler is process-wide, and there's no proper way to share it with other
* xlib users within the same process. This might confuse GUI toolkits.
* - mpv uses some other libraries that are not library-safe, such as Fribidi
- * (used through libass), LittleCMS, ALSA, FFmpeg, and possibly more.
+ * (used through libass), ALSA, FFmpeg, and possibly more.
* - The FPU precision must be set at least to double precision.
* - On Windows, mpv will call timeBeginPeriod(1).
* - On memory exhaustion, mpv will kill the process.
@@ -131,6 +131,24 @@ extern "C" {
* aspect ratio of the window and the video mismatch).
*
* On OSX, embedding is not yet possible, because Cocoa makes this non-trivial.
+ *
+ * Compatibility
+ * -------------
+ *
+ * mpv development doesn't stand still, and changes to mpv internals as well as
+ * to its interface can cause compatibility issues to client API users.
+ *
+ * The API is versioned (see MPV_CLIENT_API_VERSION), and changes to it are
+ * documented in DOCS/client-api-changes.rst. The C API itself will probably
+ * remain compatible for a long time, but the functionality exposed by it
+ * could change more rapidly. For example, it's possible that options are
+ * renamed, or change the set of allowed values.
+ *
+ * Defensive programming should be used to potentially deal with the fact that
+ * options, commands, and properties could disappear, change their value range,
+ * or change the underlying datatypes. It might be a good idea to prefer
+ * MPV_FORMAT_STRING over other types to decouple your code from potential
+ * mpv changes.
*/
/**
@@ -139,8 +157,12 @@ extern "C" {
* the API becomes incompatible to previous versions, the major version
* number is incremented. This affects only C part, and not properties and
* options.
+ *
+ * You can use MPV_MAKE_VERSION() and compare the result with integer
+ * relational operators (<, >, <=, >=).
*/
-#define MPV_CLIENT_API_VERSION 0x00010000UL
+#define MPV_MAKE_VERSION(major, minor) (((major) << 16) | (minor) | 0UL)
+#define MPV_CLIENT_API_VERSION MPV_MAKE_VERSION(1, 3)
/**
* Return the MPV_CLIENT_API_VERSION the mpv source has been compiled with.
@@ -896,8 +918,10 @@ typedef enum mpv_event_id {
*/
MPV_EVENT_UNPAUSE = 13,
/**
- * Sent every time after a video frame is displayed (or in lower frequency
- * if there is no video, or playback is paused).
+ * Sent every time after a video frame is displayed. Note that currently,
+ * this will be sent in lower frequency if there is no video, or playback
+ * is paused - but that will be removed in the future, and it will be
+ * restricted to video frames only.
*/
MPV_EVENT_TICK = 14,
/**
@@ -912,8 +936,8 @@ typedef enum mpv_event_id {
/**
* Triggered by the script_message input command. The command uses the
* first argument of the command as client name (see mpv_client_name()) to
- * dispatch the message, and passes along the all arguments starting from
- * the seconand argument as strings.
+ * dispatch the message, and passes along all arguments starting from the
+ * second argument as strings.
* See also mpv_event and mpv_event_client_message.
*/
MPV_EVENT_CLIENT_MESSAGE = 16,
@@ -960,6 +984,7 @@ typedef enum mpv_event_id {
* Happens when the current chapter changes.
*/
MPV_EVENT_CHAPTER_CHANGE = 23
+ // Internal note: adjust INTERNAL_EVENT_BASE when adding new events.
} mpv_event_id;
/**
diff --git a/libmpv/mpv.def b/libmpv/mpv.def
new file mode 100644
index 0000000..0a97c43
--- /dev/null
+++ b/libmpv/mpv.def
@@ -0,0 +1,34 @@
+mpv_client_api_version
+mpv_client_name
+mpv_command
+mpv_command_async
+mpv_command_string
+mpv_create
+mpv_detach_destroy
+mpv_error_string
+mpv_event_name
+mpv_free
+mpv_free_node_contents
+mpv_get_property
+mpv_get_property_async
+mpv_get_property_osd_string
+mpv_get_property_string
+mpv_get_time_us
+mpv_get_wakeup_pipe
+mpv_initialize
+mpv_load_config_file
+mpv_observe_property
+mpv_request_event
+mpv_request_log_messages
+mpv_resume
+mpv_set_option
+mpv_set_option_string
+mpv_set_property
+mpv_set_property_async
+mpv_set_property_string
+mpv_set_wakeup_callback
+mpv_suspend
+mpv_terminate_destroy
+mpv_unobserve_property
+mpv_wait_event
+mpv_wakeup
diff --git a/libmpv/mpv.pc.in b/libmpv/mpv.pc.in
index 75f2869..5686343 100644
--- a/libmpv/mpv.pc.in
+++ b/libmpv/mpv.pc.in
@@ -8,4 +8,5 @@ Description: mpv media player client library
Version: @VERSION@
Requires:
Libs: -L${libdir} -lmpv
+Libs.private: @PRIV_LIBS@
Cflags: -I${includedir}
diff --git a/misc/charset_conv.c b/misc/charset_conv.c
index 2146f09..31f53cc 100644
--- a/misc/charset_conv.c
+++ b/misc/charset_conv.c
@@ -21,6 +21,7 @@
#include <stdlib.h>
#include <errno.h>
+#include <strings.h>
#include <assert.h>
#include "config.h"
@@ -80,11 +81,24 @@ bool mp_charset_requires_guess(const char *user_cp)
// Note that "utf8" is the UTF-8 codepage, while "utf8:..." specifies UTF-8
// by default, plus a codepage that is used if the input is not UTF-8.
return bstrcasecmp0(res[0], "enca") == 0 ||
+ bstrcasecmp0(res[0], "auto") == 0 ||
bstrcasecmp0(res[0], "guess") == 0 ||
(r > 1 && bstrcasecmp0(res[0], "utf-8") == 0) ||
(r > 1 && bstrcasecmp0(res[0], "utf8") == 0);
}
+static const char *const utf_bom[3] = {"\xEF\xBB\xBF", "\xFF\xFE", "\xFE\xFF"};
+static const char *const utf_enc[3] = {"utf-8", "utf-16le", "utf-16be"};
+
+static const char *ms_bom_guess(bstr buf)
+{
+ for (int n = 0; n < 3; n++) {
+ if (bstr_startswith0(buf, utf_bom[n]))
+ return utf_enc[n];
+ }
+ return NULL;
+}
+
#if HAVE_ENCA
static const char *enca_guess(struct mp_log *log, bstr buf, const char *language)
{
@@ -102,8 +116,7 @@ static const char *enca_guess(struct mp_log *log, bstr buf, const char *language
detected_cp = tmp;
enca_analyser_free(analyser);
} else {
- mp_err(log, "ENCA doesn't know language '%s'\n",
- language);
+ mp_err(log, "ENCA doesn't know language '%s'\n", language);
size_t langcnt;
const char **languages = enca_get_languages(&langcnt);
mp_err(log, "ENCA supported languages:");
@@ -143,6 +156,15 @@ const char *mp_charset_guess(struct mp_log *log, bstr buf, const char *user_cp,
if (!mp_charset_requires_guess(user_cp))
return user_cp;
+ bool use_auto = strcasecmp(user_cp, "auto") == 0;
+ if (use_auto) {
+#if HAVE_ENCA
+ user_cp = "enca";
+#else
+ user_cp = "UTF-8:UTF-8-BROKEN";
+#endif
+ }
+
// Do our own UTF-8 detection, because at least ENCA seems to get it
// wrong sometimes (suggested by divVerent).
int r = bstr_validate_utf8(buf);
@@ -159,6 +181,12 @@ const char *mp_charset_guess(struct mp_log *log, bstr buf, const char *user_cp,
const char *res = NULL;
+ if (use_auto) {
+ res = ms_bom_guess(buf);
+ if (res)
+ type = bstr0("auto");
+ }
+
#if HAVE_ENCA
if (bstrcasecmp0(type, "enca") == 0)
res = enca_guess(log, buf, lang);
@@ -173,8 +201,7 @@ const char *mp_charset_guess(struct mp_log *log, bstr buf, const char *user_cp,
}
if (res) {
- mp_dbg(log, "%.*s detected charset: '%s'\n",
- BSTR_P(type), res);
+ mp_dbg(log, "%.*s detected charset: '%s'\n", BSTR_P(type), res);
} else {
res = fallback;
mp_dbg(log, "Detection with %.*s failed: fallback to %s\n",
diff --git a/misc/ctype.h b/misc/ctype.h
new file mode 100644
index 0000000..cbff799
--- /dev/null
+++ b/misc/ctype.h
@@ -0,0 +1,19 @@
+#ifndef MP_CTYPE_H_
+#define MP_CTYPE_H_
+
+// Roughly follows C semantics, but doesn't account for EOF, allows char as
+// parameter, and is locale independent (always uses "C" locale).
+
+static inline int mp_isprint(char c) { return (unsigned char)c >= 32; }
+static inline int mp_isspace(char c) { return c == ' ' || c == '\f' || c == '\n' ||
+ c == '\r' || c == '\t' || c =='\v'; }
+static inline int mp_isupper(char c) { return c >= 'A' && c <= 'Z'; }
+static inline int mp_islower(char c) { return c >= 'a' && c <= 'z'; }
+static inline int mp_isdigit(char c) { return c >= '0' && c <= '9'; }
+static inline int mp_isalpha(char c) { return mp_isupper(c) || mp_islower(c); }
+static inline int mp_isalnum(char c) { return mp_isalpha(c) || mp_isdigit(c); }
+
+static inline char mp_tolower(char c) { return mp_isupper(c) ? c - 'A' + 'a' : c; }
+static inline char mp_toupper(char c) { return mp_islower(c) ? c - 'a' + 'A' : c; }
+
+#endif
diff --git a/misc/rendezvous.c b/misc/rendezvous.c
new file mode 100644
index 0000000..9af798d
--- /dev/null
+++ b/misc/rendezvous.c
@@ -0,0 +1,54 @@
+#include <pthread.h>
+
+#include "rendezvous.h"
+
+static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t wakeup = PTHREAD_COND_INITIALIZER;
+
+static struct waiter *waiters;
+
+struct waiter {
+ void *tag;
+ struct waiter *next;
+ intptr_t *value;
+};
+
+/* A barrier for 2 threads, which can exchange a value when they meet.
+ * The first thread to call this function will block. As soon as two threads
+ * are calling this function with the same tag value, they will unblock, and
+ * on each thread the call return the value parameter of the _other_ thread.
+ *
+ * tag is an arbitrary value, but it must be an unique pointer. If there are
+ * more than 2 threads using the same tag, things won't work. Typically, it
+ * will have to point to a memory allocation or to the stack, while pointing
+ * it to static data is always a bug.
+ *
+ * This shouldn't be used for performance critical code (uses a linked list
+ * of _all_ waiters in the process, and temporarily wakes up _all_ waiters on
+ * each second call).
+ *
+ * This is inspired by: http://9atom.org/magic/man2html/2/rendezvous */
+intptr_t mp_rendezvous(void *tag, intptr_t value)
+{
+ struct waiter wait = { .tag = tag, .value = &value };
+ pthread_mutex_lock(&lock);
+ struct waiter **prev = &waiters;
+ while (*prev) {
+ if ((*prev)->tag == tag) {
+ intptr_t tmp = *(*prev)->value;
+ *(*prev)->value = value;
+ value = tmp;
+ (*prev)->value = NULL; // signals completion
+ *prev = (*prev)->next; // unlink
+ pthread_cond_broadcast(&wakeup);
+ goto done;
+ }
+ prev = &(*prev)->next;
+ }
+ *prev = &wait;
+ while (wait.value)
+ pthread_cond_wait(&wakeup, &lock);
+done:
+ pthread_mutex_unlock(&lock);
+ return value;
+}
diff --git a/misc/rendezvous.h b/misc/rendezvous.h
new file mode 100644
index 0000000..ffcc89a
--- /dev/null
+++ b/misc/rendezvous.h
@@ -0,0 +1,8 @@
+#ifndef MP_RENDEZVOUS_H_
+#define MP_RENDEZVOUS_H_
+
+#include <stdint.h>
+
+intptr_t mp_rendezvous(void *tag, intptr_t value);
+
+#endif
diff --git a/old-configure b/old-configure
index 3280dcb..910ebf7 100755
--- a/old-configure
+++ b/old-configure
@@ -720,7 +720,7 @@ check_statement_libs "RSound" $_rsound RSOUND rsound.h 'rsd_init(NULL);' -lrsoun
check_statement_libs "sndio" $_sndio SNDIO sndio.h 'struct sio_par par; sio_initpar(&par); const char *s = SIO_DEVANY' -lsndio
-check_pkg_config "PulseAudio" $_pulse PULSE 'libpulse >= 0.9'
+check_pkg_config "PulseAudio" $_pulse PULSE 'libpulse >= 1.0'
check_pkg_config "PortAudio" $_portaudio PORTAUDIO 'portaudio-2.0 >= 19'
@@ -858,6 +858,7 @@ check_compile "Video 4 Linux 2 MPEG PVR interface" $_pvr PVR waftools/fragments/
test_lua() {
if test "$_lua" = auto && $_pkg_config "$1" ; then
check_pkg_config "Lua ($1)" $_lua LUA "$1"
+ _lua=$(defretval)
fi
}
@@ -867,7 +868,7 @@ test_lua "luajit >= 2.0.0"
test_lua "lua >= 5.2.0"
test_lua "lua5.2 >= 5.2.0" # debian
-test "$_lua" = no && check_yes_no $lua LUA
+test "$_lua" != yes && check_yes_no no LUA
check_trivial "joystick" $_joystick JOYSTICK
@@ -945,6 +946,7 @@ cat > $TMPC << EOF
#define HAVE_VDA_GL 0
#define HAVE_GL_COCOA 0
#define HAVE_COCOA 0
+#define HAVE_COCOA_APPLICATION 0
#define HAVE_COREVIDEO 0
#define HAVE_COREAUDIO 0
#define HAVE_GL_WIN32 0
diff --git a/old-makefile b/old-makefile
index 986c1df..2c2540d 100644
--- a/old-makefile
+++ b/old-makefile
@@ -50,7 +50,8 @@ SOURCES-$(MPG123) += audio/decode/ad_mpg123.c
SOURCES-$(PVR) += stream/stream_pvr.c
SOURCES-$(TV) += stream/stream_tv.c stream/tv.c \
- stream/frequencies.c stream/tvi_dummy.c
+ stream/frequencies.c stream/tvi_dummy.c \
+ demux/demux_tv.c
SOURCES-$(TV_V4L2) += stream/tvi_v4l2.c stream/audio_in.c
SOURCES-$(DUMMY_OSD) += sub/osd_dummy.c
@@ -148,7 +149,6 @@ SOURCES = audio/audio.c \
bstr/bstr.c \
common/av_common.c \
common/av_log.c \
- common/av_opts.c \
common/codecs.c \
common/common.c \
common/msg.c \
@@ -159,6 +159,7 @@ SOURCES = audio/audio.c \
demux/demux.c \
demux/demux_edl.c \
demux/demux_cue.c \
+ demux/demux_disc.c \
demux/demux_lavf.c \
demux/demux_mf.c \
demux/demux_mkv.c \
@@ -167,6 +168,7 @@ SOURCES = audio/audio.c \
demux/demux_subreader.c \
demux/ebml.c \
demux/mf.c \
+ demux/packet.c \
input/cmd_list.c \
input/cmd_parse.c \
input/event.c \
@@ -174,6 +176,7 @@ SOURCES = audio/audio.c \
input/keycodes.c \
misc/charset_conv.c \
misc/dispatch.c \
+ misc/rendezvous.c \
misc/ring.c \
options/m_config.c \
options/m_option.c \
@@ -243,6 +246,7 @@ SOURCES = audio/audio.c \
video/decode/vd_lavc.c \
video/filter/vf.c \
video/filter/pullup.c \
+ video/filter/vf_buffer.c \
video/filter/vf_crop.c \
video/filter/vf_delogo.c \
video/filter/vf_divtc.c \
@@ -406,7 +410,7 @@ common/version.c: version.h
DOCS/man/mpv.1: DOCS/man/af.rst \
DOCS/man/ao.rst \
DOCS/man/changes.rst \
- DOCS/mancode.rst \
+ DOCS/man/encode.rst \
DOCS/man/input.rst \
DOCS/man/options.rst \
DOCS/man/vf.rst \
diff --git a/options/m_config.c b/options/m_config.c
index 024cdae..d8a5cce 100644
--- a/options/m_config.c
+++ b/options/m_config.c
@@ -25,6 +25,7 @@
#include <stdio.h>
#include <errno.h>
#include <string.h>
+#include <strings.h>
#include <assert.h>
#include <stdbool.h>
diff --git a/options/m_option.c b/options/m_option.c
index 04b4783..e11f96b 100644
--- a/options/m_option.c
+++ b/options/m_option.c
@@ -29,7 +29,6 @@
#include <limits.h>
#include <inttypes.h>
#include <unistd.h>
-#include <ctype.h>
#include <assert.h>
#include <libavutil/common.h>
@@ -1400,13 +1399,16 @@ static int parse_keyvalue_list(struct mp_log *log, const m_option_t *opt,
r = read_subparam(log, name, &param, &val);
if (r < 0)
break;
- MP_TARRAY_APPEND(NULL, lst, num, bstrto0(NULL, key));
- MP_TARRAY_APPEND(NULL, lst, num, bstrto0(NULL, val));
+ if (dst) {
+ MP_TARRAY_APPEND(NULL, lst, num, bstrto0(NULL, key));
+ MP_TARRAY_APPEND(NULL, lst, num, bstrto0(NULL, val));
+ }
if (!bstr_eatstart0(&param, ","))
break;
}
- MP_TARRAY_APPEND(NULL, lst, num, NULL);
+ if (dst)
+ MP_TARRAY_APPEND(NULL, lst, num, NULL);
if (param.len) {
mp_err(log, "Unparseable garbage at end of option value: '%.*s'\n",
@@ -1414,9 +1416,11 @@ static int parse_keyvalue_list(struct mp_log *log, const m_option_t *opt,
r = M_OPT_INVALID;
}
- VAL(dst) = lst;
- if (r < 0)
- free_str_list(dst);
+ if (dst) {
+ VAL(dst) = lst;
+ if (r < 0)
+ free_str_list(dst);
+ }
return r;
}
@@ -2181,10 +2185,13 @@ static int parse_rel_time(struct mp_log *log, const m_option_t *opt,
}
}
- bool sign = bstr_eatstart0(&param, "-");
double time;
if (parse_timestring(param, &time, 0)) {
- t.type = sign ? REL_TIME_NEGATIVE : REL_TIME_ABSOLUTE;
+ if (bstr_startswith0(param, "+") || bstr_startswith0(param, "-")) {
+ t.type = REL_TIME_RELATIVE;
+ } else {
+ t.type = REL_TIME_ABSOLUTE;
+ }
t.pos = time;
goto out;
}
diff --git a/options/m_option.h b/options/m_option.h
index 02fcb9b..13afea2 100644
--- a/options/m_option.h
+++ b/options/m_option.h
@@ -70,7 +70,7 @@ typedef void (*m_opt_print_fn)(struct mp_log *log);
enum m_rel_time_type {
REL_TIME_NONE,
REL_TIME_ABSOLUTE,
- REL_TIME_NEGATIVE,
+ REL_TIME_RELATIVE,
REL_TIME_PERCENT,
REL_TIME_CHAPTER,
};
diff --git a/options/options.c b/options/options.c
index 3fdc053..b557821 100644
--- a/options/options.c
+++ b/options/options.c
@@ -38,7 +38,6 @@
#include "m_option.h"
#include "common/common.h"
#include "stream/stream.h"
-#include "stream/tv.h"
#include "video/csputils.h"
#include "sub/osd.h"
#include "audio/mixer.h"
@@ -46,6 +45,7 @@
#include "audio/decode/dec_audio.h"
#include "player/core.h"
#include "player/command.h"
+#include "stream/stream.h"
extern const char mp_help_text[];
@@ -63,6 +63,7 @@ extern const struct m_sub_options tv_params_conf;
extern const struct m_sub_options stream_pvr_conf;
extern const struct m_sub_options stream_cdda_conf;
extern const struct m_sub_options stream_dvb_conf;
+extern const struct m_sub_options stream_lavf_conf;
extern const struct m_sub_options sws_conf;
extern const struct m_sub_options demux_rawaudio_conf;
extern const struct m_sub_options demux_rawvideo_conf;
@@ -214,6 +215,9 @@ const m_option_t mp_opts[] = {
OPT_STRING("demuxer", demuxer_name, 0),
OPT_STRING("audio-demuxer", audio_demuxer_name, 0),
OPT_STRING("sub-demuxer", sub_demuxer_name, 0),
+ OPT_FLAG("demuxer-thread", demuxer_thread, 0),
+ OPT_INTRANGE("demuxer-readahead-packets", demuxer_min_packs, 0, 0, MAX_PACKS),
+ OPT_INTRANGE("demuxer-readahead-bytes", demuxer_min_bytes, 0, 0, MAX_PACK_BYTES),
OPT_DOUBLE("mf-fps", mf_fps, 0),
OPT_STRING("mf-type", mf_type, 0),
@@ -226,6 +230,7 @@ const m_option_t mp_opts[] = {
#if HAVE_DVBIN
OPT_SUBSTRUCT("dvbin", stream_dvb_opts, stream_dvb_conf, 0),
#endif
+ OPT_SUBSTRUCT("", stream_lavf_opts, stream_lavf_conf, 0),
// ------------------------- a-v sync options --------------------
@@ -452,8 +457,7 @@ const m_option_t mp_opts[] = {
OPT_CHOICE("framedrop", frame_dropping, 0,
({"no", 0},
- {"yes", 1},
- {"hard", 2})),
+ {"yes", 1})),
OPT_FLAG("untimed", untimed, M_OPT_FIXED),
@@ -504,10 +508,8 @@ const m_option_t mp_opts[] = {
OPT_STRING("term-status-msg", status_msg, 0),
OPT_STRING("osd-status-msg", osd_status_msg, 0),
- OPT_FLAG("slave-broken", slave_mode, CONF_GLOBAL),
OPT_FLAG("idle", player_idle_mode, M_OPT_GLOBAL),
OPT_FLAG("input-terminal", consolecontrols, CONF_GLOBAL),
- OPT_FLAG("input-cursor", vo.enable_mouse_movements, CONF_GLOBAL),
OPT_SUBSTRUCT("screenshot", screenshot_image_opts, image_writer_conf, 0),
OPT_STRING("screenshot-template", screenshot_template, 0),
@@ -515,6 +517,7 @@ const m_option_t mp_opts[] = {
OPT_SUBSTRUCT("input", input_opts, input_config, 0),
OPT_PRINT("list-properties", property_print_help),
+ OPT_PRINT("list-protocols", stream_print_proto_list),
OPT_PRINT("help", print_help),
OPT_PRINT("h", print_help),
OPT_PRINT("version", print_version),
@@ -546,7 +549,6 @@ const struct MPOpts mp_default_opts = {
.monitor_pixel_aspect = 1.0,
.screen_id = -1,
.fsscreen_id = -1,
- .enable_mouse_movements = 1,
.panscan = 0.0f,
.keepaspect = 1,
.border = 1,
@@ -590,6 +592,9 @@ const struct MPOpts mp_default_opts = {
},
.stream_cache_pause = 50,
.stream_cache_unpause = 100,
+ .demuxer_thread = 0,
+ .demuxer_min_packs = MIN_PACKS,
+ .demuxer_min_bytes = MIN_PACK_BYTES,
.network_rtsp_transport = 2,
.chapterrange = {-1, -1},
.edition_id = -1,
@@ -629,11 +634,7 @@ const struct MPOpts mp_default_opts = {
.ass_shaper = 1,
.use_embedded_fonts = 1,
.sub_fix_timing = 1,
-#if HAVE_ENCA
- .sub_cp = "enca",
-#else
- .sub_cp = "UTF-8:UTF-8-BROKEN",
-#endif
+ .sub_cp = "auto",
.hwdec_codecs = "h264,vc1,wmv3",
diff --git a/options/options.h b/options/options.h
index 100fded..20b35d6 100644
--- a/options/options.h
+++ b/options/options.h
@@ -29,8 +29,6 @@ typedef struct mp_vo_opts {
int keepaspect;
int border;
- int enable_mouse_movements;
-
int64_t WinID;
float force_monitor_aspect;
@@ -149,7 +147,6 @@ typedef struct MPOpts {
char *heartbeat_cmd;
float heartbeat_interval;
int player_idle_mode;
- int slave_mode;
int consolecontrols;
struct m_rel_time play_start;
struct m_rel_time play_end;
@@ -183,6 +180,9 @@ typedef struct MPOpts {
char **audio_files;
char *demuxer_name;
+ int demuxer_thread;
+ int demuxer_min_packs;
+ int demuxer_min_bytes;
char *audio_demuxer_name;
char *sub_demuxer_name;
int mkv_subtitle_preroll;
@@ -249,6 +249,7 @@ typedef struct MPOpts {
struct pvr_params *stream_pvr_opts;
struct cdda_params *stream_cdda_opts;
struct dvb_params *stream_dvb_opts;
+ struct stream_lavf_params *stream_lavf_opts;
char *cdrom_device;
int dvd_title;
diff --git a/options/parse_configfile.c b/options/parse_configfile.c
index 1e12a5c..44ac649 100644
--- a/options/parse_configfile.c
+++ b/options/parse_configfile.c
@@ -22,13 +22,13 @@
#include <stdlib.h>
#include <string.h>
#include <errno.h>
-#include <ctype.h>
#include <assert.h>
#include "osdep/io.h"
#include "parse_configfile.h"
#include "common/msg.h"
+#include "misc/ctype.h"
#include "m_option.h"
#include "m_config.h"
@@ -63,16 +63,15 @@ int m_config_parse_config_file(m_config_t *config, const char *conffile,
flags = flags | M_SETOPT_FROM_CONFIG_FILE;
- MP_VERBOSE(config, "Reading config file %s", conffile);
+ MP_VERBOSE(config, "Reading config file %s\n", conffile);
if (config->recursion_depth > MAX_RECURSION_DEPTH) {
- MP_ERR(config, ": too deep 'include'. check your configfiles\n");
+ MP_ERR(config, "Maximum 'include' nesting depth exceeded.\n");
ret = -1;
goto out;
}
if ((line = malloc(MAX_LINE_LEN + 1)) == NULL) {
- MP_FATAL(config, "\ncan't get memory for 'line': %s", strerror(errno));
ret = -1;
goto out;
} else
@@ -80,7 +79,7 @@ int m_config_parse_config_file(m_config_t *config, const char *conffile,
MP_VERBOSE(config, "\n");
if ((fp = fopen(conffile, "r")) == NULL) {
- MP_VERBOSE(config, ": %s\n", strerror(errno));
+ MP_VERBOSE(config, "Can't open config file: %s\n", strerror(errno));
ret = 0;
goto out;
}
@@ -94,8 +93,12 @@ int m_config_parse_config_file(m_config_t *config, const char *conffile,
line_num++;
line_pos = 0;
+ /* skip BOM */
+ if (strncmp(line, "\xEF\xBB\xBF", 3) == 0)
+ line_pos += 3;
+
/* skip whitespaces */
- while (isspace(line[line_pos]))
+ while (mp_isspace(line[line_pos]))
++line_pos;
/* EOL / comment */
@@ -103,14 +106,14 @@ int m_config_parse_config_file(m_config_t *config, const char *conffile,
continue;
/* read option. */
- for (opt_pos = 0; isprint(line[line_pos]) &&
+ for (opt_pos = 0; mp_isprint(line[line_pos]) &&
line[line_pos] != ' ' &&
line[line_pos] != '#' &&
line[line_pos] != '='; /* NOTHING */) {
opt[opt_pos++] = line[line_pos++];
if (opt_pos >= MAX_OPT_LEN) {
PRINT_LINENUM;
- MP_ERR(config, "too long option\n");
+ MP_ERR(config, "option name too long\n");
errors++;
ret = -1;
goto nextline;
@@ -133,7 +136,7 @@ int m_config_parse_config_file(m_config_t *config, const char *conffile,
}
/* skip whitespaces */
- while (isspace(line[line_pos]))
+ while (mp_isspace(line[line_pos]))
++line_pos;
param_pos = 0;
@@ -145,7 +148,7 @@ int m_config_parse_config_file(m_config_t *config, const char *conffile,
param_set = true;
/* whitespaces... */
- while (isspace(line[line_pos]))
+ while (mp_isspace(line[line_pos]))
++line_pos;
/* read the parameter */
@@ -187,8 +190,8 @@ int m_config_parse_config_file(m_config_t *config, const char *conffile,
}
}
- for (param_pos = 0; isprint(line[line_pos])
- && !isspace(line[line_pos])
+ for (param_pos = 0; mp_isprint(line[line_pos])
+ && !mp_isspace(line[line_pos])
&& line[line_pos] != '#'; /* NOTHING */) {
param[param_pos++] = line[line_pos++];
if (param_pos >= MAX_PARAM_LEN) {
@@ -202,7 +205,7 @@ int m_config_parse_config_file(m_config_t *config, const char *conffile,
param_done:
- while (isspace(line[line_pos]))
+ while (mp_isspace(line[line_pos]))
++line_pos;
}
param[param_pos] = '\0';
diff --git a/options/path.c b/options/path.c
index 53ce3a5..9d32a2e 100644
--- a/options/path.c
+++ b/options/path.c
@@ -35,6 +35,7 @@
#include "config.h"
+#include "common/common.h"
#include "common/global.h"
#include "common/msg.h"
#include "options/options.h"
@@ -43,102 +44,149 @@
#include "osdep/io.h"
#include "osdep/path.h"
-typedef char *(*lookup_fun)(void *tctx, struct mpv_global *global, const char *);
-static const lookup_fun config_lookup_functions[] = {
- mp_find_user_config_file,
+static int mp_add_xdg_config_dirs(struct mpv_global *global, char **dirs, int i)
+{
+ void *talloc_ctx = dirs;
+
+ char *home = getenv("HOME");
+ char *tmp = NULL;
+
+ char *xdg_home = NULL;
+ tmp = getenv("XDG_CONFIG_HOME");
+ if (tmp && *tmp)
+ xdg_home = talloc_asprintf(talloc_ctx, "%s/mpv", tmp);
+ else if (home && *home)
+ xdg_home = talloc_asprintf(talloc_ctx, "%s/.config/mpv", home);
+
+ // Maintain compatibility with old ~/.mpv
+ char *old_home = NULL;
+ if (home && *home)
+ old_home = talloc_asprintf(talloc_ctx, "%s/.mpv", home);
+
+ // If the old ~/.mpv exists, and the XDG config dir doesn't, use the old
+ // config dir only.
+ if (mp_path_exists(xdg_home) || !mp_path_exists(old_home))
+ dirs[i++] = xdg_home;
+ dirs[i++] = old_home;
+
#if HAVE_COCOA
- mp_get_macosx_bundled_path,
+ i = mp_add_macosx_bundle_dir(global, dirs, i);
#endif
- mp_find_global_config_file,
- NULL
-};
-#define STRNULL(s) ((s) ? (s) : "(NULL)")
+ tmp = getenv("XDG_CONFIG_DIRS");
+ if (tmp && *tmp) {
+ char *xdgdirs = talloc_strdup(talloc_ctx, tmp);
+ while (xdgdirs) {
+ char *dir = xdgdirs;
-char *mp_find_config_file(void *talloc_ctx, struct mpv_global *global,
- const char *filename)
-{
- struct MPOpts *opts = global->opts;
+ xdgdirs = strchr(xdgdirs, ':');
+ if (xdgdirs)
+ *xdgdirs++ = 0;
- char *res = NULL;
- if (opts->load_config) {
- if (opts->force_configdir && opts->force_configdir[0]) {
- // Always force the local config dir.
- res = mp_find_user_config_file(talloc_ctx, global, filename);
- } else {
- for (int i = 0; config_lookup_functions[i] != NULL; i++) {
- res = config_lookup_functions[i](talloc_ctx, global, filename);
- if (!res)
- continue;
-
- if (mp_path_exists(res))
- break;
-
- talloc_free(res);
- res = NULL;
+ if (!dir[0])
+ continue;
+
+ dirs[i++] = talloc_asprintf(talloc_ctx, "%s%s", dir, "/mpv");
+
+ if (i + 1 >= MAX_CONFIG_PATHS) {
+ MP_WARN(global, "Too many config files, not reading any more\n");
+ break;
}
}
+ } else {
+ dirs[i++] = MPLAYER_CONFDIR;
}
- MP_VERBOSE(global, "any config path: '%s' -> '%s'\n", STRNULL(filename),
- STRNULL(res));
- return res;
+
+ return i;
}
-char *mp_find_user_config_file(void *talloc_ctx, struct mpv_global *global,
- const char *filename)
+// Return NULL-terminated array of config directories, from highest to lowest
+// priority
+static char **mp_config_dirs(void *talloc_ctx, struct mpv_global *global)
{
struct MPOpts *opts = global->opts;
- char *res = NULL;
- if (opts->load_config) {
- if (opts->force_configdir && opts->force_configdir[0]) {
- res = mp_path_join(talloc_ctx, bstr0(opts->force_configdir),
- bstr0(filename));
- } else {
- char *homedir = getenv("MPV_HOME");
- char *configdir = NULL;
-
- if (!homedir) {
-#ifdef _WIN32
- res = talloc_steal(talloc_ctx, mp_get_win_config_path(filename));
-#endif
- homedir = getenv("HOME");
- configdir = ".mpv";
- }
+ char **ret = talloc_zero_array(talloc_ctx, char*, MAX_CONFIG_PATHS);
- if (!res && homedir) {
- char *temp = mp_path_join(NULL, bstr0(homedir), bstr0(configdir));
- res = mp_path_join(talloc_ctx, bstr0(temp), bstr0(filename));
- talloc_free(temp);
- }
- }
+ if (!opts->load_config)
+ return ret;
+
+ if (opts->force_configdir && opts->force_configdir[0]) {
+ ret[0] = talloc_strdup(ret, opts->force_configdir);
+ return ret;
}
- MP_VERBOSE(global, "user config path: '%s' -> '%s'\n", STRNULL(filename),
- STRNULL(res));
- return res;
+ const char *tmp = NULL;
+ int i = 0;
+
+ tmp = getenv("MPV_HOME");
+ if (tmp && *tmp)
+ ret[i++] = talloc_strdup(ret, tmp);
+
+#if defined(_WIN32) && !defined(__CYGWIN__)
+ i = mp_add_win_config_dirs(global, ret, i);
+#else
+ i = mp_add_xdg_config_dirs(global, ret, i);
+#endif
+
+ MP_VERBOSE(global, "search dirs:");
+ for (char **c = ret; *c; c++)
+ MP_VERBOSE(global, " %s", *c);
+ MP_VERBOSE(global, "\n");
+
+ return ret;
}
-char *mp_find_global_config_file(void *talloc_ctx, struct mpv_global *global,
- const char *filename)
+char *mp_find_config_file(void *talloc_ctx, struct mpv_global *global,
+ const char *filename)
{
- struct MPOpts *opts = global->opts;
char *res = NULL;
+ char **dirs = mp_config_dirs(NULL, global);
+ for (int i = 0; dirs && dirs[i]; i++) {
+ char *file = talloc_asprintf(talloc_ctx, "%s/%s", dirs[i], filename);
- if (opts->load_config && !(opts->force_configdir && opts->force_configdir[0]))
- {
- if (filename) {
- res = mp_path_join(talloc_ctx, bstr0(MPLAYER_CONFDIR), bstr0(filename));
- } else {
- res = talloc_strdup(talloc_ctx, MPLAYER_CONFDIR);
+ if (mp_path_exists(file)) {
+ res = file;
+ break;
}
+
+ talloc_free(file);
}
+ talloc_free(dirs);
- MP_VERBOSE(global, "global config path: '%s' -> '%s'\n", STRNULL(filename),
- STRNULL(res));
+ MP_VERBOSE(global, "config path: '%s' -> '%s'\n", filename,
+ res ? res : "(NULL)");
return res;
}
+char **mp_find_all_config_files(void *talloc_ctx, struct mpv_global *global,
+ const char *filename)
+{
+ char **ret = talloc_zero_array(talloc_ctx, char*, MAX_CONFIG_PATHS + 1);
+ int num_ret = 0;
+
+ char **dirs = mp_config_dirs(NULL, global);
+ for (int i = 0; dirs && dirs[i]; i++) {
+ char *file = talloc_asprintf(ret, "%s/%s", dirs[i], filename);
+
+ if (!mp_path_exists(file) || num_ret >= MAX_CONFIG_PATHS)
+ continue;
+
+ ret[num_ret++] = file;
+ }
+ talloc_free(dirs);
+
+ for (int n = 0; n < num_ret / 2; n++)
+ MPSWAP(char*, ret[n], ret[num_ret - n - 1]);
+
+ MP_VERBOSE(global, "config file: '%s'\n", filename);
+
+ for (char** c = ret; *c; c++)
+ MP_VERBOSE(global, " -> '%s'\n", *c);
+
+ return ret;
+}
+
char *mp_get_user_path(void *talloc_ctx, struct mpv_global *global,
const char *path)
{
@@ -152,7 +200,7 @@ char *mp_get_user_path(void *talloc_ctx, struct mpv_global *global,
if (bstr_split_tok(bpath, "/", &prefix, &rest)) {
const char *rest0 = rest.start; // ok in this case
if (bstr_equals0(prefix, "~")) {
- res = mp_find_user_config_file(talloc_ctx, global, rest0);
+ res = mp_find_config_file(talloc_ctx, global, rest0);
} else if (bstr_equals0(prefix, "")) {
res = mp_path_join(talloc_ctx, bstr0(getenv("HOME")), rest);
}
@@ -245,7 +293,7 @@ char *mp_getcwd(void *talloc_ctx)
bool mp_path_exists(const char *path)
{
struct stat st;
- return mp_stat(path, &st) == 0;
+ return path && mp_stat(path, &st) == 0;
}
bool mp_path_isdir(const char *path)
@@ -281,14 +329,34 @@ bstr mp_split_proto(bstr path, bstr *out_url)
return r;
}
+void mp_mkdirp(const char *dir)
+{
+ char *path = talloc_strdup(NULL, dir);
+ char *cdir = path + 1;
+
+ while (cdir) {
+ cdir = strchr(cdir, '/');
+ if (cdir)
+ *cdir = 0;
+
+ mkdir(path, 0700);
+
+ if (cdir)
+ *cdir++ = '/';
+ }
+
+ talloc_free(path);
+}
+
void mp_mk_config_dir(struct mpv_global *global, char *subdir)
{
void *tmp = talloc_new(NULL);
- char *confdir = mp_find_user_config_file(tmp, global, "");
- if (confdir) {
- if (subdir)
- confdir = mp_path_join(tmp, bstr0(confdir), bstr0(subdir));
- mkdir(confdir, 0777);
+ char *dir = mp_config_dirs(tmp, global)[0];
+
+ if (dir) {
+ dir = talloc_asprintf(tmp, "%s/%s", dir, subdir);
+ mp_mkdirp(dir);
}
+
talloc_free(tmp);
}
diff --git a/options/path.h b/options/path.h
index 0d23dcb..30ca34d 100644
--- a/options/path.h
+++ b/options/path.h
@@ -32,13 +32,10 @@ struct mpv_global;
char *mp_find_config_file(void *talloc_ctx, struct mpv_global *global,
const char *filename);
-// Search for the input filename in the global configuration location.
-char *mp_find_global_config_file(void *talloc_ctx, struct mpv_global *global,
- const char *filename);
-
-// Search for the input filename in the user configuration location.
-char *mp_find_user_config_file(void *talloc_ctx, struct mpv_global *global,
- const char *filename);
+// Find all instances of the given config file. Paths are returned in order
+// from lowest to highest priority.
+char **mp_find_all_config_files(void *talloc_ctx, struct mpv_global *global,
+ const char *filename);
// Normally returns a talloc_strdup'ed copy of the path, except for special
// paths starting with '~'. Used to allow the user explicitly reference a
@@ -77,6 +74,7 @@ bool mp_is_url(bstr path);
bstr mp_split_proto(bstr path, bstr *out_url);
+void mp_mkdirp(const char *dir);
void mp_mk_config_dir(struct mpv_global *global, char *subdir);
#endif /* MPLAYER_PATH_H */
diff --git a/osdep/endian.h b/osdep/endian.h
new file mode 100644
index 0000000..b600f1c
--- /dev/null
+++ b/osdep/endian.h
@@ -0,0 +1,31 @@
+#ifndef MP_ENDIAN_H_
+#define MP_ENDIAN_H_
+
+#include <sys/types.h>
+
+#if !defined(BYTE_ORDER)
+
+#if defined(__BYTE_ORDER)
+#define BYTE_ORDER __BYTE_ORDER
+#define LITTLE_ENDIAN __LITTLE_ENDIAN
+#define BIG_ENDIAN __BIG_ENDIAN
+#elif defined(__DARWIN_BYTE_ORDER)
+#define BYTE_ORDER __DARWIN_BYTE_ORDER
+#define LITTLE_ENDIAN __DARWIN_LITTLE_ENDIAN
+#define BIG_ENDIAN __DARWIN_BIG_ENDIAN
+#else
+#include <libavutil/bswap.h>
+#if AV_HAVE_BIGENDIAN
+#define BYTE_ORDER 1234
+#define LITTLE_ENDIAN 4321
+#define BIG_ENDIAN 1234
+#else
+#define BYTE_ORDER 1234
+#define LITTLE_ENDIAN 1234
+#define BIG_ENDIAN 4321
+#endif
+#endif
+
+#endif /* !defined(BYTE_ORDER) */
+
+#endif
diff --git a/osdep/io.c b/osdep/io.c
index 27235e0..8423a6b 100644
--- a/osdep/io.c
+++ b/osdep/io.c
@@ -46,7 +46,7 @@ bool mp_set_cloexec(int fd)
int mp_make_wakeup_pipe(int pipes[2])
{
pipes[0] = pipes[1] = -1;
- return -ENOSYS;
+ return -1;
}
#else
// create a pipe, and set it to non-blocking (and also set FD_CLOEXEC)
@@ -54,7 +54,7 @@ int mp_make_wakeup_pipe(int pipes[2])
{
if (pipe(pipes) != 0) {
pipes[0] = pipes[1] = -1;
- return -errno;
+ return -1;
}
for (int i = 0; i < 2; i++) {
diff --git a/osdep/macosx_application.h b/osdep/macosx_application.h
index f9fca4b..23c5838 100644
--- a/osdep/macosx_application.h
+++ b/osdep/macosx_application.h
@@ -19,8 +19,6 @@
#ifndef MPV_MACOSX_APPLICATION
#define MPV_MACOSX_APPLICATION
-struct input_ctx;
-
typedef int (*mpv_main_fn)(int, char**);
// Menu Keys identifing menu items
@@ -46,8 +44,6 @@ void cocoa_run_runloop(void);
void cocoa_stop_runloop(void);
void cocoa_post_fake_event(void);
-void cocoa_set_input_context(struct input_ctx *input_context);
-
void macosx_finder_args_preinit(int *argc, char ***argv);
#endif /* MPV_MACOSX_APPLICATION */
diff --git a/osdep/macosx_application.m b/osdep/macosx_application.m
index 6c77480..9b62eb6 100644
--- a/osdep/macosx_application.m
+++ b/osdep/macosx_application.m
@@ -22,17 +22,20 @@
#include "common/msg.h"
#include "input/input.h"
-#include "input/event.h"
-#include "input/keycodes.h"
-#include "osdep/macosx_application_objc.h"
+#import "osdep/macosx_application_objc.h"
#include "osdep/macosx_compat.h"
+#import "osdep/macosx_events_objc.h"
#define MPV_PROTOCOL @"mpv://"
static pthread_t playback_thread_id;
-@interface Application (PrivateMethods)
+@interface Application ()
+{
+ EventsResponder *_eventsResponder;
+}
+
- (NSMenuItem *)menuItemWithParent:(NSMenu *)parent
title:(NSString *)title
action:(SEL)selector
@@ -61,17 +64,14 @@ Application *mpv_shared_app(void)
@synthesize argumentsList = _arguments_list;
@synthesize willStopOnOpenEvent = _will_stop_on_open_event;
-@synthesize inputContext = _input_context;
-@synthesize eventsResponder = _events_responder;
@synthesize menuItems = _menu_items;
-@synthesize input_ready = _input_ready;
- (void)sendEvent:(NSEvent *)event
{
[super sendEvent:event];
- if (self.inputContext)
- mp_input_wakeup(self.inputContext);
+ if (_eventsResponder.inputContext)
+ mp_input_wakeup(_eventsResponder.inputContext);
}
- (id)init
@@ -80,14 +80,8 @@ Application *mpv_shared_app(void)
self.menuItems = [[[NSMutableDictionary alloc] init] autorelease];
self.files = nil;
self.argumentsList = [[[NSMutableArray alloc] init] autorelease];
- self.eventsResponder = [[[EventsResponder alloc] init] autorelease];
+ _eventsResponder = [EventsResponder sharedInstance];
self.willStopOnOpenEvent = NO;
- self.input_ready = [[[NSCondition alloc] init] autorelease];
-
- [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask|NSKeyUpMask
- handler:^(NSEvent *event) {
- return [self.eventsResponder handleKey:event];
- }];
NSAppleEventManager *em = [NSAppleEventManager sharedAppleEventManager];
[em setEventHandler:self
@@ -169,9 +163,10 @@ Application *mpv_shared_app(void)
- (void)stopMPV:(char *)cmd
{
- if (self.inputContext) {
- mp_cmd_t *cmdt = mp_input_parse_cmd(self.inputContext, bstr0(cmd), "");
- mp_input_queue_cmd(self.inputContext, cmdt);
+ struct input_ctx *inputContext = _eventsResponder.inputContext;
+ if (inputContext) {
+ mp_cmd_t *cmdt = mp_input_parse_cmd(inputContext, bstr0(cmd), "");
+ mp_input_queue_cmd(inputContext, cmdt);
} else {
terminate_cocoa_application();
}
@@ -274,23 +269,9 @@ Application *mpv_shared_app(void)
}
}
-
-- (void)handleFilesArray:(NSArray *)files
-{
- size_t num_files = [files count];
- char **files_utf8 = talloc_array(NULL, char*, num_files);
- [files enumerateObjectsUsingBlock:^(id obj, NSUInteger i, BOOL *_){
- char *filename = (char *)[obj UTF8String];
- size_t bytes = [obj lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
- files_utf8[i] = talloc_memdup(files_utf8, filename, bytes + 1);
- }];
- mp_event_drop_files(self.inputContext, num_files, files_utf8);
- talloc_free(files_utf8);
-}
-
- (void)handleFiles
{
- [self handleFilesArray:self.files];
+ [_eventsResponder handleFilesArray:self.files];
}
@end
@@ -322,10 +303,7 @@ int cocoa_main(mpv_main_fn mpv_main, int argc, char *argv[])
macosx_finder_args_preinit(&argc, &argv);
pthread_create(&playback_thread_id, NULL, playback_thread, &ctx);
- [mpv_shared_app().input_ready lock];
- while (!mpv_shared_app().inputContext)
- [mpv_shared_app().input_ready wait];
- [mpv_shared_app().input_ready unlock];
+ [[EventsResponder sharedInstance] waitForInputContext];
cocoa_run_runloop();
@@ -380,14 +358,6 @@ void cocoa_stop_runloop(void)
cocoa_post_fake_event();
}
-void cocoa_set_input_context(struct input_ctx *input_context)
-{
- [mpv_shared_app().input_ready lock];
- mpv_shared_app().inputContext = input_context;
- [mpv_shared_app().input_ready signal];
- [mpv_shared_app().input_ready unlock];
-}
-
void cocoa_post_fake_event(void)
{
NSEvent* event = [NSEvent otherEventWithType:NSApplicationDefined
diff --git a/osdep/macosx_application_objc.h b/osdep/macosx_application_objc.h
index 3a3b753..bc2ff8e 100644
--- a/osdep/macosx_application_objc.h
+++ b/osdep/macosx_application_objc.h
@@ -18,33 +18,16 @@
#import <Cocoa/Cocoa.h>
#include "osdep/macosx_application.h"
-#import "ar/HIDRemote.h"
-
-@interface EventsResponder : NSObject <HIDRemoteDelegate>
-- (BOOL)handleMediaKey:(NSEvent *)event;
-- (NSEvent *)handleKey:(NSEvent *)event;
-- (void)startAppleRemote;
-- (void)stopAppleRemote;
-- (void)startMediaKeys;
-- (void)restartMediaKeys;
-- (void)stopMediaKeys;
-- (int)mapKeyModifiers:(int)cocoaModifiers;
-- (int)keyModifierMask:(NSEvent *)event;
-@end
@interface Application : NSApplication
- (void)initialize_menu;
- (void)registerSelector:(SEL)selector forKey:(MPMenuKey)key;
- (void)stopPlayback;
-- (void)handleFilesArray:(NSArray *)files;
-@property(nonatomic, assign) struct input_ctx *inputContext;
-@property(nonatomic, retain) EventsResponder *eventsResponder;
@property(nonatomic, retain) NSMutableDictionary *menuItems;
@property(nonatomic, retain) NSArray *files;
@property(nonatomic, retain) NSMutableArray *argumentsList;
@property(nonatomic, assign) BOOL willStopOnOpenEvent;
-@property(nonatomic, retain) NSCondition *input_ready;
@end
Application *mpv_shared_app(void);
diff --git a/osdep/macosx_compat.h b/osdep/macosx_compat.h
index f248538..9775529 100644
--- a/osdep/macosx_compat.h
+++ b/osdep/macosx_compat.h
@@ -22,10 +22,7 @@
#define MPV_MACOSX_COMPAT
#import <Cocoa/Cocoa.h>
-
-#if !defined(MAC_OS_X_VERSION_10_8)
-# define MAC_OS_X_VERSION_10_8 MAC_OS_X_VERSION_10_7 + 1
-#endif
+#include "osdep/macosx_versions.h"
#if (MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8)
@interface NSArray (SubscriptingAdditions)
diff --git a/osdep/macosx_events.h b/osdep/macosx_events.h
index a4b122f..f3dfbdf 100644
--- a/osdep/macosx_events.h
+++ b/osdep/macosx_events.h
@@ -21,6 +21,8 @@
#define MACOSX_EVENTS_H
#include "input/keycodes.h"
+struct input_ctx;
+
void cocoa_put_key(int keycode);
void cocoa_put_key_with_modifiers(int keycode, int modifiers);
@@ -30,4 +32,6 @@ void cocoa_uninit_apple_remote(void);
void cocoa_init_media_keys(void);
void cocoa_uninit_media_keys(void);
+void cocoa_set_input_context(struct input_ctx *input_context);
+
#endif
diff --git a/osdep/macosx_events.m b/osdep/macosx_events.m
index 56f1bd5..97ef93f 100644
--- a/osdep/macosx_events.m
+++ b/osdep/macosx_events.m
@@ -26,13 +26,34 @@
#import <Cocoa/Cocoa.h>
#include "talloc.h"
+#include "input/event.h"
#include "input/input.h"
+#include "input/keycodes.h"
// doesn't make much sense, but needed to access keymap functionality
#include "video/out/vo.h"
-#import "osdep/macosx_application_objc.h"
-#include "osdep/macosx_events.h"
#include "osdep/macosx_compat.h"
+#import "osdep/macosx_events_objc.h"
+
+@interface EventsResponder ()
+{
+ struct input_ctx *_inputContext;
+ NSCondition *_input_ready;
+ CFMachPortRef _mk_tap_port;
+ HIDRemote *_remote;
+}
+
+- (BOOL)handleMediaKey:(NSEvent *)event;
+- (NSEvent *)handleKey:(NSEvent *)event;
+- (void)startAppleRemote;
+- (void)stopAppleRemote;
+- (void)startMediaKeys;
+- (void)restartMediaKeys;
+- (void)stopMediaKeys;
+- (int)mapKeyModifiers:(int)cocoaModifiers;
+- (int)keyModifierMask:(NSEvent *)event;
+@end
+
#define NSLeftAlternateKeyMask (0x000020 | NSAlternateKeyMask)
#define NSRightAlternateKeyMask (0x000040 | NSAlternateKeyMask)
@@ -93,14 +114,12 @@ static int convert_key(unsigned key, unsigned charcode)
void cocoa_init_apple_remote(void)
{
- Application *app = mpv_shared_app();
- [app.eventsResponder startAppleRemote];
+ [[EventsResponder sharedInstance] startAppleRemote];
}
void cocoa_uninit_apple_remote(void)
{
- Application *app = mpv_shared_app();
- [app.eventsResponder stopAppleRemote];
+ [[EventsResponder sharedInstance] stopAppleRemote];
}
static int mk_code(NSEvent *event)
@@ -150,34 +169,87 @@ static CGEventRef tap_event_callback(CGEventTapProxy proxy, CGEventType type,
}
void cocoa_init_media_keys(void) {
- [mpv_shared_app().eventsResponder startMediaKeys];
+ [[EventsResponder sharedInstance] startMediaKeys];
}
void cocoa_uninit_media_keys(void) {
- [mpv_shared_app().eventsResponder stopMediaKeys];
+ [[EventsResponder sharedInstance] stopMediaKeys];
}
void cocoa_put_key(int keycode)
{
- if (mpv_shared_app().inputContext)
- mp_input_put_key(mpv_shared_app().inputContext, keycode);
+ struct input_ctx *inputContext = [EventsResponder sharedInstance].inputContext;
+ if (inputContext)
+ mp_input_put_key(inputContext, keycode);
}
void cocoa_put_key_with_modifiers(int keycode, int modifiers)
{
- keycode |= [mpv_shared_app().eventsResponder mapKeyModifiers:modifiers];
+ keycode |= [[EventsResponder sharedInstance] mapKeyModifiers:modifiers];
cocoa_put_key(keycode);
}
-@implementation EventsResponder {
- CFMachPortRef _mk_tap_port;
- HIDRemote *_remote;
+void cocoa_set_input_context(struct input_ctx *input_context)
+{
+ [EventsResponder sharedInstance].inputContext = input_context;
+}
+
+@implementation EventsResponder
+
++ (EventsResponder *)sharedInstance
+{
+ static EventsResponder *responder = nil;
+ static dispatch_once_t onceToken;
+ dispatch_once(&onceToken, ^{
+ responder = [EventsResponder new];
+ });
+ return responder;
+}
+
+- (id)init
+{
+ self = [super init];
+ if (self) {
+ _input_ready = [NSCondition new];
+
+ [NSEvent addLocalMonitorForEventsMatchingMask:NSKeyDownMask|NSKeyUpMask
+ handler:^(NSEvent *event) {
+ BOOL equivalent = [[NSApp mainMenu] performKeyEquivalent:event];
+ if (equivalent) {
+ return (NSEvent *)nil;
+ } else {
+ return [self handleKey:event];
+ }
+ }];
+ }
+ return self;
+}
+
+- (void)waitForInputContext
+{
+ [_input_ready lock];
+ while (!self.inputContext)
+ [_input_ready wait];
+ [_input_ready unlock];
+}
+
+- (void)setInputContext:(struct input_ctx *)ctx;
+{
+ [_input_ready lock];
+ _inputContext = ctx;
+ [_input_ready signal];
+ [_input_ready unlock];
+}
+
+- (struct input_ctx *)inputContext
+{
+ return _inputContext;
}
- (BOOL)useAltGr
{
- if (mpv_shared_app().inputContext)
- return mp_input_use_alt_gr(mpv_shared_app().inputContext);
+ if (self.inputContext)
+ return mp_input_use_alt_gr(self.inputContext);
else
return YES;
}
@@ -233,21 +305,6 @@ void cocoa_put_key_with_modifiers(int keycode, int modifiers)
});
}
-- (NSArray *) keyEquivalents
-{
- return @[@"h", @"q", @"Q", @"0", @"1", @"2"];
-}
-
-- (BOOL)isAppKeyEquivalent:(NSString *)eq withEvent:(NSEvent *)event
-{
- if ([event modifierFlags] & NSCommandKeyMask)
- for(NSString *c in [self keyEquivalents])
- if ([eq isEqualToString:c])
- return YES;
-
- return NO;
-}
-
- (BOOL)handleMediaKey:(NSEvent *)event
{
NSDictionary *keymapd = @{
@@ -349,14 +406,23 @@ void cocoa_put_key_with_modifiers(int keycode, int modifiers)
int key = convert_key([event keyCode], *[chars UTF8String]);
- if (key > -1) {
- if ([self isAppKeyEquivalent:chars withEvent:event])
- // propagate the event in case this is a menu key equivalent
- return event;
-
+ if (key > -1)
[self handleMPKey:key withMask:[self keyModifierMask:event]];
- }
return nil;
}
+
+- (void)handleFilesArray:(NSArray *)files
+{
+ size_t num_files = [files count];
+ char **files_utf8 = talloc_array(NULL, char*, num_files);
+ [files enumerateObjectsUsingBlock:^(id obj, NSUInteger i, BOOL *_){
+ char *filename = (char *)[obj UTF8String];
+ size_t bytes = [obj lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
+ files_utf8[i] = talloc_memdup(files_utf8, filename, bytes + 1);
+ }];
+ mp_event_drop_files(_inputContext, num_files, files_utf8);
+ talloc_free(files_utf8);
+}
+
@end
diff --git a/osdep/macosx_events_objc.h b/osdep/macosx_events_objc.h
new file mode 100644
index 0000000..e9b14ed
--- /dev/null
+++ b/osdep/macosx_events_objc.h
@@ -0,0 +1,37 @@
+/*
+ * Cocoa Application Event Handling
+ *
+ * This file is part of mpv.
+ *
+ * mpv 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.
+ *
+ * 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#import <Cocoa/Cocoa.h>
+#import "ar/HIDRemote.h"
+#include "osdep/macosx_events.h"
+
+struct input_ctx;
+
+@interface EventsResponder : NSObject <HIDRemoteDelegate>
+
++ (EventsResponder *)sharedInstance;
+
+/// Blocks until inputContext is present.
+- (void)waitForInputContext;
+
+- (void)handleFilesArray:(NSArray *)files;
+
+@property(nonatomic, assign) struct input_ctx *inputContext;
+
+@end
diff --git a/osdep/macosx_versions.h b/osdep/macosx_versions.h
new file mode 100644
index 0000000..83bcf5d
--- /dev/null
+++ b/osdep/macosx_versions.h
@@ -0,0 +1,29 @@
+/*
+ * This file is part of mpv.
+ *
+ * mpv 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.
+ *
+ * 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 General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with mpv. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef MPV_MACOSX_VERSIONS
+#define MPV_MACOSX_VERSIONS
+
+#if !defined(MAC_OS_X_VERSION_10_8)
+# define MAC_OS_X_VERSION_10_8 1080
+#endif
+
+#if !defined(MAC_OS_X_VERSION_10_9)
+# define MAC_OS_X_VERSION_10_9 1090
+#endif
+
+#endif /* MPV_MACOSX_VERSIONS */
diff --git a/osdep/path-macosx.m b/osdep/path-macosx.m
index c5240f5..33086c3 100644
--- a/osdep/path-macosx.m
+++ b/osdep/path-macosx.m
@@ -20,12 +20,12 @@
#include "options/path.h"
#include "osdep/path.h"
-char *mp_get_macosx_bundled_path(void *talloc_ctx, struct mpv_global *global,
- const char *file)
+int mp_add_macosx_bundle_dir(struct mpv_global *global, char **dirs, int i)
{
+ void *talloc_ctx = dirs;
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *path = [[NSBundle mainBundle] resourcePath];
- char *rv = mp_path_join(talloc_ctx, bstr0([path UTF8String]), bstr0(file));
+ dirs[i++] = talloc_strdup(talloc_ctx, [path UTF8String]);
[pool release];
- return rv;
+ return i;
}
diff --git a/osdep/path-win.c b/osdep/path-win.c
index 2b1e8b5..c656023 100644
--- a/osdep/path-win.c
+++ b/osdep/path-win.c
@@ -24,55 +24,48 @@
// Warning: do not use PATH_MAX. Cygwin messed it up.
-static void get_exe_dir(wchar_t path[MAX_PATH + 1])
+static char *mp_get_win_exe_dir(void *talloc_ctx)
{
- int len = (int)GetModuleFileNameW(NULL, path, MAX_PATH);
+ wchar_t w_exedir[MAX_PATH + 1] = {0};
+
+ int len = (int)GetModuleFileNameW(NULL, w_exedir, MAX_PATH);
int imax = 0;
for (int i = 0; i < len; i++) {
- if (path[i] == '\\') {
- path[i] = '/';
+ if (w_exedir[i] == '\\') {
+ w_exedir[i] = '/';
imax = i;
}
}
- path[imax] = '\0';
+ w_exedir[imax] = '\0';
+
+ return mp_to_utf8(talloc_ctx, w_exedir);
}
-char *mp_get_win_config_path(const char *filename)
+static char *mp_get_win_exe_subdir(void *talloc_ctx)
+{
+ return talloc_asprintf(talloc_ctx, "%s/mpv", mp_get_win_exe_dir(talloc_ctx));
+}
+
+static char *mp_get_win_app_dir(void *talloc_ctx)
{
wchar_t w_appdir[MAX_PATH + 1] = {0};
- wchar_t w_exedir[MAX_PATH + 1] = {0};
- char *res = NULL;
- void *tmp = talloc_new(NULL);
-#ifndef __CYGWIN__
if (SHGetFolderPathW(NULL, CSIDL_APPDATA|CSIDL_FLAG_CREATE, NULL,
SHGFP_TYPE_CURRENT, w_appdir) != S_OK)
- w_appdir[0] = '\0';
-#endif
+ return NULL;
- get_exe_dir(w_exedir);
-
- if (filename && filename[0] && w_exedir[0]) {
- char *dir = mp_to_utf8(tmp, w_exedir);
- char *temp = mp_path_join(tmp, bstr0(dir), bstr0("mpv"));
- res = mp_path_join(NULL, bstr0(temp), bstr0(filename));
- if (!mp_path_exists(res) || mp_path_isdir(res)) {
- talloc_free(res);
- res = mp_path_join(NULL, bstr0(dir), bstr0(filename));
- if (!mp_path_exists(res) || mp_path_isdir(res)) {
- talloc_free(res);
- res = NULL;
- }
- }
- }
-
- if (!res && w_appdir[0]) {
- char *dir = mp_to_utf8(tmp, w_appdir);
- char *temp = mp_path_join(tmp, bstr0(dir), bstr0("mpv"));
- res = mp_path_join(NULL, bstr0(temp), bstr0(filename));
- }
+ return talloc_asprintf(talloc_ctx, "%s/mpv", mp_to_utf8(talloc_ctx, w_appdir));
+}
- talloc_free(tmp);
- return res;
+int mp_add_win_config_dirs(struct mpv_global *global, char **dirs, int i)
+{
+ void *talloc_ctx = dirs;
+ if ((dirs[i] = mp_get_win_exe_subdir(talloc_ctx)))
+ i++;
+ if ((dirs[i] = mp_get_win_exe_dir(talloc_ctx)))
+ i++;
+ if ((dirs[i] = mp_get_win_app_dir(talloc_ctx)))
+ i++;
+ return i;
}
diff --git a/osdep/path.h b/osdep/path.h
index 91afbce..c697453 100644
--- a/osdep/path.h
+++ b/osdep/path.h
@@ -1,12 +1,15 @@
#ifndef OSDEP_PATH_H
#define OSDEP_PATH_H
-struct mpv_global;
+#define MAX_CONFIG_PATHS 32
-char *mp_get_win_config_path(const char *filename);
+struct mpv_global;
-// Returns absolute path of a resource file in a Mac OS X application bundle.
-char *mp_get_macosx_bundled_path(void *talloc_ctx, struct mpv_global *global,
- const char *filename);
+// Append paths starting at dirs[i]. The dirs array has place only for at most
+// MAX_CONFIG_PATHS paths, but it's guaranteed that at least 4 paths can be
+// added without checking for i>=MAX_CONFIG_PATHS.
+// Return the new value of i.
+int mp_add_win_config_dirs(struct mpv_global *global, char **dirs, int i);
+int mp_add_macosx_bundle_dir(struct mpv_global *global, char **dirs, int i);
#endif
diff --git a/osdep/terminal-unix.c b/osdep/terminal-unix.c
index 844054e..21ed42c 100644
--- a/osdep/terminal-unix.c
+++ b/osdep/terminal-unix.c
@@ -466,6 +466,7 @@ static int read_keys(void *ctx, int fd)
void terminal_setup_getch(struct input_ctx *ictx)
{
mp_input_add_fd(ictx, 0, 1, NULL, read_keys, NULL, ictx);
+ getch2_enable();
}
static volatile int getch2_active = 0;
@@ -624,11 +625,6 @@ void terminal_set_foreground_color(FILE *stream, int c)
}
}
-void terminal_setup_stdin_cmd_input(struct input_ctx *ictx)
-{
- mp_input_add_fd(ictx, 0, 1, input_default_read_cmd, NULL, NULL, NULL);
-}
-
int terminal_init(void)
{
use_terminal = isatty(1);
diff --git a/osdep/terminal-win.c b/osdep/terminal-win.c
index 918a073..19603d8 100644
--- a/osdep/terminal-win.c
+++ b/osdep/terminal-win.c
@@ -54,30 +54,6 @@ static const unsigned char ansi2win32[8] = {
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED,
};
-static int mp_input_slave_cmd_func(void *ctx, int fd, char *dest, int size)
-{
- DWORD retval;
- HANDLE in = GetStdHandle(STD_INPUT_HANDLE);
- if (PeekNamedPipe(in, NULL, size, &retval, NULL, NULL)) {
- if (size > retval)
- size = retval;
- } else {
- if (WaitForSingleObject(in, 0))
- size = 0;
- }
- if (!size)
- return MP_INPUT_NOTHING;
- ReadFile(in, dest, size, &retval, NULL);
- if (retval)
- return retval;
- return MP_INPUT_NOTHING;
-}
-
-void terminal_setup_stdin_cmd_input(struct input_ctx *ictx)
-{
- mp_input_add_fd(ictx, 0, 0, mp_input_slave_cmd_func, NULL, NULL, NULL);
-}
-
void get_screen_size(void)
{
CONSOLE_SCREEN_BUFFER_INFO cinfo;
@@ -170,6 +146,7 @@ static int read_keys(void *ctx, int fd)
void terminal_setup_getch(struct input_ctx *ictx)
{
mp_input_add_fd(ictx, 0, 1, NULL, read_keys, NULL, ictx);
+ getch2_enable();
}
void getch2_poll(void)
diff --git a/osdep/terminal.h b/osdep/terminal.h
index 651e31e..4495bfb 100644
--- a/osdep/terminal.h
+++ b/osdep/terminal.h
@@ -39,9 +39,6 @@ extern char *terminal_cursor_up;
/* Global initialization for terminal output. */
int terminal_init(void);
-/* Setup ictx to read input commands from stdin (slave mode) */
-void terminal_setup_stdin_cmd_input(struct input_ctx *ictx);
-
/* Setup ictx to read keys from the terminal */
void terminal_setup_getch(struct input_ctx *ictx);
diff --git a/player/audio.c b/player/audio.c
index e0c6ca9..55e3ba7 100644
--- a/player/audio.c
+++ b/player/audio.c
@@ -19,6 +19,7 @@
#include <stddef.h>
#include <stdbool.h>
#include <inttypes.h>
+#include <limits.h>
#include <math.h>
#include <assert.h>
@@ -42,13 +43,12 @@
#include "core.h"
#include "command.h"
-static int build_afilter_chain(struct MPContext *mpctx)
+static int recreate_audio_filters(struct MPContext *mpctx)
{
struct dec_audio *d_audio = mpctx->d_audio;
struct MPOpts *opts = mpctx->opts;
- if (!d_audio)
- return 0;
+ assert(d_audio);
struct mp_audio in_format;
mp_audio_buffer_get_format(d_audio->decode_buffer, &in_format);
@@ -65,16 +65,9 @@ static int build_afilter_chain(struct MPContext *mpctx)
if (new_srate != out_format.rate)
opts->playback_speed = new_srate / (double)in_format.rate;
}
- return audio_init_filters(d_audio, new_srate,
- &out_format.rate, &out_format.channels, &out_format.format);
-}
-
-static int recreate_audio_filters(struct MPContext *mpctx)
-{
- assert(mpctx->d_audio);
-
- // init audio filters:
- if (!build_afilter_chain(mpctx)) {
+ if (!audio_init_filters(d_audio, new_srate,
+ &out_format.rate, &out_format.channels, &out_format.format))
+ {
MP_ERR(mpctx, "Couldn't find matching filter/ao format!\n");
return -1;
}
@@ -99,11 +92,18 @@ int reinit_audio_filters(struct MPContext *mpctx)
return 1;
}
+void reset_audio_state(struct MPContext *mpctx)
+{
+ if (mpctx->d_audio)
+ audio_reset_decoding(mpctx->d_audio);
+ mpctx->audio_status = mpctx->d_audio ? STATUS_SYNCING : STATUS_EOF;
+}
+
void reinit_audio_chain(struct MPContext *mpctx)
{
struct MPOpts *opts = mpctx->opts;
struct track *track = mpctx->current_track[0][STREAM_AUDIO];
- struct sh_stream *sh = init_demux_stream(mpctx, track);
+ struct sh_stream *sh = track ? track->stream : NULL;
if (!sh) {
uninit_player(mpctx, INITIALIZED_AO);
goto no_audio;
@@ -111,6 +111,8 @@ void reinit_audio_chain(struct MPContext *mpctx)
mp_notify(mpctx, MPV_EVENT_AUDIO_RECONFIG, NULL);
+ mpctx->audio_status = STATUS_SYNCING;
+
if (!(mpctx->initialized_flags & INITIALIZED_ACODEC)) {
mpctx->initialized_flags |= INITIALIZED_ACODEC;
assert(!mpctx->d_audio);
@@ -119,16 +121,26 @@ void reinit_audio_chain(struct MPContext *mpctx)
mpctx->d_audio->global = mpctx->global;
mpctx->d_audio->opts = opts;
mpctx->d_audio->header = sh;
- mpctx->d_audio->metadata = mpctx->demuxer->metadata;
- mpctx->d_audio->replaygain_data = mpctx->demuxer->replaygain_data;
+ mpctx->d_audio->replaygain_data = sh->audio->replaygain_data;
if (!audio_init_best_codec(mpctx->d_audio, opts->audio_decoders))
goto init_error;
+ reset_audio_state(mpctx);
}
assert(mpctx->d_audio);
+ if (!mpctx->ao_buffer)
+ mpctx->ao_buffer = mp_audio_buffer_create(mpctx);
+
struct mp_audio in_format;
mp_audio_buffer_get_format(mpctx->d_audio->decode_buffer, &in_format);
+ if (!mp_audio_config_valid(&in_format)) {
+ // We don't know the audio format yet - so configure it later as we're
+ // resyncing. fill_audio_buffers() will call this function again.
+ mpctx->sleeptime = 0;
+ return;
+ }
+
if (mpctx->ao_decoder_fmt && (mpctx->initialized_flags & INITIALIZED_AO) &&
!mp_audio_config_equals(mpctx->ao_decoder_fmt, &in_format) &&
opts->gapless_audio < 0)
@@ -150,7 +162,7 @@ void reinit_audio_chain(struct MPContext *mpctx)
ao_channels = opts->audio_output_channels; // automatic downmix
}
- // Determine what the filter chain outputs. build_afilter_chain() also
+ // Determine what the filter chain outputs. recreate_audio_filters() also
// needs this for testing whether playback speed is changed by resampling
// or using a special filter.
if (!audio_init_filters(mpctx->d_audio, // preliminary init
@@ -178,7 +190,6 @@ void reinit_audio_chain(struct MPContext *mpctx)
struct mp_audio fmt;
ao_get_format(ao, &fmt);
- mpctx->ao_buffer = mp_audio_buffer_create(ao);
mp_audio_buffer_reinit(mpctx->ao_buffer, &fmt);
mpctx->ao_decoder_fmt = talloc(NULL, struct mp_audio);
@@ -194,7 +205,6 @@ void reinit_audio_chain(struct MPContext *mpctx)
if (recreate_audio_filters(mpctx) < 0)
goto init_error;
- mpctx->syncing_audio = true;
return;
init_error:
@@ -215,6 +225,9 @@ double written_audio_pts(struct MPContext *mpctx)
struct mp_audio in_format;
mp_audio_buffer_get_format(d_audio->decode_buffer, &in_format);
+ if (!mp_audio_config_valid(&in_format) || !d_audio->afilter)
+ return MP_NOPTS_VALUE;;
+
// first calculate the end pts of audio that has been output by decoder
double a_pts = d_audio->pts;
if (a_pts == MP_NOPTS_VALUE)
@@ -249,7 +262,7 @@ double written_audio_pts(struct MPContext *mpctx)
double playing_audio_pts(struct MPContext *mpctx)
{
double pts = written_audio_pts(mpctx);
- if (pts == MP_NOPTS_VALUE)
+ if (pts == MP_NOPTS_VALUE || !mpctx->ao)
return pts;
return pts - mpctx->opts->playback_speed * ao_get_delay(mpctx->ao);
}
@@ -264,7 +277,7 @@ static int write_to_ao(struct MPContext *mpctx, struct mp_audio *data, int flags
ao_get_format(ao, &out_format);
mpctx->ao_pts = pts;
#if HAVE_ENCODING
- encode_lavc_set_audio_pts(mpctx->encode_lavc_ctx, mpctx->ao_pts);
+ encode_lavc_set_audio_pts(mpctx->encode_lavc_ctx, playing_audio_pts(mpctx));
#endif
if (data->samples == 0)
return 0;
@@ -282,143 +295,118 @@ static int write_to_ao(struct MPContext *mpctx, struct mp_audio *data, int flags
return 0;
}
-static int write_silence_to_ao(struct MPContext *mpctx, int samples, int flags,
- double pts)
+// Return the number of samples that must be skipped or prepended to reach the
+// target audio pts after a seek (for A/V sync or hr-seek).
+// Return value (*skip):
+// >0: skip this many samples
+// =0: don't do anything
+// <0: prepend this many samples of silence
+// Returns false if PTS is not known yet.
+static bool get_sync_samples(struct MPContext *mpctx, int *skip)
{
- struct mp_audio tmp = {0};
- mp_audio_buffer_get_format(mpctx->ao_buffer, &tmp);
- tmp.samples = samples;
- char *p = talloc_size(NULL, tmp.samples * tmp.sstride);
- for (int n = 0; n < tmp.num_planes; n++)
- tmp.planes[n] = p;
- mp_audio_fill_silence(&tmp, 0, tmp.samples);
- int r = write_to_ao(mpctx, &tmp, 0, pts);
- talloc_free(p);
- return r;
-}
-
-#define ASYNC_PLAY_DONE -3
-static int audio_start_sync(struct MPContext *mpctx, int playsize)
-{
- struct ao *ao = mpctx->ao;
struct MPOpts *opts = mpctx->opts;
- struct dec_audio *d_audio = mpctx->d_audio;
- int res;
+ *skip = 0;
- assert(d_audio);
+ if (mpctx->audio_status != STATUS_SYNCING)
+ return true;
- struct mp_audio out_format;
- ao_get_format(ao, &out_format);
+ struct mp_audio out_format = {0};
+ ao_get_format(mpctx->ao, &out_format);
+ double play_samplerate = out_format.rate / opts->playback_speed;
- // Timing info may not be set without
- res = audio_decode(d_audio, mpctx->ao_buffer, 1);
- if (res < 0)
- return res;
-
- int samples;
- bool did_retry = false;
- double written_pts;
- double real_samplerate = out_format.rate / opts->playback_speed;
- bool hrseek = mpctx->hrseek_active; // audio only hrseek
- mpctx->hrseek_active = false;
- while (1) {
- written_pts = written_audio_pts(mpctx);
- double ptsdiff;
- if (hrseek)
- ptsdiff = written_pts - mpctx->hrseek_pts;
- else
- ptsdiff = written_pts - mpctx->video_next_pts - mpctx->delay
- + mpctx->audio_delay;
- samples = ptsdiff * real_samplerate;
-
- // ogg demuxers give packets without timing
- if (written_pts <= 1 && d_audio->pts == MP_NOPTS_VALUE) {
- if (!did_retry) {
- // Try to read more data to see packets that have pts
- res = audio_decode(d_audio, mpctx->ao_buffer, out_format.rate);
- if (res < 0)
- return res;
- did_retry = true;
- continue;
- }
- samples = 0;
- }
+ bool is_pcm = !(out_format.format & AF_FORMAT_SPECIAL_MASK); // no spdif
+ if (!opts->initial_audio_sync || !is_pcm) {
+ mpctx->audio_status = STATUS_FILLING;
+ return true;
+ }
+
+ double written_pts = written_audio_pts(mpctx);
+ if (written_pts == MP_NOPTS_VALUE && !mp_audio_buffer_samples(mpctx->ao_buffer))
+ return false; // no audio read yet
- if (fabs(ptsdiff) > 300 || isnan(ptsdiff)) // pts reset or just broken?
- samples = 0;
-
- if (samples > 0)
- break;
-
- mpctx->syncing_audio = false;
- int skip_samples = -samples;
- int a = MPMIN(skip_samples, MPMAX(playsize, 2500));
- res = audio_decode(d_audio, mpctx->ao_buffer, a);
- if (skip_samples <= mp_audio_buffer_samples(mpctx->ao_buffer)) {
- mp_audio_buffer_skip(mpctx->ao_buffer, skip_samples);
- if (res < 0)
- return res;
- return audio_decode(d_audio, mpctx->ao_buffer, playsize);
+ bool sync_to_video = mpctx->d_video && mpctx->sync_audio_to_video;
+
+ double sync_pts = MP_NOPTS_VALUE;
+ if (sync_to_video) {
+ if (mpctx->video_next_pts != MP_NOPTS_VALUE) {
+ sync_pts = mpctx->video_next_pts;
+ } else if (mpctx->video_status < STATUS_READY) {
+ return false; // wait until we know a video PTS
}
- mp_audio_buffer_clear(mpctx->ao_buffer);
- if (res < 0)
- return res;
+ } else if (mpctx->hrseek_active) {
+ sync_pts = mpctx->hrseek_pts;
}
- if (hrseek)
- // Don't add silence in audio-only case even if position is too late
- return 0;
- if (samples >= playsize) {
- /* This case could fall back to the one below with
- * samples = playsize, but then silence would keep accumulating
- * in ao_buffer if the AO accepts less data than it asks for
- * in playsize. */
- write_silence_to_ao(mpctx, playsize, 0,
- written_pts - samples / real_samplerate);
- return ASYNC_PLAY_DONE;
+ if (sync_pts == MP_NOPTS_VALUE) {
+ mpctx->audio_status = STATUS_FILLING;
+ return true; // syncing disabled
+ }
+
+ if (sync_to_video)
+ sync_pts += mpctx->delay - mpctx->audio_delay;
+
+ double ptsdiff = written_pts - sync_pts;
+ // Missing timestamp, or PTS reset, or just broken.
+ if (written_pts == MP_NOPTS_VALUE || fabs(ptsdiff) > 300) {
+ MP_WARN(mpctx, "Failed audio resync.\n");
+ mpctx->audio_status = STATUS_FILLING;
+ return true;
}
- mpctx->syncing_audio = false;
- mp_audio_buffer_prepend_silence(mpctx->ao_buffer, samples);
- return audio_decode(d_audio, mpctx->ao_buffer, playsize);
+
+ *skip = -ptsdiff * play_samplerate;
+ return true;
}
-int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
+void fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
{
struct MPOpts *opts = mpctx->opts;
- struct ao *ao = mpctx->ao;
- int playsize;
- int playflags = 0;
- bool audio_eof = false;
- bool signal_eof = false;
- bool partial_fill = false;
struct dec_audio *d_audio = mpctx->d_audio;
- struct mp_audio out_format;
- ao_get_format(ao, &out_format);
- // Can't adjust the start of audio with spdif pass-through.
- bool modifiable_audio_format = !(out_format.format & AF_FORMAT_SPECIAL_MASK);
-
- assert(d_audio);
- if (mpctx->paused)
- playsize = 1; // just initialize things (audio pts at least)
- else
- playsize = ao_get_space(ao);
-
- // Coming here with hrseek_active still set means audio-only
- if (!mpctx->d_video || !mpctx->sync_audio_to_video)
- mpctx->syncing_audio = false;
- if (!opts->initial_audio_sync || !modifiable_audio_format) {
- mpctx->syncing_audio = false;
- mpctx->hrseek_active = false;
+ if (!d_audio)
+ return;
+
+ if (!d_audio->afilter || !mpctx->ao) {
+ // Probe the initial audio format. Returns AD_OK (and does nothing) if
+ // the format is already known.
+ int r = initial_audio_decode(mpctx->d_audio);
+ if (r == AD_WAIT)
+ return; // continue later when new data is available
+ mpctx->d_audio->init_retries += 1;
+ MP_VERBOSE(mpctx, "Initial audio packets read: %d\n",
+ mpctx->d_audio->init_retries);
+ if (r != AD_OK && mpctx->d_audio->init_retries >= 50) {
+ MP_ERR(mpctx, "Error initializing audio.\n");
+ struct track *track = mpctx->current_track[0][STREAM_AUDIO];
+ mp_deselect_track(mpctx, track);
+ return;
+ }
+ reinit_audio_chain(mpctx);
+ return; // try again next iteration
}
- int res;
- if (mpctx->syncing_audio || mpctx->hrseek_active)
- res = audio_start_sync(mpctx, playsize);
- else
- res = audio_decode(d_audio, mpctx->ao_buffer, playsize);
+ // If audio is infinitely fast, somehow try keeping approximate A/V sync.
+ if (mpctx->audio_status == STATUS_PLAYING && ao_untimed(mpctx->ao) &&
+ mpctx->video_status != STATUS_EOF && mpctx->delay > 0)
+ return;
+
+ // if paused, just initialize things (audio format & pts)
+ int playsize = 1;
+ if (!mpctx->paused)
+ playsize = ao_get_space(mpctx->ao);
+
+ int skip = 0;
+ bool sync_known = get_sync_samples(mpctx, &skip);
+ if (skip > 0) {
+ playsize = MPMIN(skip + 1, MPMAX(playsize, 2500)); // buffer extra data
+ } else if (skip < 0) {
+ playsize = MPMAX(1, playsize + skip); // silence will be prepended
+ }
- if (res < 0) { // EOF, error or format change
- if (res == -2) {
+ int status = AD_OK;
+ if (playsize > mp_audio_buffer_samples(mpctx->ao_buffer)) {
+ status = audio_decode(d_audio, mpctx->ao_buffer, playsize);
+ if (status == AD_WAIT)
+ return;
+ if (status == AD_NEW_FMT) {
/* The format change isn't handled too gracefully. A more precise
* implementation would require draining buffered old-format audio
* while displaying video, then doing the output format switch.
@@ -426,16 +414,68 @@ int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
if (mpctx->opts->gapless_audio < 1)
uninit_player(mpctx, INITIALIZED_AO);
reinit_audio_chain(mpctx);
- return -1;
- } else if (res == ASYNC_PLAY_DONE)
- return 0;
- else if (demux_stream_eof(d_audio->header))
- audio_eof = true;
+ mpctx->sleeptime = 0;
+ return; // retry on next iteration
+ }
}
+ // If EOF was reached before, but now something can be decoded, try to
+ // restart audio properly. This helps with video files where audio starts
+ // later. Retrying is needed to get the correct sync PTS.
+ if (mpctx->audio_status == STATUS_EOF && status == AD_OK) {
+ mpctx->audio_status = STATUS_SYNCING;
+ mpctx->sleeptime = 0;
+ return; // retry on next iteration
+ }
+
+ bool end_sync = false;
+ if (skip >= 0) {
+ int max = mp_audio_buffer_samples(mpctx->ao_buffer);
+ mp_audio_buffer_skip(mpctx->ao_buffer, MPMIN(skip, max));
+ // If something is left, we definitely reached the target time.
+ end_sync |= sync_known && skip < max;
+ } else if (skip < 0) {
+ if (-skip > playsize) { // heuristic against making the buffer too large
+ ao_reset(mpctx->ao); // some AOs repeat data on underflow
+ mpctx->audio_status = STATUS_EOF;
+ mpctx->delay = 0;
+ return;
+ }
+ mp_audio_buffer_prepend_silence(mpctx->ao_buffer, -skip);
+ end_sync = true;
+ }
+
+ if (mpctx->audio_status == STATUS_SYNCING) {
+ if (end_sync)
+ mpctx->audio_status = STATUS_FILLING;
+ if (status != AD_OK)
+ mpctx->audio_status = STATUS_EOF;
+ mpctx->sleeptime = 0;
+ return; // continue on next iteration
+ }
+
+ assert(mpctx->audio_status >= STATUS_FILLING);
+
+ // Even if we're done decoding and syncing, let video start first - this is
+ // required, because sending audio to the AO already starts playback.
+ if (mpctx->audio_status == STATUS_FILLING && mpctx->sync_audio_to_video &&
+ mpctx->video_status <= STATUS_READY)
+ {
+ mpctx->audio_status = STATUS_READY;
+ return;
+ }
+
+ bool audio_eof = status == AD_EOF;
+ bool partial_fill = false;
+ int playflags = 0;
+
+ struct mp_audio out_format = {0};
+ ao_get_format(mpctx->ao, &out_format);
+ double play_samplerate = out_format.rate / opts->playback_speed;
+
if (endpts != MP_NOPTS_VALUE) {
double samples = (endpts - written_audio_pts(mpctx) - mpctx->audio_delay)
- * out_format.rate / opts->playback_speed;
+ * play_samplerate;
if (playsize > samples) {
playsize = MPMAX(samples, 0);
audio_eof = true;
@@ -447,18 +487,13 @@ int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
playsize = mp_audio_buffer_samples(mpctx->ao_buffer);
partial_fill = true;
}
- if (!playsize)
- return partial_fill && audio_eof ? -2 : -partial_fill;
-
- if (audio_eof && partial_fill) {
- if (opts->gapless_audio) {
- // With gapless audio, delay this to ao_uninit. There must be only
- // 1 final chunk, and that is handled when calling ao_uninit().
- signal_eof = true;
- } else {
- playflags |= AOPLAY_FINAL_CHUNK;
- }
- }
+
+ audio_eof &= partial_fill;
+
+ // With gapless audio, delay this to ao_uninit. There must be only
+ // 1 final chunk, and that is handled when calling ao_uninit().
+ if (audio_eof && !opts->gapless_audio)
+ playflags |= AOPLAY_FINAL_CHUNK;
if (mpctx->paused)
playsize = 0;
@@ -468,10 +503,16 @@ int fill_audio_out_buffers(struct MPContext *mpctx, double endpts)
data.samples = MPMIN(data.samples, playsize);
int played = write_to_ao(mpctx, &data, playflags, written_audio_pts(mpctx));
assert(played >= 0 && played <= data.samples);
-
mp_audio_buffer_skip(mpctx->ao_buffer, played);
- return signal_eof ? -2 : -partial_fill;
+ mpctx->audio_status = STATUS_PLAYING;
+ if (audio_eof) {
+ mpctx->audio_status = STATUS_DRAINING;
+ // Wait until the AO has played all queued data. In the gapless case,
+ // we trigger EOF immediately, and let it play asynchronously.
+ if (ao_eof_reached(mpctx->ao) || opts->gapless_audio)
+ mpctx->audio_status = STATUS_EOF;
+ }
}
// Drop data queued for output, or which the AO is currently outputting.
diff --git a/player/client.c b/player/client.c
index e7a993d..bccf2d9 100644
--- a/player/client.c
+++ b/player/client.c
@@ -63,6 +63,8 @@ struct mp_client_api {
struct observe_property {
char *name;
+ int id; // ==mp_get_property_id(name)
+ uint64_t event_mask; // ==mp_get_property_event_mask(name)
int64_t reply_id;
mpv_format format;
bool changed; // property change should be signaled to user
@@ -111,13 +113,15 @@ struct mpv_handle {
struct observe_property **properties;
int num_properties;
- int lowest_changed;
+ int lowest_changed; // attempt at making change processing incremental
int properties_updating;
+ uint64_t property_event_masks; // or-ed together event masks of all properties
struct mp_log_buffer *messages;
};
static bool gen_property_change_event(struct mpv_handle *ctx);
+static void notify_property_events(struct mpv_handle *ctx, uint64_t event_mask);
void mp_clients_init(struct MPContext *mpctx)
{
@@ -188,13 +192,15 @@ struct mpv_handle *mp_new_client(struct mp_client_api *clients, const char *name
.cur_event = talloc_zero(client, struct mpv_event),
.events = talloc_array(client, mpv_event, num_events),
.max_events = num_events,
- .event_mask = ((uint64_t)-1) & ~(1ULL << MPV_EVENT_TICK),
+ .event_mask = (1ULL << INTERNAL_EVENT_BASE) - 1, // exclude internal events
.wakeup_pipe = {-1, -1},
};
pthread_mutex_init(&client->lock, NULL);
pthread_mutex_init(&client->wakeup_lock, NULL);
pthread_cond_init(&client->wakeup, NULL);
+ mpv_request_event(client, MPV_EVENT_TICK, 0);
+
MP_TARRAY_APPEND(clients, clients->clients, clients->num_clients, client);
pthread_mutex_unlock(&clients->lock);
@@ -335,7 +341,7 @@ void mpv_terminate_destroy(mpv_handle *ctx)
mpv_command(ctx, (const char*[]){"quit", NULL});
- if (!ctx->owner) {
+ if (!ctx->owner || !ctx->mpctx->initialized) {
mpv_detach_destroy(ctx);
return;
}
@@ -429,7 +435,10 @@ static int append_event(struct mpv_handle *ctx, struct mpv_event *event)
static int send_event(struct mpv_handle *ctx, struct mpv_event *event)
{
pthread_mutex_lock(&ctx->lock);
- if (!(ctx->event_mask & (1ULL << event->event_id))) {
+ uint64_t mask = 1ULL << event->event_id;
+ if (ctx->property_event_masks & mask)
+ notify_property_events(ctx, mask);
+ if (!(ctx->event_mask & mask)) {
pthread_mutex_unlock(&ctx->lock);
return 0;
}
@@ -541,8 +550,9 @@ int mpv_request_event(mpv_handle *ctx, mpv_event_id event, int enable)
{
if (!mpv_event_name(event) || enable < 0 || enable > 1)
return MPV_ERROR_INVALID_PARAMETER;
+ assert(event < INTERNAL_EVENT_BASE); // excluded above; they have no name
pthread_mutex_lock(&ctx->lock);
- uint64_t bit = 1LLU << event;
+ uint64_t bit = 1ULL << event;
ctx->event_mask = enable ? ctx->event_mask | bit : ctx->event_mask & ~bit;
pthread_mutex_unlock(&ctx->lock);
return 0;
@@ -1120,12 +1130,15 @@ int mpv_observe_property(mpv_handle *ctx, uint64_t userdata,
*prop = (struct observe_property){
.client = ctx,
.name = talloc_strdup(prop, name),
+ .id = mp_get_property_id(name),
+ .event_mask = mp_get_property_event_mask(name),
.reply_id = userdata,
.format = format,
.changed = true,
.need_new_value = true,
};
MP_TARRAY_APPEND(ctx, ctx->properties, ctx->num_properties, prop);
+ ctx->property_event_masks |= prop->event_mask;
ctx->lowest_changed = 0;
pthread_mutex_unlock(&ctx->lock);
return 0;
@@ -1134,6 +1147,7 @@ int mpv_observe_property(mpv_handle *ctx, uint64_t userdata,
int mpv_unobserve_property(mpv_handle *ctx, uint64_t userdata)
{
pthread_mutex_lock(&ctx->lock);
+ ctx->property_event_masks = 0;
int count = 0;
for (int n = ctx->num_properties - 1; n >= 0; n--) {
struct observe_property *prop = ctx->properties[n];
@@ -1150,52 +1164,38 @@ int mpv_unobserve_property(mpv_handle *ctx, uint64_t userdata)
MP_TARRAY_REMOVE_AT(ctx->properties, ctx->num_properties, n);
count++;
}
+ if (!prop->dead)
+ ctx->property_event_masks |= prop->event_mask;
}
ctx->lowest_changed = 0;
pthread_mutex_unlock(&ctx->lock);
return count;
}
-static int prefix_len(const char *p)
-{
- const char *end = strchr(p, '/');
- return end ? end - p : strlen(p);
-}
-
-static bool match_property(const char *a, const char *b)
+static void mark_property_changed(struct mpv_handle *client, int index)
{
- if (strcmp(b, "*") == 0)
- return true;
- int len_a = prefix_len(a);
- int len_b = prefix_len(b);
- return strncmp(a, b, MPMIN(len_a, len_b)) == 0;
+ struct observe_property *prop = client->properties[index];
+ if (!prop->changed && !prop->need_new_value) {
+ prop->changed = true;
+ prop->need_new_value = prop->format != 0;
+ client->lowest_changed = MPMIN(client->lowest_changed, index);
+ }
}
-// Broadcast that properties have changed.
-void mp_client_property_change(struct MPContext *mpctx, const char *const *list)
+// Broadcast that a property has changed.
+void mp_client_property_change(struct MPContext *mpctx, const char *name)
{
struct mp_client_api *clients = mpctx->clients;
+ int id = mp_get_property_id(name);
pthread_mutex_lock(&clients->lock);
for (int n = 0; n < clients->num_clients; n++) {
struct mpv_handle *client = clients->clients[n];
pthread_mutex_lock(&client->lock);
-
- client->lowest_changed = client->num_properties;
for (int i = 0; i < client->num_properties; i++) {
- struct observe_property *prop = client->properties[i];
- if (!prop->changed && !prop->need_new_value) {
- for (int x = 0; list && list[x]; x++) {
- if (match_property(prop->name, list[x])) {
- prop->changed = true;
- prop->need_new_value = prop->format != 0;
- break;
- }
- }
- }
- if ((prop->changed || prop->updating) && i < client->lowest_changed)
- client->lowest_changed = i;
+ if (client->properties[i]->id == id)
+ mark_property_changed(client, i);
}
if (client->lowest_changed < client->num_properties)
wakeup_client(client);
@@ -1205,6 +1205,18 @@ void mp_client_property_change(struct MPContext *mpctx, const char *const *list)
pthread_mutex_unlock(&clients->lock);
}
+// Mark properties as changed in reaction to specific events.
+// Called with ctx->lock held.
+static void notify_property_events(struct mpv_handle *ctx, uint64_t event_mask)
+{
+ for (int i = 0; i < ctx->num_properties; i++) {
+ if (ctx->properties[i]->event_mask & event_mask)
+ mark_property_changed(ctx, i);
+ }
+ if (ctx->lowest_changed < ctx->num_properties)
+ wakeup_client(ctx);
+}
+
static void update_prop(void *p)
{
struct observe_property *prop = p;
@@ -1331,11 +1343,12 @@ int mpv_get_wakeup_pipe(mpv_handle *ctx)
{
pthread_mutex_lock(&ctx->wakeup_lock);
if (ctx->wakeup_pipe[0] == -1) {
- mp_make_wakeup_pipe(ctx->wakeup_pipe);
- write(ctx->wakeup_pipe[1], &(char){0}, 1);
+ if (mp_make_wakeup_pipe(ctx->wakeup_pipe) >= 0)
+ write(ctx->wakeup_pipe[1], &(char){0}, 1);
}
+ int fd = ctx->wakeup_pipe[0];
pthread_mutex_unlock(&ctx->wakeup_lock);
- return ctx->wakeup_pipe[0];
+ return fd;
}
unsigned long mpv_client_api_version(void)
diff --git a/player/client.h b/player/client.h
index af94778..b329ae6 100644
--- a/player/client.h
+++ b/player/client.h
@@ -17,7 +17,7 @@ int mp_clients_num(struct MPContext *mpctx);
void mp_client_broadcast_event(struct MPContext *mpctx, int event, void *data);
int mp_client_send_event(struct MPContext *mpctx, const char *client_name,
int event, void *data);
-void mp_client_property_change(struct MPContext *mpctx, const char *const *list);
+void mp_client_property_change(struct MPContext *mpctx, const char *name);
struct mpv_handle *mp_new_client(struct mp_client_api *clients, const char *name);
struct mp_log *mp_client_get_log(struct mpv_handle *ctx);
diff --git a/player/command.c b/player/command.c
index 1c061c4..c0800d6 100644
--- a/player/command.c
+++ b/player/command.c
@@ -78,9 +78,12 @@ struct command_ctx {
struct cycle_counter *cycle_counters;
int num_cycle_counters;
-#define OVERLAY_MAX_ID 64
- void *overlay_map[OVERLAY_MAX_ID];
- struct sub_bitmaps external2;
+ struct sub_bitmap *overlays;
+ int num_overlays;
+ // One of these is in use by the OSD; the other one exists so that the
+ // bitmap list can be manipulated without additional synchronization.
+ struct sub_bitmaps overlay_osd[2];
+ struct sub_bitmaps *overlay_osd_current;
};
static int edit_filters(struct MPContext *mpctx, enum stream_type mediatype,
@@ -205,11 +208,11 @@ static int mp_property_file_size(void *ctx, struct m_property *prop,
int action, void *arg)
{
MPContext *mpctx = ctx;
- if (!mpctx->stream)
+ if (!mpctx->demuxer)
return M_PROPERTY_UNAVAILABLE;
int64_t size;
- if (stream_control(mpctx->stream, STREAM_CTRL_GET_SIZE, &size) != STREAM_OK)
+ if (demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_SIZE, &size) < 1)
return M_PROPERTY_UNAVAILABLE;
if (action == M_PROPERTY_PRINT) {
@@ -232,13 +235,6 @@ static int mp_property_media_title(void *ctx, struct m_property *prop,
name = demux_info_get(mpctx->master_demuxer, "title");
if (name && name[0])
return m_property_strdup_ro(action, arg, name);
- struct stream *stream = mpctx->master_demuxer->stream;
- if (stream_control(stream, STREAM_CTRL_GET_DISC_NAME, &name) > 0
- && name) {
- int r = m_property_strdup_ro(action, arg, name);
- talloc_free(name);
- return r;
- }
}
return mp_property_filename(ctx, prop, action, arg);
}
@@ -247,7 +243,8 @@ static int mp_property_stream_path(void *ctx, struct m_property *prop,
int action, void *arg)
{
MPContext *mpctx = ctx;
- struct stream *stream = mpctx->stream;
+ // demuxer->stream as well as stream->url are immutable -> ok to access
+ struct stream *stream = mpctx->demuxer ? mpctx->demuxer->stream : NULL;
if (!stream || !stream->url)
return M_PROPERTY_UNAVAILABLE;
return m_property_strdup_ro(action, arg, stream->url);
@@ -257,12 +254,14 @@ static int mp_property_stream_capture(void *ctx, struct m_property *prop,
int action, void *arg)
{
MPContext *mpctx = ctx;
- if (!mpctx->stream)
+ if (!mpctx->demuxer)
return M_PROPERTY_UNAVAILABLE;
if (action == M_PROPERTY_SET) {
char *filename = *(char **)arg;
- stream_set_capture_file(mpctx->stream, filename);
+ demux_pause(mpctx->demuxer);
+ stream_set_capture_file(mpctx->demuxer->stream, filename);
+ demux_unpause(mpctx->demuxer);
// fall through to mp_property_generic_option
}
return mp_property_generic_option(mpctx, prop, action, arg);
@@ -284,14 +283,19 @@ static int mp_property_stream_pos(void *ctx, struct m_property *prop,
int action, void *arg)
{
MPContext *mpctx = ctx;
- struct stream *stream = mpctx->stream;
- if (!stream)
+ struct demuxer *demuxer = mpctx->demuxer;
+ if (!demuxer)
return M_PROPERTY_UNAVAILABLE;
+ demux_pause(demuxer);
+ int r;
if (action == M_PROPERTY_SET) {
- stream_seek(stream, *(int64_t *) arg);
- return M_PROPERTY_OK;
+ stream_seek(demuxer->stream, *(int64_t *) arg);
+ r = M_PROPERTY_OK;
+ } else {
+ r = m_property_int64_ro(action, arg, stream_tell(demuxer->stream));
}
- return m_property_int64_ro(action, arg, stream_tell(stream));
+ demux_unpause(demuxer);
+ return r;
}
/// Stream end offset (RO)
@@ -335,22 +339,6 @@ static int property_time(int action, void *arg, double time)
return M_PROPERTY_NOT_IMPLEMENTED;
}
-/// Current stream position in seconds (RO)
-static int mp_property_stream_time_pos(void *ctx, struct m_property *prop,
- int action, void *arg)
-{
- MPContext *mpctx = ctx;
- struct demuxer *demuxer = mpctx->demuxer;
- if (!demuxer)
- return M_PROPERTY_UNAVAILABLE;
- double pts = demuxer->stream_pts;
- if (pts == MP_NOPTS_VALUE)
- return M_PROPERTY_UNAVAILABLE;
-
- return property_time(action, arg, pts);
-}
-
-
/// Media length in seconds (RO)
static int mp_property_length(void *ctx, struct m_property *prop,
int action, void *arg)
@@ -462,10 +450,9 @@ static int mp_property_time_pos(void *ctx, struct m_property *prop,
static bool time_remaining(MPContext *mpctx, double *remaining)
{
double len = get_time_length(mpctx);
- double pos = get_current_time(mpctx);
- double start = get_start_time(mpctx);
+ double playback = get_playback_time(mpctx);
- *remaining = len - (pos - start);
+ *remaining = len - playback;
return len > 0;
}
@@ -492,19 +479,28 @@ static int mp_property_playtime_remaining(void *ctx, struct m_property *prop,
return property_time(action, arg, remaining / speed);
}
+static int mp_property_playback_time(void *ctx, struct m_property *prop,
+ int action, void *arg)
+{
+ MPContext *mpctx = ctx;
+ if (!mpctx->num_sources)
+ return M_PROPERTY_UNAVAILABLE;
+
+ return property_time(action, arg, get_playback_time(mpctx));
+}
+
/// Current BD/DVD title (RW)
static int mp_property_disc_title(void *ctx, struct m_property *prop,
int action, void *arg)
{
MPContext *mpctx = ctx;
- struct demuxer *demuxer = mpctx->master_demuxer;
- if (!demuxer || !demuxer->stream)
+ struct demuxer *d = mpctx->master_demuxer;
+ if (!d)
return M_PROPERTY_UNAVAILABLE;
- struct stream *stream = demuxer->stream;
unsigned int title = -1;
switch (action) {
case M_PROPERTY_GET:
- if (stream_control(stream, STREAM_CTRL_GET_CURRENT_TITLE, &title) <= 0)
+ if (demux_stream_control(d, STREAM_CTRL_GET_CURRENT_TITLE, &title) < 0)
return M_PROPERTY_UNAVAILABLE;
*(int*)arg = title;
return M_PROPERTY_OK;
@@ -517,7 +513,7 @@ static int mp_property_disc_title(void *ctx, struct m_property *prop,
return M_PROPERTY_OK;
case M_PROPERTY_SET:
title = *(int*)arg;
- if (stream_control(stream, STREAM_CTRL_SET_CURRENT_TITLE, &title) <= 0)
+ if (demux_stream_control(d, STREAM_CTRL_SET_CURRENT_TITLE, &title) < 0)
return M_PROPERTY_NOT_IMPLEMENTED;
return M_PROPERTY_OK;
}
@@ -820,8 +816,8 @@ static int mp_property_disc_titles(void *ctx, struct m_property *prop,
MPContext *mpctx = ctx;
struct demuxer *demuxer = mpctx->master_demuxer;
unsigned int num_titles;
- if (!demuxer || stream_control(demuxer->stream, STREAM_CTRL_GET_NUM_TITLES,
- &num_titles) < 1)
+ if (!demuxer || demux_stream_control(demuxer, STREAM_CTRL_GET_NUM_TITLES,
+ &num_titles) < 1)
return M_PROPERTY_UNAVAILABLE;
return m_property_int_ro(action, arg, num_titles);
}
@@ -855,15 +851,20 @@ static int mp_property_angle(void *ctx, struct m_property *prop,
{
MPContext *mpctx = ctx;
struct demuxer *demuxer = mpctx->master_demuxer;
- int angle = -1;
- int angles;
+ if (!demuxer)
+ return M_PROPERTY_UNAVAILABLE;
- if (demuxer)
- angle = demuxer_get_current_angle(demuxer);
- if (angle < 0)
+ int ris, angles = -1, angle = 1;
+
+ ris = demux_stream_control(demuxer, STREAM_CTRL_GET_NUM_ANGLES, &angles);
+ if (ris == STREAM_UNSUPPORTED)
return M_PROPERTY_UNAVAILABLE;
- angles = demuxer_angles_count(demuxer);
- if (angles <= 1)
+
+ ris = demux_stream_control(demuxer, STREAM_CTRL_GET_ANGLE, &angle);
+ if (ris == STREAM_UNSUPPORTED)
+ return -1;
+
+ if (angle < 0 || angles <= 1)
return M_PROPERTY_UNAVAILABLE;
switch (action) {
@@ -875,15 +876,23 @@ static int mp_property_angle(void *ctx, struct m_property *prop,
return M_PROPERTY_OK;
}
case M_PROPERTY_SET:
- angle = demuxer_set_angle(demuxer, *(int *)arg);
- if (angle >= 0) {
- if (mpctx->d_video)
- video_reset_decoding(mpctx->d_video);
+ angle = *(int *)arg;
+ if (angle < 0 || angle > angles)
+ return M_PROPERTY_ERROR;
- if (mpctx->d_audio)
- audio_reset_decoding(mpctx->d_audio);
- }
- return M_PROPERTY_OK;
+ demux_pause(demuxer);
+ demux_flush(demuxer);
+ ris = demux_stream_control(demuxer, STREAM_CTRL_SET_ANGLE, &angle);
+ demux_control(demuxer, DEMUXER_CTRL_RESYNC, NULL);
+ demux_unpause(demuxer);
+
+ if (mpctx->d_video)
+ video_reset_decoding(mpctx->d_video);
+
+ if (mpctx->d_audio)
+ audio_reset_decoding(mpctx->d_audio);
+
+ return ris == STREAM_OK ? M_PROPERTY_OK : M_PROPERTY_ERROR;
case M_PROPERTY_GET_TYPE: {
struct m_option opt = {
.type = CONF_TYPE_INT,
@@ -1070,33 +1079,65 @@ static int mp_property_eof_reached(void *ctx, struct m_property *prop,
int action, void *arg)
{
MPContext *mpctx = ctx;
- return m_property_flag_ro(action, arg, mpctx->eof_reached);
+ bool eof = mpctx->video_status == STATUS_EOF &&
+ mpctx->audio_status == STATUS_EOF;
+ return m_property_flag_ro(action, arg, eof);
+}
+
+static int mp_property_seeking(void *ctx, struct m_property *prop,
+ int action, void *arg)
+{
+ MPContext *mpctx = ctx;
+ return m_property_flag_ro(action, arg, !mpctx->restart_complete);
}
static int mp_property_cache(void *ctx, struct m_property *prop,
int action, void *arg)
{
MPContext *mpctx = ctx;
- int cache = mp_get_cache_percent(mpctx);
+ float cache = mp_get_cache_percent(mpctx);
if (cache < 0)
return M_PROPERTY_UNAVAILABLE;
- return m_property_int_ro(action, arg, cache);
+
+ if (action == M_PROPERTY_PRINT) {
+ *(char **)arg = talloc_asprintf(NULL, "%d %%", (int)cache);
+ return M_PROPERTY_OK;
+ }
+
+ return m_property_float_ro(action, arg, cache);
+}
+
+static int property_int_kb_size(int kb_size, int action, void *arg)
+{
+ switch (action) {
+ case M_PROPERTY_GET:
+ *(int *)arg = kb_size;
+ return M_PROPERTY_OK;
+ case M_PROPERTY_PRINT:
+ *(char **)arg = format_file_size(kb_size * 1024LL);
+ return M_PROPERTY_OK;
+ case M_PROPERTY_GET_TYPE:
+ *(struct m_option *)arg = (struct m_option){.type = CONF_TYPE_INT};
+ return M_PROPERTY_OK;
+ }
+ return M_PROPERTY_NOT_IMPLEMENTED;
}
static int mp_property_cache_size(void *ctx, struct m_property *prop,
int action, void *arg)
{
MPContext *mpctx = ctx;
- if (!mpctx->stream)
+ struct demuxer *demuxer = mpctx->demuxer;
+ if (!demuxer)
return M_PROPERTY_UNAVAILABLE;
switch (action) {
- case M_PROPERTY_GET: {
+ case M_PROPERTY_GET:
+ case M_PROPERTY_PRINT: {
int64_t size = -1;
- stream_control(mpctx->stream, STREAM_CTRL_GET_CACHE_SIZE, &size);
+ demux_stream_control(demuxer, STREAM_CTRL_GET_CACHE_SIZE, &size);
if (size <= 0)
break;
- *(int *)arg = size / 1024;
- return M_PROPERTY_OK;
+ return property_int_kb_size(size / 1024, action, arg);
}
case M_PROPERTY_GET_TYPE:
*(struct m_option *)arg = (struct m_option){
@@ -1107,7 +1148,7 @@ static int mp_property_cache_size(void *ctx, struct m_property *prop,
return M_PROPERTY_OK;
case M_PROPERTY_SET: {
int64_t size = *(int *)arg * 1024LL;
- int r = stream_control(mpctx->stream, STREAM_CTRL_SET_CACHE_SIZE, &size);
+ int r = demux_stream_control(demuxer, STREAM_CTRL_SET_CACHE_SIZE, &size);
if (r == STREAM_UNSUPPORTED)
break;
if (r == STREAM_OK)
@@ -1118,6 +1159,52 @@ static int mp_property_cache_size(void *ctx, struct m_property *prop,
return M_PROPERTY_NOT_IMPLEMENTED;
}
+static int mp_property_cache_used(void *ctx, struct m_property *prop,
+ int action, void *arg)
+{
+ MPContext *mpctx = ctx;
+ if (!mpctx->demuxer)
+ return M_PROPERTY_UNAVAILABLE;
+
+ int64_t size = -1;
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_FILL, &size);
+ if (size < 0)
+ return M_PROPERTY_UNAVAILABLE;
+ return property_int_kb_size(size / 1024, action, arg);
+}
+
+static int mp_property_cache_free(void *ctx, struct m_property *prop,
+ int action, void *arg)
+{
+ MPContext *mpctx = ctx;
+ if (!mpctx->demuxer)
+ return M_PROPERTY_UNAVAILABLE;
+
+ int64_t size_used = -1;
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_FILL, &size_used);
+ if (size_used < 0)
+ return M_PROPERTY_UNAVAILABLE;
+
+ int64_t size = -1;
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_SIZE, &size);
+ if (size <= 0)
+ return M_PROPERTY_UNAVAILABLE;
+
+ return property_int_kb_size((size - size_used) / 1024, action, arg);
+}
+
+static int mp_property_cache_idle(void *ctx, struct m_property *prop,
+ int action, void *arg)
+{
+ MPContext *mpctx = ctx;
+ int idle = -1;
+ if (mpctx->demuxer)
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_IDLE, &idle);
+ if (idle < 0)
+ return M_PROPERTY_UNAVAILABLE;
+ return m_property_flag_ro(action, arg, !!idle);
+}
+
static int mp_property_paused_for_cache(void *ctx, struct m_property *prop,
int action, void *arg)
{
@@ -1787,7 +1874,6 @@ static int mp_property_colormatrix(void *ctx, struct m_property *prop,
char *res = talloc_strdup(NULL, "");
append_csp(&res, "*Requested", mp_csp_names, opts->requested_colorspace);
append_csp(&res, "Video decoder", mp_csp_names, vd_csp.colorspace);
- append_csp(&res, "Video output", mp_csp_names, vo_csp.colorspace);
*(char **)arg = res;
return M_PROPERTY_OK;
}
@@ -1813,7 +1899,6 @@ static int mp_property_colormatrix_input_range(void *ctx, struct m_property *pro
append_csp(&res, "*Requested", mp_csp_levels_names,
opts->requested_input_range);
append_csp(&res, "Video decoder", mp_csp_levels_names, vd_csp.colorlevels);
- append_csp(&res, "Video output", mp_csp_levels_names, vo_csp.colorlevels);
*(char **)arg = res;
return M_PROPERTY_OK;
}
@@ -2252,22 +2337,11 @@ static int mp_property_sub_pos(void *ctx, struct m_property *prop,
return property_osd_helper(mpctx, prop, action, arg);
}
-static int demux_stream_control(struct MPContext *mpctx, int ctrl, void *arg)
-{
- int r = STREAM_UNSUPPORTED;
- if (mpctx->stream)
- r = stream_control(mpctx->stream, ctrl, arg);
- if (r == STREAM_UNSUPPORTED && mpctx->demuxer) {
- struct demux_ctrl_stream_ctrl c = {ctrl, arg, STREAM_UNSUPPORTED};
- demux_control(mpctx->demuxer, DEMUXER_CTRL_STREAM_CTRL, &c);
- r = c.res;
- }
- return r;
-}
-
static int prop_stream_ctrl(struct MPContext *mpctx, int ctrl, void *arg)
{
- int r = demux_stream_control(mpctx, ctrl, arg);
+ if (!mpctx->demuxer)
+ return M_PROPERTY_UNAVAILABLE;
+ int r = demux_stream_control(mpctx->demuxer, ctrl, arg);
switch (r) {
case STREAM_OK: return M_PROPERTY_OK;
case STREAM_UNSUPPORTED: return M_PROPERTY_UNAVAILABLE;
@@ -2561,6 +2635,30 @@ static int mp_property_options(void *ctx, struct m_property *prop,
return M_PROPERTY_NOT_IMPLEMENTED;
}
+static const struct m_property mp_properties[];
+
+static int mp_property_list(void *ctx, struct m_property *prop,
+ int action, void *arg)
+{
+ switch (action) {
+ case M_PROPERTY_GET_TYPE:
+ *(struct m_option *)arg = (struct m_option){.type = CONF_TYPE_STRING_LIST};
+ return M_PROPERTY_OK;
+ case M_PROPERTY_GET: {
+ char **list = NULL;
+ int num = 0;
+ for (int n = 0; mp_properties[n].name; n++) {
+ MP_TARRAY_APPEND(NULL, list, num,
+ talloc_strdup(NULL, mp_properties[n].name));
+ }
+ MP_TARRAY_APPEND(NULL, list, num, NULL);
+ *(char ***)arg = list;
+ return M_PROPERTY_OK;
+ }
+ }
+ return M_PROPERTY_NOT_IMPLEMENTED;
+}
+
// Redirect a property name to another
#define M_PROPERTY_ALIAS(name, real_property) \
{(name), mp_property_alias, .priv = (real_property)}
@@ -2584,7 +2682,6 @@ static const struct m_property mp_properties[] = {
{"demuxer", mp_property_demuxer},
{"stream-pos", mp_property_stream_pos},
{"stream-end", mp_property_stream_end},
- {"stream-time-pos", mp_property_stream_time_pos},
{"length", mp_property_length},
{"avsync", mp_property_avsync},
{"total-avsync-change", mp_property_total_avsync_change},
@@ -2594,6 +2691,7 @@ static const struct m_property mp_properties[] = {
{"time-pos", mp_property_time_pos},
{"time-remaining", mp_property_remaining},
{"playtime-remaining", mp_property_playtime_remaining},
+ {"playback-time", mp_property_playback_time},
{"disc-title", mp_property_disc_title},
{"disc-menu-active", mp_property_disc_menu},
{"chapter", mp_property_chapter},
@@ -2609,8 +2707,12 @@ static const struct m_property mp_properties[] = {
{"pause", mp_property_pause},
{"core-idle", mp_property_core_idle},
{"eof-reached", mp_property_eof_reached},
+ {"seeking", mp_property_seeking},
{"cache", mp_property_cache},
+ {"cache-free", mp_property_cache_free},
+ {"cache-used", mp_property_cache_used},
{"cache-size", mp_property_cache_size},
+ {"cache-idle", mp_property_cache_idle},
{"paused-for-cache", mp_property_paused_for_cache},
{"pts-association-mode", mp_property_generic_option},
{"hr-seek", mp_property_generic_option},
@@ -2715,6 +2817,7 @@ static const struct m_property mp_properties[] = {
M_PROPERTY_ALIAS("sub", "sid"),
{"options", mp_property_options},
+ {"property-list", mp_property_list},
{0},
};
@@ -2732,20 +2835,58 @@ static const char *const *const mp_event_property_change[] = {
E(MPV_EVENT_PAUSE, "pause", "paused-on-cache", "core-idle", "eof-reached"),
E(MPV_EVENT_UNPAUSE, "pause", "paused-on-cache", "core-idle", "eof-reached"),
E(MPV_EVENT_TICK, "time-pos", "stream-pos", "stream-time-pos", "avsync",
- "percent-pos", "time-remaining", "playtime-remaining"),
+ "percent-pos", "time-remaining", "playtime-remaining", "playback-time"),
E(MPV_EVENT_VIDEO_RECONFIG, "video-out-params", "video-params",
"video-format", "video-codec", "video-bitrate", "dwidth", "dheight",
"width", "height", "fps", "aspect"),
E(MPV_EVENT_AUDIO_RECONFIG, "audio-format", "audio-codec", "audio-bitrate",
"samplerate", "channels", "audio"),
+ E(MPV_EVENT_SEEK, "seeking"),
+ E(MPV_EVENT_PLAYBACK_RESTART, "seeking"),
E(MPV_EVENT_METADATA_UPDATE, "metadata"),
E(MPV_EVENT_CHAPTER_CHANGE, "chapter", "chapter-metadata"),
+ E(MP_EVENT_CACHE_UPDATE, "cache", "cache-free", "cache-used", "cache-idle"),
};
#undef E
-const struct m_property *mp_get_property_list(void)
+static int prefix_len(const char *p)
+{
+ const char *end = strchr(p, '/');
+ return end ? end - p : strlen(p);
+}
+
+static bool match_property(const char *a, const char *b)
+{
+ if (strcmp(a, "*") == 0)
+ return true;
+ int len_a = prefix_len(a);
+ int len_b = prefix_len(b);
+ return strncmp(a, b, MPMIN(len_a, len_b)) == 0;
+}
+
+// Return a bitset of events which change the property.
+uint64_t mp_get_property_event_mask(const char *name)
+{
+ uint64_t mask = 0;
+ for (int n = 0; n < MP_ARRAY_SIZE(mp_event_property_change); n++) {
+ const char *const *const list = mp_event_property_change[n];
+ for (int i = 0; list && list[i]; i++) {
+ if (match_property(list[i], name))
+ mask |= 1ULL << n;
+ }
+ }
+ return mask;
+}
+
+// Return an ID for the property. It might not be unique, but is good enough
+// for property change handling. Return -1 if property unknown.
+int mp_get_property_id(const char *name)
{
- return mp_properties;
+ for (int n = 0; mp_properties[n].name; n++) {
+ if (match_property(mp_properties[n].name, name))
+ return n;
+ }
+ return -1;
}
static bool is_property_set(int action, void *val)
@@ -2824,7 +2965,7 @@ static const struct property_osd_display {
int seek_msg, seek_bar;
// Free-form message (if NULL, osd_name or the property name is used)
const char *msg;
- // Extra free-from message (just for volume)
+ // Extra free-form message (just for volume)
const char *extra_msg;
} property_osd_display[] = {
// general
@@ -2887,13 +3028,9 @@ static const struct property_osd_display {
static void show_property_osd(MPContext *mpctx, const char *pname, int osd_mode)
{
struct MPOpts *opts = mpctx->opts;
- struct m_option prop = {0};
const struct property_osd_display *p;
const char *name = pname;
- if (mp_property_do(pname, M_PROPERTY_GET_TYPE, &prop, mpctx) <= 0)
- return;
-
int osd_progbar = 0;
const char *osd_name = NULL;
const char *msg = NULL;
@@ -2938,6 +3075,8 @@ static void show_property_osd(MPContext *mpctx, const char *pname, int osd_mode)
if (!msg && osd_name)
msg = talloc_asprintf(tmp, "%s: ${%s}", osd_name, name);
+ struct m_option prop = {0};
+ mp_property_do(pname, M_PROPERTY_GET_TYPE, &prop, mpctx);
if (osd_progbar && (prop.flags & CONF_RANGE) == CONF_RANGE) {
bool ok = false;
if (prop.type == CONF_TYPE_INT) {
@@ -3079,29 +3218,23 @@ static int edit_filters_osd(struct MPContext *mpctx, enum stream_type mediatype,
#if HAVE_SYS_MMAN_H
-static int ext2_sub_find(struct MPContext *mpctx, int id)
+static void recreate_overlays(struct MPContext *mpctx)
{
struct command_ctx *cmd = mpctx->command_ctx;
- struct sub_bitmaps *sub = &cmd->external2;
- void *p = NULL;
- if (id >= 0 && id < OVERLAY_MAX_ID)
- p = cmd->overlay_map[id];
- if (sub && p) {
- for (int n = 0; n < sub->num_parts; n++) {
- if (sub->parts[n].bitmap == p)
- return n;
- }
- }
- return -1;
-}
-
-static int ext2_sub_alloc(struct MPContext *mpctx)
-{
- struct command_ctx *cmd = mpctx->command_ctx;
- struct sub_bitmaps *sub = &cmd->external2;
- struct sub_bitmap b = {0};
- MP_TARRAY_APPEND(cmd, sub->parts, sub->num_parts, b);
- return sub->num_parts - 1;
+ struct sub_bitmaps *new = &cmd->overlay_osd[0];
+ if (new == cmd->overlay_osd_current)
+ new += 1; // pick the unused one
+ new->format = SUBBITMAP_RGBA;
+ new->bitmap_id = new->bitmap_pos_id = 1;
+ // overlay array can have unused entries, but parts list must be "packed"
+ new->num_parts = 0;
+ for (int n = 0; n < cmd->num_overlays; n++) {
+ struct sub_bitmap *s = &cmd->overlays[n];
+ if (s->bitmap)
+ MP_TARRAY_APPEND(cmd, new->parts, new->num_parts, *s);
+ }
+ cmd->overlay_osd_current = new;
+ osd_set_external2(mpctx->osd, cmd->overlay_osd_current);
}
static int overlay_add(struct MPContext *mpctx, int id, int x, int y,
@@ -3110,13 +3243,11 @@ static int overlay_add(struct MPContext *mpctx, int id, int x, int y,
{
struct command_ctx *cmd = mpctx->command_ctx;
int r = -1;
- // Temporarily unmap them to avoid race condition with concurrent access.
- osd_set_external2(mpctx->osd, NULL);
if (strcmp(fmt, "bgra") != 0) {
MP_ERR(mpctx, "overlay_add: unsupported OSD format '%s'\n", fmt);
goto error;
}
- if (id < 0 || id >= OVERLAY_MAX_ID) {
+ if (id < 0 || id >= 64) { // arbitrary upper limit
MP_ERR(mpctx, "overlay_add: invalid id %d\n", id);
goto error;
}
@@ -3138,50 +3269,49 @@ static int overlay_add(struct MPContext *mpctx, int id, int x, int y,
MP_ERR(mpctx, "overlay_add: could not open or map '%s'\n", file);
goto error;
}
- int index = ext2_sub_find(mpctx, id);
- if (index < 0)
- index = ext2_sub_alloc(mpctx);
- if (index < 0) {
- munmap(p, h * stride);
- goto error;
- }
- cmd->overlay_map[id] = p;
- cmd->external2.parts[index] = (struct sub_bitmap) {
+ MP_TARRAY_GROW(cmd, cmd->overlays, id);
+ while (cmd->num_overlays <= id)
+ cmd->overlays[cmd->num_overlays++].bitmap = NULL;
+ struct sub_bitmap *overlay = &cmd->overlays[id];
+ void *prev = overlay->bitmap;
+ size_t prev_size = overlay->stride * overlay->h;
+ *overlay = (struct sub_bitmap) {
.bitmap = p,
.stride = stride,
.x = x, .y = y,
.w = w, .h = h,
.dw = w, .dh = h,
};
- cmd->external2.bitmap_id = cmd->external2.bitmap_pos_id = 1;
- cmd->external2.format = SUBBITMAP_RGBA;
+ recreate_overlays(mpctx);
+ // unmap afterwards, to avoid unmapping while OSD uses the memory
+ if (prev)
+ munmap(prev, prev_size);
r = 0;
error:
- osd_set_external2(mpctx->osd, &cmd->external2);
return r;
}
static void overlay_remove(struct MPContext *mpctx, int id)
{
struct command_ctx *cmd = mpctx->command_ctx;
- osd_set_external2(mpctx->osd, NULL);
- int index = ext2_sub_find(mpctx, id);
- if (index >= 0) {
- struct sub_bitmaps *sub = &cmd->external2;
- struct sub_bitmap *part = &sub->parts[index];
- munmap(part->bitmap, part->h * part->stride);
- MP_TARRAY_REMOVE_AT(sub->parts, sub->num_parts, index);
- cmd->overlay_map[id] = NULL;
- sub->bitmap_id = sub->bitmap_pos_id = 1;
+ if (id >= 0 && id < cmd->num_overlays) {
+ struct sub_bitmap *overlay = &cmd->overlays[id];
+ if (overlay->bitmap) {
+ void *ptr = overlay->bitmap;
+ size_t ptr_size = overlay->h * overlay->stride;
+ overlay->bitmap = NULL; // remove
+ recreate_overlays(mpctx);
+ munmap(ptr, ptr_size);
+ }
}
- osd_set_external2(mpctx->osd, &cmd->external2);
}
static void overlay_uninit(struct MPContext *mpctx)
{
+ struct command_ctx *cmd = mpctx->command_ctx;
if (!mpctx->osd)
return;
- for (int id = 0; id < OVERLAY_MAX_ID; id++)
+ for (int id = 0; id < cmd->num_overlays; id++)
overlay_remove(mpctx, id);
osd_set_external2(mpctx->osd, NULL);
}
@@ -3645,7 +3775,8 @@ int run_command(MPContext *mpctx, mp_cmd_t *cmd)
break;
case MP_CMD_TV_LAST_CHANNEL: {
- demux_stream_control(mpctx, STREAM_CTRL_TV_LAST_CHAN, NULL);
+ if (mpctx->demuxer)
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_TV_LAST_CHAN, NULL);
break;
}
@@ -3768,7 +3899,7 @@ int run_command(MPContext *mpctx, mp_cmd_t *cmd)
*event = (mpv_event_client_message){0};
for (int n = 1; n < cmd->nargs; n++) {
MP_TARRAY_APPEND(event, event->args, event->num_args,
- cmd->args[n].v.s);
+ talloc_strdup(event, cmd->args[n].v.s));
}
if (mp_client_send_event(mpctx, cmd->args[0].v.s,
MPV_EVENT_CLIENT_MESSAGE, event) < 0)
@@ -3844,11 +3975,9 @@ void mp_notify(struct MPContext *mpctx, int event, void *arg)
ctx->last_seek_pts = MP_NOPTS_VALUE;
mp_client_broadcast_event(mpctx, event, arg);
- if (event >= 0 && event < MP_ARRAY_SIZE(mp_event_property_change))
- mp_client_property_change(mpctx, mp_event_property_change[event]);
}
void mp_notify_property(struct MPContext *mpctx, const char *property)
{
- mp_client_property_change(mpctx, (const char*[]){property, NULL});
+ mp_client_property_change(mpctx, property);
}
diff --git a/player/command.h b/player/command.h
index 846067b..6e3312b 100644
--- a/player/command.h
+++ b/player/command.h
@@ -33,10 +33,14 @@ void property_print_help(struct mp_log *log);
int mp_property_do(const char* name, int action, void* val,
struct MPContext *mpctx);
-const struct m_property *mp_get_property_list(void);
-int mp_find_property_index(const char *property);
-
void mp_notify(struct MPContext *mpctx, int event, void *arg);
void mp_notify_property(struct MPContext *mpctx, const char *property);
+int mp_get_property_id(const char *name);
+uint64_t mp_get_property_event_mask(const char *name);
+
+// Must start with the first unused positive value in enum mpv_event_id
+#define INTERNAL_EVENT_BASE 24
+#define MP_EVENT_CACHE_UPDATE (INTERNAL_EVENT_BASE + 0)
+
#endif /* MPLAYER_COMMAND_H */
diff --git a/player/configfiles.c b/player/configfiles.c
index 2794dda..d1c79c9 100644
--- a/player/configfiles.c
+++ b/player/configfiles.c
@@ -22,7 +22,6 @@
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
-#include <ctype.h>
#include <libavutil/md5.h>
@@ -34,6 +33,7 @@
#include "common/global.h"
#include "common/encode.h"
#include "common/msg.h"
+#include "misc/ctype.h"
#include "options/path.h"
#include "options/m_config.h"
#include "options/parse_configfile.h"
@@ -46,18 +46,26 @@
#include "core.h"
#include "command.h"
+static void load_all_cfgfiles(struct MPContext *mpctx, char *section,
+ char *filename)
+{
+ char **cf = mp_find_all_config_files(NULL, mpctx->global, filename);
+ for (int i = 0; cf && cf[i]; i++)
+ m_config_parse_config_file(mpctx->mconfig, cf[i], section, 0);
+ talloc_free(cf);
+}
+
#define SECT_ENCODE "encoding"
-bool mp_parse_cfgfiles(struct MPContext *mpctx)
+void mp_parse_cfgfiles(struct MPContext *mpctx)
{
struct MPOpts *opts = mpctx->opts;
if (!opts->load_config)
- return true;
+ return;
+
+ mp_mk_config_dir(mpctx->global, "");
m_config_t *conf = mpctx->mconfig;
- void *tmp = talloc_new(NULL);
- bool r = true;
- char *conffile;
char *section = NULL;
bool encoding = opts->encode_opts &&
opts->encode_opts->file && opts->encode_opts->file[0];
@@ -70,30 +78,17 @@ bool mp_parse_cfgfiles(struct MPContext *mpctx)
// The #if is a stupid hack to avoid errors if libavfilter is not available.
#if HAVE_LIBAVFILTER && HAVE_ENCODING
- conffile = mp_find_config_file(tmp, mpctx->global, "encoding-profiles.conf");
- if (conffile && mp_path_exists(conffile))
- m_config_parse_config_file(mpctx->mconfig, conffile, SECT_ENCODE, 0);
+ char *cf = mp_find_config_file(NULL, mpctx->global, "encoding-profiles.conf");
+ if (cf)
+ m_config_parse_config_file(mpctx->mconfig, cf, SECT_ENCODE, 0);
+ talloc_free(cf);
#endif
- conffile = mp_find_global_config_file(tmp, mpctx->global, "mpv.conf");
- if (conffile && m_config_parse_config_file(conf, conffile, section, 0) < 0) {
- r = false;
- goto done;
- }
- mp_mk_config_dir(mpctx->global, NULL);
- if (!(conffile = mp_find_user_config_file(tmp, mpctx->global, "config")))
- MP_ERR(mpctx, "mp_find_user_config_file(\"config\") problem\n");
- else if (m_config_parse_config_file(conf, conffile, section, 0) < 0) {
- r = false;
- goto done;
- }
+ load_all_cfgfiles(mpctx, section, "config");
+ load_all_cfgfiles(mpctx, section, "mpv.conf");
if (encoding)
m_config_set_profile(conf, m_config_add_profile(conf, SECT_ENCODE), 0);
-
-done:
- talloc_free(tmp);
- return r;
}
static int try_load_config(struct MPContext *mpctx, const char *file, int flags)
@@ -134,7 +129,7 @@ static void mp_load_per_file_config(struct MPContext *mpctx)
return;
}
- if ((confpath = mp_find_user_config_file(NULL, mpctx->global, name))) {
+ if ((confpath = mp_find_config_file(NULL, mpctx->global, name))) {
try_load_config(mpctx, confpath, FILE_LOCAL_FLAGS);
talloc_free(confpath);
@@ -200,9 +195,13 @@ static char *mp_get_playback_resume_config_filename(struct mpv_global *global,
for (int i = 0; i < 16; i++)
conf = talloc_asprintf_append(conf, "%02X", md5[i]);
- conf = talloc_asprintf(tmp, "%s/%s", MP_WATCH_LATER_CONF, conf);
+ res = talloc_asprintf(tmp, MP_WATCH_LATER_CONF "/%s", conf);
+ res = mp_find_config_file(NULL, global, res);
- res = mp_find_user_config_file(NULL, global, conf);
+ if (!res) {
+ res = mp_find_config_file(tmp, global, MP_WATCH_LATER_CONF);
+ res = talloc_asprintf(NULL, "%s/%s", res, conf);
+ }
exit:
talloc_free(tmp);
@@ -268,7 +267,7 @@ static bool needs_config_quoting(const char *s)
{
for (int i = 0; s && s[i]; i++) {
unsigned char c = s[i];
- if (!isprint(c) || isspace(c) || c == '#' || c == '\'' || c == '"')
+ if (!mp_isprint(c) || mp_isspace(c) || c == '#' || c == '\'' || c == '"')
return true;
}
return false;
@@ -276,8 +275,8 @@ static bool needs_config_quoting(const char *s)
void mp_write_watch_later_conf(struct MPContext *mpctx)
{
- void *tmp = talloc_new(NULL);
char *filename = mpctx->filename;
+ char *conffile = NULL;
if (!filename)
goto exit;
@@ -287,9 +286,8 @@ void mp_write_watch_later_conf(struct MPContext *mpctx)
mp_mk_config_dir(mpctx->global, MP_WATCH_LATER_CONF);
- char *conffile = mp_get_playback_resume_config_filename(mpctx->global,
- mpctx->filename);
- talloc_steal(tmp, conffile);
+ conffile = mp_get_playback_resume_config_filename(mpctx->global,
+ mpctx->filename);
if (!conffile)
goto exit;
@@ -324,7 +322,7 @@ void mp_write_watch_later_conf(struct MPContext *mpctx)
fclose(file);
exit:
- talloc_free(tmp);
+ talloc_free(conffile);
}
void mp_load_playback_resume(struct MPContext *mpctx, const char *file)
diff --git a/player/core.h b/player/core.h
index e3d84f4..61d7821 100644
--- a/player/core.h
+++ b/player/core.h
@@ -88,6 +88,8 @@ enum {
MAX_TERM_OSD_LEVEL = 1,
OSD_LEVEL_INVISIBLE = 4,
OSD_BAR_SEEK = 256,
+
+ MAX_NUM_VO_PTS = 100,
};
enum seek_type {
@@ -125,6 +127,9 @@ struct track {
// If the track's stream changes with the timeline (ordered chapters).
bool under_timeline;
+ // Does not change with under_timeline, but it useless for most purposes.
+ struct sh_stream *original_stream;
+
// Value can change if under_timeline==true.
struct demuxer *demuxer;
// Invariant: !stream || stream->demuxer == demuxer
@@ -135,8 +140,20 @@ struct track {
bool preloaded;
};
-enum {
- MAX_NUM_VO_PTS = 100,
+/* Note that playback can be paused, stopped, etc. at any time. While paused,
+ * playback restart is still active, because you want seeking to work even
+ * if paused.
+ * The main purpose of distinguishing these states is proper reinitialization
+ * of A/V sync.
+ */
+enum playback_status {
+ // code may compare status values numerically
+ STATUS_SYNCING, // seeking for a position to resume
+ STATUS_FILLING, // decoding more data (so you start with full buffers)
+ STATUS_READY, // buffers full, playback can be started any time
+ STATUS_PLAYING, // normal playback
+ STATUS_DRAINING, // decoding has ended; still playing out queued buffers
+ STATUS_EOF, // playback has ended, or is disabled
};
#define NUM_PTRACKS 2
@@ -214,6 +231,7 @@ typedef struct MPContext {
// Uses: accessing metadata (consider ordered chapters case, where the main
// demuxer defines metadata), or special purpose demuxers like TV.
struct demuxer *master_demuxer;
+ struct demuxer *track_layout; // complication for ordered chapters
struct mixer *mixer;
struct ao *ao;
@@ -223,16 +241,11 @@ typedef struct MPContext {
struct vo *video_out;
- /* We're starting playback from scratch or after a seek. Show first
- * video frame immediately and reinitialize sync. */
- bool restart_playback;
+ enum playback_status video_status, audio_status;
+ bool restart_complete;
/* Set if audio should be timed to start with video frame after seeking,
* not set when e.g. playing cover art */
bool sync_audio_to_video;
- /* After playback restart (above) or audio stream change, adjust audio
- * stream by cutting samples or adding silence at the beginning to make
- * audio playback position match video position. */
- bool syncing_audio;
bool hrseek_active;
bool hrseek_framedrop;
double hrseek_pts;
@@ -291,9 +304,11 @@ typedef struct MPContext {
double audio_delay;
- double last_heartbeat;
- double last_metadata_update;
+ double next_heartbeat;
double last_idle_tick;
+ double next_cache_update;
+
+ double sleeptime; // number of seconds to sleep before next iteration
double mouse_timer;
unsigned int mouse_event_ts;
@@ -313,8 +328,6 @@ typedef struct MPContext {
double amount;
int exact; // -1 = disable, 0 = default, 1 = enable
bool immediate; // disable seek delay logic
- // currently not set by commands, only used internally by seek()
- int direction; // -1 = backward, 0 = default, 1 = forward
} seek;
/* Heuristic for relative chapter seeks: keep track which chapter
@@ -334,7 +347,6 @@ typedef struct MPContext {
int last_dvb_step;
bool paused;
- bool eof_reached;
// step this many frames, then pause
int step_frames;
// Counted down each frame, stop playback if 0 is reached. (-1 = disable)
@@ -354,16 +366,17 @@ typedef struct MPContext {
} MPContext;
// audio.c
+void reset_audio_state(struct MPContext *mpctx);
void reinit_audio_chain(struct MPContext *mpctx);
int reinit_audio_filters(struct MPContext *mpctx);
double playing_audio_pts(struct MPContext *mpctx);
-int fill_audio_out_buffers(struct MPContext *mpctx, double endpts);
+void fill_audio_out_buffers(struct MPContext *mpctx, double endpts);
double written_audio_pts(struct MPContext *mpctx);
void clear_audio_output_buffers(struct MPContext *mpctx);
void clear_audio_decode_buffers(struct MPContext *mpctx);
// configfiles.c
-bool mp_parse_cfgfiles(struct MPContext *mpctx);
+void mp_parse_cfgfiles(struct MPContext *mpctx);
void mp_load_auto_profiles(struct MPContext *mpctx);
void mp_get_resume_defaults(struct MPContext *mpctx);
void mp_load_playback_resume(struct MPContext *mpctx, const char *file);
@@ -393,14 +406,13 @@ struct track *mp_track_by_tid(struct MPContext *mpctx, enum stream_type type,
int tid);
bool timeline_set_part(struct MPContext *mpctx, int i, bool force);
double timeline_set_from_time(struct MPContext *mpctx, double pts, bool *need_reset);
-struct sh_stream *init_demux_stream(struct MPContext *mpctx, struct track *track);
-void reselect_demux_streams(struct MPContext *mpctx);
void add_demuxer_tracks(struct MPContext *mpctx, struct demuxer *demuxer);
bool mp_remove_track(struct MPContext *mpctx, struct track *track);
struct playlist_entry *mp_next_file(struct MPContext *mpctx, int direction,
bool force);
void mp_set_playlist_entry(struct MPContext *mpctx, struct playlist_entry *e);
void mp_play_files(struct MPContext *mpctx);
+void update_demuxer_properties(struct MPContext *mpctx);
// main.c
int mpv_main(int argc, char *argv[]);
@@ -416,7 +428,7 @@ double rel_time_to_abs(struct MPContext *mpctx, struct m_rel_time t);
double get_play_end_pts(struct MPContext *mpctx);
double get_relative_time(struct MPContext *mpctx);
void merge_playlist_files(struct playlist *pl);
-int mp_get_cache_percent(struct MPContext *mpctx);
+float mp_get_cache_percent(struct MPContext *mpctx);
bool mp_get_cache_idle(struct MPContext *mpctx);
void update_window_title(struct MPContext *mpctx, bool force);
void stream_dump(struct MPContext *mpctx);
@@ -431,6 +443,7 @@ void set_osd_function(struct MPContext *mpctx, int osd_function);
void set_osd_subtitle(struct MPContext *mpctx, const char *text);
// playloop.c
+void reset_playback_state(struct MPContext *mpctx);
void pause_player(struct MPContext *mpctx);
void unpause_player(struct MPContext *mpctx);
void add_step_frame(struct MPContext *mpctx, int dir);
@@ -439,6 +452,7 @@ void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
bool mp_seek_chapter(struct MPContext *mpctx, int chapter);
double get_time_length(struct MPContext *mpctx);
double get_current_time(struct MPContext *mpctx);
+double get_playback_time(struct MPContext *mpctx);
int get_percent_pos(struct MPContext *mpctx);
double get_current_pos_ratio(struct MPContext *mpctx, bool use_range);
int get_current_chapter(struct MPContext *mpctx);
@@ -460,6 +474,7 @@ struct mp_scripting {
void mp_load_scripts(struct MPContext *mpctx);
// sub.c
+void reset_subtitle_state(struct MPContext *mpctx);
void reset_subtitles(struct MPContext *mpctx, int order);
void uninit_subs(struct demuxer *demuxer);
void reinit_subs(struct MPContext *mpctx, int order);
@@ -474,10 +489,10 @@ void build_mpv_edl_timeline(struct MPContext *mpctx);
void build_cue_timeline(struct MPContext *mpctx);
// video.c
+void reset_video_state(struct MPContext *mpctx);
int reinit_video_chain(struct MPContext *mpctx);
int reinit_video_filters(struct MPContext *mpctx);
-int update_video(struct MPContext *mpctx, double endpts, bool reconfig_ok,
- double *frame_duration);
+void write_video(struct MPContext *mpctx, double endpts);
void mp_force_video_refresh(struct MPContext *mpctx);
void update_fps(struct MPContext *mpctx);
diff --git a/player/discnav.c b/player/discnav.c
index 5051dbf..2c24fc9 100644
--- a/player/discnav.c
+++ b/player/discnav.c
@@ -26,6 +26,7 @@
#include "common/common.h"
#include "input/input.h"
+#include "demux/demux.h"
#include "stream/discnav.h"
#include "sub/dec_sub.h"
@@ -90,6 +91,18 @@ int mp_nav_in_menu(struct MPContext *mpctx)
return mpctx->nav_state ? mpctx->nav_state->nav_menu : -1;
}
+// If a demuxer is accessing the stream, we have to use demux_stream_control()
+// to avoid synchronization issues; otherwise access it directly.
+static int run_stream_control(struct MPContext *mpctx, int cmd, void *arg)
+{
+ if (mpctx->demuxer) {
+ return demux_stream_control(mpctx->demuxer, cmd, arg);
+ } else if (mpctx->stream) {
+ return stream_control(mpctx->stream, cmd, arg);
+ }
+ return STREAM_ERROR;
+}
+
// Allocate state and enable navigation features. Must happen before
// initializing cache, because the cache would read data. Since stream_dvdnav is
// in a mode which skips all transitions on reading data (before enabling
@@ -103,7 +116,7 @@ void mp_nav_init(struct MPContext *mpctx)
return;
struct mp_nav_cmd inp = {MP_NAV_CMD_ENABLE};
- if (stream_control(mpctx->stream, STREAM_CTRL_NAV_CMD, &inp) < 1)
+ if (run_stream_control(mpctx, STREAM_CTRL_NAV_CMD, &inp) < 1)
return;
mpctx->nav_state = talloc_zero(NULL, struct mp_nav_state);
@@ -125,14 +138,14 @@ void mp_nav_reset(struct MPContext *mpctx)
if (!nav)
return;
struct mp_nav_cmd inp = {MP_NAV_CMD_RESUME};
- stream_control(mpctx->stream, STREAM_CTRL_NAV_CMD, &inp);
+ run_stream_control(mpctx, STREAM_CTRL_NAV_CMD, &inp);
osd_set_nav_highlight(mpctx->osd, NULL);
nav->hi_visible = 0;
nav->nav_menu = false;
nav->nav_draining = false;
nav->nav_still_frame = 0;
mp_input_disable_section(mpctx->input, "discnav-menu");
- stream_control(mpctx->stream, STREAM_CTRL_RESUME_CACHE, NULL);
+ run_stream_control(mpctx, STREAM_CTRL_RESUME_CACHE, NULL);
update_state(mpctx);
}
@@ -164,11 +177,11 @@ void mp_nav_user_input(struct MPContext *mpctx, char *command)
osd_coords_to_video(mpctx->osd, vid.w, vid.h, &x, &y);
inp.u.mouse_pos.x = x;
inp.u.mouse_pos.y = y;
- stream_control(mpctx->stream, STREAM_CTRL_NAV_CMD, &inp);
+ run_stream_control(mpctx, STREAM_CTRL_NAV_CMD, &inp);
} else {
struct mp_nav_cmd inp = {MP_NAV_CMD_MENU};
inp.u.menu.action = command;
- stream_control(mpctx->stream, STREAM_CTRL_NAV_CMD, &inp);
+ run_stream_control(mpctx, STREAM_CTRL_NAV_CMD, &inp);
}
}
@@ -179,7 +192,7 @@ void mp_handle_nav(struct MPContext *mpctx)
return;
while (1) {
struct mp_nav_event *ev = NULL;
- stream_control(mpctx->stream, STREAM_CTRL_GET_NAV_EVENT, &ev);
+ run_stream_control(mpctx, STREAM_CTRL_GET_NAV_EVENT, &ev);
if (!ev)
break;
switch (ev->event) {
@@ -261,15 +274,15 @@ void mp_handle_nav(struct MPContext *mpctx)
nav->nav_still_frame = -2;
} else if (nav->nav_still_frame == -2) {
struct mp_nav_cmd inp = {MP_NAV_CMD_SKIP_STILL};
- stream_control(mpctx->stream, STREAM_CTRL_NAV_CMD, &inp);
+ run_stream_control(mpctx, STREAM_CTRL_NAV_CMD, &inp);
}
}
if (nav->nav_draining && mpctx->stop_play == AT_END_OF_FILE) {
MP_VERBOSE(nav, "execute drain\n");
struct mp_nav_cmd inp = {MP_NAV_CMD_DRAIN_OK};
- stream_control(mpctx->stream, STREAM_CTRL_NAV_CMD, &inp);
+ run_stream_control(mpctx, STREAM_CTRL_NAV_CMD, &inp);
nav->nav_draining = false;
- stream_control(mpctx->stream, STREAM_CTRL_RESUME_CACHE, NULL);
+ run_stream_control(mpctx, STREAM_CTRL_RESUME_CACHE, NULL);
}
// E.g. keep displaying still frames
if (mpctx->stop_play == AT_END_OF_FILE && !nav->nav_eof)
@@ -277,7 +290,7 @@ void mp_handle_nav(struct MPContext *mpctx)
}
// Render "fake" highlights, because using actual dvd sub highlight elements
-// is too hard, and would require extra libavcodec to begin with.
+// is too hard, and would require changes to libavcodec's dvdsub decoder.
// Note: a proper solution would introduce something like
// SD_CTRL_APPLY_DVDNAV, which would crop the vobsub frame,
// and apply the current CLUT.
diff --git a/player/loadfile.c b/player/loadfile.c
index 18d1147..a941f7a 100644
--- a/player/loadfile.c
+++ b/player/loadfile.c
@@ -18,6 +18,7 @@
#include <stddef.h>
#include <stdbool.h>
+#include <strings.h>
#include <inttypes.h>
#include <assert.h>
@@ -59,6 +60,8 @@
#include "command.h"
#include "libmpv/client.h"
+static void reselect_demux_streams(struct MPContext *mpctx);
+
static void uninit_sub(struct MPContext *mpctx, int order)
{
if (mpctx->d_sub[order])
@@ -83,6 +86,7 @@ void uninit_player(struct MPContext *mpctx, unsigned int mask)
mixer_uninit_audio(mpctx->mixer);
audio_uninit(mpctx->d_audio);
mpctx->d_audio = NULL;
+ mpctx->audio_status = STATUS_EOF;
reselect_demux_streams(mpctx);
}
@@ -110,6 +114,7 @@ void uninit_player(struct MPContext *mpctx, unsigned int mask)
if (mpctx->d_video)
video_uninit(mpctx->d_video);
mpctx->d_video = NULL;
+ mpctx->video_status = STATUS_EOF;
mpctx->sync_audio_to_video = false;
reselect_demux_streams(mpctx);
}
@@ -183,102 +188,119 @@ void uninit_player(struct MPContext *mpctx, unsigned int mask)
mpctx->initialized_flags &= ~INITIALIZED_PLAYBACK;
}
+#define APPEND(s, ...) mp_snprintf_cat(s, sizeof(s), __VA_ARGS__)
+
static void print_stream(struct MPContext *mpctx, struct track *t)
{
struct sh_stream *s = t->stream;
const char *tname = "?";
const char *selopt = "?";
const char *langopt = "?";
- const char *iid = NULL;
switch (t->type) {
case STREAM_VIDEO:
- tname = "Video"; selopt = "vid"; langopt = NULL; iid = "VID";
+ tname = "Video"; selopt = "vid"; langopt = NULL;
break;
case STREAM_AUDIO:
- tname = "Audio"; selopt = "aid"; langopt = "alang"; iid = "AID";
+ tname = "Audio"; selopt = "aid"; langopt = "alang";
break;
case STREAM_SUB:
- tname = "Subs"; selopt = "sid"; langopt = "slang"; iid = "SID";
+ tname = "Subs"; selopt = "sid"; langopt = "slang";
break;
}
- MP_INFO(mpctx, "[stream] %-5s %3s", tname, t->selected ? "(+)" : "");
- MP_INFO(mpctx, " --%s=%d", selopt, t->user_tid);
+ char b[2048] = {0};
+ APPEND(b, "[stream] %-5s %3s", tname, t->selected ? "(+)" : "");
+ APPEND(b, " --%s=%d", selopt, t->user_tid);
if (t->lang && langopt)
- MP_INFO(mpctx, " --%s=%s", langopt, t->lang);
+ APPEND(b, " --%s=%s", langopt, t->lang);
if (t->default_track)
- MP_INFO(mpctx, " (*)");
+ APPEND(b, " (*)");
if (t->attached_picture)
- MP_INFO(mpctx, " [P]");
+ APPEND(b, " [P]");
if (t->title)
- MP_INFO(mpctx, " '%s'", t->title);
+ APPEND(b, " '%s'", t->title);
const char *codec = s ? s->codec : NULL;
- MP_INFO(mpctx, " (%s)", codec ? codec : "<unknown>");
+ APPEND(b, " (%s)", codec ? codec : "<unknown>");
if (t->is_external)
- MP_INFO(mpctx, " (external)");
- MP_INFO(mpctx, "\n");
- // legacy compatibility
- if (!iid)
- return;
+ APPEND(b, " (external)");
+ MP_INFO(mpctx, "%s\n", b);
}
-static void print_file_properties(struct MPContext *mpctx)
+void update_demuxer_properties(struct MPContext *mpctx)
{
struct demuxer *demuxer = mpctx->master_demuxer;
- if (demuxer->num_editions > 1) {
+ if (!demuxer)
+ return;
+ demux_update(demuxer);
+ int events = demuxer->events;
+ if ((events & DEMUX_EVENT_INIT) && demuxer->num_editions > 1) {
for (int n = 0; n < demuxer->num_editions; n++) {
struct demux_edition *edition = &demuxer->editions[n];
- MP_INFO(mpctx, "[edition] %3s --edition=%d",
- n == demuxer->edition ? "(+)" : "", n);
+ char b[128] = {0};
+ APPEND(b, "[edition] %3s --edition=%d",
+ n == demuxer->edition ? "(+)" : "", n);
char *name = mp_tags_get_str(edition->metadata, "title");
if (name)
- MP_INFO(mpctx, " '%s'", name);
+ APPEND(b, " '%s'", name);
if (edition->default_edition)
- MP_INFO(mpctx, " (*)");
- MP_INFO(mpctx, "\n");
+ APPEND(b, " (*)");
+ MP_INFO(mpctx, "%s\n", b);
}
}
- for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
- for (int n = 0; n < mpctx->num_tracks; n++)
- if (mpctx->tracks[n]->type == t)
- print_stream(mpctx, mpctx->tracks[n]);
+ struct demuxer *tracks = mpctx->track_layout;
+ if (tracks->events & DEMUX_EVENT_STREAMS) {
+ add_demuxer_tracks(mpctx, tracks);
+ for (int t = 0; t < STREAM_TYPE_COUNT; t++) {
+ for (int n = 0; n < mpctx->num_tracks; n++)
+ if (mpctx->tracks[n]->type == t)
+ print_stream(mpctx, mpctx->tracks[n]);
+ }
+ tracks->events &= ~DEMUX_EVENT_STREAMS;
+ }
+ struct mp_tags *info = demuxer->metadata;
+ if ((events & DEMUX_EVENT_METADATA) && info->num_keys) {
+ MP_INFO(mpctx, "File tags:\n");
+ for (int n = 0; n < info->num_keys; n++)
+ MP_INFO(mpctx, " %s: %s\n", info->keys[n], info->values[n]);
+ mp_notify(mpctx, MPV_EVENT_METADATA_UPDATE, NULL);
}
+ demuxer->events = 0;
+}
+
+static bool need_init_seek(struct demuxer *demux)
+{
+ for (int n = 0; n < demux->num_streams; n++) {
+ struct sh_stream *stream = demux->streams[n];
+ // Subtitle streams are not properly interleaved -> force init. seek.
+ if (stream->type != STREAM_SUB && demux_stream_is_selected(stream))
+ return false;
+ }
+ return true;
}
// Enable needed streams, disable others.
// Note that switching all tracks at once (instead when initializing something)
// can be important, because reading from a demuxer stream (e.g. during init)
// will implicitly discard interleaved packets from unselected streams.
-void reselect_demux_streams(struct MPContext *mpctx)
+// Also initializes position for external streams.
+static void reselect_demux_streams(struct MPContext *mpctx)
{
// Note: we assume that all demuxer streams are covered by the track list.
for (int t = 0; t < mpctx->num_tracks; t++) {
struct track *track = mpctx->tracks[t];
- if (track->demuxer && track->stream)
+ if (track->demuxer && track->stream) {
+ bool need_init = track->selected &&
+ mpctx->demuxer != track->demuxer &&
+ need_init_seek(track->demuxer);
demuxer_select_track(track->demuxer, track->stream, track->selected);
- }
-}
-
-// External demuxers might need a seek to the current playback position.
-static void external_track_seek(struct MPContext *mpctx, struct track *track)
-{
- if (track && track->demuxer && track->selected && track->is_external) {
- for (int t = 0; t < mpctx->num_tracks; t++) {
- struct track *other = mpctx->tracks[t];
- if (other->demuxer == track->demuxer &&
- demuxer_stream_is_selected(other->demuxer, other->stream))
- return;
+ if (need_init) {
+ double pts = get_main_demux_pts(mpctx);
+ if (pts != MP_NOPTS_VALUE)
+ demux_seek(track->demuxer, pts, SEEK_ABSOLUTE);
+ }
}
- double pts = get_main_demux_pts(mpctx);
- demux_seek(track->demuxer, pts, SEEK_ABSOLUTE);
}
}
-struct sh_stream *init_demux_stream(struct MPContext *mpctx, struct track *track)
-{
- external_track_seek(mpctx, track);
- return track ? track->stream : NULL;
-}
-
static struct sh_stream *select_fallback_stream(struct demuxer *d,
enum stream_type type,
int index)
@@ -296,6 +318,21 @@ static struct sh_stream *select_fallback_stream(struct demuxer *d,
return best_stream;
}
+// Called from the demuxer thread if a new packet is available.
+static void wakeup_demux(void *pctx)
+{
+ struct MPContext *mpctx = pctx;
+ mp_input_wakeup(mpctx->input);
+}
+
+static void enable_demux_thread(struct MPContext *mpctx)
+{
+ if (mpctx->demuxer && mpctx->opts->demuxer_thread) {
+ demux_set_wakeup_cb(mpctx->demuxer, wakeup_demux, mpctx);
+ demux_start_thread(mpctx->demuxer);
+ }
+}
+
bool timeline_set_part(struct MPContext *mpctx, int i, bool force)
{
struct timeline_part *p = mpctx->timeline + mpctx->timeline_part;
@@ -310,6 +347,11 @@ bool timeline_set_part(struct MPContext *mpctx, int i, bool force)
uninit_player(mpctx, INITIALIZED_VCODEC | (mpctx->opts->fixed_vo ? 0 : INITIALIZED_VO) | (mpctx->opts->gapless_audio ? 0 : INITIALIZED_AO) | INITIALIZED_ACODEC | INITIALIZED_SUB | INITIALIZED_SUB2);
mpctx->stop_play = orig_stop_play;
+ if (mpctx->demuxer) {
+ demux_stop_thread(mpctx->demuxer);
+ demux_flush(mpctx->demuxer);
+ }
+
mpctx->demuxer = n->source;
mpctx->stream = mpctx->demuxer->stream;
@@ -332,6 +374,8 @@ bool timeline_set_part(struct MPContext *mpctx, int i, bool force)
}
reselect_demux_streams(mpctx);
+ enable_demux_thread(mpctx);
+
return true;
}
@@ -351,14 +395,6 @@ double timeline_set_from_time(struct MPContext *mpctx, double pts, bool *need_re
return -1;
}
-// Map stream number (as used by libdvdread) to MPEG IDs (as used by demuxer).
-static int map_id_from_demuxer(struct demuxer *d, enum stream_type type, int id)
-{
- if (d->stream->uncached_type == STREAMTYPE_DVD && type == STREAM_SUB)
- id = id & 0x1F;
- return id;
-}
-
static int find_new_tid(struct MPContext *mpctx, enum stream_type t)
{
int new_id = 0;
@@ -371,29 +407,14 @@ static int find_new_tid(struct MPContext *mpctx, enum stream_type t)
}
static struct track *add_stream_track(struct MPContext *mpctx,
+ struct demuxer *demuxer,
struct sh_stream *stream,
bool under_timeline)
{
for (int i = 0; i < mpctx->num_tracks; i++) {
struct track *track = mpctx->tracks[i];
- if (track->stream == stream)
+ if (track->original_stream == stream)
return track;
- // DVD subtitle track that was added later
- if (stream->type == STREAM_SUB && track->type == STREAM_SUB &&
- map_id_from_demuxer(stream->demuxer, stream->type,
- stream->demuxer_id) == track->demuxer_id
- && !track->stream)
- {
- track->stream = stream;
- track->demuxer_id = stream->demuxer_id;
- // Initialize lazily selected track
- demuxer_select_track(track->demuxer, stream, track->selected);
- if (mpctx->current_track[0][STREAM_SUB] == track)
- reinit_subs(mpctx, 0);
- if (mpctx->current_track[1][STREAM_SUB] == track)
- reinit_subs(mpctx, 1);
- return track;
- }
}
struct track *track = talloc_ptrtype(NULL, track);
@@ -406,26 +427,12 @@ static struct track *add_stream_track(struct MPContext *mpctx,
.attached_picture = stream->attached_picture != NULL,
.lang = stream->lang,
.under_timeline = under_timeline,
- .demuxer = stream->demuxer,
+ .demuxer = demuxer,
.stream = stream,
+ .original_stream = stream,
};
MP_TARRAY_APPEND(mpctx, mpctx->tracks, mpctx->num_tracks, track);
- // Needed for DVD and Blu-ray.
- struct stream *st = track->demuxer->stream;
- if (!track->lang && (st->uncached_type == STREAMTYPE_BLURAY ||
- st->uncached_type == STREAMTYPE_DVD))
- {
- struct stream_lang_req req = {
- .type = track->type,
- .id = map_id_from_demuxer(track->demuxer, track->type,
- track->demuxer_id)
- };
- stream_control(st, STREAM_CTRL_GET_LANG, &req);
- if (req.name[0])
- track->lang = talloc_strdup(track, req.name);
- }
-
demuxer_select_track(track->demuxer, stream, false);
mp_notify(mpctx, MPV_EVENT_TRACKS_CHANGED, NULL);
@@ -436,35 +443,7 @@ static struct track *add_stream_track(struct MPContext *mpctx,
void add_demuxer_tracks(struct MPContext *mpctx, struct demuxer *demuxer)
{
for (int n = 0; n < demuxer->num_streams; n++)
- add_stream_track(mpctx, demuxer->streams[n], !!mpctx->timeline);
-}
-
-static void add_dvd_tracks(struct MPContext *mpctx)
-{
- struct demuxer *demuxer = mpctx->demuxer;
- struct stream *stream = demuxer->stream;
- struct stream_dvd_info_req info;
- if (stream->uncached_type != STREAMTYPE_DVD)
- return;
- if (stream_control(stream, STREAM_CTRL_GET_DVD_INFO, &info) > 0) {
- for (int n = 0; n < info.num_subs; n++) {
- struct track *track = talloc_ptrtype(NULL, track);
- *track = (struct track) {
- .type = STREAM_SUB,
- .user_tid = find_new_tid(mpctx, STREAM_SUB),
- .demuxer_id = n,
- .demuxer = mpctx->demuxer,
- };
- MP_TARRAY_APPEND(mpctx, mpctx->tracks, mpctx->num_tracks, track);
-
- struct stream_lang_req req = {.type = STREAM_SUB, .id = n};
- stream_control(stream, STREAM_CTRL_GET_LANG, &req);
- track->lang = talloc_strdup(track, req.name);
-
- mp_notify(mpctx, MPV_EVENT_TRACKS_CHANGED, NULL);
- }
- }
- demuxer_enable_autoselect(demuxer);
+ add_stream_track(mpctx, demuxer, demuxer->streams[n], !!mpctx->timeline);
}
// Result numerically higher => better match. 0 == no match.
@@ -717,9 +696,11 @@ static void open_subtitles_from_options(struct MPContext *mpctx)
void *tmp = talloc_new(NULL);
char *base_filename = mpctx->filename;
char *stream_filename = NULL;
- if (stream_control(mpctx->stream, STREAM_CTRL_GET_BASE_FILENAME,
- &stream_filename) > 0)
- base_filename = talloc_steal(tmp, stream_filename);
+ if (mpctx->demuxer) {
+ if (demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_BASE_FILENAME,
+ &stream_filename) > 0)
+ base_filename = talloc_steal(tmp, stream_filename);
+ }
struct subfn *list = find_text_subtitles(mpctx->global, base_filename);
talloc_steal(tmp, list);
for (int i = 0; list && list[i].fname; i++) {
@@ -769,9 +750,9 @@ static struct track *open_external_file(struct MPContext *mpctx, char *filename,
for (int n = 0; n < demuxer->num_streams; n++) {
struct sh_stream *sh = demuxer->streams[n];
if (sh->type == filter) {
- struct track *t = add_stream_track(mpctx, sh, false);
+ struct track *t = add_stream_track(mpctx, demuxer, sh, false);
t->is_external = true;
- t->title = talloc_strdup(t, disp_filename);
+ t->title = talloc_strdup(t, mp_basename(disp_filename));
t->external_filename = talloc_strdup(t, filename);
first = t;
}
@@ -1172,19 +1153,20 @@ goto_reopen_demuxer: ;
print_timeline(mpctx);
load_chapters(mpctx);
+ mpctx->track_layout = mpctx->demuxer;
if (mpctx->timeline) {
// With Matroska, the "master" file usually dictates track layout etc.
// On the contrary, the EDL and CUE demuxers are empty wrappers, as
// well as Matroska ordered chapter playlist-like files.
+ mpctx->track_layout = mpctx->timeline[0].source;
for (int n = 0; n < mpctx->num_timeline_parts; n++) {
- if (mpctx->timeline[n].source == mpctx->demuxer)
- goto main_is_ok;
+ if (mpctx->timeline[n].source == mpctx->demuxer) {
+ mpctx->track_layout = mpctx->demuxer;
+ break;
+ }
}
- mpctx->demuxer = mpctx->timeline[0].source;
- main_is_ok: ;
}
- add_dvd_tracks(mpctx);
- add_demuxer_tracks(mpctx, mpctx->demuxer);
+ add_demuxer_tracks(mpctx, mpctx->track_layout);
mpctx->timeline_part = 0;
if (mpctx->timeline)
@@ -1227,6 +1209,10 @@ goto_reopen_demuxer: ;
}
reselect_demux_streams(mpctx);
+ update_demuxer_properties(mpctx);
+
+ enable_demux_thread(mpctx);
+
if (mpctx->current_track[0][STREAM_VIDEO] &&
mpctx->current_track[0][STREAM_VIDEO]->attached_picture)
{
@@ -1234,9 +1220,6 @@ goto_reopen_demuxer: ;
"Displaying attached picture. Use --no-audio-display to prevent this.\n");
}
- demux_info_update(mpctx->master_demuxer);
- print_file_properties(mpctx);
-
#if HAVE_ENCODING
if (mpctx->encode_lavc_ctx && mpctx->current_track[0][STREAM_VIDEO])
encode_lavc_expect_stream(mpctx->encode_lavc_ctx, AVMEDIA_TYPE_VIDEO);
@@ -1256,11 +1239,11 @@ goto_reopen_demuxer: ;
//==================== START PLAYING =======================
if (!mpctx->d_video && !mpctx->d_audio) {
- struct stream *s = mpctx->stream;
+ struct demuxer *d = mpctx->demuxer;
MP_FATAL(mpctx, "No video or audio streams selected.\n");
- if (s->uncached_type == STREAMTYPE_DVB) {
+ if (d->stream->uncached_type == STREAMTYPE_DVB) {
int dir = mpctx->last_dvb_step;
- if (stream_control(s, STREAM_CTRL_DVB_STEP_CHANNEL, &dir) > 0)
+ if (demux_stream_control(d, STREAM_CTRL_DVB_STEP_CHANNEL, &dir) > 0)
mpctx->stop_play = PT_RELOAD_DEMUXER;
}
goto terminate_playback;
@@ -1268,8 +1251,6 @@ goto_reopen_demuxer: ;
MP_VERBOSE(mpctx, "Starting playback...\n");
- mpctx->drop_frame_cnt = 0;
- mpctx->dropped_frames = 0;
mpctx->max_frames = opts->play_frames;
if (mpctx->max_frames == 0) {
@@ -1277,25 +1258,17 @@ goto_reopen_demuxer: ;
goto terminate_playback;
}
- mpctx->time_frame = 0;
- mpctx->drop_message_shown = 0;
- mpctx->restart_playback = true;
- mpctx->video_pts = 0;
+ reset_playback_state(mpctx);
+
mpctx->last_vo_pts = MP_NOPTS_VALUE;
- mpctx->last_frame_duration = 0;
- mpctx->last_seek_pts = 0;
- mpctx->playback_pts = MP_NOPTS_VALUE;
- mpctx->hrseek_active = false;
- mpctx->hrseek_framedrop = false;
- mpctx->step_frames = 0;
- mpctx->backstep_active = false;
- mpctx->total_avsync_change = 0;
mpctx->last_chapter_seek = -2;
- mpctx->playing_msg_shown = false;
+ mpctx->last_chapter_pts = MP_NOPTS_VALUE;
+ mpctx->last_chapter = -2;
mpctx->paused = false;
mpctx->paused_for_cache = false;
- mpctx->eof_reached = false;
- mpctx->last_chapter = -2;
+ mpctx->playing_msg_shown = false;
+ mpctx->step_frames = 0;
+ mpctx->backstep_active = false;
mpctx->seek = (struct seek_params){ 0 };
// If there's a timeline force an absolute seek to initialize state
diff --git a/player/lua.c b/player/lua.c
index ab00c58..ce0de90 100644
--- a/player/lua.c
+++ b/player/lua.c
@@ -17,6 +17,7 @@
#include <assert.h>
#include <string.h>
+#include <strings.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
@@ -68,6 +69,7 @@ static const char * const builtin_lua_scripts[][2] = {
// Represents a loaded script. Each has its own Lua state.
struct script_ctx {
const char *name;
+ const char *filename;
lua_State *state;
struct mp_log *log;
struct mpv_handle *client;
@@ -75,6 +77,19 @@ struct script_ctx {
int suspended;
};
+#if LUA_VERSION_NUM <= 501
+#define mp_cpcall lua_cpcall
+#else
+// Curse whoever had this stupid idea. Curse whoever thought it would be a good
+// idea not to include an emulated lua_cpcall() even more.
+static int mp_cpcall (lua_State *L, lua_CFunction func, void *ud)
+{
+ lua_pushcfunction(L, func); // doesn't allocate in 5.2 (but does in 5.1)
+ lua_pushlightuserdata(L, ud);
+ return lua_pcall(L, 1, 0, 0);
+}
+#endif
+
static struct script_ctx *get_ctx(lua_State *L)
{
lua_getfield(L, LUA_REGISTRYINDEX, "ctx");
@@ -89,34 +104,18 @@ static struct MPContext *get_mpctx(lua_State *L)
return get_ctx(L)->mpctx;
}
-static int wrap_cpcall(lua_State *L)
+static int error_handler(lua_State *L)
{
- lua_CFunction fn = lua_touserdata(L, -1);
- lua_pop(L, 1);
- return fn(L);
-}
+ struct script_ctx *ctx = get_ctx(L);
-// Call the given function fn under a Lua error handler (similar to lua_cpcall).
-// Pass the given number of args from the Lua stack to fn.
-// Returns 0 (and empty stack) on success.
-// Returns LUA_ERR[RUN|MEM|ERR] otherwise, with the error value on the stack.
-static int mp_cpcall(lua_State *L, lua_CFunction fn, int args)
-{
- // Don't use lua_pushcfunction() - it allocates memory on Lua 5.1.
- // Instead, emulate C closures by making wrap_cpcall call fn.
- lua_pushlightuserdata(L, fn); // args... fn
- // Will always succeed if mp_lua_init() set it up correctly.
- lua_getfield(L, LUA_REGISTRYINDEX, "wrap_cpcall"); // args... fn wrap_cpcall
- lua_insert(L, -(args + 2)); // wrap_cpcall args... fn
- return lua_pcall(L, args + 1, 0, 0);
-}
+ if (luaL_loadstring(L, "return debug.traceback('', 3)") == 0) { // e fn|err
+ lua_call(L, 0, 1); // e backtrace
+ const char *tr = lua_tostring(L, -1);
+ MP_WARN(ctx, "%s\n", tr);
+ }
+ lua_pop(L, 1); // e
-static void report_error(lua_State *L)
-{
- struct script_ctx *ctx = get_ctx(L);
- const char *err = lua_tostring(L, -1);
- MP_WARN(ctx, "Error: %s\n", err ? err : "[unknown]");
- lua_pop(L, 1);
+ return 1;
}
// Check client API error code:
@@ -133,30 +132,18 @@ static int check_error(lua_State *L, int err)
return 2;
}
-static int run_event_loop(lua_State *L)
-{
- lua_getglobal(L, "mp_event_loop");
- if (lua_isnil(L, -1))
- luaL_error(L, "no event loop function\n");
- lua_call(L, 0, 0);
- return 0;
-}
-
static void add_functions(struct script_ctx *ctx);
-static int load_file(struct script_ctx *ctx, const char *fname)
+static void load_file(lua_State *L, const char *fname)
{
- int r = 0;
- lua_State *L = ctx->state;
+ struct script_ctx *ctx = get_ctx(L);
char *res_name = mp_get_user_path(NULL, ctx->mpctx->global, fname);
MP_VERBOSE(ctx, "loading file %s\n", res_name);
- if (luaL_loadfile(L, res_name) || lua_pcall(L, 0, 0, 0)) {
- report_error(L);
- r = -1;
- }
- assert(lua_gettop(L) == 0);
- talloc_free(res_name);
- return r;
+ int r = luaL_loadfile(L, res_name);
+ talloc_free(res_name); // careful to not leak this on Lua errors
+ if (r)
+ lua_error(L);
+ lua_call(L, 0, 0);
}
static int load_builtin(lua_State *L)
@@ -173,22 +160,21 @@ static int load_builtin(lua_State *L)
return 1;
}
}
+ luaL_error(L, "builtin module '%s' not found\n", name);
return 0;
}
// Execute "require " .. name
-static bool require(lua_State *L, const char *name)
+static void require(lua_State *L, const char *name)
{
struct script_ctx *ctx = get_ctx(L);
MP_VERBOSE(ctx, "loading %s\n", name);
// Lazy, but better than calling the "require" function manually
char buf[80];
snprintf(buf, sizeof(buf), "require '%s'", name);
- if (luaL_loadstring(L, buf) || lua_pcall(L, 0, 0, 0)) {
- report_error(L);
- return false;
- }
- return true;
+ if (luaL_loadstring(L, buf))
+ lua_error(L);
+ lua_call(L, 0, 0);
}
// Push the table of a module. If it doesn't exist, it's created.
@@ -208,31 +194,38 @@ static void push_module_table(lua_State *L, const char *module)
lua_remove(L, -2); // module
}
-static int load_lua(struct mpv_handle *client, const char *fname)
+static int load_scripts(lua_State *L)
{
- struct MPContext *mpctx = mp_client_get_core(client);
- int r = -1;
+ struct script_ctx *ctx = get_ctx(L);
+ const char *fname = ctx->filename;
- struct script_ctx *ctx = talloc_ptrtype(NULL, ctx);
- *ctx = (struct script_ctx) {
- .mpctx = mpctx,
- .client = client,
- .name = mpv_client_name(client),
- .log = mp_client_get_log(client),
- };
+ require(L, "mp.defaults");
- lua_State *L = ctx->state = luaL_newstate();
- if (!L)
- goto error_out;
+ if (fname[0] == '@') {
+ require(L, fname);
+ } else {
+ load_file(L, fname);
+ }
+
+ lua_getglobal(L, "mp_event_loop"); // fn
+ if (lua_isnil(L, -1))
+ luaL_error(L, "no event loop function\n");
+ lua_call(L, 0, 0); // -
+
+ return 0;
+}
+
+static int run_lua(lua_State *L)
+{
+ struct script_ctx *ctx = lua_touserdata(L, -1);
+ lua_pop(L, 1); // -
+
+ luaL_openlibs(L);
// used by get_ctx()
lua_pushlightuserdata(L, ctx); // ctx
lua_setfield(L, LUA_REGISTRYINDEX, "ctx"); // -
- lua_pushcfunction(L, wrap_cpcall); // closure
- lua_setfield(L, LUA_REGISTRYINDEX, "wrap_cpcall"); // -
-
- luaL_openlibs(L);
add_functions(ctx); // mp
push_module_table(L, "mp"); // mp
@@ -275,24 +268,40 @@ static int load_lua(struct mpv_handle *client, const char *fname)
assert(lua_gettop(L) == 0);
- if (!require(L, "mp.defaults")) {
- report_error(L);
- goto error_out;
- }
+ // run this under an error handler that can do backtraces
+ lua_pushcfunction(L, error_handler); // errf
+ lua_pushcfunction(L, load_scripts); // errf fn
+ if (lua_pcall(L, 0, 0, -2)) // errf [error]
+ MP_FATAL(ctx, "Lua error: %s\n", lua_tostring(L, -1));
- assert(lua_gettop(L) == 0);
+ return 0;
+}
- if (fname[0] == '@') {
- if (!require(L, fname))
- goto error_out;
- } else {
- if (load_file(ctx, fname) < 0)
- goto error_out;
- }
+static int load_lua(struct mpv_handle *client, const char *fname)
+{
+ struct MPContext *mpctx = mp_client_get_core(client);
+ int r = -1;
- // Call the script's event loop runs until the script terminates and unloads.
- if (mp_cpcall(L, run_event_loop, 0) != 0)
- report_error(L);
+ struct script_ctx *ctx = talloc_ptrtype(NULL, ctx);
+ *ctx = (struct script_ctx) {
+ .mpctx = mpctx,
+ .client = client,
+ .name = mpv_client_name(client),
+ .log = mp_client_get_log(client),
+ .filename = fname,
+ };
+
+ lua_State *L = ctx->state = luaL_newstate();
+ if (!L)
+ goto error_out;
+
+ if (mp_cpcall(L, run_lua, ctx)) {
+ const char *err = "unknown error";
+ if (lua_type(L, -1) == LUA_TSTRING) // avoid allocation
+ err = lua_tostring(L, -1);
+ MP_FATAL(ctx, "Lua error: %s\n", err);
+ goto error_out;
+ }
r = 0;
@@ -343,7 +352,7 @@ static int script_find_config_file(lua_State *L)
{
struct MPContext *mpctx = get_mpctx(L);
const char *s = luaL_checkstring(L, 1);
- char *path = mp_find_user_config_file(NULL, mpctx->global, s);
+ char *path = mp_find_config_file(NULL, mpctx->global, s);
if (path) {
lua_pushstring(L, path);
} else {
@@ -690,18 +699,6 @@ static int script_set_property_native(lua_State *L)
}
-static int script_property_list(lua_State *L)
-{
- const struct m_property *props = mp_get_property_list();
- lua_newtable(L);
- for (int i = 0; props[i].name; i++) {
- lua_pushinteger(L, i + 1);
- lua_pushstring(L, props[i].name);
- lua_settable(L, -3);
- }
- return 1;
-}
-
static int script_get_property(lua_State *L)
{
struct script_ctx *ctx = get_ctx(L);
@@ -1090,7 +1087,6 @@ static const struct fn_entry main_fns[] = {
FN_ENTRY(set_property_native),
FN_ENTRY(raw_observe_property),
FN_ENTRY(raw_unobserve_property),
- FN_ENTRY(property_list),
FN_ENTRY(set_osd_ass),
FN_ENTRY(get_osd_resolution),
FN_ENTRY(get_screen_size),
diff --git a/player/lua/osc.lua b/player/lua/osc.lua
index 1fc3522..f688d0f 100644
--- a/player/lua/osc.lua
+++ b/player/lua/osc.lua
@@ -68,7 +68,6 @@ local state = {
tc_ms = false, -- Should the timecodes display their time with milliseconds
mp_screen_sizeX, mp_screen_sizeY, -- last screen-resolution, to detect resolution changes to issue reINITs
initREQ = false, -- is a re-init request pending?
- last_seek, -- last seek position, to avoid deadlocks by repeatedly seeking to the same position
last_mouseX, last_mouseY, -- last mouse position, to detect siginificant mouse movement
message_text,
message_timeout,
@@ -314,6 +313,7 @@ function register_element(type, x, y, an, w, h, style, content, eventresponder,
content = content,
eventresponder = eventresponder,
metainfo = metainfo,
+ state = {},
}
table.insert(elements, element)
@@ -864,7 +864,7 @@ function osc_init()
possec = duration * (pos / 100)
return mp.format_time(possec)
else
- return nil
+ return ""
end
end
@@ -882,16 +882,19 @@ function osc_init()
end
local eventresponder = {}
- local sliderF = function (element)
- local seek_to = get_slider_value(element)
- -- ignore identical seeks
- if not(state.last_seek == seek_to) then
- mp.commandv("seek", seek_to, "absolute-percent", "keyframes")
- state.last_seek = seek_to
- end
+
+ -- Do keyframe seeking when mouse is dragged
+ local sliderFfast = function (element)
+ mp.commandv("seek", get_slider_value(element), "absolute-percent", "keyframes")
+ end
+ eventresponder["mouse_move"] = sliderFfast
+
+ -- Do exact seeks on single clicks
+ local sliderFexact = function (element)
+ mp.commandv("seek", get_slider_value(element), "absolute-percent", "exact")
end
- eventresponder.render = sliderF
- eventresponder.mouse_btn0_down = sliderF
+ eventresponder.mouse_btn0_down = sliderFexact
+
register_slider(posX, posY+pos_offsetY-22, 2, pos_offsetX*2, 15, osc_styles.timecodes, 0, 100, markerF, posF, eventresponder, metainfo)
--
@@ -906,9 +909,9 @@ function osc_init()
local contentF = function (ass)
if state.tc_ms then
- ass:append(mp.get_property_osd("time-pos/full"))
+ ass:append(mp.get_property_osd("playback-time/full"))
else
- ass:append(mp.get_property_osd("time-pos"))
+ ass:append(mp.get_property_osd("playback-time"))
end
end
@@ -920,12 +923,9 @@ function osc_init()
local eventresponder = {}
local contentF = function (ass)
- local cache = mp.get_property("cache")
- if not (cache == nil) then
- cache = tonumber(mp.get_property("cache"))
- if (cache < 45) then
- ass:append("Cache: " .. (cache) .."%")
- end
+ local cache = mp.get_property_number("cache")
+ if not (cache == nil) and (cache < 45) then
+ ass:append("Cache: " .. (math.floor(cache)) .."%")
end
end
register_button(posX, bottomrowY, 5, 110, 18, osc_styles.timecodes, contentF, eventresponder, metainfo)
@@ -1139,10 +1139,15 @@ function process_event(source, what)
elements[n].eventresponder[source .. "_" .. what](elements[n])
end
end
+
+ --reset active element
+ if not (elements[n].eventresponder["reset"] == nil) then
+ elements[n].eventresponder["reset"](elements[n])
+ end
+
end
state.active_element = nil
state.mouse_down_counter = 0
- state.last_seek = nil
elseif source == "mouse_move" then
local mouseX, mouseY = mp.get_mouse_pos()
diff --git a/player/main.c b/player/main.c
index e2b15f6..9de7802 100644
--- a/player/main.c
+++ b/player/main.c
@@ -21,7 +21,6 @@
#include <stdbool.h>
#include <math.h>
#include <assert.h>
-#include <ctype.h>
#include <string.h>
#include <pthread.h>
@@ -72,8 +71,9 @@
#endif
#endif
-#if HAVE_COCOA
+#if HAVE_COCOA_APPLICATION
#include "osdep/macosx_application.h"
+#include "osdep/macosx_events.h"
#endif
#ifdef PTW32_STATIC_LIB
@@ -160,7 +160,7 @@ static MP_NORETURN void exit_player(struct MPContext *mpctx,
{
int rc;
-#if HAVE_COCOA
+#if HAVE_COCOA_APPLICATION
cocoa_set_input_context(NULL);
#endif
@@ -200,7 +200,7 @@ static MP_NORETURN void exit_player(struct MPContext *mpctx,
mp_destroy(mpctx);
-#if HAVE_COCOA
+#if HAVE_COCOA_APPLICATION
terminate_cocoa_application();
// never reach here:
// terminate calls exit itself, just silence compiler warning
@@ -403,15 +403,8 @@ int mp_initialize(struct MPContext *mpctx)
}
#endif
- if (opts->use_terminal) {
- if (mpctx->opts->slave_mode)
- terminal_setup_stdin_cmd_input(mpctx->input);
- else if (mpctx->opts->consolecontrols)
- terminal_setup_getch(mpctx->input);
-
- if (opts->consolecontrols)
- getch2_enable();
- }
+ if (opts->use_terminal && opts->consolecontrols)
+ terminal_setup_getch(mpctx->input);
#if HAVE_LIBASS
mpctx->ass_log = mp_log_new(mpctx, mpctx->global->log, "!libass");
@@ -428,7 +421,7 @@ int mp_initialize(struct MPContext *mpctx)
mp_get_resume_defaults(mpctx);
-#if HAVE_COCOA
+#if HAVE_COCOA_APPLICATION
if (mpctx->is_cplayer)
cocoa_set_input_context(mpctx->input);
#endif
@@ -491,8 +484,7 @@ int mpv_main(int argc, char *argv[])
mp_print_version(mpctx->log, false);
- if (!mp_parse_cfgfiles(mpctx))
- exit_player(mpctx, EXIT_ERROR);
+ mp_parse_cfgfiles(mpctx);
int r = m_config_parse_mp_command_line(mpctx->mconfig, mpctx->playlist,
mpctx->global, argc, argv);
diff --git a/player/main_fn.c b/player/main_fn.c
index 87e1681..23a047b 100644
--- a/player/main_fn.c
+++ b/player/main_fn.c
@@ -1,13 +1,13 @@
#include "config.h"
#include "core.h"
-#if HAVE_COCOA
+#if HAVE_COCOA_APPLICATION
#include "osdep/macosx_application.h"
#endif
int main(int argc, char *argv[])
{
-#if HAVE_COCOA
+#if HAVE_COCOA_APPLICATION
return cocoa_main(mpv_main, argc, argv);
#else
return mpv_main(argc, argv);
diff --git a/player/misc.c b/player/misc.c
index 6eae646..3ae4a8a 100644
--- a/player/misc.c
+++ b/player/misc.c
@@ -53,16 +53,21 @@ double get_relative_time(struct MPContext *mpctx)
double rel_time_to_abs(struct MPContext *mpctx, struct m_rel_time t)
{
double length = get_time_length(mpctx);
+ double start = get_start_time(mpctx);
switch (t.type) {
case REL_TIME_ABSOLUTE:
return t.pos;
- case REL_TIME_NEGATIVE:
- if (length != 0)
- return MPMAX(length - t.pos, 0.0);
+ case REL_TIME_RELATIVE:
+ if (t.pos >= 0) {
+ return start + t.pos;
+ } else {
+ if (length != 0)
+ return MPMAX(start + length + t.pos, 0.0);
+ }
break;
case REL_TIME_PERCENT:
if (length != 0)
- return length * (t.pos / 100.0);
+ return start + length * (t.pos / 100.0);
break;
case REL_TIME_CHAPTER:
if (chapter_start_time(mpctx, t.pos) != MP_NOPTS_VALUE)
@@ -95,8 +100,9 @@ double get_main_demux_pts(struct MPContext *mpctx)
double main_new_pos = MP_NOPTS_VALUE;
if (mpctx->demuxer) {
for (int n = 0; n < mpctx->demuxer->num_streams; n++) {
- if (main_new_pos == MP_NOPTS_VALUE)
- main_new_pos = demux_get_next_pts(mpctx->demuxer->streams[n]);
+ struct sh_stream *stream = mpctx->demuxer->streams[n];
+ if (main_new_pos == MP_NOPTS_VALUE && stream->type != STREAM_SUB)
+ main_new_pos = demux_get_next_pts(stream);
}
}
return main_new_pos;
@@ -104,25 +110,18 @@ double get_main_demux_pts(struct MPContext *mpctx)
double get_start_time(struct MPContext *mpctx)
{
- struct demuxer *demuxer = mpctx->demuxer;
- if (!demuxer)
- return 0;
- // We reload the demuxer on menu transitions; don't make it use the first
- // timestamp it finds as start PTS.
- if (mpctx->nav_state)
- return 0;
- return demuxer_get_start_time(demuxer);
+ return mpctx->demuxer ? mpctx->demuxer->start_time : 0;
}
-int mp_get_cache_percent(struct MPContext *mpctx)
+float mp_get_cache_percent(struct MPContext *mpctx)
{
- if (mpctx->stream) {
+ if (mpctx->demuxer) {
int64_t size = -1;
int64_t fill = -1;
- stream_control(mpctx->stream, STREAM_CTRL_GET_CACHE_SIZE, &size);
- stream_control(mpctx->stream, STREAM_CTRL_GET_CACHE_FILL, &fill);
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_SIZE, &size);
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_FILL, &fill);
if (size > 0 && fill >= 0)
- return fill / (size / 100);
+ return fill / (size / 100.0);
}
return -1;
}
@@ -130,8 +129,8 @@ int mp_get_cache_percent(struct MPContext *mpctx)
bool mp_get_cache_idle(struct MPContext *mpctx)
{
int idle = 0;
- if (mpctx->stream)
- stream_control(mpctx->stream, STREAM_CTRL_GET_CACHE_IDLE, &idle);
+ if (mpctx->demuxer)
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_IDLE, &idle);
return idle;
}
diff --git a/player/osd.c b/player/osd.c
index 32533ea..4efac8e 100644
--- a/player/osd.c
+++ b/player/osd.c
@@ -168,7 +168,9 @@ void print_status(struct MPContext *mpctx)
char *line = NULL;
// Playback status
- if (mpctx->paused_for_cache && !opts->pause) {
+ if (!mpctx->restart_complete && mp_time_sec() - mpctx->start_timestamp > 0.3) {
+ saddf(&line, "(...) ");
+ } else if (mpctx->paused_for_cache && !opts->pause) {
saddf(&line, "(Buffering) ");
} else if (mpctx->paused) {
saddf(&line, "(Paused) ");
@@ -181,8 +183,7 @@ void print_status(struct MPContext *mpctx)
saddf(&line, ": ");
// Playback position
- double cur = get_current_time(mpctx);
- sadd_hhmmssff(&line, cur, mpctx->opts->osd_fractions);
+ sadd_hhmmssff(&line, get_playback_time(mpctx), mpctx->opts->osd_fractions);
double len = get_time_length(mpctx);
if (len >= 0) {
@@ -222,9 +223,9 @@ void print_status(struct MPContext *mpctx)
saddf(&line, " Late: %d", mpctx->drop_frame_cnt);
}
- int cache = mp_get_cache_percent(mpctx);
+ float cache = mp_get_cache_percent(mpctx);
if (cache >= 0)
- saddf(&line, " Cache: %d%%", cache);
+ saddf(&line, " Cache: %.2f%%", cache);
if (opts->term_osd_bar) {
saddf(&line, "\n");
@@ -296,10 +297,15 @@ static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
double now = mp_time_sec();
double diff;
- if (mpctx->osd_visible && now >= mpctx->osd_visible) {
- mpctx->osd_visible = 0;
- mpctx->osd_progbar.type = -1; // disable
- osd_set_progbar(mpctx->osd, &mpctx->osd_progbar);
+ if (mpctx->osd_visible) {
+ double sleep = mpctx->osd_visible - now;
+ if (sleep > 0) {
+ mpctx->sleeptime = MPMIN(mpctx->sleeptime, sleep);
+ } else {
+ mpctx->osd_visible = 0;
+ mpctx->osd_progbar.type = -1; // disable
+ osd_set_progbar(mpctx->osd, &mpctx->osd_progbar);
+ }
}
if (mpctx->osd_function_visible && now >= mpctx->osd_function_visible) {
mpctx->osd_function_visible = 0;
@@ -315,19 +321,21 @@ static mp_osd_msg_t *get_osd_msg(struct MPContext *mpctx)
mp_osd_msg_t *msg = mpctx->osd_msg_stack;
if (msg) {
if (!msg->started || msg->time > diff) {
+ // display it
if (msg->started)
msg->time -= diff;
else
msg->started = 1;
- // display it
- return msg;
+ } else {
+ // kill the message
+ talloc_free(msg);
+ msg = NULL;
+ mpctx->osd_msg_stack = NULL;
}
- // kill the message
- talloc_free(msg);
- mpctx->osd_msg_stack = NULL;
}
- // Nothing found
- return NULL;
+ if (msg)
+ mpctx->sleeptime = MPMIN(mpctx->sleeptime, msg->time);
+ return msg;
}
// type: mp_osd_font_codepoints, ASCII, or OSD_BAR_*
@@ -341,6 +349,7 @@ void set_osd_bar(struct MPContext *mpctx, int type, const char* name,
if (mpctx->video_out && opts->term_osd != 1) {
mpctx->osd_visible = mp_time_sec() + opts->osd_duration / 1000.0;
+ mpctx->sleeptime = 0;
mpctx->osd_progbar.type = type;
mpctx->osd_progbar.value = (val - min) / (max - min);
mpctx->osd_progbar.num_stops = 0;
@@ -437,14 +446,11 @@ static void sadd_osd_status(char **buffer, struct MPContext *mpctx, bool full)
*buffer = talloc_strdup_append(*buffer, text);
talloc_free(text);
} else {
- sadd_hhmmssff(buffer, get_current_time(mpctx), fractions);
+ sadd_hhmmssff(buffer, get_playback_time(mpctx), fractions);
if (full) {
saddf(buffer, " / ");
sadd_hhmmssff(buffer, get_time_length(mpctx), fractions);
sadd_percentage(buffer, get_percent_pos(mpctx));
- int cache = mp_get_cache_percent(mpctx);
- if (cache >= 0)
- saddf(buffer, " Cache: %d%%", cache);
}
}
}
diff --git a/player/playloop.c b/player/playloop.c
index 96326da..361b928 100644
--- a/player/playloop.c
+++ b/player/playloop.c
@@ -49,35 +49,8 @@
#include "video/out/vo.h"
#include "core.h"
-#include "screenshot.h"
#include "command.h"
-#define WAKEUP_PERIOD 0.5
-
-static const char av_desync_help_text[] =
-"\n\n"
-" *************************************************\n"
-" **** Audio/Video desynchronisation detected! ****\n"
-" *************************************************\n\n"
-"This means either the audio or the video is played too slowly.\n"
-"Possible reasons, problems, workarounds:\n"
-"- Your system is simply too slow for this file.\n"
-" Transcode it to a lower bitrate file with tools like HandBrake.\n"
-"- Broken/buggy _audio_ driver.\n"
-" Experiment with different values for --autosync, 30 is a good start.\n"
-" If you have PulseAudio, try --ao=alsa .\n"
-"- Slow video output.\n"
-" Try a different --vo driver (--vo=help for a list) or try --framedrop!\n"
-"- Playing a video file with --vo=opengl with higher FPS than the monitor.\n"
-" This is due to vsync limiting the framerate.\n"
-"- Playing from a slow network source.\n"
-" Download the file instead.\n"
-"- Try to find out whether audio/video/subs are causing this by experimenting\n"
-" with --no-video, --no-audio, or --no-sub.\n"
-"- If you swiched audio or video tracks, try seeking to force synchronization.\n"
-"If none of this helps you, file a bug report.\n\n";
-
-
void pause_player(struct MPContext *mpctx)
{
mpctx->opts->pause = 1;
@@ -148,42 +121,22 @@ void add_step_frame(struct MPContext *mpctx, int dir)
}
}
-static void seek_reset(struct MPContext *mpctx, bool reset_ao, bool reset_ac)
+// Clear some playback-related fields on file loading or after seeks.
+void reset_playback_state(struct MPContext *mpctx)
{
- if (mpctx->d_video) {
- video_reset_decoding(mpctx->d_video);
- vo_seek_reset(mpctx->video_out);
- }
-
- if (mpctx->d_audio && reset_ac) {
- audio_reset_decoding(mpctx->d_audio);
- if (reset_ao)
- clear_audio_output_buffers(mpctx);
- }
+ reset_video_state(mpctx);
+ reset_audio_state(mpctx);
+ reset_subtitle_state(mpctx);
- reset_subtitles(mpctx, 0);
- reset_subtitles(mpctx, 1);
-
- mpctx->video_pts = MP_NOPTS_VALUE;
- mpctx->video_next_pts = MP_NOPTS_VALUE;
- mpctx->playing_last_frame = false;
- mpctx->last_frame_duration = 0;
- mpctx->delay = 0;
- mpctx->time_frame = 0;
- mpctx->restart_playback = true;
mpctx->hrseek_active = false;
mpctx->hrseek_framedrop = false;
- mpctx->total_avsync_change = 0;
- mpctx->drop_frame_cnt = 0;
- mpctx->dropped_frames = 0;
mpctx->playback_pts = MP_NOPTS_VALUE;
- mpctx->eof_reached = false;
+ mpctx->last_seek_pts = MP_NOPTS_VALUE;
+ mpctx->restart_complete = false;
#if HAVE_ENCODING
encode_lavc_discontinuity(mpctx->encode_lavc_ctx);
#endif
-
- mp_notify(mpctx, MPV_EVENT_SEEK, NULL);
}
// return -1 if seek failed (non-seekable stream?), 0 otherwise
@@ -213,8 +166,7 @@ static int mp_seek(MPContext *mpctx, struct seek_params seek,
if (hr_seek_very_exact)
hr_seek_offset = MPMAX(hr_seek_offset, 0.5); // arbitrary
- bool hr_seek = mpctx->demuxer->accurate_seek && opts->correct_pts;
- hr_seek &= seek.exact >= 0 && seek.type != MPSEEK_FACTOR;
+ bool hr_seek = opts->correct_pts && seek.exact >= 0;
hr_seek &= (opts->hr_seek == 0 && seek.type == MPSEEK_ABSOLUTE) ||
opts->hr_seek > 0 || seek.exact > 0;
if (seek.type == MPSEEK_FACTOR || seek.amount < 0 ||
@@ -227,19 +179,17 @@ static int mp_seek(MPContext *mpctx, struct seek_params seek,
seek.type = MPSEEK_ABSOLUTE;
}
}
- if ((mpctx->demuxer->accurate_seek || mpctx->timeline)
- && seek.type == MPSEEK_RELATIVE) {
+ int direction = 0;
+ if (seek.type == MPSEEK_RELATIVE) {
seek.type = MPSEEK_ABSOLUTE;
- seek.direction = seek.amount > 0 ? 1 : -1;
+ direction = seek.amount > 0 ? 1 : -1;
seek.amount += get_current_time(mpctx);
}
+ hr_seek &= seek.type == MPSEEK_ABSOLUTE; // otherwise, no target PTS known
- /* At least the liba52 decoder wants to read from the input stream
- * during initialization, so reinit must be done after the demux_seek()
- * call that clears possible stream EOF. */
- bool need_reset = false;
double demuxer_amount = seek.amount;
if (mpctx->timeline) {
+ bool need_reset = false;
demuxer_amount = timeline_set_from_time(mpctx, seek.amount,
&need_reset);
if (demuxer_amount == -1) {
@@ -252,11 +202,12 @@ static int mp_seek(MPContext *mpctx, struct seek_params seek,
}
return -1;
}
- }
- if (need_reset) {
- reinit_video_chain(mpctx);
- reinit_subs(mpctx, 0);
- reinit_subs(mpctx, 1);
+ if (need_reset) {
+ reinit_video_chain(mpctx);
+ reinit_audio_chain(mpctx);
+ reinit_subs(mpctx, 0);
+ reinit_subs(mpctx, 1);
+ }
}
int demuxer_style = 0;
@@ -268,23 +219,16 @@ static int mp_seek(MPContext *mpctx, struct seek_params seek,
demuxer_style |= SEEK_ABSOLUTE;
break;
}
- if (hr_seek || seek.direction < 0)
+ if (hr_seek || direction < 0)
demuxer_style |= SEEK_BACKWARD;
- else if (seek.direction > 0)
+ else if (direction > 0)
demuxer_style |= SEEK_FORWARD;
if (hr_seek || opts->mkv_subtitle_preroll)
demuxer_style |= SEEK_SUBPREROLL;
if (hr_seek)
demuxer_amount -= hr_seek_offset;
- int seekresult = demux_seek(mpctx->demuxer, demuxer_amount, demuxer_style);
- if (seekresult == 0) {
- if (need_reset) {
- reinit_audio_chain(mpctx);
- seek_reset(mpctx, !timeline_fallthrough, false);
- }
- return -1;
- }
+ demux_seek(mpctx->demuxer, demuxer_amount, demuxer_style);
// Seek external, extra files too:
for (int t = 0; t < mpctx->num_tracks; t++) {
@@ -300,11 +244,10 @@ static int mp_seek(MPContext *mpctx, struct seek_params seek,
}
}
- if (need_reset)
- reinit_audio_chain(mpctx);
- /* If we just reinitialized audio it doesn't need to be reset,
- * and resetting could lose audio some decoders produce during init. */
- seek_reset(mpctx, !timeline_fallthrough, !need_reset);
+ if (!timeline_fallthrough)
+ clear_audio_output_buffers(mpctx);
+
+ reset_playback_state(mpctx);
if (timeline_fallthrough) {
// Important if video reinit happens.
@@ -319,8 +262,7 @@ static int mp_seek(MPContext *mpctx, struct seek_params seek,
if (seek.type == MPSEEK_ABSOLUTE) {
mpctx->video_pts = seek.amount;
mpctx->last_seek_pts = seek.amount;
- } else
- mpctx->last_seek_pts = MP_NOPTS_VALUE;
+ }
// The hr_seek==false case is for skipping frames with PTS before the
// current timeline chapter start. It's not really known where the demuxer
@@ -336,6 +278,10 @@ static int mp_seek(MPContext *mpctx, struct seek_params seek,
}
mpctx->start_timestamp = mp_time_sec();
+ mpctx->sleeptime = 0;
+
+ mp_notify(mpctx, MPV_EVENT_SEEK, NULL);
+ mp_notify(mpctx, MPV_EVENT_TICK, NULL);
return 0;
}
@@ -381,10 +327,13 @@ void queue_seek(struct MPContext *mpctx, enum seek_type type, double amount,
void execute_queued_seek(struct MPContext *mpctx)
{
if (mpctx->seek.type) {
+ // Let explicitly imprecise seeks cancel precise seeks:
+ if (mpctx->hrseek_active && mpctx->seek.exact < 0)
+ mpctx->start_timestamp = -1e9;
/* If the user seeks continuously (keeps arrow key down)
* try to finish showing a frame from one location before doing
* another seek (which could lead to unchanging display). */
- if (!mpctx->seek.immediate && mpctx->restart_playback &&
+ if (!mpctx->seek.immediate && mpctx->video_status < STATUS_READY &&
mp_time_sec() - mpctx->start_timestamp < 0.3)
return;
mp_seek(mpctx, mpctx->seek, false);
@@ -417,8 +366,6 @@ double get_current_time(struct MPContext *mpctx)
struct demuxer *demuxer = mpctx->demuxer;
if (!demuxer)
return 0;
- if (demuxer->stream_pts != MP_NOPTS_VALUE)
- return demuxer->stream_pts;
if (mpctx->playback_pts != MP_NOPTS_VALUE)
return mpctx->playback_pts;
if (mpctx->last_seek_pts != MP_NOPTS_VALUE)
@@ -426,6 +373,13 @@ double get_current_time(struct MPContext *mpctx)
return 0;
}
+double get_playback_time(struct MPContext *mpctx)
+{
+ double cur = get_current_time(mpctx);
+ double start = get_start_time(mpctx);
+ return cur >= start ? cur - start : cur;
+}
+
// Return playback position in 0.0-1.0 ratio, or -1 if unknown.
double get_current_pos_ratio(struct MPContext *mpctx, bool use_range)
{
@@ -451,12 +405,10 @@ double get_current_pos_ratio(struct MPContext *mpctx, bool use_range)
if (len > 0 && !demuxer->ts_resets_possible) {
ans = MPCLAMP((pos - start) / len, 0, 1);
} else {
- struct stream *s = demuxer->stream;
int64_t size;
- if (stream_control(s, STREAM_CTRL_GET_SIZE, &size) > 0 && size > 0) {
- int64_t fpos =
- demuxer->filepos >= 0 ? demuxer->filepos : stream_tell(s);
- ans = MPCLAMP(fpos / (double)size, 0, 1);
+ if (demux_stream_control(demuxer, STREAM_CTRL_GET_SIZE, &size) > 0) {
+ if (size > 0 && demuxer->filepos >= 0)
+ ans = MPCLAMP(demuxer->filepos / (double)size, 0, 1);
}
}
if (use_range) {
@@ -480,7 +432,7 @@ int get_current_chapter(struct MPContext *mpctx)
return -2;
double current_pts = get_current_time(mpctx);
int i;
- for (i = 1; i < mpctx->num_chapters; i++)
+ for (i = 0; i < mpctx->num_chapters; i++)
if (current_pts < mpctx->chapters[i].start)
break;
return MPMAX(mpctx->last_chapter_seek, i - 1);
@@ -551,88 +503,34 @@ bool mp_seek_chapter(struct MPContext *mpctx, int chapter)
return true;
}
-static void update_avsync(struct MPContext *mpctx)
+static void handle_osd_redraw(struct MPContext *mpctx)
{
- if (!mpctx->d_audio || !mpctx->d_video)
+ if (!mpctx->video_out || !mpctx->video_out->config_ok)
return;
-
- double a_pos = playing_audio_pts(mpctx);
-
- mpctx->last_av_difference = a_pos - mpctx->video_pts + mpctx->audio_delay;
- if (mpctx->time_frame > 0)
- mpctx->last_av_difference +=
- mpctx->time_frame * mpctx->opts->playback_speed;
- if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
- mpctx->last_av_difference = MP_NOPTS_VALUE;
- if (mpctx->last_av_difference > 0.5 && mpctx->drop_frame_cnt > 50
- && !mpctx->drop_message_shown) {
- MP_WARN(mpctx, "%s", av_desync_help_text);
- mpctx->drop_message_shown = true;
+ // If we're playing normally, let OSD be redrawn naturally as part of
+ // video display.
+ if (!mpctx->paused) {
+ if (mpctx->sleeptime < 0.1 && mpctx->video_status == STATUS_PLAYING)
+ return;
}
-}
-
-/* Modify video timing to match the audio timeline. There are two main
- * reasons this is needed. First, video and audio can start from different
- * positions at beginning of file or after a seek (MPlayer starts both
- * immediately even if they have different pts). Second, the file can have
- * audio timestamps that are inconsistent with the duration of the audio
- * packets, for example two consecutive timestamp values differing by
- * one second but only a packet with enough samples for half a second
- * of playback between them.
- */
-static void adjust_sync(struct MPContext *mpctx, double frame_time)
-{
- struct MPOpts *opts = mpctx->opts;
-
- if (!mpctx->d_audio || mpctx->syncing_audio)
+ // Don't redraw immediately during a seek (makes it significantly slower).
+ if (mp_time_sec() - mpctx->start_timestamp < 0.1)
return;
-
- double a_pts = written_audio_pts(mpctx) - mpctx->delay;
- double v_pts = mpctx->video_next_pts;
- double av_delay = a_pts - v_pts;
- // Try to sync vo_flip() so it will *finish* at given time
- av_delay += mpctx->last_vo_flip_duration;
- av_delay += mpctx->audio_delay; // This much pts difference is desired
-
- double change = av_delay * 0.1;
- double max_change = opts->default_max_pts_correction >= 0 ?
- opts->default_max_pts_correction : frame_time * 0.1;
- if (change < -max_change)
- change = -max_change;
- else if (change > max_change)
- change = max_change;
- mpctx->delay += change;
- mpctx->total_avsync_change += change;
-}
-
-static bool handle_osd_redraw(struct MPContext *mpctx)
-{
- if (!mpctx->video_out || !mpctx->video_out->config_ok)
- return false;
bool want_redraw = vo_get_want_redraw(mpctx->video_out) |
osd_query_and_reset_want_redraw(mpctx->osd);
if (!want_redraw)
- return false;
+ return;
vo_redraw(mpctx->video_out);
- return true;
-}
-
-static void handle_metadata_update(struct MPContext *mpctx)
-{
- if (mp_time_sec() > mpctx->last_metadata_update + 2) {
- if (demux_info_update(mpctx->demuxer))
- mp_notify(mpctx, MPV_EVENT_METADATA_UPDATE, NULL);
- mpctx->last_metadata_update = mp_time_sec();
- }
+ mpctx->sleeptime = 0;
}
static void handle_pause_on_low_cache(struct MPContext *mpctx)
{
struct MPOpts *opts = mpctx->opts;
- if (!mpctx->stream)
+ if (!mpctx->demuxer)
return;
int64_t fill = -1;
- stream_control(mpctx->stream, STREAM_CTRL_GET_CACHE_FILL, &fill);
+ demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_FILL, &fill);
int cache_kb = fill > 0 ? (fill + 1023) / 1024 : -1;
bool idle = mp_get_cache_idle(mpctx);
if (mpctx->paused && mpctx->paused_for_cache) {
@@ -641,6 +539,7 @@ static void handle_pause_on_low_cache(struct MPContext *mpctx)
if (!opts->pause)
unpause_player(mpctx);
}
+ mpctx->sleeptime = MPMIN(mpctx->sleeptime, 0.2);
} else {
if (cache_kb >= 0 && cache_kb <= opts->stream_cache_pause && !idle &&
opts->stream_cache_pause < opts->stream_cache_unpause)
@@ -651,17 +550,30 @@ static void handle_pause_on_low_cache(struct MPContext *mpctx)
opts->pause = prev_paused_user;
}
}
+ // Also update cache properties.
+ if (cache_kb > 0 || mpctx->next_cache_update > 0) {
+ double now = mp_time_sec();
+ if (mpctx->next_cache_update <= now) {
+ mpctx->next_cache_update = cache_kb > 0 ? now + 0.25 : 0;
+ mp_notify(mpctx, MP_EVENT_CACHE_UPDATE, NULL);
+ }
+ if (mpctx->next_cache_update > 0) {
+ mpctx->sleeptime =
+ MPMIN(mpctx->sleeptime, mpctx->next_cache_update - now);
+ }
+ }
}
static void handle_heartbeat_cmd(struct MPContext *mpctx)
{
struct MPOpts *opts = mpctx->opts;
- if (opts->heartbeat_cmd && !mpctx->paused) {
+ if (opts->heartbeat_cmd && !mpctx->paused && mpctx->video_out) {
double now = mp_time_sec();
- if (now - mpctx->last_heartbeat > opts->heartbeat_interval) {
- mpctx->last_heartbeat = now;
+ if (mpctx->next_heartbeat <= now) {
+ mpctx->next_heartbeat = now + opts->heartbeat_interval;
system(opts->heartbeat_cmd);
}
+ mpctx->sleeptime = MPMIN(mpctx->sleeptime, mpctx->next_heartbeat - now);
}
}
@@ -674,17 +586,20 @@ static void handle_cursor_autohide(struct MPContext *mpctx)
return;
bool mouse_cursor_visible = mpctx->mouse_cursor_visible;
+ double now = mp_time_sec();
unsigned mouse_event_ts = mp_input_get_mouse_event_counter(mpctx->input);
if (mpctx->mouse_event_ts != mouse_event_ts) {
mpctx->mouse_event_ts = mouse_event_ts;
- mpctx->mouse_timer =
- mp_time_sec() + opts->cursor_autohide_delay / 1000.0;
+ mpctx->mouse_timer = now + opts->cursor_autohide_delay / 1000.0;
mouse_cursor_visible = true;
}
- if (mp_time_sec() >= mpctx->mouse_timer)
+ if (mpctx->mouse_timer > now) {
+ mpctx->sleeptime = MPMIN(mpctx->sleeptime, mpctx->mouse_timer - now);
+ } else {
mouse_cursor_visible = false;
+ }
if (opts->cursor_autohide_delay == -1)
mouse_cursor_visible = true;
@@ -757,8 +672,7 @@ static void handle_backstep(struct MPContext *mpctx)
double current_pts = mpctx->last_vo_pts;
mpctx->backstep_active = false;
- bool demuxer_ok = mpctx->demuxer && mpctx->demuxer->accurate_seek;
- if (demuxer_ok && mpctx->d_video && current_pts != MP_NOPTS_VALUE) {
+ if (mpctx->d_video && current_pts != MP_NOPTS_VALUE) {
double seek_pts = find_previous_pts(mpctx, current_pts);
if (seek_pts != MP_NOPTS_VALUE) {
queue_seek(mpctx, MPSEEK_ABSOLUTE, seek_pts, 2, true);
@@ -800,12 +714,20 @@ static void handle_backstep(struct MPContext *mpctx)
static void handle_sstep(struct MPContext *mpctx)
{
struct MPOpts *opts = mpctx->opts;
- if (opts->step_sec > 0 && !mpctx->stop_play && !mpctx->paused &&
- !mpctx->restart_playback)
- {
+ if (mpctx->stop_play || !mpctx->restart_complete)
+ return;
+
+ if (opts->step_sec > 0 && !mpctx->paused) {
set_osd_function(mpctx, OSD_FFW);
queue_seek(mpctx, MPSEEK_RELATIVE, opts->step_sec, 0, true);
}
+
+ if (mpctx->video_status >= STATUS_DRAINING) {
+ if (mpctx->max_frames >= 0)
+ mpctx->stop_play = PT_NEXT_ENTRY;
+ if (mpctx->step_frames > 0 && !mpctx->paused)
+ pause_player(mpctx);
+ }
}
static void handle_loop_file(struct MPContext *mpctx)
@@ -823,8 +745,8 @@ static void handle_keep_open(struct MPContext *mpctx)
if (opts->keep_open && mpctx->stop_play == AT_END_OF_FILE) {
mpctx->stop_play = KEEP_PLAYING;
mpctx->playback_pts = mpctx->last_vo_pts;
- mpctx->eof_reached = true;
- pause_player(mpctx);
+ if (!mpctx->opts->pause)
+ pause_player(mpctx);
}
}
@@ -873,34 +795,20 @@ void handle_force_window(struct MPContext *mpctx, bool reconfig)
}
}
-static double timing_sleep(struct MPContext *mpctx, double time_frame)
+// Potentially needed by some Lua scripts, which assume TICK always comes.
+static void handle_dummy_ticks(struct MPContext *mpctx)
{
- // assume kernel HZ=100 for softsleep, works with larger HZ but with
- // unnecessarily high CPU usage
- struct MPOpts *opts = mpctx->opts;
- double margin = opts->softsleep ? 0.011 : 0;
- while (time_frame > margin) {
- mp_sleep_us(1000000 * (time_frame - margin));
- time_frame -= get_relative_time(mpctx);
- }
- if (opts->softsleep) {
- if (time_frame < 0)
- MP_WARN(mpctx, "Warning! Softsleep underflow!\n");
- while (time_frame > 0)
- time_frame -= get_relative_time(mpctx); // burn the CPU
+ if (mpctx->video_status == STATUS_EOF || mpctx->paused) {
+ if (mp_time_sec() - mpctx->last_idle_tick > 0.5) {
+ mpctx->last_idle_tick = mp_time_sec();
+ mp_notify(mpctx, MPV_EVENT_TICK, NULL);
+ }
}
- return time_frame;
}
static double get_wakeup_period(struct MPContext *mpctx)
{
- /* Even if we can immediately wake up in response to most input events,
- * there are some timers which are not registered to the event loop
- * and need to be checked periodically (like automatic mouse cursor hiding).
- * OSD content updates behave similarly. Also some uncommon input devices
- * may not have proper FD event support.
- */
- double sleeptime = WAKEUP_PERIOD;
+ double sleeptime = 100.0; // infinite for all practical purposes
#if !HAVE_POSIX_SELECT
// No proper file descriptor event handling; keep waking up to poll input
@@ -917,13 +825,8 @@ static double get_wakeup_period(struct MPContext *mpctx)
void run_playloop(struct MPContext *mpctx)
{
struct MPOpts *opts = mpctx->opts;
- bool full_audio_buffers = false;
- bool audio_left = false, video_left = false;
double endpts = get_play_end_pts(mpctx);
- bool end_is_chapter = false;
- double sleeptime = get_wakeup_period(mpctx);
- bool was_restart = mpctx->restart_playback;
- bool new_frame_shown = false;
+ bool end_is_new_segment = false;
#if HAVE_ENCODING
if (encode_lavc_didfail(mpctx->encode_lavc_ctx)) {
@@ -932,15 +835,13 @@ void run_playloop(struct MPContext *mpctx)
}
#endif
- // Add tracks that were added by the demuxer later (e.g. MPEG)
- if (!mpctx->timeline && mpctx->demuxer)
- add_demuxer_tracks(mpctx, mpctx->demuxer);
+ update_demuxer_properties(mpctx);
if (mpctx->timeline) {
double end = mpctx->timeline[mpctx->timeline_part + 1].start;
if (endpts == MP_NOPTS_VALUE || end < endpts) {
+ end_is_new_segment = true;
endpts = end;
- end_is_chapter = true;
}
}
@@ -950,277 +851,72 @@ void run_playloop(struct MPContext *mpctx)
endpts = end;
}
- if (mpctx->d_audio && !mpctx->restart_playback && !ao_untimed(mpctx->ao)) {
- int status = fill_audio_out_buffers(mpctx, endpts);
- full_audio_buffers = status >= 0;
- // Not at audio stream EOF yet
- audio_left = status > -2;
- }
-
- if (mpctx->video_out) {
+ if (mpctx->video_out)
vo_check_events(mpctx->video_out);
- handle_cursor_autohide(mpctx);
- handle_heartbeat_cmd(mpctx);
- }
- while (mpctx->d_video) { // never loops, for "break;" only
- struct vo *vo = mpctx->video_out;
- update_fps(mpctx);
-
- // Whether there's still at least 1 video frame that can be shown.
- // If false, it means we can reconfig the VO if needed (normally, this
- // would disrupt playback, so only do it on !still_playing).
- bool still_playing = vo_has_next_frame(vo, true);
- // For the last frame case (frame is being displayed).
- still_playing |= mpctx->playing_last_frame;
- still_playing |= mpctx->last_frame_duration > 0;
-
- double frame_time = 0;
- int r = update_video(mpctx, endpts, !still_playing, &frame_time);
-
- MP_TRACE(mpctx, "update_video: %d\n", r);
- if (r < 0) {
- MP_FATAL(mpctx, "Could not initialize video chain.\n");
- int uninit = INITIALIZED_VCODEC;
- if (!opts->force_vo)
- uninit |= INITIALIZED_VO;
- uninit_player(mpctx, uninit);
- if (!mpctx->current_track[STREAM_AUDIO])
- mpctx->stop_play = PT_NEXT_ENTRY;
- mpctx->error_playing = true;
- handle_force_window(mpctx, true);
- break;
- }
+ handle_cursor_autohide(mpctx);
+ handle_heartbeat_cmd(mpctx);
- if (r == 0) {
- if (!mpctx->playing_last_frame && mpctx->last_frame_duration > 0) {
- mpctx->time_frame += mpctx->last_frame_duration;
- mpctx->last_frame_duration = 0;
- mpctx->playing_last_frame = true;
- MP_VERBOSE(mpctx, "showing last frame\n");
- }
- if (mpctx->playing_last_frame) {
- r = 1; // don't stop playback yet
- MP_TRACE(mpctx, "still showing last frame\n");
- }
- }
-
- video_left = r > 0;
-
- if (r == 2)
- MP_TRACE(mpctx, "frametime=%5.3f\n", frame_time);
+ fill_audio_out_buffers(mpctx, endpts);
+ write_video(mpctx, endpts);
- if (r == 2 && !mpctx->restart_playback) {
- mpctx->time_frame += frame_time / opts->playback_speed;
- adjust_sync(mpctx, frame_time);
- }
-
- if (!video_left) {
- mpctx->delay = 0;
- mpctx->last_av_difference = 0;
- }
-
- if (!video_left || (mpctx->paused && !mpctx->restart_playback)) {
- if (mpctx->paused)
- video_left |= vo->hasframe;
- break;
- }
-
- if (r != 2 && !mpctx->playing_last_frame) {
- sleeptime = 0;
- break;
- }
-
- mpctx->time_frame -= get_relative_time(mpctx);
- double audio_pts = playing_audio_pts(mpctx);
- if (!mpctx->sync_audio_to_video) {
- mpctx->time_frame = 0;
- } else if (full_audio_buffers && !mpctx->restart_playback) {
- double buffered_audio = ao_get_delay(mpctx->ao);
- MP_TRACE(mpctx, "audio delay=%f\n", buffered_audio);
-
- if (opts->autosync) {
- /* Smooth reported playback position from AO by averaging
- * it with the value expected based on previus value and
- * time elapsed since then. May help smooth video timing
- * with audio output that have inaccurate position reporting.
- * This is badly implemented; the behavior of the smoothing
- * now undesirably depends on how often this code runs
- * (mainly depends on video frame rate). */
- float predicted = (mpctx->delay / opts->playback_speed +
- mpctx->time_frame);
- float difference = buffered_audio - predicted;
- buffered_audio = predicted + difference / opts->autosync;
- }
-
- mpctx->time_frame = (buffered_audio -
- mpctx->delay / opts->playback_speed);
- } else {
- /* If we're more than 200 ms behind the right playback
- * position, don't try to speed up display of following
- * frames to catch up; continue with default speed from
- * the current frame instead.
- * If untimed is set always output frames immediately
- * without sleeping.
- */
- if (mpctx->time_frame < -0.2 || opts->untimed || vo->untimed)
- mpctx->time_frame = 0;
- }
-
- double vsleep = mpctx->time_frame - vo->flip_queue_offset;
- if (vsleep > 0.050) {
- sleeptime = MPMIN(sleeptime, vsleep - 0.040);
- break;
- }
- sleeptime = 0;
- mpctx->playing_last_frame = false;
-
- // last frame case (don't set video_left - consider format changes)
- if (r != 2)
- break;
-
- //=================== FLIP PAGE (VIDEO BLT): ======================
-
-
- mpctx->video_pts = mpctx->video_next_pts;
- mpctx->last_vo_pts = mpctx->video_pts;
- mpctx->playback_pts = mpctx->video_pts;
-
- update_subtitles(mpctx);
- update_osd_msg(mpctx);
-
- MP_STATS(mpctx, "vo draw frame");
-
- vo_new_frame_imminent(vo);
-
- MP_STATS(mpctx, "vo sleep");
-
- mpctx->time_frame -= get_relative_time(mpctx);
- mpctx->time_frame -= vo->flip_queue_offset;
- if (mpctx->time_frame > 0.001)
- mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
- mpctx->time_frame += vo->flip_queue_offset;
-
- int64_t t2 = mp_time_us();
- /* Playing with playback speed it's possible to get pathological
- * cases with mpctx->time_frame negative enough to cause an
- * overflow in pts_us calculation, thus the MPMAX. */
- double time_frame = MPMAX(mpctx->time_frame, -1);
- int64_t pts_us = mpctx->last_time + time_frame * 1e6;
- int duration = -1;
- double pts2 = vo_get_next_pts(vo, 0); // this is the next frame PTS
- if (mpctx->video_pts != MP_NOPTS_VALUE && pts2 == MP_NOPTS_VALUE) {
- // Make up a frame duration. Using the frame rate is not a good
- // choice, since the frame rate could be unset/broken/random.
- float fps = mpctx->d_video->fps;
- double frame_duration = fps > 0 ? 1.0 / fps : 0;
- pts2 = mpctx->video_pts + MPCLAMP(frame_duration, 0.0, 5.0);
- }
- if (pts2 != MP_NOPTS_VALUE) {
- // expected A/V sync correction is ignored
- double diff = (pts2 - mpctx->video_pts);
- diff /= opts->playback_speed;
- if (mpctx->time_frame < 0)
- diff += mpctx->time_frame;
- if (diff < 0)
- diff = 0;
- if (diff > 10)
- diff = 10;
- duration = diff * 1e6;
- mpctx->last_frame_duration = diff;
- }
- if (mpctx->restart_playback)
- duration = -1;
-
- MP_STATS(mpctx, "start flip");
- vo_flip_page(vo, pts_us | 1, duration);
- MP_STATS(mpctx, "end flip");
-
- if (audio_pts != MP_NOPTS_VALUE)
- MP_STATS(mpctx, "value %f ptsdiff", mpctx->video_pts - audio_pts);
-
- mpctx->last_vo_flip_duration = (mp_time_us() - t2) * 0.000001;
- if (vo->driver->flip_page_timed) {
- // No need to adjust sync based on flip speed
- mpctx->last_vo_flip_duration = 0;
- // For print_status - VO call finishing early is OK for sync
- mpctx->time_frame -= get_relative_time(mpctx);
- }
- mpctx->shown_vframes++;
- if (mpctx->restart_playback) {
- if (mpctx->sync_audio_to_video) {
- mpctx->syncing_audio = true;
- if (mpctx->d_audio)
- fill_audio_out_buffers(mpctx, endpts);
- mpctx->restart_playback = false;
- mp_notify(mpctx, MPV_EVENT_PLAYBACK_RESTART, NULL);
- }
- mpctx->time_frame = 0;
+ // We always make sure audio and video buffers are filled before actually
+ // starting playback. This code handles starting them at the same time.
+ if (mpctx->audio_status >= STATUS_READY &&
+ mpctx->video_status >= STATUS_READY)
+ {
+ if (mpctx->video_status == STATUS_READY) {
+ mpctx->video_status = STATUS_PLAYING;
get_relative_time(mpctx);
+ mpctx->sleeptime = 0;
}
- update_avsync(mpctx);
- screenshot_flip(mpctx);
- new_frame_shown = true;
-
- mp_notify(mpctx, MPV_EVENT_TICK, NULL);
-
- break;
- } // video
-
- if (!video_left || mpctx->paused) {
- if (mp_time_sec() - mpctx->last_idle_tick > 0.5) {
- mpctx->last_idle_tick = mp_time_sec();
- mp_notify(mpctx, MPV_EVENT_TICK, NULL);
+ if (mpctx->audio_status == STATUS_READY)
+ fill_audio_out_buffers(mpctx, endpts); // actually play prepared buffer
+ if (!mpctx->restart_complete) {
+ mpctx->hrseek_active = false;
+ mp_notify(mpctx, MPV_EVENT_PLAYBACK_RESTART, NULL);
+ mpctx->restart_complete = true;
+ if (opts->playing_msg && !mpctx->playing_msg_shown) {
+ mpctx->playing_msg_shown = true;
+ char *msg =
+ mp_property_expand_escaped_string(mpctx, opts->playing_msg);
+ MP_INFO(mpctx, "%s\n", msg);
+ talloc_free(msg);
+ }
}
}
- video_left &= mpctx->sync_audio_to_video; // force no-video semantics
-
- if (mpctx->d_audio && (mpctx->restart_playback ? !video_left :
- ao_untimed(mpctx->ao) && (mpctx->delay <= 0 ||
- !video_left)))
+ if (mpctx->video_status == STATUS_EOF &&
+ mpctx->audio_status >= STATUS_PLAYING)
{
- int status = fill_audio_out_buffers(mpctx, endpts);
- full_audio_buffers = status >= 0 && !ao_untimed(mpctx->ao);
- // Not at audio stream EOF yet
- audio_left = status > -2;
- }
- if (!video_left)
- mpctx->restart_playback = false;
-
- update_osd_msg(mpctx);
-
- if (!video_left && (!mpctx->paused || was_restart)) {
double a_pos = 0;
if (mpctx->d_audio)
a_pos = playing_audio_pts(mpctx);
mpctx->playback_pts = a_pos;
- if (was_restart)
- mp_notify(mpctx, MPV_EVENT_PLAYBACK_RESTART, NULL);
}
+ handle_dummy_ticks(mpctx);
+
+ update_osd_msg(mpctx);
update_subtitles(mpctx);
- /* It's possible for the user to simultaneously switch both audio
+ /* If we're paused, don't end playback yet. But if video is enabled, is EOF,
+ * and we don't have a video frame, then the user probably seeked outside
+ * of the video, and we want to quit. */
+ bool prevent_eof = mpctx->paused;
+ if (mpctx->d_video && mpctx->video_status == STATUS_EOF)
+ prevent_eof &= mpctx->video_out && mpctx->video_out->hasframe;
+ /* Handles terminating on end of playback (or switching to next segment).
+ *
+ * It's possible for the user to simultaneously switch both audio
* and video streams to "disabled" at runtime. Handle this by waiting
* rather than immediately stopping playback due to EOF.
- *
- * When all audio has been written to output driver, stay in the
- * main loop handling commands until it has been mostly consumed,
- * except in the gapless case, where the next file will be started
- * while audio from the current one still remains to be played.
- *
- * We want this check to trigger if we seeked to this position,
- * but not if we paused at it with audio possibly still buffered in
- * the AO. There's currently no working way to check buffered audio
- * inside AO while paused. Thus the "was_restart" check below, which
- * should trigger after seek only, when we know there's no audio
- * buffered.
*/
- if ((mpctx->d_audio || mpctx->d_video) && !audio_left && !video_left
- && (opts->gapless_audio || !mpctx->d_audio || ao_eof_reached(mpctx->ao))
- && (!mpctx->paused || was_restart)) {
- if (end_is_chapter) {
+ if ((mpctx->d_audio || mpctx->d_video) && !prevent_eof &&
+ mpctx->audio_status == STATUS_EOF &&
+ mpctx->video_status == STATUS_EOF)
+ {
+ if (end_is_new_segment) {
mp_seek(mpctx, (struct seek_params){
.type = MPSEEK_ABSOLUTE,
.amount = mpctx->timeline[mpctx->timeline_part+1].start
@@ -1231,52 +927,23 @@ void run_playloop(struct MPContext *mpctx)
mp_handle_nav(mpctx);
- if (!mpctx->stop_play && !mpctx->restart_playback) {
-
- // If no more video is available, one frame means one playloop iteration.
- // Otherwise, one frame means one video frame.
- if (!video_left)
- new_frame_shown = true;
+ handle_keep_open(mpctx);
- if (opts->playing_msg && !mpctx->playing_msg_shown && new_frame_shown) {
- mpctx->playing_msg_shown = true;
- char *msg =
- mp_property_expand_escaped_string(mpctx, opts->playing_msg);
- MP_INFO(mpctx, "%s\n", msg);
- talloc_free(msg);
- }
+ handle_sstep(mpctx);
- if (mpctx->max_frames >= 0) {
- if (new_frame_shown)
- mpctx->max_frames--;
- if (mpctx->max_frames <= 0)
- mpctx->stop_play = PT_NEXT_ENTRY;
- }
+ handle_loop_file(mpctx);
- if (mpctx->step_frames > 0 && !mpctx->paused) {
- if (new_frame_shown)
- mpctx->step_frames--;
- if (mpctx->step_frames == 0)
- pause_player(mpctx);
- }
+ if (mpctx->stop_play)
+ return;
- }
+ handle_osd_redraw(mpctx);
- if (!mpctx->stop_play) {
- if (mpctx->restart_playback)
- sleeptime = 0;
- if (sleeptime > 0) {
- if (handle_osd_redraw(mpctx))
- sleeptime = 0;
- }
- if (sleeptime > 0) {
- MP_STATS(mpctx, "start sleep");
- mp_input_get_cmd(mpctx->input, sleeptime * 1000, true);
- MP_STATS(mpctx, "end sleep");
- }
+ if (mpctx->sleeptime > 0) {
+ MP_STATS(mpctx, "start sleep");
+ mp_input_get_cmd(mpctx->input, mpctx->sleeptime * 1000, true);
+ MP_STATS(mpctx, "end sleep");
}
-
- handle_metadata_update(mpctx);
+ mpctx->sleeptime = get_wakeup_period(mpctx);
handle_pause_on_low_cache(mpctx);
@@ -1284,12 +951,6 @@ void run_playloop(struct MPContext *mpctx)
handle_backstep(mpctx);
- handle_sstep(mpctx);
-
- handle_loop_file(mpctx);
-
- handle_keep_open(mpctx);
-
handle_chapter_change(mpctx);
handle_force_window(mpctx, false);
@@ -1308,12 +969,14 @@ void idle_loop(struct MPContext *mpctx)
while (mpctx->opts->player_idle_mode && !mpctx->playlist->current
&& mpctx->stop_play != PT_QUIT)
{
- mpctx->eof_reached = true;
+ mpctx->video_status = STATUS_EOF;
+ mpctx->audio_status = STATUS_EOF;
if (need_reinit) {
mp_notify(mpctx, MPV_EVENT_IDLE, NULL);
handle_force_window(mpctx, true);
}
need_reinit = false;
+ handle_dummy_ticks(mpctx);
int uninit = INITIALIZED_AO;
if (!mpctx->opts->force_vo)
uninit |= INITIALIZED_VO;
@@ -1323,9 +986,9 @@ void idle_loop(struct MPContext *mpctx)
vo_check_events(mpctx->video_out);
update_osd_msg(mpctx);
handle_osd_redraw(mpctx);
- mp_cmd_t *cmd = mp_input_get_cmd(mpctx->input,
- get_wakeup_period(mpctx) * 1000,
+ mp_cmd_t *cmd = mp_input_get_cmd(mpctx->input, mpctx->sleeptime * 1000,
false);
+ mpctx->sleeptime = get_wakeup_period(mpctx);
if (cmd)
run_command(mpctx, cmd);
mp_cmd_free(cmd);
diff --git a/player/screenshot.c b/player/screenshot.c
index 30eceed..1ee58c2 100644
--- a/player/screenshot.c
+++ b/player/screenshot.c
@@ -199,7 +199,7 @@ static char *create_fname(struct MPContext *mpctx, char *template,
}
case 'p':
case 'P': {
- char *t = mp_format_time(get_current_time(mpctx), fmt == 'P');
+ char *t = mp_format_time(get_playback_time(mpctx), fmt == 'P');
append_filename(&res, t);
talloc_free(t);
break;
@@ -210,7 +210,7 @@ static char *create_fname(struct MPContext *mpctx, char *template,
goto error_exit;
template++;
char fmtstr[] = {'%', tfmt, '\0'};
- char *s = mp_format_time_fmt(fmtstr, get_current_time(mpctx));
+ char *s = mp_format_time_fmt(fmtstr, get_playback_time(mpctx));
if (!s)
goto error_exit;
append_filename(&res, s);
diff --git a/player/scripting.c b/player/scripting.c
index 7b3d408..0393427 100644
--- a/player/scripting.c
+++ b/player/scripting.c
@@ -16,6 +16,7 @@
*/
#include <string.h>
+#include <strings.h>
#include <sys/types.h>
#include <dirent.h>
#include <math.h>
@@ -167,11 +168,12 @@ void mp_load_scripts(struct MPContext *mpctx)
}
if (!mpctx->opts->auto_load_scripts)
return;
- // Load ~/.mpv/lua/*
+
+ // Load all lua scripts
void *tmp = talloc_new(NULL);
- char *script_path = mp_find_user_config_file(tmp, mpctx->global, "lua");
- if (script_path) {
- files = list_script_files(tmp, script_path);
+ char **luadir = mp_find_all_config_files(tmp, mpctx->global, "lua");
+ for (int i = 0; luadir && luadir[i]; i++) {
+ files = list_script_files(tmp, luadir[i]);
for (int n = 0; files && files[n]; n++)
mp_load_script(mpctx, files[n]);
}
diff --git a/player/sub.c b/player/sub.c
index e46438e..d6903c1 100644
--- a/player/sub.c
+++ b/player/sub.c
@@ -64,7 +64,7 @@ static bool is_interleaved(struct MPContext *mpctx, struct track *track)
(other->type == STREAM_VIDEO || other->type == STREAM_AUDIO))
return true;
}
- return false;
+ return track->demuxer == mpctx->demuxer;
}
void reset_subtitles(struct MPContext *mpctx, int order)
@@ -76,6 +76,12 @@ void reset_subtitles(struct MPContext *mpctx, int order)
osd_set_text(mpctx->osd, obj, NULL);
}
+void reset_subtitle_state(struct MPContext *mpctx)
+{
+ reset_subtitles(mpctx, 0);
+ reset_subtitles(mpctx, 1);
+}
+
static void update_subtitle(struct MPContext *mpctx, int order)
{
struct MPOpts *opts = mpctx->opts;
@@ -101,7 +107,12 @@ static void update_subtitle(struct MPContext *mpctx, int order)
struct osd_sub_state state;
osd_get_sub(mpctx->osd, obj, &state);
- state.video_offset = track->under_timeline ? mpctx->video_offset : 0;
+ state.video_offset = 0;
+ if (track->under_timeline) {
+ state.video_offset += mpctx->video_offset;
+ } else if (track->is_external) {
+ state.video_offset += get_start_time(mpctx);
+ };
osd_set_sub(mpctx->osd, obj, &state);
@@ -158,46 +169,6 @@ void update_subtitles(struct MPContext *mpctx)
update_subtitle(mpctx, 1);
}
-static void set_dvdsub_fake_extradata(struct dec_sub *dec_sub, struct stream *st,
- int width, int height)
-{
- if (!st)
- return;
-
- struct stream_dvd_info_req info;
- if (stream_control(st, STREAM_CTRL_GET_DVD_INFO, &info) < 0)
- return;
-
- struct mp_csp_params csp = MP_CSP_PARAMS_DEFAULTS;
- csp.int_bits_in = 8;
- csp.int_bits_out = 8;
- float cmatrix[3][4];
- mp_get_yuv2rgb_coeffs(&csp, cmatrix);
-
- if (width == 0 || height == 0) {
- width = 720;
- height = 480;
- }
-
- char *s = NULL;
- s = talloc_asprintf_append(s, "size: %dx%d\n", width, height);
- s = talloc_asprintf_append(s, "palette: ");
- for (int i = 0; i < 16; i++) {
- int color = info.palette[i];
- int c[3] = {(color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff};
- mp_map_int_color(cmatrix, 8, c);
- color = (c[2] << 16) | (c[1] << 8) | c[0];
-
- if (i != 0)
- s = talloc_asprintf_append(s, ", ");
- s = talloc_asprintf_append(s, "%06x", color);
- }
- s = talloc_asprintf_append(s, "\n");
-
- sub_set_extradata(dec_sub, s, strlen(s));
- talloc_free(s);
-}
-
static void reinit_subdec(struct MPContext *mpctx, struct track *track,
struct dec_sub *dec_sub)
{
@@ -210,7 +181,6 @@ static void reinit_subdec(struct MPContext *mpctx, struct track *track,
int h = sh_video ? sh_video->disp_h : 0;
float fps = sh_video ? sh_video->fps : 25;
- set_dvdsub_fake_extradata(dec_sub, track->demuxer->stream, w, h);
sub_set_video_res(dec_sub, w, h);
sub_set_video_fps(dec_sub, fps);
sub_set_ass_renderer(dec_sub, mpctx->ass_library, mpctx->ass_renderer);
@@ -234,10 +204,7 @@ void reinit_subs(struct MPContext *mpctx, int order)
assert(!(mpctx->initialized_flags & init_flag));
- struct sh_stream *sh = init_demux_stream(mpctx, track);
-
- // No track selected, or lazily added DVD track (will actually be created
- // on first sub packet)
+ struct sh_stream *sh = track ? track->stream : NULL;
if (!sh)
return;
diff --git a/player/timeline/tl_cue.c b/player/timeline/tl_cue.c
index 6731ab4..d5e8b08 100644
--- a/player/timeline/tl_cue.c
+++ b/player/timeline/tl_cue.c
@@ -20,7 +20,6 @@
#include <stdlib.h>
#include <stdbool.h>
#include <inttypes.h>
-#include <ctype.h>
#include "talloc.h"
diff --git a/player/timeline/tl_mpv_edl.c b/player/timeline/tl_mpv_edl.c
index aba9738..69cd4e9 100644
--- a/player/timeline/tl_mpv_edl.c
+++ b/player/timeline/tl_mpv_edl.c
@@ -19,7 +19,6 @@
#include <stdlib.h>
#include <stdbool.h>
#include <inttypes.h>
-#include <ctype.h>
#include <math.h>
#include "talloc.h"
@@ -204,7 +203,7 @@ static void resolve_timestamps(struct tl_part *part, struct demuxer *demuxer)
part->length = length;
}
if (!part->offset_set)
- part->offset = demuxer_get_start_time(demuxer);
+ part->offset = demuxer->start_time;
}
static void build_timeline(struct MPContext *mpctx, struct tl_parts *parts)
@@ -224,7 +223,7 @@ static void build_timeline(struct MPContext *mpctx, struct tl_parts *parts)
double len = source_get_length(source);
if (len > 0) {
- len += demuxer_get_start_time(source);
+ len += source->start_time;
} else {
MP_WARN(mpctx, "EDL: source file '%s' has unknown duration.\n",
part->filename);
diff --git a/player/video.c b/player/video.c
index c7d5cd8..5b2748c 100644
--- a/player/video.c
+++ b/player/video.c
@@ -32,6 +32,7 @@
#include "common/common.h"
#include "common/encode.h"
#include "options/m_property.h"
+#include "osdep/timer.h"
#include "audio/out/ao.h"
#include "demux/demux.h"
@@ -45,6 +46,39 @@
#include "core.h"
#include "command.h"
+#include "screenshot.h"
+
+enum {
+ // update_video() - code also uses: <0 error, 0 eof, >0 progress
+ VD_ERROR = -1,
+ VD_EOF = 0, // end of file - no new output
+ VD_PROGRESS = 1, // progress, but no output; repeat call with no waiting
+ VD_NEW_FRAME = 2, // the call produced a new frame
+ VD_WAIT = 3, // no EOF, but no output; wait until wakeup
+};
+
+static const char av_desync_help_text[] =
+"\n\n"
+" *************************************************\n"
+" **** Audio/Video desynchronisation detected! ****\n"
+" *************************************************\n\n"
+"This means either the audio or the video is played too slowly.\n"
+"Possible reasons, problems, workarounds:\n"
+"- Your system is simply too slow for this file.\n"
+" Transcode it to a lower bitrate file with tools like HandBrake.\n"
+"- Broken/buggy _audio_ driver.\n"
+" Experiment with different values for --autosync, 30 is a good start.\n"
+" If you have PulseAudio, try --ao=alsa .\n"
+"- Slow video output.\n"
+" Try a different --vo driver (--vo=help for a list) or try --framedrop!\n"
+"- Playing a video file with --vo=opengl with higher FPS than the monitor.\n"
+" This is due to vsync limiting the framerate.\n"
+"- Playing from a slow network source.\n"
+" Download the file instead.\n"
+"- Try to find out whether audio/video/subs are causing this by experimenting\n"
+" with --no-video, --no-audio, or --no-sub.\n"
+"- If you swiched audio or video tracks, try seeking to force synchronization.\n"
+"If none of this helps you, file a bug report.\n\n";
void update_fps(struct MPContext *mpctx)
{
@@ -93,6 +127,8 @@ static void filter_reconfig(struct MPContext *mpctx,
struct mp_image_params params = d_video->decoder_output;
+ mp_notify(mpctx, MPV_EVENT_VIDEO_RECONFIG, NULL);
+
set_allowed_vo_formats(d_video->vfilter, mpctx->video_out);
if (video_reconfig_filters(d_video, &params) < 0) {
@@ -137,7 +173,7 @@ static void recreate_video_filters(struct MPContext *mpctx)
vf_destroy(d_video->vfilter);
d_video->vfilter = vf_new(mpctx->global);
- d_video->vfilter->hwdec = &d_video->hwdec_info;
+ d_video->vfilter->hwdec = d_video->hwdec_info;
vf_append_filter_list(d_video->vfilter, opts->vf_settings);
@@ -168,13 +204,33 @@ int reinit_video_filters(struct MPContext *mpctx)
return d_video->vfilter->initialized;
}
+void reset_video_state(struct MPContext *mpctx)
+{
+ if (mpctx->d_video)
+ video_reset_decoding(mpctx->d_video);
+ if (mpctx->video_out)
+ vo_seek_reset(mpctx->video_out);
+
+ mpctx->delay = 0;
+ mpctx->time_frame = 0;
+ mpctx->video_next_pts = MP_NOPTS_VALUE;
+ mpctx->playing_last_frame = false;
+ mpctx->last_frame_duration = 0;
+ mpctx->total_avsync_change = 0;
+ mpctx->drop_frame_cnt = 0;
+ mpctx->dropped_frames = 0;
+ mpctx->drop_message_shown = 0;
+
+ mpctx->video_status = mpctx->d_video ? STATUS_SYNCING : STATUS_EOF;
+}
+
int reinit_video_chain(struct MPContext *mpctx)
{
struct MPOpts *opts = mpctx->opts;
assert(!(mpctx->initialized_flags & INITIALIZED_VCODEC));
assert(!mpctx->d_video);
struct track *track = mpctx->current_track[0][STREAM_VIDEO];
- struct sh_stream *sh = init_demux_stream(mpctx, track);
+ struct sh_stream *sh = track ? track->stream : NULL;
if (!sh)
goto no_video;
@@ -183,7 +239,6 @@ int reinit_video_chain(struct MPContext *mpctx)
sh->video->disp_w, sh->video->disp_h,
sh->video->fps);
- double ar = -1.0;
//================== Init VIDEO (codec & libvo) ==========================
if (!opts->fixed_vo || !(mpctx->initialized_flags & INITIALIZED_VO)) {
mpctx->video_out = init_best_video_out(mpctx->global, mpctx->input,
@@ -212,10 +267,6 @@ int reinit_video_chain(struct MPContext *mpctx)
vo_control(mpctx->video_out, VOCTRL_GET_HWDEC_INFO, &d_video->hwdec_info);
- if (stream_control(sh->demuxer->stream, STREAM_CTRL_GET_ASPECT_RATIO, &ar)
- != STREAM_UNSUPPORTED)
- d_video->stream_aspect = ar;
-
recreate_video_filters(mpctx);
if (!video_init_best_codec(d_video, opts->video_decoders))
@@ -228,17 +279,15 @@ int reinit_video_chain(struct MPContext *mpctx)
vo_control(mpctx->video_out, mpctx->paused ? VOCTRL_PAUSE
: VOCTRL_RESUME, NULL);
- mpctx->restart_playback = true;
mpctx->sync_audio_to_video = !sh->attached_picture;
- mpctx->delay = 0;
- mpctx->video_next_pts = MP_NOPTS_VALUE;
- mpctx->playing_last_frame = false;
- mpctx->last_frame_duration = 0;
mpctx->vo_pts_history_seek_ts++;
- vo_seek_reset(mpctx->video_out);
- reset_subtitles(mpctx, 0);
- reset_subtitles(mpctx, 1);
+ // If we switch on video again, ensure audio position matches up.
+ if (mpctx->d_audio)
+ mpctx->audio_status = STATUS_SYNCING;
+
+ reset_video_state(mpctx);
+ reset_subtitle_state(mpctx);
if (opts->force_fps) {
d_video->fps = opts->force_fps;
@@ -282,7 +331,7 @@ static int check_framedrop(struct MPContext *mpctx, double frame_time)
struct track *t_audio = mpctx->current_track[0][STREAM_AUDIO];
struct sh_stream *sh_audio = t_audio ? t_audio->stream : NULL;
// check for frame-drop:
- if (mpctx->d_audio && !ao_untimed(mpctx->ao) && sh_audio &&
+ if (mpctx->d_audio && mpctx->ao && !ao_untimed(mpctx->ao) && sh_audio &&
!demux_stream_eof(sh_audio))
{
float delay = opts->playback_speed * ao_get_delay(mpctx->ao);
@@ -293,7 +342,7 @@ static int check_framedrop(struct MPContext *mpctx, double frame_time)
// we should avoid dropping too many frames in sequence unless we
// are too late. and we allow 100ms A-V delay here:
if (d < -mpctx->dropped_frames * frame_time - 0.100 && !mpctx->paused
- && !mpctx->restart_playback) {
+ && mpctx->video_status == STATUS_PLAYING) {
mpctx->drop_frame_cnt++;
mpctx->dropped_frames++;
return mpctx->opts->frame_dropping;
@@ -304,7 +353,7 @@ static int check_framedrop(struct MPContext *mpctx, double frame_time)
}
// Read a packet, store decoded image into d_video->waiting_decoded_mpi
-// Return 0 if EOF was reached (though the decoder still can have frames buffered)
+// returns VD_* code
static int decode_image(struct MPContext *mpctx)
{
struct dec_video *d_video = mpctx->d_video;
@@ -312,10 +361,12 @@ static int decode_image(struct MPContext *mpctx)
if (d_video->header->attached_picture) {
d_video->waiting_decoded_mpi =
video_decode(d_video, d_video->header->attached_picture, 0);
- return 0;
+ return VD_EOF;
}
- struct demux_packet *pkt = demux_read_packet(d_video->header);
+ struct demux_packet *pkt;
+ if (demux_read_packet_async(d_video->header, &pkt) == 0)
+ return VD_WAIT;
if (pkt && pkt->pts != MP_NOPTS_VALUE)
pkt->pts += mpctx->video_offset;
if ((pkt && pkt->pts >= mpctx->hrseek_pts - .005) ||
@@ -324,14 +375,15 @@ static int decode_image(struct MPContext *mpctx)
{
mpctx->hrseek_framedrop = false;
}
- int framedrop_type = mpctx->hrseek_active && mpctx->hrseek_framedrop ?
- 1 : check_framedrop(mpctx, -1);
+ bool hrseek = mpctx->hrseek_active && mpctx->video_status == STATUS_SYNCING;
+ int framedrop_type = hrseek && mpctx->hrseek_framedrop ?
+ 2 : check_framedrop(mpctx, -1);
d_video->waiting_decoded_mpi =
video_decode(d_video, pkt, framedrop_type);
bool had_packet = !!pkt;
talloc_free(pkt);
- return had_packet;
+ return had_packet ? VD_PROGRESS : VD_EOF;
}
@@ -350,20 +402,20 @@ static void init_filter_params(struct MPContext *mpctx)
}
// Make sure at least 1 filtered image is available.
-// Returns: -1: error, 0: EOF, 1: ok or progress was made
-// A return value of 1 doesn't necessarily output a frame, but makes the promise
-// that calling this function again will eventually do something.
+// returns VD_* code
+// A return value of VD_PROGRESS doesn't necessarily output a frame, but makes
+// the promise that calling this function again will eventually do something.
static int video_decode_and_filter(struct MPContext *mpctx)
{
struct dec_video *d_video = mpctx->d_video;
struct vf_chain *vf = d_video->vfilter;
if (vf->initialized < 0)
- return -1;
+ return VD_ERROR;
// There is already a filtered frame available.
if (vf_output_frame(vf, false) > 0)
- return 1;
+ return VD_PROGRESS;
// Decoder output is different from filter input?
bool need_vf_reconfig = !vf->input_params.imgfmt || vf->initialized < 1 ||
@@ -373,36 +425,41 @@ static int video_decode_and_filter(struct MPContext *mpctx)
if (need_vf_reconfig && d_video->decoder_output.imgfmt) {
// Drain the filter chain.
if (vf_output_frame(vf, true) > 0)
- return 1;
+ return VD_PROGRESS;
// The filter chain is drained; execute the filter format change.
filter_reconfig(mpctx, false);
if (vf->initialized == 0)
- return 1; // hw decoding fallback; try again
+ return VD_PROGRESS; // hw decoding fallback; try again
if (vf->initialized < 1)
- return -1;
+ return VD_ERROR;
init_filter_params(mpctx);
- return 1;
+ return VD_PROGRESS;
}
// If something was decoded, and the filter chain is ready, filter it.
if (!need_vf_reconfig && d_video->waiting_decoded_mpi) {
vf_filter_frame(vf, d_video->waiting_decoded_mpi);
d_video->waiting_decoded_mpi = NULL;
- return 1;
+ return VD_PROGRESS;
}
if (!d_video->waiting_decoded_mpi) {
// Decode a new image, or at least feed the decoder a packet.
int r = decode_image(mpctx);
+ if (r == VD_WAIT)
+ return r;
if (d_video->waiting_decoded_mpi)
d_video->decoder_output = d_video->waiting_decoded_mpi->params;
- if (!d_video->waiting_decoded_mpi && r < 1)
- return 0; // true EOF
+ if (!d_video->waiting_decoded_mpi && (r == VD_EOF || r < 0)) {
+ if (vf_output_frame(vf, true) > 0)
+ return VD_PROGRESS;
+ return VD_EOF; // true EOF
+ }
}
// Image will be filtered on the next iteration.
- return 1;
+ return VD_PROGRESS;
}
static void init_vo(struct MPContext *mpctx)
@@ -425,11 +482,10 @@ static void init_vo(struct MPContext *mpctx)
}
// Fill the VO buffer with a newly filtered or decoded image.
-// Returns: -1: error, 0: EOF, 1: ok or progress was made
+// returns VD_* code
static int video_output_image(struct MPContext *mpctx, double endpts,
bool reconfig_ok)
{
- struct vf_chain *vf = mpctx->d_video->vfilter;
struct vo *vo = mpctx->video_out;
// Already enough video buffered in VO?
@@ -442,6 +498,7 @@ static int video_output_image(struct MPContext *mpctx, double endpts,
if (r < 0)
return r; // error
+ struct vf_chain *vf = mpctx->d_video->vfilter;
vf_output_frame(vf, false);
if (vf->output) {
double pts = vf->output->pts;
@@ -450,11 +507,13 @@ static int video_output_image(struct MPContext *mpctx, double endpts,
add_frame_pts(mpctx, pts);
bool drop = false;
- if (mpctx->hrseek_active && pts < mpctx->hrseek_pts - .005)
+ bool hrseek = mpctx->hrseek_active && mpctx->video_status == STATUS_SYNCING
+ && !mpctx->d_video->header->attached_picture;
+ if (hrseek && pts < mpctx->hrseek_pts - .005)
drop = true;
if (endpts != MP_NOPTS_VALUE && pts >= endpts) {
drop = true;
- r = 0; // EOF
+ r = VD_EOF;
}
if (drop) {
talloc_free(vf->output);
@@ -491,7 +550,7 @@ static int video_output_image(struct MPContext *mpctx, double endpts,
int vo_r = vo_reconfig(vo, &p, 0);
if (vo_r < 0) {
vf->initialized = -1;
- return -1;
+ return VD_ERROR;
}
init_vo(mpctx);
// Display the frame queued after this immediately.
@@ -503,42 +562,41 @@ static int video_output_image(struct MPContext *mpctx, double endpts,
struct mp_image *img = vf_read_output_frame(vf);
if (img) {
vo_queue_image(vo, img);
- return 1;
+ return VD_PROGRESS;
}
return r; // includes the true EOF case
}
-// returns: <0 on error, 0: eof, 1: progress, but no output, 2: new frame
-int update_video(struct MPContext *mpctx, double endpts, bool reconfig_ok,
- double *frame_duration)
+// returns VD_* code
+static int update_video(struct MPContext *mpctx, double endpts, bool reconfig_ok,
+ double *frame_duration)
{
struct vo *video_out = mpctx->video_out;
if (mpctx->d_video->header->attached_picture) {
if (video_out->hasframe)
- return 0;
+ return VD_EOF;
if (vo_has_next_frame(video_out, true))
- return 2;
+ return VD_NEW_FRAME;
}
int r = video_output_image(mpctx, endpts, reconfig_ok);
- if (r < 0)
+ if (r < 0 || r == VD_WAIT)
return r;
- // On EOF (r==0), we always drain the VO; otherwise we must ensure that
+ // On EOF, we always drain the VO; otherwise we must ensure that
// the VO will have enough frames buffered (matters especially for VO based
// frame dropping).
- if (!vo_has_next_frame(video_out, !r))
- return !!r;
+ if (!vo_has_next_frame(video_out, r == VD_EOF))
+ return r ? VD_PROGRESS : VD_EOF;
if (mpctx->d_video->header->attached_picture) {
mpctx->video_next_pts = MP_NOPTS_VALUE;
- return 2;
+ return VD_NEW_FRAME;
}
double pts = vo_get_next_pts(video_out, 0);
- mpctx->hrseek_active = false;
double last_pts = mpctx->video_next_pts;
if (last_pts == MP_NOPTS_VALUE)
last_pts = pts;
@@ -552,5 +610,305 @@ int update_video(struct MPContext *mpctx, double endpts, bool reconfig_ok,
if (mpctx->d_audio)
mpctx->delay -= frame_time;
*frame_duration = frame_time;
- return 2;
+ return VD_NEW_FRAME;
+}
+
+static double timing_sleep(struct MPContext *mpctx, double time_frame)
+{
+ // assume kernel HZ=100 for softsleep, works with larger HZ but with
+ // unnecessarily high CPU usage
+ struct MPOpts *opts = mpctx->opts;
+ double margin = opts->softsleep ? 0.011 : 0;
+ while (time_frame > margin) {
+ mp_sleep_us(1000000 * (time_frame - margin));
+ time_frame -= get_relative_time(mpctx);
+ }
+ if (opts->softsleep) {
+ if (time_frame < 0)
+ MP_WARN(mpctx, "Warning! Softsleep underflow!\n");
+ while (time_frame > 0)
+ time_frame -= get_relative_time(mpctx); // burn the CPU
+ }
+ return time_frame;
+}
+
+static void update_avsync(struct MPContext *mpctx)
+{
+ if (mpctx->audio_status != STATUS_PLAYING ||
+ mpctx->video_status != STATUS_PLAYING)
+ return;
+
+ double a_pos = playing_audio_pts(mpctx);
+
+ mpctx->last_av_difference = a_pos - mpctx->video_pts + mpctx->audio_delay;
+ if (mpctx->time_frame > 0)
+ mpctx->last_av_difference +=
+ mpctx->time_frame * mpctx->opts->playback_speed;
+ if (a_pos == MP_NOPTS_VALUE || mpctx->video_pts == MP_NOPTS_VALUE)
+ mpctx->last_av_difference = MP_NOPTS_VALUE;
+ if (mpctx->last_av_difference > 0.5 && mpctx->drop_frame_cnt > 50
+ && !mpctx->drop_message_shown) {
+ MP_WARN(mpctx, "%s", av_desync_help_text);
+ mpctx->drop_message_shown = true;
+ }
+}
+
+/* Modify video timing to match the audio timeline. There are two main
+ * reasons this is needed. First, video and audio can start from different
+ * positions at beginning of file or after a seek (MPlayer starts both
+ * immediately even if they have different pts). Second, the file can have
+ * audio timestamps that are inconsistent with the duration of the audio
+ * packets, for example two consecutive timestamp values differing by
+ * one second but only a packet with enough samples for half a second
+ * of playback between them.
+ */
+static void adjust_sync(struct MPContext *mpctx, double frame_time)
+{
+ struct MPOpts *opts = mpctx->opts;
+
+ if (mpctx->audio_status != STATUS_PLAYING)
+ return;
+
+ double a_pts = written_audio_pts(mpctx) - mpctx->delay;
+ double v_pts = mpctx->video_next_pts;
+ double av_delay = a_pts - v_pts;
+ // Try to sync vo_flip() so it will *finish* at given time
+ av_delay += mpctx->last_vo_flip_duration;
+ av_delay += mpctx->audio_delay; // This much pts difference is desired
+
+ double change = av_delay * 0.1;
+ double max_change = opts->default_max_pts_correction >= 0 ?
+ opts->default_max_pts_correction : frame_time * 0.1;
+ if (change < -max_change)
+ change = -max_change;
+ else if (change > max_change)
+ change = max_change;
+ mpctx->delay += change;
+ mpctx->total_avsync_change += change;
+}
+
+void write_video(struct MPContext *mpctx, double endpts)
+{
+ struct MPOpts *opts = mpctx->opts;
+ struct vo *vo = mpctx->video_out;
+
+ if (!mpctx->d_video)
+ return;
+
+ update_fps(mpctx);
+
+ // Whether there's still at least 1 video frame that can be shown.
+ // If false, it means we can reconfig the VO if needed (normally, this
+ // would disrupt playback, so only do it on !still_playing).
+ bool still_playing = vo_has_next_frame(vo, true);
+ // For the last frame case (frame is being displayed).
+ still_playing |= mpctx->playing_last_frame;
+ still_playing |= mpctx->last_frame_duration > 0;
+
+ double frame_time = 0;
+ int r = update_video(mpctx, endpts, !still_playing, &frame_time);
+ MP_TRACE(mpctx, "update_video: %d (still_playing=%d)\n", r, still_playing);
+
+ if (r == VD_WAIT) // Demuxer will wake us up for more packets to decode.
+ return;
+
+ if (r < 0) {
+ MP_FATAL(mpctx, "Could not initialize video chain.\n");
+ int uninit = INITIALIZED_VCODEC;
+ if (!opts->force_vo)
+ uninit |= INITIALIZED_VO;
+ uninit_player(mpctx, uninit);
+ if (!mpctx->current_track[STREAM_AUDIO])
+ mpctx->stop_play = PT_NEXT_ENTRY;
+ mpctx->error_playing = true;
+ handle_force_window(mpctx, true);
+ return; // restart loop
+ }
+
+ if (r == VD_EOF) {
+ if (!mpctx->playing_last_frame && mpctx->last_frame_duration > 0) {
+ mpctx->time_frame += mpctx->last_frame_duration;
+ mpctx->last_frame_duration = 0;
+ mpctx->playing_last_frame = true;
+ MP_VERBOSE(mpctx, "showing last frame\n");
+ }
+ }
+
+ if (r == VD_NEW_FRAME) {
+ MP_TRACE(mpctx, "frametime=%5.3f\n", frame_time);
+
+ if (mpctx->video_status > STATUS_PLAYING)
+ mpctx->video_status = STATUS_PLAYING;
+
+ if (mpctx->video_status >= STATUS_READY) {
+ mpctx->time_frame += frame_time / opts->playback_speed;
+ adjust_sync(mpctx, frame_time);
+ }
+ } else if (r == VD_EOF && mpctx->playing_last_frame) {
+ // Let video timing code continue displaying.
+ mpctx->video_status = STATUS_DRAINING;
+ MP_VERBOSE(mpctx, "still showing last frame\n");
+ } else if (r <= 0) {
+ // EOF or error
+ mpctx->delay = 0;
+ mpctx->last_av_difference = 0;
+ mpctx->video_status = STATUS_EOF;
+ MP_VERBOSE(mpctx, "video EOF\n");
+ return;
+ } else {
+ if (mpctx->video_status > STATUS_PLAYING)
+ mpctx->video_status = STATUS_PLAYING;
+
+ // Decode more in next iteration.
+ mpctx->sleeptime = 0;
+ MP_TRACE(mpctx, "filtering more video\n");
+ }
+
+ // Actual playback starts when both audio and video are ready.
+ if (mpctx->video_status == STATUS_READY)
+ return;
+
+ if (mpctx->paused && mpctx->video_status >= STATUS_READY)
+ return;
+
+ mpctx->time_frame -= get_relative_time(mpctx);
+ double audio_pts = playing_audio_pts(mpctx);
+ if (!mpctx->sync_audio_to_video || mpctx->video_status < STATUS_READY) {
+ mpctx->time_frame = 0;
+ } else if (mpctx->audio_status == STATUS_PLAYING &&
+ mpctx->video_status == STATUS_PLAYING &&
+ !ao_untimed(mpctx->ao))
+ {
+ double buffered_audio = ao_get_delay(mpctx->ao);
+ MP_TRACE(mpctx, "audio delay=%f\n", buffered_audio);
+
+ if (opts->autosync) {
+ /* Smooth reported playback position from AO by averaging
+ * it with the value expected based on previus value and
+ * time elapsed since then. May help smooth video timing
+ * with audio output that have inaccurate position reporting.
+ * This is badly implemented; the behavior of the smoothing
+ * now undesirably depends on how often this code runs
+ * (mainly depends on video frame rate). */
+ float predicted = (mpctx->delay / opts->playback_speed +
+ mpctx->time_frame);
+ float difference = buffered_audio - predicted;
+ buffered_audio = predicted + difference / opts->autosync;
+ }
+
+ mpctx->time_frame = (buffered_audio -
+ mpctx->delay / opts->playback_speed);
+ } else {
+ /* If we're more than 200 ms behind the right playback
+ * position, don't try to speed up display of following
+ * frames to catch up; continue with default speed from
+ * the current frame instead.
+ * If untimed is set always output frames immediately
+ * without sleeping.
+ */
+ if (mpctx->time_frame < -0.2 || opts->untimed || vo->untimed)
+ mpctx->time_frame = 0;
+ }
+
+ double vsleep = mpctx->time_frame - vo->flip_queue_offset;
+ if (vsleep > 0.050) {
+ mpctx->sleeptime = MPMIN(mpctx->sleeptime, vsleep - 0.040);
+ return;
+ }
+ mpctx->sleeptime = 0;
+ mpctx->playing_last_frame = false;
+
+ // last frame case
+ if (r != VD_NEW_FRAME)
+ return;
+
+ //=================== FLIP PAGE (VIDEO BLT): ======================
+
+
+ mpctx->video_pts = mpctx->video_next_pts;
+ mpctx->last_vo_pts = mpctx->video_pts;
+ mpctx->playback_pts = mpctx->video_pts;
+
+ update_subtitles(mpctx);
+ update_osd_msg(mpctx);
+
+ MP_STATS(mpctx, "vo draw frame");
+
+ vo_new_frame_imminent(vo);
+
+ MP_STATS(mpctx, "vo sleep");
+
+ mpctx->time_frame -= get_relative_time(mpctx);
+ mpctx->time_frame -= vo->flip_queue_offset;
+ if (mpctx->time_frame > 0.001)
+ mpctx->time_frame = timing_sleep(mpctx, mpctx->time_frame);
+ mpctx->time_frame += vo->flip_queue_offset;
+
+ int64_t t2 = mp_time_us();
+ /* Playing with playback speed it's possible to get pathological
+ * cases with mpctx->time_frame negative enough to cause an
+ * overflow in pts_us calculation, thus the MPMAX. */
+ double time_frame = MPMAX(mpctx->time_frame, -1);
+ int64_t pts_us = mpctx->last_time + time_frame * 1e6;
+ int duration = -1;
+ double pts2 = vo_get_next_pts(vo, 0); // this is the next frame PTS
+ if (mpctx->video_pts != MP_NOPTS_VALUE && pts2 == MP_NOPTS_VALUE) {
+ // Make up a frame duration. Using the frame rate is not a good
+ // choice, since the frame rate could be unset/broken/random.
+ float fps = mpctx->d_video->fps;
+ double frame_duration = fps > 0 ? 1.0 / fps : 0;
+ pts2 = mpctx->video_pts + MPCLAMP(frame_duration, 0.0, 5.0);
+ }
+ if (pts2 != MP_NOPTS_VALUE) {
+ // expected A/V sync correction is ignored
+ double diff = (pts2 - mpctx->video_pts);
+ diff /= opts->playback_speed;
+ if (mpctx->time_frame < 0)
+ diff += mpctx->time_frame;
+ if (diff < 0)
+ diff = 0;
+ if (diff > 10)
+ diff = 10;
+ duration = diff * 1e6;
+ mpctx->last_frame_duration = diff;
+ }
+ if (mpctx->video_status != STATUS_PLAYING)
+ duration = -1;
+
+ MP_STATS(mpctx, "start flip");
+ vo_flip_page(vo, pts_us | 1, duration);
+ MP_STATS(mpctx, "end flip");
+
+ if (audio_pts != MP_NOPTS_VALUE)
+ MP_STATS(mpctx, "value %f ptsdiff", mpctx->video_pts - audio_pts);
+
+ mpctx->last_vo_flip_duration = (mp_time_us() - t2) * 0.000001;
+ if (vo->driver->flip_page_timed) {
+ // No need to adjust sync based on flip speed
+ mpctx->last_vo_flip_duration = 0;
+ // For print_status - VO call finishing early is OK for sync
+ mpctx->time_frame -= get_relative_time(mpctx);
+ }
+ mpctx->shown_vframes++;
+ if (mpctx->video_status < STATUS_PLAYING)
+ mpctx->video_status = STATUS_READY;
+ update_avsync(mpctx);
+ screenshot_flip(mpctx);
+
+ mp_notify(mpctx, MPV_EVENT_TICK, NULL);
+
+ if (!mpctx->sync_audio_to_video)
+ mpctx->video_status = STATUS_EOF;
+
+ if (mpctx->video_status != STATUS_EOF) {
+ if (mpctx->step_frames > 0) {
+ mpctx->step_frames--;
+ if (!mpctx->step_frames && !opts->pause)
+ pause_player(mpctx);
+ }
+ if (mpctx->max_frames == 0)
+ mpctx->stop_play = PT_NEXT_ENTRY;
+ if (mpctx->max_frames > 0)
+ mpctx->max_frames--;
+ }
}
diff --git a/stream/cache.c b/stream/cache.c
index db05073..6bd729c 100644
--- a/stream/cache.c
+++ b/stream/cache.c
@@ -56,6 +56,7 @@
#include "osdep/threads.h"
#include "common/msg.h"
+#include "common/tags.h"
#include "options/options.h"
#include "stream.h"
@@ -75,7 +76,6 @@ struct priv {
int64_t buffer_size; // size of the allocated buffer memory
int64_t back_size; // keep back_size amount of old bytes for backward seek
int64_t seek_limit; // keep filling cache if distance is less that seek limit
- struct byte_meta *bm; // additional per-byte metadata
bool seekable; // underlying stream is seekable
struct mp_log *log;
@@ -109,25 +109,12 @@ struct priv {
// Cached STREAM_CTRLs
double stream_time_length;
- double stream_start_time;
int64_t stream_size;
- bool stream_manages_timeline;
- unsigned int stream_num_chapters;
- int stream_cache_idle;
- int stream_cache_fill;
- char **stream_metadata;
- char *disc_name;
-};
-
-// Store additional per-byte metadata. Since per-byte would be way too
-// inefficient, store it only for every BYTE_META_CHUNK_SIZE byte.
-struct byte_meta {
- float stream_pts;
+ struct mp_tags *stream_metadata;
+ double start_pts;
};
enum {
- BYTE_META_CHUNK_SIZE = 8 * 1024,
-
CACHE_INTERRUPTED = -1,
CACHE_CTRL_NONE = 0,
@@ -135,7 +122,7 @@ enum {
CACHE_CTRL_PING = -2,
// we should fill buffer only if space>=FILL_LIMIT
- FILL_LIMIT = FFMAX(16 * 1024, BYTE_META_CHUNK_SIZE * 2),
+ FILL_LIMIT = 16 * 1024,
};
static int64_t mp_clipi64(int64_t val, int64_t min, int64_t max)
@@ -180,6 +167,7 @@ static void cache_drop_contents(struct priv *s)
{
s->offset = s->min_filepos = s->max_filepos = s->read_filepos;
s->eof = false;
+ s->start_pts = MP_NOPTS_VALUE;
}
// Copy at most dst_size from the cache at the given absolute file position pos.
@@ -279,13 +267,12 @@ static bool cache_fill(struct priv *s)
len = stream_read_partial(s->stream, &s->buffer[pos], space);
pthread_mutex_lock(&s->mutex);
- double pts;
- if (stream_control(s->stream, STREAM_CTRL_GET_CURRENT_TIME, &pts) <= 0)
- pts = MP_NOPTS_VALUE;
- for (int64_t b_pos = pos; b_pos < pos + len + BYTE_META_CHUNK_SIZE;
- b_pos += BYTE_META_CHUNK_SIZE)
- {
- s->bm[b_pos / BYTE_META_CHUNK_SIZE] = (struct byte_meta){.stream_pts = pts};
+ // Do this after reading a block, because at least libdvdnav updates the
+ // stream position only after actually reading something after a seek.
+ if (s->start_pts == MP_NOPTS_VALUE) {
+ double pts;
+ if (stream_control(s->stream, STREAM_CTRL_GET_CURRENT_TIME, &pts) > 0)
+ s->start_pts = pts;
}
s->max_filepos += len;
@@ -312,11 +299,8 @@ static int resize_cache(struct priv *s, int64_t size)
int64_t buffer_size = MPMIN(MPMAX(size, min_size), max_size);
unsigned char *buffer = malloc(buffer_size);
- struct byte_meta *bm = calloc(buffer_size / BYTE_META_CHUNK_SIZE + 2,
- sizeof(struct byte_meta));
- if (!buffer || !bm) {
+ if (!buffer) {
free(buffer);
- free(bm);
return STREAM_ERROR;
}
@@ -347,12 +331,10 @@ static int resize_cache(struct priv *s, int64_t size)
}
free(s->buffer);
- free(s->bm);
s->buffer_size = buffer_size;
s->back_size = buffer_size / 2;
s->buffer = buffer;
- s->bm = bm;
s->idle = false;
s->eof = false;
@@ -361,39 +343,20 @@ static int resize_cache(struct priv *s, int64_t size)
if (s->seek_limit > s->buffer_size - FILL_LIMIT)
s->seek_limit = s->buffer_size - FILL_LIMIT;
- for (size_t n = 0; n < s->buffer_size / BYTE_META_CHUNK_SIZE + 2; n++)
- s->bm[n] = (struct byte_meta){.stream_pts = MP_NOPTS_VALUE};
-
return STREAM_OK;
}
static void update_cached_controls(struct priv *s)
{
- unsigned int ui;
int64_t i64;
double d;
- char **m;
- char *t;
+ struct mp_tags *tags;
s->stream_time_length = 0;
if (stream_control(s->stream, STREAM_CTRL_GET_TIME_LENGTH, &d) == STREAM_OK)
s->stream_time_length = d;
- s->stream_start_time = MP_NOPTS_VALUE;
- if (stream_control(s->stream, STREAM_CTRL_GET_START_TIME, &d) == STREAM_OK)
- s->stream_start_time = d;
- s->stream_manages_timeline = false;
- if (stream_control(s->stream, STREAM_CTRL_MANAGES_TIMELINE, NULL) == STREAM_OK)
- s->stream_manages_timeline = true;
- s->stream_num_chapters = 0;
- if (stream_control(s->stream, STREAM_CTRL_GET_NUM_CHAPTERS, &ui) == STREAM_OK)
- s->stream_num_chapters = ui;
- if (stream_control(s->stream, STREAM_CTRL_GET_METADATA, &m) == STREAM_OK) {
+ if (stream_control(s->stream, STREAM_CTRL_GET_METADATA, &tags) == STREAM_OK) {
talloc_free(s->stream_metadata);
- s->stream_metadata = talloc_steal(s, m);
- }
- if (stream_control(s->stream, STREAM_CTRL_GET_DISC_NAME, &t) == STREAM_OK)
- {
- talloc_free(s->disc_name);
- s->disc_name = talloc_steal(s, t);
+ s->stream_metadata = talloc_steal(s, tags);
}
s->stream_size = -1;
if (stream_control(s->stream, STREAM_CTRL_GET_SIZE, &i64) == STREAM_OK)
@@ -417,59 +380,26 @@ static int cache_get_cached_control(stream_t *cache, int cmd, void *arg)
case STREAM_CTRL_GET_TIME_LENGTH:
*(double *)arg = s->stream_time_length;
return s->stream_time_length ? STREAM_OK : STREAM_UNSUPPORTED;
- case STREAM_CTRL_GET_START_TIME:
- if (s->stream_start_time == MP_NOPTS_VALUE)
- return STREAM_UNSUPPORTED;
- *(double *)arg = s->stream_start_time;
- return STREAM_OK;
case STREAM_CTRL_GET_SIZE:
if (s->stream_size < 0)
return STREAM_UNSUPPORTED;
*(int64_t *)arg = s->stream_size;
return STREAM_OK;
- case STREAM_CTRL_MANAGES_TIMELINE:
- return s->stream_manages_timeline ? STREAM_OK : STREAM_UNSUPPORTED;
- case STREAM_CTRL_GET_NUM_CHAPTERS:
- *(unsigned int *)arg = s->stream_num_chapters;
- return STREAM_OK;
case STREAM_CTRL_GET_CURRENT_TIME: {
- if (s->read_filepos >= s->min_filepos &&
- s->read_filepos <= s->max_filepos &&
- s->min_filepos < s->max_filepos)
- {
- int64_t fpos = FFMIN(s->read_filepos, s->max_filepos - 1);
- int64_t pos = fpos - s->offset;
- if (pos < 0)
- pos += s->buffer_size;
- else if (pos >= s->buffer_size)
- pos -= s->buffer_size;
- double pts = s->bm[pos / BYTE_META_CHUNK_SIZE].stream_pts;
- *(double *)arg = pts;
- return pts == MP_NOPTS_VALUE ? STREAM_UNSUPPORTED : STREAM_OK;
- }
- return STREAM_UNSUPPORTED;
+ if (s->start_pts == MP_NOPTS_VALUE)
+ return STREAM_UNSUPPORTED;
+ *(double *)arg = s->start_pts;
+ return STREAM_OK;
}
case STREAM_CTRL_GET_METADATA: {
- if (s->stream_metadata && s->stream_metadata[0]) {
- char **m = talloc_new(NULL);
- int num_m = 0;
- for (int n = 0; s->stream_metadata[n]; n++) {
- char *t = talloc_strdup(m, s->stream_metadata[n]);
- MP_TARRAY_APPEND(NULL, m, num_m, t);
- }
- MP_TARRAY_APPEND(NULL, m, num_m, NULL);
- MP_TARRAY_APPEND(NULL, m, num_m, NULL);
- *(char ***)arg = m;
+ if (s->stream_metadata) {
+ ta_set_parent(s->stream_metadata, NULL);
+ *(struct mp_tags **)arg = s->stream_metadata;
+ s->stream_metadata = NULL;
return STREAM_OK;
}
return STREAM_UNSUPPORTED;
}
- case STREAM_CTRL_GET_DISC_NAME: {
- if (!s->disc_name)
- return STREAM_UNSUPPORTED;
- *(char **)arg = talloc_strdup(NULL, s->disc_name);
- return STREAM_OK;
- }
case STREAM_CTRL_RESUME_CACHE:
s->idle = s->eof = false;
pthread_cond_signal(&s->wakeup);
@@ -482,6 +412,7 @@ static bool control_needs_flush(int stream_ctrl)
{
switch (stream_ctrl) {
case STREAM_CTRL_SEEK_TO_TIME:
+ case STREAM_CTRL_AVSEEK:
case STREAM_CTRL_SET_ANGLE:
case STREAM_CTRL_SET_CURRENT_TITLE:
return true;
@@ -662,7 +593,6 @@ static void cache_uninit(stream_t *cache)
pthread_mutex_destroy(&s->mutex);
pthread_cond_destroy(&s->wakeup);
free(s->buffer);
- free(s->bm);
talloc_free(s);
}
@@ -677,6 +607,8 @@ int stream_cache_init(stream_t *cache, stream_t *stream,
struct priv *s = talloc_zero(NULL, struct priv);
s->log = cache->log;
+ cache_drop_contents(s);
+
s->seek_limit = opts->seek_min * 1024ULL;
if (resize_cache(s, opts->size * 1024ULL) != STREAM_OK) {
diff --git a/stream/cache_file.c b/stream/cache_file.c
index cd1d5ca..af315b3 100644
--- a/stream/cache_file.c
+++ b/stream/cache_file.c
@@ -17,6 +17,8 @@
#include <stdio.h>
#include <stdint.h>
+#include "osdep/io.h"
+
#include "common/common.h"
#include "common/msg.h"
diff --git a/stream/dvb_tune.c b/stream/dvb_tune.c
index 7065a77..056592b 100644
--- a/stream/dvb_tune.c
+++ b/stream/dvb_tune.c
@@ -25,7 +25,6 @@
#include <stdio.h>
#include <stdlib.h>
-#include <ctype.h>
#include <sys/ioctl.h>
#include <poll.h>
#include <unistd.h>
diff --git a/stream/dvbin.h b/stream/dvbin.h
index 1eb7174..e225e38 100644
--- a/stream/dvbin.h
+++ b/stream/dvbin.h
@@ -95,6 +95,7 @@ typedef struct dvb_params {
char *cfg_prog;
int cfg_card;
int cfg_timeout;
+ char *cfg_file;
} dvb_priv_t;
diff --git a/stream/stream.c b/stream/stream.c
index 69e2faf..d600088 100644
--- a/stream/stream.c
+++ b/stream/stream.c
@@ -970,7 +970,24 @@ struct bstr stream_read_complete(struct stream *s, void *talloc_ctx,
return (struct bstr){buf, total_read};
}
-bool stream_manages_timeline(struct stream *s)
+void stream_print_proto_list(struct mp_log *log)
{
- return stream_control(s, STREAM_CTRL_MANAGES_TIMELINE, NULL) == STREAM_OK;
+ int count = 0;
+
+ mp_info(log, "Protocols:\n\n");
+ for (int i = 0; stream_list[i]; i++) {
+ const stream_info_t *stream_info = stream_list[i];
+
+ if (!stream_info->protocols)
+ continue;
+
+ for (int j = 0; stream_info->protocols[j]; j++) {
+ if (*stream_info->protocols[j] == '\0')
+ continue;
+
+ mp_info(log, " %s://\n", stream_info->protocols[j]);
+ count++;
+ }
+ }
+ mp_info(log, "\nTotal: %d protocols\n", count);
}
diff --git a/stream/stream.h b/stream/stream.h
index 4f8ca6d..2cd3d9f 100644
--- a/stream/stream.h
+++ b/stream/stream.h
@@ -39,6 +39,7 @@ enum streamtype {
STREAMTYPE_MF,
STREAMTYPE_EDL,
STREAMTYPE_AVDEVICE,
+ STREAMTYPE_CDDA,
};
#define STREAM_BUFFER_SIZE 2048
@@ -80,9 +81,6 @@ enum stream_ctrl {
STREAM_CTRL_GET_CACHE_IDLE,
STREAM_CTRL_RESUME_CACHE,
STREAM_CTRL_RECONNECT,
- // DVD/Bluray, signal general support for GET_CURRENT_TIME etc.
- STREAM_CTRL_MANAGES_TIMELINE,
- STREAM_CTRL_GET_START_TIME,
STREAM_CTRL_GET_CHAPTER_TIME,
STREAM_CTRL_GET_DVD_INFO,
STREAM_CTRL_SET_CONTENTS,
@@ -103,6 +101,7 @@ enum stream_ctrl {
STREAM_CTRL_TV_LAST_CHAN,
STREAM_CTRL_DVB_SET_CHANNEL,
STREAM_CTRL_DVB_STEP_CHANNEL,
+ STREAM_CTRL_AVSEEK,
};
struct stream_lang_req {
@@ -122,6 +121,13 @@ struct stream_dvd_info_req {
#define TV_COLOR_SATURATION 3
#define TV_COLOR_CONTRAST 4
+// for STREAM_CTRL_AVSEEK
+struct stream_avseek {
+ int stream_index;
+ int64_t timestamp;
+ int flags;
+};
+
struct stream;
typedef struct stream_info_st {
const char *name;
@@ -243,12 +249,12 @@ stream_t *open_memory_stream(void *data, int len);
bool stream_check_interrupt(struct stream *s);
-bool stream_manages_timeline(stream_t *s);
-
void mp_url_unescape_inplace(char *buf);
char *mp_url_escape(void *talloc_ctx, const char *s, const char *ok);
// stream_file.c
char *mp_file_url_to_filename(void *talloc_ctx, bstr url);
+void stream_print_proto_list(struct mp_log *log);
+
#endif /* MPLAYER_STREAM_H */
diff --git a/stream/stream_bluray.c b/stream/stream_bluray.c
index fb3c6d7..686541b 100644
--- a/stream/stream_bluray.c
+++ b/stream/stream_bluray.c
@@ -580,12 +580,6 @@ static int bluray_stream_control(stream_t *s, int cmd, void *arg)
}
return STREAM_ERROR;
}
- case STREAM_CTRL_GET_START_TIME: {
- *((double *)arg) = 0;
- return STREAM_OK;
- }
- case STREAM_CTRL_MANAGES_TIMELINE:
- return STREAM_OK;
case STREAM_CTRL_GET_DISC_NAME: {
const struct meta_dl *meta = bd_get_meta(b->bd);
if (!meta || !meta->di_name || !meta->di_name[0])
@@ -801,6 +795,7 @@ static int bluray_stream_open(stream_t *s)
s->end_pos = bd_get_title_size(bd);
s->sector_size = BLURAY_SECTOR_SIZE;
s->priv = b;
+ s->demuxer = "+disc";
MP_VERBOSE(s, "Blu-ray successfully opened.\n");
diff --git a/stream/stream_cdda.c b/stream/stream_cdda.c
index 8ad7608..1a03c44 100644
--- a/stream/stream_cdda.c
+++ b/stream/stream_cdda.c
@@ -37,7 +37,8 @@
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
-#include <sys/types.h>
+
+#include "osdep/endian.h"
#include "talloc.h"
@@ -396,7 +397,8 @@ static int open_cdda(stream_t *st)
st->control = control;
st->close = close_cdda;
- st->demuxer = "rawaudio";
+ st->type = STREAMTYPE_CDDA;
+ st->demuxer = "+disc";
print_cdtext(st, 0);
diff --git a/stream/stream_dvb.c b/stream/stream_dvb.c
index 1462d56..573a923 100644
--- a/stream/stream_dvb.c
+++ b/stream/stream_dvb.c
@@ -34,7 +34,6 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
-#include <ctype.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <poll.h>
@@ -45,6 +44,7 @@ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include <libavutil/avstring.h>
#include "osdep/io.h"
+#include "misc/ctype.h"
#include "stream.h"
#include "options/m_config.h"
@@ -77,6 +77,7 @@ const struct m_sub_options stream_dvb_conf = {
OPT_STRING("prog", cfg_prog, 0),
OPT_INTRANGE("card", cfg_card, 0, 1, 4),
OPT_INTRANGE("timeout", cfg_timeout, 0, 1, 30),
+ OPT_STRING("file", cfg_file, 0),
{0}
},
.size = sizeof(struct dvb_params),
@@ -177,7 +178,7 @@ static dvb_channels_list *dvb_get_channels(struct mp_log *log, char *filename, i
{
fields = sscanf(&line[k], sat_conf,
&ptr->freq, &ptr->pol, &ptr->diseqc, &ptr->srate, vpid_str, apid_str);
- ptr->pol = toupper(ptr->pol);
+ ptr->pol = mp_toupper(ptr->pol);
ptr->freq *= 1000UL;
ptr->srate *= 1000UL;
ptr->tone = -1;
@@ -717,8 +718,9 @@ dvb_config_t *dvb_get_config(stream_t *stream)
{
struct mp_log *log = stream->log;
struct mpv_global *global = stream->global;
+ dvb_priv_t *priv = stream->priv;
int i, fd, type, size;
- char filename[30], *conf_file, *name;
+ char filename[30], *name;
dvb_channels_list *list;
dvb_card_config_t *cards = NULL, *tmp;
dvb_config_t *conf = NULL;
@@ -750,27 +752,28 @@ dvb_config_t *dvb_get_config(stream_t *stream)
}
void *talloc_ctx = talloc_new(NULL);
- conf_file = mp_find_user_config_file(talloc_ctx, global, "channels.conf");
- switch(type) {
+ char *conf_file = NULL;
+ if (priv->cfg_file && priv->cfg_file[0]) {
+ conf_file = priv->cfg_file;
+ } else {
+ switch(type) {
case TUNER_TER:
- conf_file = mp_find_user_config_file(talloc_ctx, global, "channels.conf.ter");
+ conf_file = mp_find_config_file(talloc_ctx, global, "channels.conf.ter");
break;
case TUNER_CBL:
- conf_file = mp_find_user_config_file(talloc_ctx, global, "channels.conf.cbl");
+ conf_file = mp_find_config_file(talloc_ctx, global, "channels.conf.cbl");
break;
case TUNER_SAT:
- conf_file = mp_find_user_config_file(talloc_ctx, global, "channels.conf.sat");
+ conf_file = mp_find_config_file(talloc_ctx, global, "channels.conf.sat");
break;
case TUNER_ATSC:
- conf_file = mp_find_user_config_file(talloc_ctx, global, "channels.conf.atsc");
+ conf_file = mp_find_config_file(talloc_ctx, global, "channels.conf.atsc");
break;
- }
-
- if(conf_file && (access(conf_file, F_OK | R_OK) != 0)) {
- conf_file = mp_find_user_config_file(talloc_ctx, global, "channels.conf");
-
- if(conf_file && (access(conf_file, F_OK | R_OK) != 0)) {
- conf_file = mp_find_global_config_file(talloc_ctx, global, "channels.conf");
+ }
+ if (conf_file) {
+ mp_verbose(log, "Ignoring other channels.conf files.\n");
+ } else {
+ conf_file = mp_find_config_file(talloc_ctx, global, "channels.conf");
}
}
diff --git a/stream/stream_dvd.c b/stream/stream_dvd.c
index 2195189..857d144 100644
--- a/stream/stream_dvd.c
+++ b/stream/stream_dvd.c
@@ -18,12 +18,12 @@
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
-#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <string.h>
+#include <strings.h>
#include <libgen.h>
#include <errno.h>
#include <stdint.h>
@@ -533,11 +533,6 @@ static int control(stream_t *stream,int cmd,void* arg)
*((double *)arg) = (double) mp_get_titleset_length(d->vts_file, d->tt_srpt, d->cur_title)/1000.0;
return 1;
}
- case STREAM_CTRL_GET_START_TIME:
- {
- *((double *)arg) = 0;
- return 1;
- }
case STREAM_CTRL_GET_NUM_TITLES:
{
*((unsigned int *)arg) = d->vmg_file->tt_srpt->nr_of_srpts;
@@ -620,8 +615,6 @@ static int control(stream_t *stream,int cmd,void* arg)
snprintf(req->name, sizeof(req->name), "%c%c", lang >> 8, lang);
return STREAM_OK;
}
- case STREAM_CTRL_MANAGES_TIMELINE:
- return STREAM_OK;
case STREAM_CTRL_GET_DVD_INFO:
{
struct stream_dvd_info_req *req = arg;
@@ -900,6 +893,8 @@ static int open_s(stream_t *stream)
// ... (unimplemented)
// return NULL;
stream->type = STREAMTYPE_DVD;
+ stream->demuxer = "+disc";
+ stream->lavf_type = "mpeg";
stream->sector_size = 2048;
stream->fill_buffer = fill_buffer;
stream->control = control;
diff --git a/stream/stream_dvdnav.c b/stream/stream_dvdnav.c
index 8772125..2d9658b 100644
--- a/stream/stream_dvdnav.c
+++ b/stream/stream_dvdnav.c
@@ -545,15 +545,18 @@ static int control(stream_t *stream, int cmd, void *arg)
return STREAM_OK;
}
case STREAM_CTRL_SEEK_TO_TIME: {
- int64_t tm = (int64_t) (*((double *)arg) * 90000);
+ double d = *(double *)arg;
+ int64_t tm = (int64_t)(d * 90000);
if (tm < 0)
tm = 0;
if (priv->duration && tm >= (priv->duration * 90))
tm = priv->duration * 90 - 1;
- MP_VERBOSE(stream, "seek to PTS %"PRId64"\n", tm);
+ MP_VERBOSE(stream, "seek to PTS %f (%"PRId64")\n", d, tm);
if (dvdnav_time_search(dvdnav, tm) != DVDNAV_STATUS_OK)
break;
stream_drop_buffers(stream);
+ d = dvdnav_get_current_time(dvdnav) / 90000.0f;
+ MP_VERBOSE(stream, "landed at: %f\n", d);
return STREAM_OK;
}
case STREAM_CTRL_GET_NUM_ANGLES: {
@@ -596,8 +599,6 @@ static int control(stream_t *stream, int cmd, void *arg)
snprintf(req->name, sizeof(req->name), "%c%c", lang >> 8, lang);
return STREAM_OK;
}
- case STREAM_CTRL_MANAGES_TIMELINE:
- return STREAM_OK;
case STREAM_CTRL_GET_DVD_INFO: {
struct stream_dvd_info_req *req = arg;
memset(req, 0, sizeof(*req));
@@ -732,7 +733,7 @@ static int open_s(stream_t *stream)
stream->control = control;
stream->close = stream_dvdnav_close;
stream->type = STREAMTYPE_DVD;
- stream->demuxer = "lavf";
+ stream->demuxer = "+disc";
stream->lavf_type = "mpeg";
stream->allow_caching = false;
diff --git a/stream/stream_lavf.c b/stream/stream_lavf.c
index 82aa4ab..c84945e 100644
--- a/stream/stream_lavf.c
+++ b/stream/stream_lavf.c
@@ -24,6 +24,8 @@
#include "options/options.h"
#include "options/path.h"
#include "common/msg.h"
+#include "common/tags.h"
+#include "common/av_common.h"
#include "stream.h"
#include "options/m_option.h"
@@ -32,8 +34,23 @@
#include "bstr/bstr.h"
#include "talloc.h"
+struct stream_lavf_params *stream_lavf_opts;
+
+#define OPT_BASE_STRUCT struct stream_lavf_params
+struct stream_lavf_params {
+ char **avopts;
+};
+
+const struct m_sub_options stream_lavf_conf = {
+ .opts = (const m_option_t[]) {
+ OPT_KEYVALUELIST("stream-lavf-o", avopts, 0),
+ {0}
+ },
+ .size = sizeof(struct stream_lavf_params),
+};
+
static int open_f(stream_t *stream);
-static char **read_icy(stream_t *stream);
+static struct mp_tags *read_icy(stream_t *stream);
static int fill_buffer(stream_t *s, char *buffer, int max_len)
{
@@ -84,8 +101,7 @@ static int control(stream_t *s, int cmd, void *arg)
AVIOContext *avio = s->priv;
if (!avio && cmd != STREAM_CTRL_RECONNECT)
return -1;
- int64_t size, ts;
- double pts;
+ int64_t size;
switch(cmd) {
case STREAM_CTRL_GET_SIZE:
size = avio_size(avio);
@@ -94,16 +110,16 @@ static int control(stream_t *s, int cmd, void *arg)
return 1;
}
break;
- case STREAM_CTRL_SEEK_TO_TIME:
- pts = *(double *)arg;
- ts = pts * AV_TIME_BASE;
- ts = avio_seek_time(avio, -1, ts, 0);
- if (ts >= 0)
+ case STREAM_CTRL_AVSEEK: {
+ struct stream_avseek *c = arg;
+ int64_t r = avio_seek_time(avio, c->stream_index, c->timestamp, c->flags);
+ if (r >= 0)
return 1;
break;
+ }
case STREAM_CTRL_GET_METADATA: {
- *(char ***)arg = read_icy(s);
- if (!*(char ***)arg)
+ *(struct mp_tags **)arg = read_icy(s);
+ if (!*(struct mp_tags **)arg)
break;
return 1;
}
@@ -198,6 +214,7 @@ static int open_f(stream_t *stream)
if (strlen(cust_headers))
av_dict_set(&dict, "headers", cust_headers, 0);
av_dict_set(&dict, "icy", "1", 0);
+ mp_set_avdict(&dict, opts->stream_lavf_opts->avopts);
AVIOInterruptCB cb = {
.callback = interrupt_cb,
@@ -212,11 +229,7 @@ static int open_f(stream_t *stream)
goto out;
}
- AVDictionaryEntry *t = NULL;
- while ((t = av_dict_get(dict, "", t, AV_DICT_IGNORE_SUFFIX))) {
- MP_VERBOSE(stream, "Could not set stream option %s=%s\n",
- t->key, t->value);
- }
+ mp_avdict_print_unset(stream->log, MSGL_V, dict);
if (avio->av_class) {
uint8_t *mt = NULL;
@@ -247,17 +260,7 @@ out:
return res;
}
-static void append_meta(char ***info, int *num_info, bstr name, bstr val)
-{
- if (name.len && val.len) {
- char *cname = talloc_asprintf(*info, "icy-%.*s", BSTR_P(name));
- char *cval = talloc_asprintf(*info, "%.*s", BSTR_P(val));
- MP_TARRAY_APPEND(NULL, *info, *num_info, cname);
- MP_TARRAY_APPEND(NULL, *info, *num_info, cval);
- }
-}
-
-static char **read_icy(stream_t *s)
+static struct mp_tags *read_icy(stream_t *s)
{
AVIOContext *avio = s->priv;
@@ -274,37 +277,38 @@ static char **read_icy(stream_t *s)
&icy_packet) < 0)
icy_packet = NULL;
- char **res = NULL;
+ // Send a metadata update only 1. on start, and 2. on a new metadata packet.
+ // To detect new packages, set the icy_metadata_packet to "-" once we've
+ // read it (a bit hacky, but works).
+ struct mp_tags *res = NULL;
if ((!icy_header || !icy_header[0]) && (!icy_packet || !icy_packet[0]))
goto done;
- res = talloc_new(NULL);
- int num_res = 0;
+ bstr packet = bstr0(icy_packet);
+ if (bstr_equals0(packet, "-"))
+ goto done;
+
+ res = talloc_zero(NULL, struct mp_tags);
+
bstr header = bstr0(icy_header);
while (header.len) {
bstr line = bstr_strip_linebreaks(bstr_getline(header, &header));
bstr name, val;
- if (bstr_split_tok(line, ": ", &name, &val)) {
- bstr_eatstart0(&name, "icy-");
- append_meta(&res, &num_res, name, val);
- }
+ if (bstr_split_tok(line, ": ", &name, &val))
+ mp_tags_set_bstr(res, name, val);
}
- bstr packet = bstr0(icy_packet);
bstr head = bstr0("StreamTitle='");
int i = bstr_find(packet, head);
if (i >= 0) {
packet = bstr_cut(packet, i + head.len);
int end = bstrchr(packet, '\'');
packet = bstr_splice(packet, 0, end);
- append_meta(&res, &num_res, bstr0("title"), packet);
+ mp_tags_set_bstr(res, bstr0("icy-title"), packet);
}
- if (res) {
- MP_TARRAY_APPEND(NULL, res, num_res, NULL);
- MP_TARRAY_APPEND(NULL, res, num_res, NULL);
- }
+ av_opt_set(avio, "icy_metadata_packet", "-", AV_OPT_SEARCH_CHILDREN);
done:
av_free(icy_header);
diff --git a/stream/stream_pvr.c b/stream/stream_pvr.c
index db35513..6fa0b93 100644
--- a/stream/stream_pvr.c
+++ b/stream/stream_pvr.c
@@ -30,7 +30,7 @@
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
-#include <ctype.h>
+#include <strings.h>
#include <sys/time.h>
#include <errno.h>
#include <sys/ioctl.h>
diff --git a/stream/tv.c b/stream/tv.c
index 17b1f9e..65260e0 100644
--- a/stream/tv.c
+++ b/stream/tv.c
@@ -29,7 +29,7 @@
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
-#include <ctype.h>
+#include <strings.h>
#include <sys/time.h>
#include <assert.h>
#include <libavutil/avstring.h>
@@ -38,14 +38,13 @@
#include "common/msg.h"
+#include "misc/ctype.h"
#include "options/m_option.h"
#include "options/m_config.h"
#include "options/options.h"
#include "stream.h"
-#include "demux/demux.h"
-#include "demux/stheader.h"
#include "audio/format.h"
#include "video/img_fourcc.h"
@@ -191,7 +190,7 @@ static int tv_set_freq_float(tvi_handle_t *tvh, float freq)
return tv_set_freq(tvh, freq/1000.0*16);
}
-static void tv_scan(tvi_handle_t *tvh)
+void tv_scan(tvi_handle_t *tvh)
{
unsigned int now;
struct CHANLIST cl;
@@ -281,63 +280,6 @@ static void tv_scan(tvi_handle_t *tvh)
}
}
-/* ================== DEMUX_TV ===================== */
-/*
- Return value:
- 0 = EOF(?) or no stream
- 1 = successfully read a packet
-*/
-/* fill demux->video and demux->audio */
-
-static int demux_tv_fill_buffer(demuxer_t *demux)
-{
- tvi_handle_t *tvh=(tvi_handle_t*)(demux->priv);
- demux_packet_t* dp;
- unsigned int len=0;
- struct sh_stream *want_audio = NULL, *want_video = NULL;
-
- for (int n = 0; n < demux->num_streams; n++) {
- struct sh_stream *sh = demux->streams[n];
- if (!demuxer_stream_has_packets_queued(demux, sh) &&
- demuxer_stream_is_selected(demux, sh))
- {
- if (sh->type == STREAM_AUDIO)
- want_audio = sh;
- if (sh->type == STREAM_VIDEO)
- want_video = sh;
- }
- }
-
- /* ================== ADD AUDIO PACKET =================== */
-
- if (want_audio && tvh->tv_param->audio &&
- tvh->functions->control(tvh->priv,
- TVI_CONTROL_IS_AUDIO, 0) == TVI_CONTROL_TRUE)
- {
- len = tvh->functions->get_audio_framesize(tvh->priv);
-
- dp=new_demux_packet(len);
- dp->keyframe = true;
- dp->pts=tvh->functions->grab_audio_frame(tvh->priv, dp->buffer,len);
- demuxer_add_packet(demux, want_audio, dp);
- }
-
- /* ================== ADD VIDEO PACKET =================== */
-
- if (want_video && tvh->functions->control(tvh->priv,
- TVI_CONTROL_IS_VIDEO, 0) == TVI_CONTROL_TRUE)
- {
- len = tvh->functions->get_video_framesize(tvh->priv);
- dp=new_demux_packet(len);
- dp->keyframe = true;
- dp->pts=tvh->functions->grab_video_frame(tvh->priv, dp->buffer, len);
- demuxer_add_packet(demux, want_video, dp);
- }
-
- if (tvh->tv_param->scan) tv_scan(tvh);
- return 1;
-}
-
static int norm_from_string(tvi_handle_t *tvh, char* norm)
{
const tvi_functions_t *funcs = tvh->functions;
@@ -492,7 +434,7 @@ static void set_norm_and_freq(tvi_handle_t *tvh, tv_channels_t *chan)
tv_set_freq_float(tvh, chan->freq);
}
-static int open_tv(tvi_handle_t *tvh)
+int open_tv(tvi_handle_t *tvh)
{
int i;
const tvi_functions_t *funcs = tvh->functions;
@@ -628,7 +570,7 @@ static int open_tv(tvi_handle_t *tvh)
int channel = 0;
if (tvh->tv_param->channel)
{
- if (isdigit(*tvh->tv_param->channel))
+ if (mp_isdigit(*tvh->tv_param->channel))
/* if tvh->tv_param->channel begins with a digit interpret it as a number */
channel = atoi(tvh->tv_param->channel);
else
@@ -717,7 +659,7 @@ done:
return 1;
}
-static tvi_handle_t *tv_begin(tv_param_t* tv_param, struct mp_log *log)
+tvi_handle_t *tv_begin(tv_param_t* tv_param, struct mp_log *log)
{
int i;
tvi_handle_t* h;
@@ -755,7 +697,7 @@ static tvi_handle_t *tv_begin(tv_param_t* tv_param, struct mp_log *log)
return NULL;
}
-static int tv_uninit(tvi_handle_t *tvh)
+int tv_uninit(tvi_handle_t *tvh)
{
int res;
if(!tvh) return 1;
@@ -768,173 +710,6 @@ static int tv_uninit(tvi_handle_t *tvh)
return res;
}
-static int demux_open_tv(demuxer_t *demuxer, enum demux_check check)
-{
- tvi_handle_t *tvh;
- sh_video_t *sh_video;
- sh_audio_t *sh_audio = NULL;
- const tvi_functions_t *funcs;
-
- if (check > DEMUX_CHECK_REQUEST || demuxer->stream->type != STREAMTYPE_TV)
- return -1;
-
- tv_param_t *params = m_sub_options_copy(demuxer, &tv_params_conf,
- demuxer->opts->tv_params);
- struct tv_stream_params *sparams = demuxer->stream->priv;
- if (sparams->channel && sparams->channel[0]) {
- talloc_free(params->channel);
- params->channel = talloc_strdup(NULL, sparams->channel);
- }
- if (sparams->input >= 0)
- params->input = sparams->input;
-
- assert(demuxer->priv==NULL);
- if(!(tvh=tv_begin(params, demuxer->log))) return -1;
- if (!tvh->functions->init(tvh->priv)) return -1;
-
- tvh->demuxer = demuxer;
-
- if (!open_tv(tvh)){
- tv_uninit(tvh);
- return -1;
- }
- funcs = tvh->functions;
- demuxer->priv=tvh;
-
- struct sh_stream *sh_v = new_sh_stream(demuxer, STREAM_VIDEO);
- sh_video = sh_v->video;
-
- /* get IMAGE FORMAT */
- int fourcc;
- funcs->control(tvh->priv, TVI_CONTROL_VID_GET_FORMAT, &fourcc);
- if (fourcc == MP_FOURCC_MJPEG) {
- sh_v->codec = "mjpeg";
- } else {
- sh_v->codec = "rawvideo";
- sh_v->format = fourcc;
- }
-
- /* set FPS and FRAMETIME */
-
- if(!sh_video->fps)
- {
- float tmp;
- if (funcs->control(tvh->priv, TVI_CONTROL_VID_GET_FPS, &tmp) != TVI_CONTROL_TRUE)
- sh_video->fps = 25.0f; /* on PAL */
- else sh_video->fps = tmp;
- }
-
- if (tvh->tv_param->fps != -1.0f)
- sh_video->fps = tvh->tv_param->fps;
-
- /* If playback only mode, go to immediate mode, fail silently */
- if(tvh->tv_param->immediate == 1)
- {
- funcs->control(tvh->priv, TVI_CONTROL_IMMEDIATE, 0);
- tvh->tv_param->audio = 0;
- }
-
- /* set width */
- funcs->control(tvh->priv, TVI_CONTROL_VID_GET_WIDTH, &sh_video->disp_w);
-
- /* set height */
- funcs->control(tvh->priv, TVI_CONTROL_VID_GET_HEIGHT, &sh_video->disp_h);
-
- demuxer->seekable = 0;
-
- /* here comes audio init */
- if (tvh->tv_param->audio && funcs->control(tvh->priv, TVI_CONTROL_IS_AUDIO, 0) == TVI_CONTROL_TRUE)
- {
- int audio_format;
-
- /* yeah, audio is present */
-
- funcs->control(tvh->priv, TVI_CONTROL_AUD_SET_SAMPLERATE,
- &tvh->tv_param->audiorate);
-
- if (funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_FORMAT, &audio_format) != TVI_CONTROL_TRUE)
- goto no_audio;
-
- switch(audio_format)
- {
- case AF_FORMAT_U8:
- case AF_FORMAT_S8:
- case AF_FORMAT_U16_LE:
- case AF_FORMAT_U16_BE:
- case AF_FORMAT_S16_LE:
- case AF_FORMAT_S16_BE:
- case AF_FORMAT_S32_LE:
- case AF_FORMAT_S32_BE:
- break;
- case AF_FORMAT_MPEG2:
- default:
- MP_ERR(tvh, "Audio type '%s' unsupported!\n",
- af_fmt_to_str(audio_format));
- goto no_audio;
- }
-
- struct sh_stream *sh_a = new_sh_stream(demuxer, STREAM_AUDIO);
- sh_audio = sh_a->audio;
-
- funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_SAMPLERATE,
- &sh_audio->samplerate);
- int nchannels = sh_audio->channels.num;
- funcs->control(tvh->priv, TVI_CONTROL_AUD_GET_CHANNELS,
- &nchannels);
- mp_chmap_from_channels(&sh_audio->channels, nchannels);
-
- sh_a->codec = "mp-pcm";
- sh_a->format = audio_format;
-
- int samplesize = af_fmt2bps(audio_format);
- int block_align = samplesize * sh_audio->channels.num;
- int bytes_per_second = sh_audio->samplerate * block_align;
-
- sh_audio->bitrate = bytes_per_second * 8;
-
- // emulate WF for win32 codecs:
- sh_audio->wf = talloc_zero(sh_audio, MP_WAVEFORMATEX);
- sh_audio->wf->wFormatTag = sh_a->format;
- sh_audio->wf->nChannels = sh_audio->channels.num;
- sh_audio->wf->wBitsPerSample = samplesize * 8;
- sh_audio->wf->nSamplesPerSec = sh_audio->samplerate;
- sh_audio->wf->nBlockAlign = block_align;
- sh_audio->wf->nAvgBytesPerSec = bytes_per_second;
-
- MP_VERBOSE(tvh, " TV audio: %d channels, %d bits, %d Hz\n",
- sh_audio->wf->nChannels, sh_audio->wf->wBitsPerSample,
- sh_audio->wf->nSamplesPerSec);
- }
-no_audio:
-
- if(!(funcs->start(tvh->priv))){
- // start failed :(
- tv_uninit(tvh);
- return -1;
- }
-
- /* set color eq */
- tv_set_color_options(tvh, TV_COLOR_BRIGHTNESS, tvh->tv_param->brightness);
- tv_set_color_options(tvh, TV_COLOR_HUE, tvh->tv_param->hue);
- tv_set_color_options(tvh, TV_COLOR_SATURATION, tvh->tv_param->saturation);
- tv_set_color_options(tvh, TV_COLOR_CONTRAST, tvh->tv_param->contrast);
-
- if(tvh->tv_param->gain!=-1)
- if(funcs->control(tvh->priv,TVI_CONTROL_VID_SET_GAIN,&tvh->tv_param->gain)!=TVI_CONTROL_TRUE)
- MP_WARN(tvh, "Unable to set gain control!\n");
-
- return 0;
-}
-
-static void demux_close_tv(demuxer_t *demuxer)
-{
- tvi_handle_t *tvh=(tvi_handle_t*)(demuxer->priv);
- if (!tvh) return;
- tv_uninit(tvh);
- free(tvh);
- demuxer->priv=NULL;
-}
-
int tv_set_color_options(tvi_handle_t *tvh, int opt, int value)
{
const tvi_functions_t *funcs = tvh->functions;
@@ -1171,7 +946,7 @@ int tv_step_norm(tvi_handle_t *tvh)
return 1;
}
-static int tv_stream_control(tvi_handle_t *tvh, int cmd, void *arg)
+int tv_stream_control(tvi_handle_t *tvh, int cmd, void *arg)
{
switch (cmd) {
case STREAM_CTRL_TV_SET_SCAN:
@@ -1214,23 +989,3 @@ static int tv_stream_control(tvi_handle_t *tvh, int cmd, void *arg)
}
return STREAM_UNSUPPORTED;
}
-
-static int demux_tv_control(demuxer_t *demuxer, int cmd, void *arg)
-{
- tvi_handle_t *tvh=(tvi_handle_t*)(demuxer->priv);
- if (cmd != DEMUXER_CTRL_STREAM_CTRL)
- return DEMUXER_CTRL_NOTIMPL;
- struct demux_ctrl_stream_ctrl *ctrl = arg;
- ctrl->res = tv_stream_control(tvh, ctrl->ctrl, ctrl->arg);
- return DEMUXER_CTRL_OK;
-}
-
-const demuxer_desc_t demuxer_desc_tv = {
- .name = "tv",
- .desc = "TV card demuxer",
- .type = DEMUXER_TYPE_TV,
- .fill_buffer = demux_tv_fill_buffer,
- .control = demux_tv_control,
- .open = demux_open_tv,
- .close = demux_close_tv,
-};
diff --git a/stream/tv.h b/stream/tv.h
index d6d75e8..0f9fa1d 100644
--- a/stream/tv.h
+++ b/stream/tv.h
@@ -231,4 +231,12 @@ void tv_free_handle(tvi_handle_t *h);
#define TV_NORM_PALN 6
#define TV_NORM_NTSCJP 7
+int tv_uninit(tvi_handle_t *tvh);
+void tv_scan(tvi_handle_t *tvh);
+int open_tv(tvi_handle_t *tvh);
+tvi_handle_t *tv_begin(tv_param_t* tv_param, struct mp_log *log);
+int tv_stream_control(tvi_handle_t *tvh, int cmd, void *arg);
+
+extern const struct m_sub_options tv_params_conf;
+
#endif /* MPLAYER_TV_H */
diff --git a/stream/tvi_v4l2.c b/stream/tvi_v4l2.c
index 96ddd63..13067b8 100644
--- a/stream/tvi_v4l2.c
+++ b/stream/tvi_v4l2.c
@@ -40,6 +40,7 @@ known issues:
#include <pthread.h>
#include <stdio.h>
#include <string.h>
+#include <strings.h>
#include <time.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
diff --git a/sub/ass_mp.c b/sub/ass_mp.c
index 0217260..f5da319 100644
--- a/sub/ass_mp.c
+++ b/sub/ass_mp.c
@@ -132,18 +132,14 @@ void mp_ass_configure(ASS_Renderer *priv, struct MPOpts *opts,
ass_set_margins(priv, dim->mt, dim->mb, dim->ml, dim->mr);
int set_use_margins = 0;
-#if LIBASS_VERSION >= 0x01010000
int set_sub_pos = 0;
-#endif
float set_line_spacing = 0;
float set_font_scale = 1;
int set_hinting = 0;
int set_force_override = 0;
if (opts->ass_style_override) {
set_use_margins = opts->ass_use_margins;
-#if LIBASS_VERSION >= 0x01010000
set_sub_pos = 100 - opts->sub_pos;
-#endif
set_line_spacing = opts->ass_line_spacing;
set_hinting = opts->ass_hinting;
set_force_override = opts->ass_style_override == 3;
@@ -177,7 +173,7 @@ void mp_ass_configure_fonts(ASS_Renderer *priv, struct osd_style_opts *opts,
struct mpv_global *global, struct mp_log *log)
{
void *tmp = talloc_new(NULL);
- char *default_font = mp_find_user_config_file(tmp, global, "subfont.ttf");
+ char *default_font = mp_find_config_file(tmp, global, "subfont.ttf");
char *config = mp_find_config_file(tmp, global, "fonts.conf");
if (default_font && !mp_path_exists(default_font))
@@ -249,7 +245,7 @@ static void message_callback(int level, const char *format, va_list va, void *ct
ASS_Library *mp_ass_init(struct mpv_global *global, struct mp_log *log)
{
- char *path = mp_find_user_config_file(NULL, global, "fonts");
+ char *path = mp_find_config_file(NULL, global, "fonts");
ASS_Library *priv = ass_library_init();
if (!priv)
abort();
diff --git a/sub/find_subfiles.c b/sub/find_subfiles.c
index a8d6348..b4132aa 100644
--- a/sub/find_subfiles.c
+++ b/sub/find_subfiles.c
@@ -1,16 +1,17 @@
#include <dirent.h>
#include <string.h>
+#include <strings.h>
#include <stdlib.h>
-#include <ctype.h>
#include <assert.h>
#include "osdep/io.h"
+#include "common/common.h"
#include "common/global.h"
#include "common/msg.h"
+#include "misc/ctype.h"
#include "options/options.h"
#include "options/path.h"
-#include "common/common.h"
#include "sub/find_subfiles.h"
static const char *const sub_exts[] = {"utf", "utf8", "utf-8", "idx", "sub", "srt",
@@ -75,7 +76,7 @@ static struct bstr guess_lang_from_filename(struct bstr name)
if (name.start[i] == ')' || name.start[i] == ']')
i--;
- while (i >= 0 && isalpha(name.start[i])) {
+ while (i >= 0 && mp_isalpha(name.start[i])) {
n++;
if (n > 3)
return (struct bstr){NULL, 0};
@@ -242,7 +243,7 @@ struct subfn *find_text_subtitles(struct mpv_global *global, const char *fname)
}
// Load subtitles in ~/.mpv/sub limiting sub fuzziness
- char *mp_subdir = mp_find_user_config_file(NULL, global, "sub/");
+ char *mp_subdir = mp_find_config_file(NULL, global, "sub/");
if (mp_subdir)
append_dir_subtitles(global, &slist, &n, bstr0(mp_subdir), fname, 1);
talloc_free(mp_subdir);
diff --git a/sub/sd_microdvd.c b/sub/sd_microdvd.c
index 6e6a9c3..5de9a18 100644
--- a/sub/sd_microdvd.c
+++ b/sub/sd_microdvd.c
@@ -24,7 +24,6 @@
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
-#include <ctype.h>
#include <libavutil/common.h>
#include "common/msg.h"
diff --git a/sub/sd_srt.c b/sub/sd_srt.c
index 733a27d..160f865 100644
--- a/sub/sd_srt.c
+++ b/sub/sd_srt.c
@@ -19,16 +19,17 @@
*/
#include <string.h>
+#include <strings.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
-#include <ctype.h>
-#include <libavutil/common.h>
+#include "common/common.h"
#include "common/msg.h"
#include "bstr/bstr.h"
+#include "misc/ctype.h"
#include "sd.h"
struct line {
@@ -259,7 +260,7 @@ static int read_attr(char **s, struct bstr *attr, struct bstr *val)
attr->start = *s;
attr->len = eq - *s;
for (int i = 0; i < attr->len; i++)
- if (!isalnum(attr->start[i]))
+ if (!mp_isalnum(attr->start[i]))
return -1;
val->start = eq + 1;
bool quoted = val->start[0] == '"';
@@ -290,7 +291,7 @@ static void convert_subrip(struct sd *sd, const char *orig,
while (*line && new_line.len < new_line.bufsize - 1) {
char *orig_line = line;
- for (int i = 0; i < FF_ARRAY_ELEMS(subrip_basic_tags); i++) {
+ for (int i = 0; i < MP_ARRAY_SIZE(subrip_basic_tags); i++) {
const struct tag_conv *tag = &subrip_basic_tags[i];
int from_len = strlen(tag->from);
if (strncmp(line, tag->from, from_len) == 0) {
@@ -331,7 +332,7 @@ static void convert_subrip(struct sd *sd, const char *orig,
}
}
} else if (strncmp(line, "<font ", 6) == 0
- && sp + 1 < FF_ARRAY_ELEMS(font_stack)) {
+ && sp + 1 < MP_ARRAY_SIZE(font_stack)) {
/* Opening font tag */
char *potential_font_tag_start = line;
int len_backup = new_line.len;
@@ -360,7 +361,7 @@ static void convert_subrip(struct sd *sd, const char *orig,
int found = 0;
// Try to lookup the string in standard web colors
- for (int i = 0; i < FF_ARRAY_ELEMS(subrip_web_colors); i++) {
+ for (int i = 0; i < MP_ARRAY_SIZE(subrip_web_colors); i++) {
char *color = subrip_web_colors[i].s;
if (bstrcasecmp(val, bstr0(color)) == 0) {
uint32_t xcolor = subrip_web_colors[i].v;
diff --git a/travis-deps b/travis-deps
index f43a78d..8df9147 100755
--- a/travis-deps
+++ b/travis-deps
@@ -2,26 +2,57 @@
class TravisDepsBuilder
def self.make(name)
- info = build_map[name]
- raise "unrecognized dependency identifier '#{name}'" unless info
- instance = new(name, info[:url], info[:action])
+ instance = klass.new(name)
+ instance.fill_data
instance.deps
instance.build
end
- attr_reader :name, :url, :action
+ def self.klass
+ Module.const_get([self.name, self.os.capitalize].join)
+ rescue NameError
+ self
+ end
+
+ def self.os
+ ENV['TRAVIS_OS_NAME']
+ end
+
+ attr_reader :name, :url, :action, :os
+
+ def initialize(name)
+ @name, @os = name, self.class.os
+ end
- def initialize(name, url=nil, action=nil)
- @name, @url, @action = name, url, action
+ def fill_data
+ data = build_map.fetch(name)
+ @url, @action = data[:url], data[:action]
end
def build
- send(@action)
+ send(action)
end
def deps; end
private
+ def package_manager_update
+ # yes class variable, you wanna update only once across all instances
+ @@updated ||= false
+ return if @@updated
+ sh({'linux' => 'sudo apt-get update -y', 'osx' => 'brew update'}[os])
+ @@updated = true
+ end
+
+ def package_install(*packages)
+ cmd = {
+ 'linux' => 'sudo apt-get install %s -y',
+ 'osx' => 'brew install %s'
+ }[os] % [packages.join(" ")]
+
+ sh cmd
+ end
+
def git
sh "git clone --depth=1 #{url} #{name}"
compile name
@@ -35,6 +66,10 @@ class TravisDepsBuilder
compile dirname
end
+ def package
+ package_install(url)
+ end
+
def compile(dirname)
sh "cd #{dirname} && #{configure} && make && sudo make install"
sh "cd $TRAVIS_BUILD_DIR"
@@ -50,7 +85,7 @@ class TravisDepsBuilder
end
class Libav < TravisDepsBuilder
- def self.build_map
+ def build_map
{
"libav-stable" => {
:action => :stable,
@@ -76,8 +111,16 @@ class Libav < TravisDepsBuilder
end
end
+class LibavOsx < Libav
+ def build_map
+ {
+ "ffmpeg-stable" => { :action => :package, :url => 'ffmpeg' },
+ }
+ end
+end
+
class Libass < TravisDepsBuilder
- def self.build_map
+ def build_map
{
"libass-stable" => {
:action => :stable,
@@ -89,8 +132,12 @@ end
class Dependencies < TravisDepsBuilder
def deps
- sh "sudo apt-get update -y"
- sh "sudo apt-get install pkg-config fontconfig libfribidi-dev yasm -y"
+ packages = {
+ 'linux' => 'pkg-config fontconfig libfribidi-dev yasm',
+ 'osx' => 'pkg-config fontconfig freetype fribidi yasm'
+ }
+ package_manager_update
+ package_install(packages.fetch(os))
end
end
diff --git a/video/csputils.c b/video/csputils.c
index c462c43..1cbaf47 100644
--- a/video/csputils.c
+++ b/video/csputils.c
@@ -305,6 +305,9 @@ struct mp_csp_primaries mp_get_csp_primaries(enum mp_csp_prim spc)
.blue = {0.150, 0.060},
.white = d65
};
+ // This is the default assumption if no colorspace information could
+ // be determined, eg. for files which have no video channel.
+ case MP_CSP_PRIM_AUTO:
case MP_CSP_PRIM_BT_709:
return (struct mp_csp_primaries) {
.red = {0.640, 0.330},
diff --git a/video/decode/dec_video.c b/video/decode/dec_video.c
index 807ce20..b700280 100644
--- a/video/decode/dec_video.c
+++ b/video/decode/dec_video.c
@@ -408,9 +408,6 @@ int video_reconfig_filters(struct dec_video *d_video,
}
float force_aspect = opts->movie_aspect;
- if (force_aspect > 0.0 && d_video->stream_aspect != 0.0)
- force_aspect = d_video->stream_aspect;
-
if (force_aspect >= 0.0)
vf_set_dar(&p.d_w, &p.d_h, p.w, p.h, force_aspect);
diff --git a/video/decode/dec_video.h b/video/decode/dec_video.h
index 9541cb3..5298a56 100644
--- a/video/decode/dec_video.h
+++ b/video/decode/dec_video.h
@@ -35,7 +35,7 @@ struct dec_video {
struct vf_chain *vfilter; // video filter chain
struct vo *vo; // (still) needed by video_set/get_colors
const struct vd_functions *vd_driver;
- struct mp_hwdec_info hwdec_info; // video output hwdec handles
+ struct mp_hwdec_info *hwdec_info; // video output hwdec handles
struct sh_stream *header;
char *decoder_desc;
@@ -72,7 +72,6 @@ struct dec_video {
// Final PTS of previously decoded image
double decoded_pts;
- float stream_aspect; // aspect ratio in media headers (DVD IFO files)
int bitrate; // compressed bits/sec
float fps; // FPS from demuxer or from user override
float initial_decoder_aspect;
diff --git a/video/decode/vaapi.c b/video/decode/vaapi.c
index 0e88b86..19395f6 100644
--- a/video/decode/vaapi.c
+++ b/video/decode/vaapi.c
@@ -129,7 +129,7 @@ static int find_entrypoint(int format, VAEntrypoint *ep, int num_ep)
static int is_direct_mapping(VADisplay display)
{
- VADisplayAttribute attr;
+ VADisplayAttribute attr = {0};
VAStatus status;
#if VA_CHECK_VERSION(0,34,0)
diff --git a/video/decode/vd_lavc.c b/video/decode/vd_lavc.c
index a59fffa..1cd4503 100644
--- a/video/decode/vd_lavc.c
+++ b/video/decode/vd_lavc.c
@@ -35,7 +35,6 @@
#include "common/msg.h"
#include "options/options.h"
#include "bstr/bstr.h"
-#include "common/av_opts.h"
#include "common/av_common.h"
#include "common/codecs.h"
@@ -76,10 +75,11 @@ struct vd_lavc_params {
int skip_loop_filter;
int skip_idct;
int skip_frame;
+ int framedrop;
int threads;
int bitexact;
int check_hw_profile;
- char *avopt;
+ char **avopts;
};
static const struct m_opt_choice_alternatives discard_names[] = {
@@ -102,10 +102,11 @@ const struct m_sub_options vd_lavc_conf = {
OPT_DISCARD("skiploopfilter", skip_loop_filter, 0),
OPT_DISCARD("skipidct", skip_idct, 0),
OPT_DISCARD("skipframe", skip_frame, 0),
+ OPT_DISCARD("framedrop", framedrop, 0),
OPT_INTRANGE("threads", threads, 0, 0, 16),
OPT_FLAG("bitexact", bitexact, 0),
OPT_FLAG("check-hw-profile", check_hw_profile, 0),
- OPT_STRING("o", avopt, 0),
+ OPT_KEYVALUELIST("o", avopts, 0),
{0}
},
.size = sizeof(struct vd_lavc_params),
@@ -115,6 +116,7 @@ const struct m_sub_options vd_lavc_conf = {
.skip_loop_filter = AVDISCARD_DEFAULT,
.skip_idct = AVDISCARD_DEFAULT,
.skip_frame = AVDISCARD_DEFAULT,
+ .framedrop = AVDISCARD_NONREF,
},
};
@@ -225,7 +227,7 @@ static struct vd_lavc_hwdec *probe_hwdec(struct dec_video *vd, bool autoprobe,
MP_VERBOSE(vd, "Requested hardware decoder not compiled.\n");
return NULL;
}
- int r = hwdec_probe(hwdec, &vd->hwdec_info, decoder);
+ int r = hwdec_probe(hwdec, vd->hwdec_info, decoder);
if (r == HWDEC_ERR_EMULATED) {
if (autoprobe)
return NULL;
@@ -340,7 +342,7 @@ static void init_avctx(struct dec_video *vd, const char *decoder,
if (!lavc_codec)
return;
- ctx->hwdec_info = &vd->hwdec_info;
+ ctx->hwdec_info = vd->hwdec_info;
ctx->pix_fmt = AV_PIX_FMT_NONE;
ctx->hwdec = hwdec;
@@ -383,14 +385,7 @@ static void init_avctx(struct dec_video *vd, const char *decoder,
avctx->skip_idct = lavc_param->skip_idct;
avctx->skip_frame = lavc_param->skip_frame;
- if (lavc_param->avopt) {
- if (parse_avopts(avctx, lavc_param->avopt) < 0) {
- MP_ERR(vd, "Your options /%s/ look like gibberish to me pal\n",
- lavc_param->avopt);
- uninit_avctx(vd);
- return;
- }
- }
+ mp_set_avopts(vd->log, avctx, lavc_param->avopts);
// Do this after the above avopt handling in case it changes values
ctx->skip_frame = avctx->skip_frame;
@@ -600,14 +595,16 @@ static int decode(struct dec_video *vd, struct demux_packet *packet,
int ret;
vd_ffmpeg_ctx *ctx = vd->priv;
AVCodecContext *avctx = ctx->avctx;
+ struct vd_lavc_params *lavc_param = ctx->opts->vd_lavc_params;
AVPacket pkt;
- if (flags & 2)
- avctx->skip_frame = AVDISCARD_ALL;
- else if (flags & 1)
- avctx->skip_frame = AVDISCARD_NONREF;
- else
+ if (flags) {
+ // hr-seek framedrop vs. normal framedrop
+ avctx->skip_frame = flags == 2 ? AVDISCARD_NONREF : lavc_param->framedrop;
+ } else {
+ // normal playback
avctx->skip_frame = ctx->skip_frame;
+ }
mp_set_av_packet(&pkt, packet, NULL);
diff --git a/video/decode/vda.c b/video/decode/vda.c
index acfadc7..6e54479 100644
--- a/video/decode/vda.c
+++ b/video/decode/vda.c
@@ -37,55 +37,22 @@ static int probe(struct vd_lavc_hwdec *hwdec, struct mp_hwdec_info *info,
return 0;
}
-#if HAVE_VDA_AV_VDA_ALLOC_CONTEXT
-
static int init(struct lavc_ctx *ctx)
{
return 0;
}
-static int init_decoder(struct lavc_ctx *ctx, int fmt, int w, int h)
-{
- av_vda_default_free(ctx->avctx);
-
- if (av_vda_default_init(ctx->avctx) < 0)
- return -1;
- return 0;
-}
-
-static void uninit(struct lavc_ctx *ctx)
-{
- if (ctx->avctx)
- av_vda_default_free(ctx->avctx);
-}
-
-const struct vd_lavc_hwdec mp_vd_lavc_vda = {
- .type = HWDEC_VDA,
- .image_format = IMGFMT_VDA,
- .probe = probe,
- .init = init,
- .uninit = uninit,
- .init_decoder = init_decoder,
-};
-
-#else
-struct priv {
- struct vda_context vda_ctx;
-};
-
struct vda_error {
int code;
char *reason;
};
static const struct vda_error vda_errors[] = {
- { kVDADecoderHardwareNotSupportedErr,
- "Hardware doesn't support accelerated decoding" },
- { kVDADecoderFormatNotSupportedErr,
- "Hardware doesn't support requested output format" },
- { kVDADecoderConfigurationError,
+ { AVERROR(ENOSYS),
+ "Hardware doesn't support accelerated decoding for this stream" },
+ { AVERROR(EINVAL),
"Invalid configuration provided to VDADecoderCreate" },
- { kVDADecoderDecoderFailedErr,
+ { AVERROR_INVALIDDATA,
"Generic error returned by the decoder layer. The cause can range from"
" VDADecoder finding errors in the bitstream to another application"
" using VDA at the moment. Only one application can use VDA at a"
@@ -106,117 +73,21 @@ static void print_vda_error(struct mp_log *log, int lev, char *message,
mp_msg(log, lev, "%s: %d\n", message, error_code);
}
-static int init_vda_decoder(struct lavc_ctx *ctx)
+static int init_decoder(struct lavc_ctx *ctx, int fmt, int w, int h)
{
- struct priv *p = ctx->hwdec_priv;
-
- if (p->vda_ctx.decoder)
- ff_vda_destroy_decoder(&p->vda_ctx);
-
- p->vda_ctx = (struct vda_context) {
- .width = ctx->avctx->width,
- .height = ctx->avctx->height,
- .format = 'avc1',
- // equals to k2vuyPixelFormat (= YUY2/UYVY)
- .cv_pix_fmt_type = kCVPixelFormatType_422YpCbCr8,
-
-#if HAVE_VDA_LIBAVCODEC_REFCOUNTING
- .use_ref_buffer = 1,
-#endif
- // use_ref_buffer is 1 in ffmpeg (while libav doesn't support this
- // feature). This means that in the libav case, libavcodec returns us
- // a CVPixelBuffer with refcount=1 AND hands over ownership of that
- // reference.
-
- // This is slightly different from a typical refcounted situation
- // where the API would return something that we need to to retain
- // for it to stay around (ffmpeg behaves like expected when using
- // use_ref_buffer = 1).
-
- // If mpv doesn't properly free CVPixelBufferRefs that are no longer
- // used, the wrapped IOSurface ids increase monotonically hinting at
- // a leaking of both CVPixelBuffers and IOSurfaces.
- };
-
- int status = ff_vda_create_decoder(
- &p->vda_ctx, ctx->avctx->extradata, ctx->avctx->extradata_size);
-
- if (status) {
- print_vda_error(ctx->log, MSGL_ERR, "failed to init VDA decoder", status);
+ av_vda_default_free(ctx->avctx);
+ int err = av_vda_default_init(ctx->avctx);
+ if (err < 0) {
+ print_vda_error(ctx->log, MSGL_ERR, "failed to init VDA decoder", err);
return -1;
}
-
- return 0;
-}
-
-static int init(struct lavc_ctx *ctx)
-{
- struct priv *p = talloc_zero(NULL, struct priv);
- ctx->hwdec_priv = p;
- ctx->avctx->hwaccel_context = &p->vda_ctx;
return 0;
}
-static void uninit(struct lavc_ctx *ctx) {
- struct priv *p = ctx->hwdec_priv;
- if (p->vda_ctx.decoder)
- ff_vda_destroy_decoder(&p->vda_ctx);
-}
-
-// This actually returns dummy images, since vda_264 creates it's own AVFrames
-// to wrap CVPixelBuffers in planes[3].
-static struct mp_image *allocate_image(struct lavc_ctx *ctx, int fmt,
- int w, int h)
-{
- struct priv *p = ctx->hwdec_priv;
-
- if (fmt != IMGFMT_VDA)
- return NULL;
-
- if (w != p->vda_ctx.width || h != p->vda_ctx.height)
- init_vda_decoder(ctx);
-
- struct mp_image img = {0};
- mp_image_setfmt(&img, fmt);
- mp_image_set_size(&img, w, h);
-
- // There is an `assert(!dst->f.buf[0])` in libavcodec/h264.c
- // Setting the first plane to some dummy value allows to satisfy it
- img.planes[0] = (void*)"dummy";
-
- return mp_image_new_custom_ref(&img, NULL, NULL);
-}
-
-static void cv_retain(void *pbuf)
-{
- CVPixelBufferRetain((CVPixelBufferRef)pbuf);
-}
-
-static void cv_release(void *pbuf)
-{
- CVPixelBufferRelease((CVPixelBufferRef)pbuf);
-}
-
-static struct mp_image *mp_image_new_cv_ref(struct mp_image *mpi)
-{
- CVPixelBufferRef pbuf = (CVPixelBufferRef)mpi->planes[3];
- // mp_image_new_external_ref assumes the external reference count is
- // already 1 so the calls to cv_retain and cv_release are unbalanced (
- // in favor of cv_release). To balance out the retain count we need to
- // retain the CVPixelBufferRef if ffmpeg is set to automatically release
- // it when the AVFrame is unreffed.
-#if HAVE_VDA_LIBAVCODEC_REFCOUNTING
- cv_retain(pbuf);
-#endif
- return mp_image_new_external_ref(mpi,
- pbuf, cv_retain, cv_release, NULL, NULL);
-}
-
-static struct mp_image *process_image(struct lavc_ctx *ctx, struct mp_image *mpi)
+static void uninit(struct lavc_ctx *ctx)
{
- struct mp_image *cv_mpi = mp_image_new_cv_ref(mpi);
- mp_image_unrefp(&mpi);
- return cv_mpi;
+ if (ctx->avctx)
+ av_vda_default_free(ctx->avctx);
}
const struct vd_lavc_hwdec mp_vd_lavc_vda = {
@@ -225,8 +96,5 @@ const struct vd_lavc_hwdec mp_vd_lavc_vda = {
.probe = probe,
.init = init,
.uninit = uninit,
- .allocate_image = allocate_image,
- .process_image = process_image,
+ .init_decoder = init_decoder,
};
-
-#endif
diff --git a/video/filter/vf.c b/video/filter/vf.c
index f187f7f..e76d30e 100644
--- a/video/filter/vf.c
+++ b/video/filter/vf.c
@@ -26,6 +26,7 @@
#include "config.h"
+#include "common/common.h"
#include "common/global.h"
#include "common/msg.h"
#include "options/m_option.h"
@@ -71,6 +72,7 @@ extern const vf_info_t vf_info_lavfi;
extern const vf_info_t vf_info_vaapi;
extern const vf_info_t vf_info_vapoursynth;
extern const vf_info_t vf_info_vdpaupp;
+extern const vf_info_t vf_info_buffer;
// list of available filters:
static const vf_info_t *const filter_list[] = {
@@ -108,6 +110,7 @@ static const vf_info_t *const filter_list[] = {
&vf_info_sub,
&vf_info_yadif,
&vf_info_stereo3d,
+ &vf_info_buffer,
#if HAVE_DLOPEN
&vf_info_dlopen,
#endif
@@ -223,22 +226,22 @@ static int vf_default_query_format(struct vf_instance *vf, unsigned int fmt)
return vf_next_query_format(vf, fmt);
}
-static void print_fmt(struct mp_log *log, int msglevel, struct mp_image_params *p)
+static void fmt_cat(char *b, size_t bs, struct mp_image_params *p)
{
if (p && p->imgfmt) {
- mp_msg(log, msglevel, "%dx%d", p->w, p->h);
+ mp_snprintf_cat(b, bs, "%dx%d", p->w, p->h);
if (p->w != p->d_w || p->h != p->d_h)
- mp_msg(log, msglevel, "->%dx%d", p->d_w, p->d_h);
- mp_msg(log, msglevel, " %s", mp_imgfmt_to_name(p->imgfmt));
- mp_msg(log, msglevel, " %s/%s", mp_csp_names[p->colorspace],
- mp_csp_levels_names[p->colorlevels]);
- mp_msg(log, msglevel, " CL=%d", (int)p->chroma_location);
+ mp_snprintf_cat(b, bs, "->%dx%d", p->d_w, p->d_h);
+ mp_snprintf_cat(b, bs, " %s", mp_imgfmt_to_name(p->imgfmt));
+ mp_snprintf_cat(b, bs, " %s/%s", mp_csp_names[p->colorspace],
+ mp_csp_levels_names[p->colorlevels]);
+ mp_snprintf_cat(b, bs, " CL=%d", (int)p->chroma_location);
if (p->outputlevels)
- mp_msg(log, msglevel, " out=%s", mp_csp_levels_names[p->outputlevels]);
+ mp_snprintf_cat(b, bs, " out=%s", mp_csp_levels_names[p->outputlevels]);
if (p->rotate)
- mp_msg(log, msglevel, " rot=%d", p->rotate);
+ mp_snprintf_cat(b, bs, " rot=%d", p->rotate);
} else {
- mp_msg(log, msglevel, "???");
+ mp_snprintf_cat(b, bs, "???");
}
}
@@ -248,17 +251,20 @@ void vf_print_filter_chain(struct vf_chain *c, int msglevel,
if (!mp_msg_test(c->log, msglevel))
return;
- mp_msg(c->log, msglevel, " [vd] ");
- print_fmt(c->log, msglevel, &c->input_params);
- mp_msg(c->log, msglevel, "\n");
+ char b[128] = {0};
+
+ fmt_cat(b, sizeof(b), &c->input_params);
+ mp_msg(c->log, msglevel, " [vd] %s\n", b);
+
for (vf_instance_t *f = c->first; f; f = f->next) {
- mp_msg(c->log, msglevel, " [%s] ", f->info->name);
- print_fmt(c->log, msglevel, &f->fmt_out);
+ b[0] = '\0';
+ mp_snprintf_cat(b, sizeof(b), " [%s] ", f->info->name);
+ fmt_cat(b, sizeof(b), &f->fmt_out);
if (f->autoinserted)
- mp_msg(c->log, msglevel, " [a]");
+ mp_snprintf_cat(b, sizeof(b), " [a]");
if (f == vf)
- mp_msg(c->log, msglevel, " <---");
- mp_msg(c->log, msglevel, "\n");
+ mp_snprintf_cat(b, sizeof(b), " <---");
+ mp_msg(c->log, msglevel, "%s\n", b);
}
}
diff --git a/video/filter/vf_buffer.c b/video/filter/vf_buffer.c
new file mode 100644
index 0000000..2a7e458
--- /dev/null
+++ b/video/filter/vf_buffer.c
@@ -0,0 +1,93 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <inttypes.h>
+
+#include "talloc.h"
+
+#include "options/m_option.h"
+
+#include "video/img_format.h"
+#include "video/mp_image.h"
+
+#include "vf.h"
+
+#define MAX_Q 100
+
+struct vf_priv_s {
+ struct mp_image *queued[MAX_Q];
+ int num_queued;
+ int cfg_num;
+};
+
+static void flush(struct vf_instance *vf)
+{
+ for (int n = 0; n < vf->priv->num_queued; n++)
+ mp_image_unrefp(&vf->priv->queued[n]);
+ vf->priv->num_queued = 0;
+}
+
+static int config(struct vf_instance *vf,
+ int width, int height, int d_width, int d_height,
+ unsigned int flags, unsigned int outfmt)
+{
+ flush(vf);
+ return vf_next_config(vf,width,height,d_width,d_height,flags,outfmt);
+}
+
+static int filter_ext(struct vf_instance *vf, struct mp_image *mpi)
+{
+ struct vf_priv_s *p = vf->priv;
+ if (mpi) {
+ if (p->num_queued == p->cfg_num) {
+ vf_add_output_frame(vf, p->queued[p->num_queued - 1]);
+ p->num_queued--;
+ }
+ p->num_queued++;
+ for (int n = p->num_queued - 1; n > 0; n--)
+ p->queued[n] = p->queued[n - 1];
+ p->queued[0] = mpi;
+ } else {
+ // EOF
+ while (p->num_queued) {
+ vf_add_output_frame(vf, p->queued[p->num_queued - 1]);
+ p->num_queued--;
+ }
+ }
+ return 0;
+}
+
+static int control(vf_instance_t *vf, int request, void *data)
+{
+ if (request == VFCTRL_SEEK_RESET) {
+ flush(vf);
+ return CONTROL_OK;
+ }
+ return CONTROL_UNKNOWN;
+}
+
+static void uninit(vf_instance_t *vf)
+{
+ flush(vf);
+}
+
+static int vf_open(vf_instance_t *vf)
+{
+ vf->config = config;
+ vf->filter_ext = filter_ext;
+ vf->control = control;
+ vf->uninit = uninit;
+ return 1;
+}
+
+#define OPT_BASE_STRUCT struct vf_priv_s
+const vf_info_t vf_info_buffer = {
+ .description = "buffer a number of frames",
+ .name = "buffer",
+ .open = vf_open,
+ .priv_size = sizeof(struct vf_priv_s),
+ .options = (const struct m_option[]){
+ OPT_INTRANGE("num", cfg_num, 0, 1, MAX_Q, OPTDEF_INT(2)),
+ {0}
+ },
+};
diff --git a/video/filter/vf_lavfi.c b/video/filter/vf_lavfi.c
index c6f0783..8f1ee24 100644
--- a/video/filter/vf_lavfi.c
+++ b/video/filter/vf_lavfi.c
@@ -37,9 +37,9 @@
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
+#include "common/av_common.h"
#include "common/msg.h"
#include "options/m_option.h"
-#include "common/av_opts.h"
#include "common/tags.h"
#include "video/img_format.h"
@@ -78,7 +78,7 @@ struct vf_priv_s {
// options
char *cfg_graph;
int64_t cfg_sws_flags;
- char *cfg_avopts;
+ char **cfg_avopts;
};
static const struct vf_priv_s vf_priv_dflt = {
@@ -143,11 +143,8 @@ static bool recreate_graph(struct vf_instance *vf, int width, int height,
if (!graph)
goto error;
- if (parse_avopts(graph, p->cfg_avopts) < 0) {
- MP_FATAL(vf, "lavfi: could not set opts: '%s'\n",
- p->cfg_avopts);
+ if (mp_set_avopts(vf->log, graph, p->cfg_avopts) < 0)
goto error;
- }
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
@@ -426,7 +423,7 @@ static void print_help(struct mp_log *log)
static const m_option_t vf_opts_fields[] = {
OPT_STRING("graph", cfg_graph, M_OPT_MIN, .min = 1),
OPT_INT64("sws-flags", cfg_sws_flags, 0),
- OPT_STRING("o", cfg_avopts, 0),
+ OPT_KEYVALUELIST("o", cfg_avopts, 0),
{0}
};
@@ -445,7 +442,7 @@ const vf_info_t vf_info_lavfi = {
struct vf_lw_opts {
int enable;
int64_t sws_flags;
- char *avopts;
+ char **avopts;
};
#undef OPT_BASE_STRUCT
@@ -454,7 +451,7 @@ const struct m_sub_options vf_lw_conf = {
.opts = (const m_option_t[]) {
OPT_FLAG("lavfi", enable, 0),
OPT_INT64("lavfi-sws-flags", sws_flags, 0),
- OPT_STRING("lavfi-o", avopts, 0),
+ OPT_KEYVALUELIST("lavfi-o", avopts, 0),
{0}
},
.defaults = &(const struct vf_lw_opts){
diff --git a/video/filter/vf_vapoursynth.c b/video/filter/vf_vapoursynth.c
index 5e104bb..c8c9169 100644
--- a/video/filter/vf_vapoursynth.c
+++ b/video/filter/vf_vapoursynth.c
@@ -455,8 +455,10 @@ static int reinit_vs(struct vf_instance *vf)
goto error;
p->vsapi = vsscript_getVSApi();
p->vscore = vsscript_getCore(p->se);
- if (!p->vsapi || !p->vscore)
+ if (!p->vsapi || !p->vscore) {
+ MP_FATAL(vf, "Could not get vapoursynth API handle.\n");
goto error;
+ }
in = p->vsapi->createMap();
out = p->vsapi->createMap();
@@ -468,8 +470,10 @@ static int reinit_vs(struct vf_instance *vf)
infiltFree, fmSerial, 0, vf, p->vscore);
int vserr;
p->in_node = p->vsapi->propGetNode(out, "clip", 0, &vserr);
- if (!p->in_node)
+ if (!p->in_node) {
+ MP_FATAL(vf, "Could not get our own input node.\n");
goto error;
+ }
if (p->vsapi->propSetNode(vars, "video_in", p->in_node, 0))
goto error;
@@ -481,8 +485,10 @@ static int reinit_vs(struct vf_instance *vf)
goto error;
}
p->out_node = vsscript_getOutput(p->se, 0);
- if (!p->out_node)
+ if (!p->out_node) {
+ MP_FATAL(vf, "Could not get script output node.\n");
goto error;
+ }
const VSVideoInfo *vi = p->vsapi->getVideoInfo(p->out_node);
if (!isConstantFormat(vi)) {
diff --git a/video/fmt-conversion.c b/video/fmt-conversion.c
index 44fafa6..a8ae905 100644
--- a/video/fmt-conversion.c
+++ b/video/fmt-conversion.c
@@ -172,13 +172,11 @@ static const struct {
{IMGFMT_BGR0, AV_PIX_FMT_BGRA},
#endif
- {IMGFMT_VDPAU, AV_PIX_FMT_VDPAU},
-#if HAVE_VDA_AV_VDA_ALLOC_CONTEXT
- {IMGFMT_VDA, AV_PIX_FMT_VDA},
-#else
- {IMGFMT_VDA, AV_PIX_FMT_VDA_VLD},
+ {IMGFMT_VDPAU, AV_PIX_FMT_VDPAU},
+#if HAVE_VDA_HWACCEL
+ {IMGFMT_VDA, AV_PIX_FMT_VDA},
#endif
- {IMGFMT_VAAPI, AV_PIX_FMT_VAAPI_VLD},
+ {IMGFMT_VAAPI, AV_PIX_FMT_VAAPI_VLD},
{0, AV_PIX_FMT_NONE}
};
diff --git a/video/img_format.h b/video/img_format.h
index c6c26e7..03ae1e9 100644
--- a/video/img_format.h
+++ b/video/img_format.h
@@ -20,7 +20,8 @@
#define MPLAYER_IMG_FORMAT_H
#include <inttypes.h>
-#include <sys/types.h>
+
+#include "osdep/endian.h"
#include "bstr/bstr.h"
#if BYTE_ORDER == BIG_ENDIAN
diff --git a/video/img_fourcc.h b/video/img_fourcc.h
index ee30ff0..1539a7b 100644
--- a/video/img_fourcc.h
+++ b/video/img_fourcc.h
@@ -1,7 +1,7 @@
#ifndef MPV_IMG_FOURCC_H
#define MPV_IMG_FOURCC_H
-#include <sys/types.h>
+#include "osdep/endian.h"
#define MP_FOURCC(a,b,c,d) ((a) | ((b)<<8) | ((c)<<16) | ((unsigned)(d)<<24))
diff --git a/video/out/cocoa/window.m b/video/out/cocoa/window.m
index aca488c..3dc9375 100644
--- a/video/out/cocoa/window.m
+++ b/video/out/cocoa/window.m
@@ -19,7 +19,6 @@
#include "input/keycodes.h"
-#include "osdep/macosx_application.h"
#include "osdep/macosx_events.h"
#include "osdep/macosx_compat.h"
diff --git a/video/out/cocoa_common.h b/video/out/cocoa_common.h
index e0696eb..8e59ab6 100644
--- a/video/out/cocoa_common.h
+++ b/video/out/cocoa_common.h
@@ -29,7 +29,7 @@ void *vo_cocoa_glgetaddr(const char *s);
int vo_cocoa_init(struct vo *vo);
void vo_cocoa_uninit(struct vo *vo);
-int vo_cocoa_config_window(struct vo *vo, uint32_t flags, int gl3profile);
+int vo_cocoa_config_window(struct vo *vo, uint32_t flags, void *gl_ctx);
void vo_cocoa_set_current_context(struct vo *vo, bool current);
void vo_cocoa_swap_buffers(struct vo *vo);
@@ -42,11 +42,10 @@ void vo_cocoa_register_resize_callback(struct vo *vo,
void vo_cocoa_register_gl_clear_callback(struct vo *vo, void *ctx,
void (*cb)(void *ctx));
-// returns an int to conform to the gl extensions from other platforms
-int vo_cocoa_swap_interval(int enabled);
-
void *vo_cocoa_cgl_context(struct vo *vo);
void *vo_cocoa_cgl_pixel_format(struct vo *vo);
-int vo_cocoa_cgl_color_size(struct vo *vo);
+
+void vo_cocoa_create_nsgl_ctx(struct vo *vo, void *ctx);
+void vo_cocoa_release_nsgl_ctx(struct vo *vo);
#endif /* MPLAYER_COCOA_COMMON_H */
diff --git a/video/out/cocoa_common.m b/video/out/cocoa_common.m
index 1e0b7ab..a1ea157 100644
--- a/video/out/cocoa_common.m
+++ b/video/out/cocoa_common.m
@@ -28,12 +28,15 @@
#import "video/out/cocoa/mpvadapter.h"
#include "osdep/macosx_compat.h"
-#include "osdep/macosx_application.h"
-#include "osdep/macosx_application_objc.h"
-#include "osdep/macosx_events.h"
+#include "osdep/macosx_events_objc.h"
#include "config.h"
+#if HAVE_COCOA_APPLICATION
+# include "osdep/macosx_application.h"
+# include "osdep/macosx_application_objc.h"
+#endif
+
#include "options/options.h"
#include "video/out/vo.h"
#include "win_state.h"
@@ -177,9 +180,6 @@ void vo_cocoa_uninit(struct vo *vo)
[s->window release];
s->window = nil;
- [s->gl_ctx release];
- s->gl_ctx = nil;
-
[s->lock release];
s->lock = nil;
});
@@ -301,11 +301,13 @@ static void create_window(struct vo *vo, struct mp_rect *win, int geo_flags)
[s->view setWantsBestResolutionOpenGLSurface:YES];
+#if HAVE_COCOA_APPLICATION
cocoa_register_menu_item_action(MPM_H_SIZE, @selector(halfSize));
cocoa_register_menu_item_action(MPM_N_SIZE, @selector(normalSize));
cocoa_register_menu_item_action(MPM_D_SIZE, @selector(doubleSize));
cocoa_register_menu_item_action(MPM_MINIMIZE, @selector(performMiniaturize:));
cocoa_register_menu_item_action(MPM_ZOOM, @selector(performZoom:));
+#endif
[s->window setRestorable:NO];
[s->window setContentView:s->view];
@@ -330,66 +332,6 @@ static void create_window(struct vo *vo, struct mp_rect *win, int geo_flags)
}
}
-static CGLOpenGLProfile cgl_profile(int gl3profile) {
- if (gl3profile) {
- return kCGLOGLPVersion_3_2_Core;
- } else {
- return kCGLOGLPVersion_Legacy;
- }
-}
-
-static int create_gl_context(struct vo *vo, int gl3profile)
-{
- struct vo_cocoa_state *s = vo->cocoa;
- CGLError err;
-
- CGLPixelFormatAttribute attrs[] = {
- kCGLPFAOpenGLProfile,
- (CGLPixelFormatAttribute) cgl_profile(gl3profile),
- kCGLPFADoubleBuffer,
- kCGLPFAAccelerated,
- #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_8
- // leave this as the last entry of the array to not break the fallback
- // code
- kCGLPFASupportsAutomaticGraphicsSwitching,
- #endif
- 0
- };
-
- CGLPixelFormatObj pix;
- GLint npix;
-
- err = CGLChoosePixelFormat(attrs, &pix, &npix);
- if (err == kCGLBadAttribute) {
- // kCGLPFASupportsAutomaticGraphicsSwitching is probably not supported
- // by the current hardware. Falling back to not using it.
- MP_ERR(vo, "error creating CGL pixel format with automatic GPU "
- "switching. falling back\n");
- attrs[MP_ARRAY_SIZE(attrs) - 2] = 0;
- err = CGLChoosePixelFormat(attrs, &pix, &npix);
- }
-
- if (err != kCGLNoError) {
- MP_FATAL(s, "error creating CGL pixel format: %s (%d)\n",
- CGLErrorString(err), err);
- }
-
- CGLContextObj ctx;
- if ((err = CGLCreateContext(pix, 0, &ctx)) != kCGLNoError) {
- MP_FATAL(s, "error creating CGL context: %s (%d)\n",
- CGLErrorString(err), err);
- return -1;
- }
-
- s->gl_ctx = [[NSOpenGLContext alloc] initWithCGLContextObj:ctx];
- [s->gl_ctx makeCurrentContext];
-
- CGLReleasePixelFormat(pix);
- CGLReleaseContext(ctx);
-
- return 0;
-}
-
static void cocoa_set_window_title(struct vo *vo, const char *title)
{
struct vo_cocoa_state *s = vo->cocoa;
@@ -408,6 +350,9 @@ static void vo_cocoa_resize_redraw(struct vo *vo, int width, int height)
if (!s->resize_redraw)
return;
+ if (!s->gl_ctx)
+ return;
+
vo_cocoa_set_current_context(vo, true);
[s->gl_ctx update];
@@ -452,7 +397,21 @@ static void cocoa_add_fs_screen_profile_observer(struct vo *vo)
usingBlock:nblock];
}
-int vo_cocoa_config_window(struct vo *vo, uint32_t flags, int gl3profile)
+void vo_cocoa_create_nsgl_ctx(struct vo *vo, void *ctx)
+{
+ struct vo_cocoa_state *s = vo->cocoa;
+ s->gl_ctx = [[NSOpenGLContext alloc] initWithCGLContextObj:ctx];
+ [s->gl_ctx makeCurrentContext];
+}
+
+void vo_cocoa_release_nsgl_ctx(struct vo *vo)
+{
+ struct vo_cocoa_state *s = vo->cocoa;
+ [s->gl_ctx release];
+ s->gl_ctx = nil;
+}
+
+int vo_cocoa_config_window(struct vo *vo, uint32_t flags, void *gl_ctx)
{
struct vo_cocoa_state *s = vo->cocoa;
__block int ctxok = 0;
@@ -474,30 +433,10 @@ int vo_cocoa_config_window(struct vo *vo, uint32_t flags, int gl3profile)
s->old_dwidth = width;
s->old_dheight = height;
- if (flags & VOFLAG_HIDDEN) {
- // This is certainly the first execution of vo_config_window and
- // is called in order for an OpenGL based VO to perform detection
- // of OpenGL extensions. On OSX to accomplish this task we are
- // allowed only create a OpenGL context without attaching it to
- // a drawable.
- ctxok = create_gl_context(vo, gl3profile);
- if (ctxok < 0) return;
- } else if (!s->gl_ctx || !s->window) {
- // Either gl_ctx+window or window alone is not created.
- // Handle each of them independently. This is to handle correctly
- // both VOs like vo_corevideo who skip the the OpenGL detection
- // phase completly and generic OpenGL VOs who use VOFLAG_HIDDEN.
- if (!s->gl_ctx) {
- ctxok = create_gl_context(vo, gl3profile);
- if (ctxok < 0) return;
- }
-
- if (!s->window)
- create_window(vo, &geo.win, geo.flags);
- }
+ if (!(flags & VOFLAG_HIDDEN) && !s->window)
+ create_window(vo, &geo.win, geo.flags);
if (s->window) {
- // Everything is properly initialized
if (reset_size)
[s->window queueNewVideoSize:NSMakeSize(width, height)];
cocoa_set_window_title(vo, vo_get_window_title(vo));
@@ -524,7 +463,8 @@ void vo_cocoa_set_current_context(struct vo *vo, bool current)
if (!s->inside_sync_section)
[s->lock lock];
- [s->gl_ctx makeCurrentContext];
+ if (s->gl_ctx)
+ [s->gl_ctx makeCurrentContext];
} else {
[NSOpenGLContext clearCurrentContext];
@@ -751,13 +691,6 @@ int vo_cocoa_control(struct vo *vo, int *events, int request, void *arg)
return VO_NOTIMPL;
}
-int vo_cocoa_swap_interval(int enabled)
-{
- [[NSOpenGLContext currentContext] setValues:&enabled
- forParameter:NSOpenGLCPSwapInterval];
- return 0;
-}
-
void *vo_cocoa_cgl_context(struct vo *vo)
{
struct vo_cocoa_state *s = vo->cocoa;
@@ -769,22 +702,6 @@ void *vo_cocoa_cgl_pixel_format(struct vo *vo)
return CGLGetPixelFormat(vo_cocoa_cgl_context(vo));
}
-int vo_cocoa_cgl_color_size(struct vo *vo)
-{
- GLint value;
- CGLDescribePixelFormat(vo_cocoa_cgl_pixel_format(vo), 0,
- kCGLPFAColorSize, &value);
- switch (value) {
- case 32:
- case 24:
- return 8;
- case 16:
- return 5;
- }
-
- return 8;
-}
-
@implementation MpvCocoaAdapter
@synthesize vout = _video_output;
@@ -804,7 +721,7 @@ int vo_cocoa_cgl_color_size(struct vo *vo)
}
- (void)signalMouseMovement:(NSPoint)point {
- vo_mouse_movement(self.vout, point.x, point.y);
+ mp_input_set_mouse_pos(self.vout->input_ctx, point.x, point.y);
[self recalcMovableByWindowBackground:point];
}
@@ -841,7 +758,7 @@ int vo_cocoa_cgl_color_size(struct vo *vo)
- (void)handleFilesArray:(NSArray *)files
{
- [mpv_shared_app() handleFilesArray:files];
+ [[EventsResponder sharedInstance] handleFilesArray:files];
}
- (void)didChangeWindowedScreenProfile:(NSScreen *)screen
diff --git a/video/out/gl_cocoa.c b/video/out/gl_cocoa.c
index 77f4161..9df1eec 100644
--- a/video/out/gl_cocoa.c
+++ b/video/out/gl_cocoa.c
@@ -19,9 +19,16 @@
* version 2.1 of the License, or (at your option) any later version.
*/
+#include <OpenGL/OpenGL.h>
#include "cocoa_common.h"
+#include "osdep/macosx_versions.h"
#include "gl_common.h"
+struct cgl_context {
+ CGLPixelFormatObj pix;
+ CGLContextObj ctx;
+};
+
static void gl_clear(void *ctx)
{
struct GL *gl = ctx;
@@ -29,22 +36,98 @@ static void gl_clear(void *ctx)
gl->Clear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
}
-static bool config_window_cocoa(struct MPGLContext *ctx, int flags)
+static int set_swap_interval(int enabled)
+{
+ CGLContextObj ctx = CGLGetCurrentContext();
+ CGLError err = CGLSetParameter(ctx, kCGLCPSwapInterval, &enabled);
+ return (err == kCGLNoError) ? 0 : -1;
+}
+
+static int cgl_color_size(struct MPGLContext *ctx)
{
- int rv = vo_cocoa_config_window(ctx->vo, flags,
- ctx->requested_gl_version >= MPGL_VER(3, 0));
- if (rv != 0)
+ struct cgl_context *p = ctx->priv;
+ GLint value;
+ CGLDescribePixelFormat(p->pix, 0, kCGLPFAColorSize, &value);
+ return value > 16 ? 8 : 5;
+}
+
+static bool create_gl_context(struct MPGLContext *ctx)
+{
+ struct cgl_context *p = ctx->priv;
+ CGLError err;
+
+ CGLOpenGLProfile gl_vers_map[] = {
+ [2] = kCGLOGLPVersion_Legacy,
+ #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_9
+ [3] = kCGLOGLPVersion_GL3_Core,
+ [4] = kCGLOGLPVersion_GL4_Core,
+ #else
+ [3] = kCGLOGLPVersion_3_2_Core,
+ #endif
+ };
+
+ int gl_major = MPGL_VER_GET_MAJOR(ctx->requested_gl_version);
+ if (gl_major < 2 || gl_major >= MP_ARRAY_SIZE(gl_vers_map)) {
+ MP_FATAL(ctx->vo, "OpenGL major version %d not supported", gl_major);
+ return false;
+ }
+
+ CGLPixelFormatAttribute attrs[] = {
+ kCGLPFAOpenGLProfile,
+ (CGLPixelFormatAttribute) gl_vers_map[gl_major],
+ kCGLPFADoubleBuffer,
+ kCGLPFAAccelerated,
+ #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_8
+ // leave this as the last entry of the array to not break the fallback
+ // code
+ kCGLPFASupportsAutomaticGraphicsSwitching,
+ #endif
+ 0
+ };
+
+ GLint npix;
+ err = CGLChoosePixelFormat(attrs, &p->pix, &npix);
+ if (err == kCGLBadAttribute) {
+ // kCGLPFASupportsAutomaticGraphicsSwitching is probably not supported
+ // by the current hardware. Falling back to not using it.
+ MP_ERR(ctx->vo, "error creating CGL pixel format with automatic GPU "
+ "switching. falling back\n");
+ attrs[MP_ARRAY_SIZE(attrs) - 2] = 0;
+ err = CGLChoosePixelFormat(attrs, &p->pix, &npix);
+ }
+
+ if (err != kCGLNoError) {
+ MP_FATAL(ctx->vo, "error creating CGL pixel format: %s (%d)\n",
+ CGLErrorString(err), err);
+ }
+
+ if ((err = CGLCreateContext(p->pix, 0, &p->ctx)) != kCGLNoError) {
+ MP_FATAL(ctx->vo, "error creating CGL context: %s (%d)\n",
+ CGLErrorString(err), err);
return false;
+ }
+ vo_cocoa_create_nsgl_ctx(ctx->vo, p->ctx);
+ ctx->depth_r = ctx->depth_g = ctx->depth_b = cgl_color_size(ctx);
mpgl_load_functions(ctx->gl, (void *)vo_cocoa_glgetaddr, NULL, ctx->vo->log);
- ctx->depth_r = vo_cocoa_cgl_color_size(ctx->vo);
- ctx->depth_g = vo_cocoa_cgl_color_size(ctx->vo);
- ctx->depth_b = vo_cocoa_cgl_color_size(ctx->vo);
+ CGLReleasePixelFormat(p->pix);
+
+ return true;
+}
+
+static bool config_window_cocoa(struct MPGLContext *ctx, int flags)
+{
+ struct cgl_context *p = ctx->priv;
+
+ if (p->ctx == NULL)
+ if (!create_gl_context(ctx))
+ return false;
if (!ctx->gl->SwapInterval)
- ctx->gl->SwapInterval = vo_cocoa_swap_interval;
+ ctx->gl->SwapInterval = set_swap_interval;
+ vo_cocoa_config_window(ctx->vo, flags, p->ctx);
vo_cocoa_register_gl_clear_callback(ctx->vo, ctx->gl, gl_clear);
return true;
@@ -52,6 +135,9 @@ static bool config_window_cocoa(struct MPGLContext *ctx, int flags)
static void releaseGlContext_cocoa(MPGLContext *ctx)
{
+ struct cgl_context *p = ctx->priv;
+ vo_cocoa_release_nsgl_ctx(ctx->vo);
+ CGLReleaseContext(p->ctx);
}
static void swapGlBuffers_cocoa(MPGLContext *ctx)
@@ -66,6 +152,7 @@ static void set_current_cocoa(MPGLContext *ctx, bool current)
void mpgl_set_backend_cocoa(MPGLContext *ctx)
{
+ ctx->priv = talloc_zero(ctx, struct cgl_context);
ctx->config_window = config_window_cocoa;
ctx->releaseGlContext = releaseGlContext_cocoa;
ctx->swapGlBuffers = swapGlBuffers_cocoa;
diff --git a/video/out/gl_common.c b/video/out/gl_common.c
index 131a35d..dd90bee 100644
--- a/video/out/gl_common.c
+++ b/video/out/gl_common.c
@@ -36,12 +36,12 @@
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
-#include <ctype.h>
#include <stdbool.h>
#include <math.h>
#include <assert.h>
#include "talloc.h"
#include "gl_common.h"
+#include "common/common.h"
#include "options/options.h"
#include "options/m_option.h"
@@ -121,11 +121,12 @@ static const struct feature features[] = {
static void list_features(int set, struct mp_log *log, int msgl, bool invert)
{
+ char b[128] = {0};
for (const struct feature *f = &features[0]; f->id; f++) {
if (invert == !(f->id & set))
- mp_msg(log, msgl, " [%s]", f->name);
+ mp_snprintf_cat(b, sizeof(b), " [%s]", f->name);
}
- mp_msg(log, msgl, "\n");
+ mp_msg(log, msgl, "%s\n", b);
}
// This guesses if the current GL context is a suspected software renderer.
diff --git a/video/out/gl_w32.c b/video/out/gl_w32.c
index 852cea7..79e3165 100644
--- a/video/out/gl_w32.c
+++ b/video/out/gl_w32.c
@@ -19,14 +19,62 @@
* version 2.1 of the License, or (at your option) any later version.
*/
+#include <assert.h>
#include <windows.h>
#include "w32_common.h"
#include "gl_common.h"
struct w32_context {
HGLRC context;
+ HDC hdc;
+ int flags;
};
+static bool create_dc(struct MPGLContext *ctx, int flags)
+{
+ struct w32_context *w32_ctx = ctx->priv;
+ HWND win = vo_w32_hwnd(ctx->vo);
+
+ if (w32_ctx->hdc)
+ return true;
+
+ HDC hdc = GetDC(win);
+ if (!hdc)
+ return false;
+
+ PIXELFORMATDESCRIPTOR pfd;
+ memset(&pfd, 0, sizeof pfd);
+ pfd.nSize = sizeof pfd;
+ pfd.nVersion = 1;
+ pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
+
+ if (flags & VOFLAG_STEREO)
+ pfd.dwFlags |= PFD_STEREO;
+
+ pfd.iPixelType = PFD_TYPE_RGBA;
+ pfd.cColorBits = 24;
+ pfd.iLayerType = PFD_MAIN_PLANE;
+ int pf = ChoosePixelFormat(hdc, &pfd);
+
+ if (!pf) {
+ MP_ERR(ctx->vo, "unable to select a valid pixel format!\n");
+ ReleaseDC(win, hdc);
+ return false;
+ }
+
+ SetPixelFormat(hdc, pf, &pfd);
+
+ int pfmt = GetPixelFormat(hdc);
+ if (DescribePixelFormat(hdc, pfmt, sizeof(PIXELFORMATDESCRIPTOR), &pfd)) {
+ ctx->depth_r = pfd.cRedBits;
+ ctx->depth_g = pfd.cGreenBits;
+ ctx->depth_b = pfd.cBlueBits;
+ }
+
+ w32_ctx->hdc = hdc;
+ return true;
+}
+
static void *w32gpa(const GLubyte *procName)
{
HMODULE oglmod;
@@ -40,57 +88,44 @@ static void *w32gpa(const GLubyte *procName)
static bool create_context_w32_old(struct MPGLContext *ctx)
{
struct w32_context *w32_ctx = ctx->priv;
- HGLRC *context = &w32_ctx->context;
-
- if (*context)
- return true;
- HWND win = ctx->vo->w32->window;
- HDC windc = GetDC(win);
+ HDC windc = w32_ctx->hdc;
bool res = false;
- HGLRC new_context = wglCreateContext(windc);
- if (!new_context) {
+ HGLRC context = wglCreateContext(windc);
+ if (!context) {
MP_FATAL(ctx->vo, "Could not create GL context!\n");
- goto out;
+ return res;
}
- if (!wglMakeCurrent(windc, new_context)) {
+ if (!wglMakeCurrent(windc, context)) {
MP_FATAL(ctx->vo, "Could not set GL context!\n");
- wglDeleteContext(new_context);
- goto out;
+ wglDeleteContext(context);
+ return res;
}
- *context = new_context;
+ w32_ctx->context = context;
mpgl_load_functions(ctx->gl, w32gpa, NULL, ctx->vo->log);
- res = true;
-
-out:
- ReleaseDC(win, windc);
- return res;
+ return true;
}
static bool create_context_w32_gl3(struct MPGLContext *ctx)
{
struct w32_context *w32_ctx = ctx->priv;
- HGLRC *context = &w32_ctx->context;
-
- if (*context) // reuse existing context
- return true; // not reusing it breaks gl3!
- HWND win = ctx->vo->w32->window;
- HDC windc = GetDC(win);
- HGLRC new_context = 0;
+ HDC windc = w32_ctx->hdc;
+ HGLRC context = 0;
- new_context = wglCreateContext(windc);
- if (!new_context) {
+ // A legacy context is needed to get access to the new functions.
+ HGLRC legacy_context = wglCreateContext(windc);
+ if (!legacy_context) {
MP_FATAL(ctx->vo, "Could not create GL context!\n");
return false;
}
// set context
- if (!wglMakeCurrent(windc, new_context)) {
+ if (!wglMakeCurrent(windc, legacy_context)) {
MP_FATAL(ctx->vo, "Could not set GL context!\n");
goto out;
}
@@ -121,78 +156,100 @@ static bool create_context_w32_gl3(struct MPGLContext *ctx)
0
};
- *context = wglCreateContextAttribsARB(windc, 0, attribs);
- if (! *context) {
+ context = wglCreateContextAttribsARB(windc, 0, attribs);
+ if (!context) {
// NVidia, instead of ignoring WGL_CONTEXT_FLAGS_ARB, will error out if
// it's present on pre-3.2 contexts.
// Remove it from attribs and retry the context creation.
attribs[6] = attribs[7] = 0;
- *context = wglCreateContextAttribsARB(windc, 0, attribs);
+ context = wglCreateContextAttribsARB(windc, 0, attribs);
}
- if (! *context) {
+ if (!context) {
int err = GetLastError();
MP_FATAL(ctx->vo, "Could not create an OpenGL 3.x context: error 0x%x\n", err);
goto out;
}
- wglMakeCurrent(NULL, NULL);
- wglDeleteContext(new_context);
+ wglMakeCurrent(windc, NULL);
+ wglDeleteContext(legacy_context);
- if (!wglMakeCurrent(windc, *context)) {
+ if (!wglMakeCurrent(windc, context)) {
MP_FATAL(ctx->vo, "Could not set GL3 context!\n");
- wglDeleteContext(*context);
+ wglDeleteContext(context);
return false;
}
+ w32_ctx->context = context;
+
/* update function pointers */
mpgl_load_functions(ctx->gl, w32gpa, NULL, ctx->vo->log);
- int pfmt = GetPixelFormat(windc);
- PIXELFORMATDESCRIPTOR pfd;
- if (DescribePixelFormat(windc, pfmt, sizeof(PIXELFORMATDESCRIPTOR), &pfd)) {
- ctx->depth_r = pfd.cRedBits;
- ctx->depth_g = pfd.cGreenBits;
- ctx->depth_b = pfd.cBlueBits;
- }
-
return true;
unsupported:
- MP_ERR(ctx->vo, "The current OpenGL implementation does not support OpenGL 3.x \n");
+ MP_ERR(ctx->vo, "The OpenGL driver does not support OpenGL 3.x \n");
out:
- wglDeleteContext(new_context);
+ wglMakeCurrent(windc, NULL);
+ wglDeleteContext(legacy_context);
return false;
}
+static void create_ctx(void *ptr)
+{
+ struct MPGLContext *ctx = ptr;
+ struct w32_context *w32_ctx = ctx->priv;
+
+ if (!create_dc(ctx, w32_ctx->flags))
+ return;
+
+ if (ctx->requested_gl_version >= MPGL_VER(3, 0))
+ create_context_w32_gl3(ctx);
+ if (!w32_ctx->context)
+ create_context_w32_old(ctx);
+ wglMakeCurrent(w32_ctx->hdc, NULL);
+}
+
static bool config_window_w32(struct MPGLContext *ctx, int flags)
{
+ struct w32_context *w32_ctx = ctx->priv;
if (!vo_w32_config(ctx->vo, flags))
return false;
- bool success = false;
- if (ctx->requested_gl_version >= MPGL_VER(3, 0))
- success = create_context_w32_gl3(ctx);
- if (!success)
- success = create_context_w32_old(ctx);
- return success;
+ if (w32_ctx->context) // reuse existing context
+ return true;
+
+ w32_ctx->flags = flags;
+ vo_w32_run_on_thread(ctx->vo, create_ctx, ctx);
+
+ if (w32_ctx->context)
+ wglMakeCurrent(w32_ctx->hdc, w32_ctx->context);
+ return !!w32_ctx->context;
+}
+
+static void destroy_gl(void *ptr)
+{
+ struct MPGLContext *ctx = ptr;
+ struct w32_context *w32_ctx = ctx->priv;
+ if (w32_ctx->context)
+ wglDeleteContext(w32_ctx->context);
+ w32_ctx->context = 0;
+ if (w32_ctx->hdc)
+ ReleaseDC(vo_w32_hwnd(ctx->vo), w32_ctx->hdc);
+ w32_ctx->hdc = NULL;
}
static void releaseGlContext_w32(MPGLContext *ctx)
{
struct w32_context *w32_ctx = ctx->priv;
- HGLRC *context = &w32_ctx->context;
- if (*context) {
- wglMakeCurrent(0, 0);
- wglDeleteContext(*context);
- }
- *context = 0;
+ if (w32_ctx->context)
+ wglMakeCurrent(w32_ctx->hdc, 0);
+ vo_w32_run_on_thread(ctx->vo, destroy_gl, ctx);
}
static void swapGlBuffers_w32(MPGLContext *ctx)
{
- HDC vo_hdc = GetDC(ctx->vo->w32->window);
- SwapBuffers(vo_hdc);
- ReleaseDC(ctx->vo->w32->window, vo_hdc);
+ struct w32_context *w32_ctx = ctx->priv;
+ SwapBuffers(w32_ctx->hdc);
}
void mpgl_set_backend_w32(MPGLContext *ctx)
diff --git a/video/out/gl_wayland.c b/video/out/gl_wayland.c
index 71b1d42..ca98a26 100644
--- a/video/out/gl_wayland.c
+++ b/video/out/gl_wayland.c
@@ -26,6 +26,9 @@ static void egl_resize(struct vo_wayland_state *wl)
int32_t width = wl->window.sh_width;
int32_t height = wl->window.sh_height;
+ if (!wl->egl_context.egl_window)
+ return;
+
// get the real size of the window
// this improves moving the window while resizing it
wl_egl_window_get_attached_size(wl->egl_context.egl_window,
diff --git a/video/out/pnm_loader.c b/video/out/pnm_loader.c
index 048461e..70afe0f 100644
--- a/video/out/pnm_loader.c
+++ b/video/out/pnm_loader.c
@@ -33,7 +33,7 @@
#include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
-#include <ctype.h>
+#include "misc/ctype.h"
#include "pnm_loader.h"
/**
@@ -48,7 +48,7 @@ static void ppm_skip(FILE *f) {
comment = 1;
if (c == '\n')
comment = 0;
- } while (c != EOF && (isspace(c) || comment));
+ } while (c != EOF && (mp_isspace(c) || comment));
if (c != EOF)
ungetc(c, f);
}
@@ -77,7 +77,7 @@ uint8_t *read_pnm(FILE *f, int *width, int *height,
if (fscanf(f, "%u", &m) != 1)
return NULL;
val = fgetc(f);
- if (!isspace(val))
+ if (!mp_isspace(val))
return NULL;
if (w > MAXDIM || h > MAXDIM)
return NULL;
diff --git a/video/out/vo.c b/video/out/vo.c
index cbf06a9..3962ed6 100644
--- a/video/out/vo.c
+++ b/video/out/vo.c
@@ -177,6 +177,7 @@ static struct vo *vo_create(struct mpv_global *global,
.max_video_queue = 1,
};
talloc_steal(vo, log);
+ mp_input_set_mouse_transform(vo->input_ctx, NULL, NULL);
if (vo->driver->encode != !!vo->encode_lavc_ctx)
goto error;
struct m_config *config = m_config_from_obj_desc(vo, vo->log, &desc);
@@ -287,12 +288,6 @@ void vo_queue_image(struct vo *vo, struct mp_image *mpi)
if (!vo->config_ok)
return;
assert(mp_image_params_equal(vo->params, &mpi->params));
- if (vo->driver->filter_image && mpi)
- mpi = vo->driver->filter_image(vo, mpi);
- if (!mpi) {
- MP_ERR(vo, "Could not upload image.\n");
- return;
- }
assert(vo->max_video_queue <= VO_MAX_QUEUE);
assert(vo->num_video_queue < vo->max_video_queue);
vo->video_queue[vo->num_video_queue++] = mpi;
@@ -405,22 +400,6 @@ const char *vo_get_window_title(struct vo *vo)
}
/**
- * Generates a mouse movement message if those are enable and sends it
- * to the "main" MPlayer.
- *
- * \param posx new x position of mouse
- * \param posy new y position of mouse
- */
-void vo_mouse_movement(struct vo *vo, int posx, int posy)
-{
- if (!vo->opts->enable_mouse_movements)
- return;
- float p[2] = {posx, posy};
- vo_control(vo, VOCTRL_WINDOW_TO_OSD_COORDS, p);
- mp_input_set_mouse_pos(vo->input_ctx, p[0], p[1]);
-}
-
-/**
* \brief lookup an integer in a table, table must have 0 as the last key
* \param key key to search for
* \result translation corresponding to key or "to" value of last mapping
diff --git a/video/out/vo.h b/video/out/vo.h
index c07c071..1d8182f 100644
--- a/video/out/vo.h
+++ b/video/out/vo.h
@@ -52,7 +52,7 @@ enum mp_voctrl {
VOCTRL_GET_EQUALIZER, // struct voctrl_get_equalizer_args*
/* for hardware decoding */
- VOCTRL_GET_HWDEC_INFO, // struct mp_hwdec_info*
+ VOCTRL_GET_HWDEC_INFO, // struct mp_hwdec_info**
// Redraw the image previously passed to draw_image() (basically, repeat
// the previous draw_image call). If this is handled, the OSD should also
@@ -71,7 +71,6 @@ enum mp_voctrl {
VOCTRL_SET_DEINTERLACE,
VOCTRL_GET_DEINTERLACE,
- VOCTRL_WINDOW_TO_OSD_COORDS, // float[2] (x/y)
VOCTRL_GET_WINDOW_SIZE, // int[2] (w/h)
VOCTRL_SET_WINDOW_SIZE, // int[2] (w/h)
@@ -165,20 +164,6 @@ struct vo_driver {
int (*query_format)(struct vo *vo, uint32_t format);
/*
- * Optional. Can be used to convert the input image into something VO
- * internal, such as GPU surfaces. Ownership of mpi is passed to the
- * function, and the returned image is owned by the caller.
- * The following guarantees are given:
- * - mpi has the format with which the VO was configured
- * - the returned image can be arbitrary, and the VO merely manages its
- * lifetime
- * - images passed to draw_image are always passed through this function
- * - the maximum number of images kept alive is not over vo->max_video_queue
- * - if vo->max_video_queue is large enough, some images may be buffered ahead
- */
- struct mp_image *(*filter_image)(struct vo *vo, struct mp_image *mpi);
-
- /*
* Initialize or reconfigure the display driver.
* params: video parameters, like pixel format and frame size
* flags: combination of VOFLAG_ values
@@ -294,9 +279,6 @@ struct mp_keymap {
};
int lookup_keymap_table(const struct mp_keymap *map, int key);
-void vo_mouse_movement(struct vo *vo, int posx, int posy);
-void vo_drop_files(struct vo *vo, int num_files, char **files);
-
struct mp_osd_res;
void vo_get_src_dst_rects(struct vo *vo, struct mp_rect *out_src,
struct mp_rect *out_dst, struct mp_osd_res *out_osd);
diff --git a/video/out/vo_caca.c b/video/out/vo_caca.c
index 00b9e23..bcef785 100644
--- a/video/out/vo_caca.c
+++ b/video/out/vo_caca.c
@@ -178,16 +178,14 @@ static void check_events(struct vo *vo)
mp_input_put_key(vo->input_ctx, MP_KEY_CLOSE_WIN);
break;
case CACA_EVENT_MOUSE_MOTION:
- vo_mouse_movement(vo, cev.data.mouse.x, cev.data.mouse.y);
+ mp_input_set_mouse_pos(vo->input_ctx, cev.data.mouse.x, cev.data.mouse.y);
break;
case CACA_EVENT_MOUSE_PRESS:
- if (vo->opts->enable_mouse_movements)
- mp_input_put_key(vo->input_ctx,
+ mp_input_put_key(vo->input_ctx,
(MP_MOUSE_BTN0 + cev.data.mouse.button - 1) | MP_KEY_STATE_DOWN);
break;
case CACA_EVENT_MOUSE_RELEASE:
- if (vo->opts->enable_mouse_movements)
- mp_input_put_key(vo->input_ctx,
+ mp_input_put_key(vo->input_ctx,
(MP_MOUSE_BTN0 + cev.data.mouse.button - 1) | MP_KEY_STATE_UP);
break;
case CACA_EVENT_KEY_PRESS:
diff --git a/video/out/vo_direct3d.c b/video/out/vo_direct3d.c
index 902d437..c942c96 100644
--- a/video/out/vo_direct3d.c
+++ b/video/out/vo_direct3d.c
@@ -674,7 +674,7 @@ static void fill_d3d_presentparams(d3d_priv *priv,
present_params->SwapEffect =
priv->opt_swap_discard ? D3DSWAPEFFECT_DISCARD : D3DSWAPEFFECT_COPY;
present_params->Flags = D3DPRESENTFLAG_VIDEO;
- present_params->hDeviceWindow = priv->vo->w32->window;
+ present_params->hDeviceWindow = vo_w32_hwnd(priv->vo);
present_params->BackBufferWidth = priv->cur_backbuf_width;
present_params->BackBufferHeight = priv->cur_backbuf_height;
present_params->MultiSampleType = D3DMULTISAMPLE_NONE;
@@ -713,7 +713,7 @@ static bool change_d3d_backbuffer(d3d_priv *priv)
if (!priv->d3d_device) {
if (FAILED(IDirect3D9_CreateDevice(priv->d3d_handle,
D3DADAPTER_DEFAULT,
- DEVTYPE, priv->vo->w32->window,
+ DEVTYPE, vo_w32_hwnd(priv->vo),
D3DCREATE_SOFTWARE_VERTEXPROCESSING
| D3DCREATE_FPU_PRESERVE,
&present_params, &priv->d3d_device)))
@@ -772,7 +772,8 @@ static bool resize_d3d(d3d_priv *priv)
{
D3DVIEWPORT9 vp = {0, 0, priv->vo->dwidth, priv->vo->dheight, 0, 1};
- MP_VERBOSE(priv, "resize_d3d called.\n");
+ MP_VERBOSE(priv, "resize_d3d %dx%d called.\n",
+ priv->vo->dwidth, priv->vo->dheight);
/* Make sure that backbuffer is large enough to accomodate the new
viewport dimensions. Grow it if necessary. */
@@ -792,7 +793,7 @@ static bool resize_d3d(d3d_priv *priv)
return 0;
}
- if (!priv->d3d_device)
+ if (!priv->d3d_device || !priv->image_format)
return 1;
if (!create_d3d_surfaces(priv))
@@ -1479,9 +1480,9 @@ static mp_image_t *get_window_screenshot(d3d_priv *priv)
goto error_exit;
}
- GetClientRect(priv->vo->w32->window, &window_rc);
+ GetClientRect(vo_w32_hwnd(priv->vo), &window_rc);
pt = (POINT) { 0, 0 };
- ClientToScreen(priv->vo->w32->window, &pt);
+ ClientToScreen(vo_w32_hwnd(priv->vo), &pt);
window_rc.left = pt.x;
window_rc.top = pt.y;
window_rc.right += window_rc.left;
diff --git a/video/out/vo_opengl.c b/video/out/vo_opengl.c
index c6464f0..7e6a03b 100644
--- a/video/out/vo_opengl.c
+++ b/video/out/vo_opengl.c
@@ -60,6 +60,7 @@ struct gl_priv {
struct gl_video *renderer;
struct gl_hwdec *hwdec;
+ struct mp_hwdec_info hwdec_info;
// Options
struct gl_video_opts *renderer_opts;
@@ -183,7 +184,6 @@ static int reconfig(struct vo *vo, struct mp_image_params *params, int flags)
return 0;
}
-
static void load_hwdec_driver(struct gl_priv *p,
const struct gl_hwdec_driver *drv)
{
@@ -193,7 +193,7 @@ static void load_hwdec_driver(struct gl_priv *p,
.driver = drv,
.log = mp_log_new(hwdec, p->vo->log, drv->api_name),
.mpgl = p->glctx,
- .info = talloc_zero(hwdec, struct mp_hwdec_info),
+ .info = &p->hwdec_info,
.gl_texture_target = GL_TEXTURE_2D,
};
mpgl_lock(p->glctx);
@@ -208,9 +208,8 @@ static void load_hwdec_driver(struct gl_priv *p,
mpgl_unlock(p->glctx);
}
-static void request_hwdec_api(struct mp_hwdec_info *info, const char *api_name)
+static void request_hwdec_api(struct gl_priv *p, const char *api_name)
{
- struct gl_priv *p = info->load_api_ctx;
// Load at most one hwdec API
if (p->hwdec)
return;
@@ -218,24 +217,18 @@ static void request_hwdec_api(struct mp_hwdec_info *info, const char *api_name)
const struct gl_hwdec_driver *drv = mpgl_hwdec_drivers[n];
if (api_name && strcmp(drv->api_name, api_name) == 0) {
load_hwdec_driver(p, drv);
- if (p->hwdec) {
- *info = *p->hwdec->info;
+ if (p->hwdec)
return;
- }
}
}
}
-static void get_hwdec_info(struct gl_priv *p, struct mp_hwdec_info *info)
+static void call_request_hwdec_api(struct mp_hwdec_info *info,
+ const char *api_name)
{
- if (p->hwdec) {
- *info = *p->hwdec->info;
- } else {
- *info = (struct mp_hwdec_info) {
- .load_api = request_hwdec_api,
- .load_api_ctx = p,
- };
- }
+ struct vo *vo = info->load_api_ctx;
+ assert(&((struct gl_priv *)vo->priv)->hwdec_info == info);
+ request_hwdec_api(vo->priv, api_name);
}
static void unload_hwdec_driver(struct gl_priv *p)
@@ -363,7 +356,8 @@ static int control(struct vo *vo, uint32_t request, void *data)
return true;
}
case VOCTRL_GET_HWDEC_INFO: {
- get_hwdec_info(p, data);
+ struct mp_hwdec_info **arg = data;
+ *arg = &p->hwdec_info;
return true;
}
case VOCTRL_REDRAW_FRAME:
@@ -432,6 +426,9 @@ static int preinit(struct vo *vo)
mpgl_unset_context(p->glctx);
+ p->hwdec_info.load_api = call_request_hwdec_api;
+ p->hwdec_info.load_api_ctx = vo;
+
return 0;
err_out:
diff --git a/video/out/vo_opengl_old.c b/video/out/vo_opengl_old.c
index d9c7e8b..87ba480 100644
--- a/video/out/vo_opengl_old.c
+++ b/video/out/vo_opengl_old.c
@@ -28,12 +28,12 @@
#include <string.h>
#include <math.h>
#include <stdbool.h>
-#include <ctype.h>
#include <assert.h>
#include "config.h"
#include "talloc.h"
#include "common/msg.h"
+#include "misc/ctype.h"
#include "options/m_option.h"
#include "vo.h"
#include "video/vfcap.h"
@@ -538,7 +538,7 @@ static void replace_var_str(char **text, const char *name, const char *replace)
nextvar += namelen;
// try not to replace prefixes of other vars (e.g. $foo vs. $foo_bar)
char term = nextvar[0];
- if (isalnum(term) || term == '_')
+ if (mp_isalnum(term) || term == '_')
continue;
int prelength = until - *text;
int postlength = nextvar - *text;
diff --git a/video/out/vo_sdl.c b/video/out/vo_sdl.c
index 64d0916..ee8e0d8 100644
--- a/video/out/vo_sdl.c
+++ b/video/out/vo_sdl.c
@@ -603,7 +603,7 @@ static void check_events(struct vo *vo)
break;
}
case SDL_MOUSEMOTION:
- vo_mouse_movement(vo, ev.motion.x, ev.motion.y);
+ mp_input_set_mouse_pos(vo->input_ctx, ev.motion.x, ev.motion.y);
break;
case SDL_MOUSEBUTTONDOWN:
mp_input_put_key(vo->input_ctx,
@@ -825,7 +825,7 @@ static int preinit(struct vo *vo)
vc->reinit_renderer = true;
// we don't have proper event handling
- vo->wakeup_period = 0.02;
+ vo->wakeup_period = 0.2;
return 0;
}
@@ -952,9 +952,9 @@ static int set_eq(struct vo *vo, const char *name, int value)
{
struct priv *vc = vo->priv;
- if (!strcasecmp(name, "brightness"))
+ if (!strcmp(name, "brightness"))
vc->brightness = value;
- else if (!strcasecmp(name, "contrast"))
+ else if (!strcmp(name, "contrast"))
vc->contrast = value;
else
return VO_NOTIMPL;
@@ -968,9 +968,9 @@ static int get_eq(struct vo *vo, const char *name, int *value)
{
struct priv *vc = vo->priv;
- if (!strcasecmp(name, "brightness"))
+ if (!strcmp(name, "brightness"))
*value = vc->brightness;
- else if (!strcasecmp(name, "contrast"))
+ else if (!strcmp(name, "contrast"))
*value = vc->contrast;
else
return VO_NOTIMPL;
diff --git a/video/out/vo_vaapi.c b/video/out/vo_vaapi.c
index 16218dd..3c760ac 100644
--- a/video/out/vo_vaapi.c
+++ b/video/out/vo_vaapi.c
@@ -70,6 +70,7 @@ struct priv {
struct vo *vo;
VADisplay display;
struct mp_vaapi_ctx *mpvaapi;
+ struct mp_hwdec_info hwdec_info;
struct mp_image_params image_params;
struct mp_rect src_rect;
@@ -442,13 +443,13 @@ static void draw_osd(struct vo *vo)
static int get_displayattribtype(const char *name)
{
- if (!strcasecmp(name, "brightness"))
+ if (!strcmp(name, "brightness"))
return VADisplayAttribBrightness;
- else if (!strcasecmp(name, "contrast"))
+ else if (!strcmp(name, "contrast"))
return VADisplayAttribContrast;
- else if (!strcasecmp(name, "saturation"))
+ else if (!strcmp(name, "saturation"))
return VADisplayAttribSaturation;
- else if (!strcasecmp(name, "hue"))
+ else if (!strcmp(name, "hue"))
return VADisplayAttribHue;
return -1;
}
@@ -516,8 +517,8 @@ static int control(struct vo *vo, uint32_t request, void *data)
p->deint = *(int*)data ? p->deint_type : 0;
return VO_TRUE;
case VOCTRL_GET_HWDEC_INFO: {
- struct mp_hwdec_info *arg = data;
- arg->vaapi_ctx = p->mpvaapi;
+ struct mp_hwdec_info **arg = data;
+ *arg = &p->hwdec_info;
return true;
}
case VOCTRL_GET_COLORSPACE: {
@@ -598,6 +599,8 @@ static int preinit(struct vo *vo)
goto fail;
}
+ p->hwdec_info.vaapi_ctx = p->mpvaapi;
+
if (va_guess_if_emulated(p->mpvaapi)) {
MP_WARN(vo, "VA-API is most likely emulated via VDPAU.\n"
"It's better to use VDPAU directly with: --vo=vdpau\n");
diff --git a/video/out/vo_vdpau.c b/video/out/vo_vdpau.c
index 56a52d6..7cf1154 100644
--- a/video/out/vo_vdpau.c
+++ b/video/out/vo_vdpau.c
@@ -73,6 +73,7 @@ struct vdpctx {
struct vdp_functions *vdp;
VdpDevice vdp_device;
uint64_t preemption_counter;
+ struct mp_hwdec_info hwdec_info;
struct m_color colorkey;
@@ -847,28 +848,21 @@ static void draw_image(struct vo *vo, struct mp_image *mpi)
{
struct vdpctx *vc = vo->priv;
- talloc_free(vc->current_image);
- vc->current_image = mpi;
-
- if (status_ok(vo))
- video_to_output_surface(vo);
-}
-
-static struct mp_image *filter_image(struct vo *vo, struct mp_image *mpi)
-{
- struct vdpctx *vc = vo->priv;
-
check_preemption(vo);
- struct mp_image *reserved_mpi = mp_vdpau_upload_video_surface(vc->mpvdp, mpi);
- if (!reserved_mpi)
- goto end;
+ struct mp_image *vdp_mpi = mp_vdpau_upload_video_surface(vc->mpvdp, mpi);
+ if (vdp_mpi) {
+ mp_image_copy_attributes(vdp_mpi, mpi);
+ } else {
+ MP_ERR(vo, "Could not upload image.\n");
+ }
+ talloc_free(mpi);
- mp_image_copy_attributes(reserved_mpi, mpi);
+ talloc_free(vc->current_image);
+ vc->current_image = vdp_mpi;
-end:
- talloc_free(mpi);
- return reserved_mpi;
+ if (status_ok(vo))
+ video_to_output_surface(vo);
}
// warning: the size and pixel format of surface must match that of the
@@ -1011,6 +1005,8 @@ static int preinit(struct vo *vo)
return -1;
}
+ vc->hwdec_info.vdpau_ctx = vc->mpvdp;
+
vc->video_mixer = mp_vdpau_mixer_create(vc->mpvdp, vo->log);
if (mp_vdpau_guess_if_emulated(vc->mpvdp)) {
@@ -1077,8 +1073,8 @@ static int control(struct vo *vo, uint32_t request, void *data)
vo->want_redraw = true;
return true;
case VOCTRL_GET_HWDEC_INFO: {
- struct mp_hwdec_info *arg = data;
- arg->vdpau_ctx = vc->mpvdp;
+ struct mp_hwdec_info **arg = data;
+ *arg = &vc->hwdec_info;
return true;
}
case VOCTRL_GET_PANSCAN:
@@ -1148,7 +1144,6 @@ const struct vo_driver video_out_vdpau = {
.reconfig = reconfig,
.control = control,
.draw_image = draw_image,
- .filter_image = filter_image,
.flip_page_timed = flip_page_timed,
.uninit = uninit,
.priv_size = sizeof(struct vdpctx),
diff --git a/video/out/vo_wayland.c b/video/out/vo_wayland.c
index be9966e..2abb2b5 100644
--- a/video/out/vo_wayland.c
+++ b/video/out/vo_wayland.c
@@ -40,6 +40,7 @@
#include "sub/img_convert.h"
#include "common/msg.h"
+#include "input/input.h"
#include "wayland_common.h"
#include "wayland-version.h"
@@ -501,6 +502,8 @@ static bool resize(struct priv *p)
p->dst_w = p->dst.x1 - p->dst.x0;
p->dst_h = p->dst.y1 - p->dst.y0;
+ mp_input_set_mouse_transform(p->vo->input_ctx, &p->dst, NULL);
+
MP_DBG(wl, "resizing %dx%d -> %dx%d\n", wl->window.width,
wl->window.height,
p->dst_w,
@@ -898,15 +901,6 @@ static int control(struct vo *vo, uint32_t request, void *data)
return VO_TRUE;
case VOCTRL_REDRAW_FRAME:
return redraw_frame(p);
- case VOCTRL_WINDOW_TO_OSD_COORDS:
- {
- // OSD is rendered into the scaled image
- float *c = data;
- struct mp_rect *dst = &p->dst;
- c[0] = av_clipf(c[0], dst->x0, dst->x1) - dst->x0;
- c[1] = av_clipf(c[1], dst->y0, dst->y1) - dst->y0;
- return VO_TRUE;
- }
case VOCTRL_SCREENSHOT:
{
struct voctrl_screenshot_args *args = data;
diff --git a/video/out/vo_x11.c b/video/out/vo_x11.c
index 63c256c..b3fd88d 100644
--- a/video/out/vo_x11.c
+++ b/video/out/vo_x11.c
@@ -24,7 +24,6 @@
#include <sys/types.h>
#include <libswscale/swscale.h>
-#include <libavutil/common.h>
#include "config.h"
#include "vo.h"
@@ -53,11 +52,10 @@
#include "video/fmt-conversion.h"
#include "common/msg.h"
+#include "input/input.h"
#include "options/options.h"
#include "osdep/timer.h"
-extern int sws_flags;
-
struct priv {
struct vo *vo;
@@ -335,10 +333,12 @@ static bool resize(struct vo *vo)
// between window and video rectangle (i.e. not into panscan borders).
p->osd.w = p->dst_w;
p->osd.h = p->dst_h;
- p->osd.mt = FFMIN(0, p->osd.mt);
- p->osd.mb = FFMIN(0, p->osd.mb);
- p->osd.mr = FFMIN(0, p->osd.mr);
- p->osd.ml = FFMIN(0, p->osd.ml);
+ p->osd.mt = MPMIN(0, p->osd.mt);
+ p->osd.mb = MPMIN(0, p->osd.mb);
+ p->osd.mr = MPMIN(0, p->osd.mr);
+ p->osd.ml = MPMIN(0, p->osd.ml);
+
+ mp_input_set_mouse_transform(vo->input_ctx, &p->dst, NULL);
p->image_width = (p->dst_w + 7) & (~7);
p->image_height = p->dst_h;
@@ -622,14 +622,6 @@ static int control(struct vo *vo, uint32_t request, void *data)
case VOCTRL_REDRAW_FRAME:
draw_image(vo, p->original_image);
return true;
- case VOCTRL_WINDOW_TO_OSD_COORDS: {
- // OSD is rendered into the scaled image
- float *c = data;
- struct mp_rect *dst = &p->dst;
- c[0] = av_clipf(c[0], dst->x0, dst->x1) - dst->x0;
- c[1] = av_clipf(c[1], dst->y0, dst->y1) - dst->y0;
- return VO_TRUE;
- }
case VOCTRL_SCREENSHOT: {
struct voctrl_screenshot_args *args = data;
args->out_image = get_screenshot(vo);
diff --git a/video/out/vo_xv.c b/video/out/vo_xv.c
index dcc9257..1ea1655 100644
--- a/video/out/vo_xv.c
+++ b/video/out/vo_xv.c
@@ -57,6 +57,7 @@
#include "sub/draw_bmp.h"
#include "video/csputils.h"
#include "options/m_option.h"
+#include "input/input.h"
#include "osdep/timer.h"
#define CK_METHOD_NONE 0 // no colorkey drawing
@@ -140,29 +141,29 @@ static int xv_find_atom(struct vo *vo, uint32_t xv_port, const char *name,
then trigger it if it's ok so that the other values are at default upon query */
if (atom != None) {
if (!strcmp(attributes[i].name, "XV_BRIGHTNESS") &&
- (!strcasecmp(name, "brightness")))
+ (!strcmp(name, "brightness")))
break;
else if (!strcmp(attributes[i].name, "XV_CONTRAST") &&
- (!strcasecmp(name, "contrast")))
+ (!strcmp(name, "contrast")))
break;
else if (!strcmp(attributes[i].name, "XV_SATURATION") &&
- (!strcasecmp(name, "saturation")))
+ (!strcmp(name, "saturation")))
break;
else if (!strcmp(attributes[i].name, "XV_HUE") &&
- (!strcasecmp(name, "hue")))
+ (!strcmp(name, "hue")))
break;
if (!strcmp(attributes[i].name, "XV_RED_INTENSITY") &&
- (!strcasecmp(name, "red_intensity")))
+ (!strcmp(name, "red_intensity")))
break;
else if (!strcmp(attributes[i].name, "XV_GREEN_INTENSITY")
- && (!strcasecmp(name, "green_intensity")))
+ && (!strcmp(name, "green_intensity")))
break;
else if (!strcmp(attributes[i].name, "XV_BLUE_INTENSITY")
- && (!strcasecmp(name, "blue_intensity")))
+ && (!strcmp(name, "blue_intensity")))
break;
else if ((!strcmp(attributes[i].name, "XV_ITURBT_709") //NVIDIA
|| !strcmp(attributes[i].name, "XV_COLORSPACE")) //ATI
- && (!strcasecmp(name, "bt_709")))
+ && (!strcmp(name, "bt_709")))
break;
atom = None;
continue;
@@ -412,6 +413,8 @@ static void resize(struct vo *vo)
xv_draw_colorkey(vo, &ctx->dst_rect);
read_xv_csp(vo);
+ mp_input_set_mouse_transform(vo->input_ctx, &ctx->dst_rect, &ctx->src_rect);
+
vo->want_redraw = true;
}
@@ -843,16 +846,6 @@ static int control(struct vo *vo, uint32_t request, void *data)
args->out_image = get_screenshot(vo);
return true;
}
- case VOCTRL_WINDOW_TO_OSD_COORDS: {
- float *c = data;
- struct mp_rect *src = &ctx->src_rect;
- struct mp_rect *dst = &ctx->dst_rect;
- c[0] = av_clipf(c[0], dst->x0, dst->x1) - dst->x0;
- c[1] = av_clipf(c[1], dst->y0, dst->y1) - dst->y0;
- c[0] = c[0] / (dst->x1 - dst->x0) * (src->x1 - src->x0) + src->x0;
- c[1] = c[1] / (dst->y1 - dst->y0) * (src->y1 - src->y0) + src->y0;
- return VO_TRUE;
- }
}
int events = 0;
int r = vo_x11_control(vo, &events, request, data);
diff --git a/video/out/w32_common.c b/video/out/w32_common.c
index 96e8c69..f59c3cc 100644
--- a/video/out/w32_common.c
+++ b/video/out/w32_common.c
@@ -18,6 +18,7 @@
#include <stdio.h>
#include <limits.h>
+#include <pthread.h>
#include <assert.h>
#include <windows.h>
#include <windowsx.h>
@@ -34,18 +35,74 @@
#include "w32_common.h"
#include "osdep/io.h"
#include "osdep/w32_keyboard.h"
+#include "misc/dispatch.h"
+#include "misc/rendezvous.h"
#include "talloc.h"
#define WIN_ID_TO_HWND(x) ((HWND)(intptr_t)(x))
static const wchar_t classname[] = L"mpv";
+static __thread struct vo_w32_state *w32_thread_context;
+
+struct vo_w32_state {
+ struct mp_log *log;
+ struct vo *vo;
+ struct mp_vo_opts *opts;
+ struct input_ctx *input_ctx;
+
+ pthread_t thread;
+ bool terminate;
+ struct mp_dispatch_queue *dispatch; // used to run stuff on the GUI thread
+
+ HWND window;
+
+ // Size and virtual position of the current screen.
+ struct mp_rect screenrc;
+
+ // last non-fullscreen extends (updated only on fullscreen or on initialization)
+ int prev_width;
+ int prev_height;
+ int prev_x;
+ int prev_y;
+
+ // whether the window position and size were intialized
+ bool window_bounds_initialized;
+
+ bool current_fs;
+
+ // currently known window state
+ int window_x;
+ int window_y;
+ int dw;
+ int dh;
+
+ // video size
+ uint32_t o_dwidth;
+ uint32_t o_dheight;
+
+ bool disable_screensaver;
+ bool cursor_visible;
+ int event_flags;
+ int mon_cnt;
+ int mon_id;
+
+ BOOL tracking;
+ TRACKMOUSEEVENT trackEvent;
+
+ int mouse_x;
+ int mouse_y;
+
+ // UTF-16 decoding state for WM_CHAR and VK_PACKET
+ int high_surrogate;
+};
+
typedef struct tagDropTarget {
IDropTarget iface;
ULONG refCnt;
DWORD lastEffect;
IDataObject* dataObj;
- struct vo *vo;
+ struct vo_w32_state *w32;
} DropTarget;
static FORMATETC fmtetc_file = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
@@ -173,17 +230,17 @@ static HRESULT STDMETHODCALLTYPE DropTarget_Drop(IDropTarget* This,
char* fname = mp_to_utf8(files, buf);
files[nrecvd_files++] = fname;
- MP_VERBOSE(t->vo, "win32: received dropped file: %s\n",
+ MP_VERBOSE(t->w32, "received dropped file: %s\n",
fname);
} else {
- MP_ERR(t->vo, "win32: error getting dropped file name\n");
+ MP_ERR(t->w32, "error getting dropped file name\n");
}
talloc_free(buf);
}
GlobalUnlock(medium.hGlobal);
- mp_event_drop_files(t->vo->input_ctx, nrecvd_files, files);
+ mp_event_drop_files(t->w32->input_ctx, nrecvd_files, files);
talloc_free(files);
}
@@ -194,11 +251,11 @@ static HRESULT STDMETHODCALLTYPE DropTarget_Drop(IDropTarget* This,
// get the URL encoded in US-ASCII
char* url = (char*)GlobalLock(medium.hGlobal);
if (url != NULL) {
- if (mp_event_drop_mime_data(t->vo->input_ctx, "text/uri-list",
+ if (mp_event_drop_mime_data(t->w32->input_ctx, "text/uri-list",
bstr0(url)) > 0) {
- MP_VERBOSE(t->vo, "win32: received dropped URL: %s\n", url);
+ MP_VERBOSE(t->w32, "received dropped URL: %s\n", url);
} else {
- MP_ERR(t->vo, "win32: error getting dropped URL\n");
+ MP_ERR(t->w32, "error getting dropped URL\n");
}
GlobalUnlock(medium.hGlobal);
@@ -216,7 +273,7 @@ static HRESULT STDMETHODCALLTYPE DropTarget_Drop(IDropTarget* This,
}
-static void DropTarget_Init(DropTarget* This, struct vo *vo)
+static void DropTarget_Init(DropTarget* This, struct vo_w32_state *w32)
{
IDropTargetVtbl* vtbl = talloc(This, IDropTargetVtbl);
*vtbl = (IDropTargetVtbl){
@@ -229,7 +286,7 @@ static void DropTarget_Init(DropTarget* This, struct vo *vo)
This->refCnt = 0;
This->lastEffect = 0;
This->dataObj = NULL;
- This->vo = vo;
+ This->w32 = w32;
}
static void add_window_borders(HWND hwnd, RECT *rc)
@@ -265,24 +322,24 @@ static int get_resize_border(int v)
}
}
-static bool key_state(struct vo *vo, int vk)
+static bool key_state(int vk)
{
return GetKeyState(vk) & 0x8000;
}
-static int mod_state(struct vo *vo)
+static int mod_state(struct vo_w32_state *w32)
{
int res = 0;
// AltGr is represented as LCONTROL+RMENU on Windows
- bool alt_gr = mp_input_use_alt_gr(vo->input_ctx) &&
- key_state(vo, VK_RMENU) && key_state(vo, VK_LCONTROL);
+ bool alt_gr = mp_input_use_alt_gr(w32->input_ctx) &&
+ key_state(VK_RMENU) && key_state(VK_LCONTROL);
- if (key_state(vo, VK_RCONTROL) || (key_state(vo, VK_LCONTROL) && !alt_gr))
+ if (key_state(VK_RCONTROL) || (key_state(VK_LCONTROL) && !alt_gr))
res |= MP_KEY_MODIFIER_CTRL;
- if (key_state(vo, VK_SHIFT))
+ if (key_state(VK_SHIFT))
res |= MP_KEY_MODIFIER_SHIFT;
- if (key_state(vo, VK_LMENU) || (key_state(vo, VK_RMENU) && !alt_gr))
+ if (key_state(VK_LMENU) || (key_state(VK_RMENU) && !alt_gr))
res |= MP_KEY_MODIFIER_ALT;
return res;
}
@@ -292,10 +349,8 @@ static int decode_surrogate_pair(wchar_t lead, wchar_t trail)
return 0x10000 + ((lead & 0x3ff) << 10) | (trail & 0x3ff);
}
-static int decode_utf16(struct vo *vo, wchar_t c)
+static int decode_utf16(struct vo_w32_state *w32, wchar_t c)
{
- struct vo_w32_state *w32 = vo->w32;
-
// Decode UTF-16, keeping state in w32->high_surrogate
if (IS_HIGH_SURROGATE(c)) {
w32->high_surrogate = c;
@@ -303,7 +358,7 @@ static int decode_utf16(struct vo *vo, wchar_t c)
}
if (IS_LOW_SURROGATE(c)) {
if (!w32->high_surrogate) {
- MP_ERR(vo, "Invalid UTF-16 input\n");
+ MP_ERR(w32, "Invalid UTF-16 input\n");
return 0;
}
int codepoint = decode_surrogate_pair(w32->high_surrogate, c);
@@ -312,7 +367,7 @@ static int decode_utf16(struct vo *vo, wchar_t c)
}
if (w32->high_surrogate != 0) {
w32->high_surrogate = 0;
- MP_ERR(vo, "Invalid UTF-16 input\n");
+ MP_ERR(w32, "Invalid UTF-16 input\n");
return 0;
}
@@ -362,7 +417,7 @@ static int to_unicode(UINT vkey, UINT scancode, const BYTE keys[256])
return 0;
}
-static int decode_key(struct vo *vo, UINT vkey, UINT scancode)
+static int decode_key(struct vo_w32_state *w32, UINT vkey, UINT scancode)
{
BYTE keys[256];
GetKeyboardState(keys);
@@ -371,7 +426,7 @@ static int decode_key(struct vo *vo, UINT vkey, UINT scancode)
// characters are generated. Note that AltGr is represented as
// LCONTROL+RMENU on Windows.
if ((keys[VK_RMENU] & 0x80) && (keys[VK_LCONTROL] & 0x80) &&
- !mp_input_use_alt_gr(vo->input_ctx))
+ !mp_input_use_alt_gr(w32->input_ctx))
{
keys[VK_RMENU] = keys[VK_LCONTROL] = 0;
keys[VK_MENU] = keys[VK_LMENU];
@@ -396,11 +451,11 @@ static int decode_key(struct vo *vo, UINT vkey, UINT scancode)
// Decode lone UTF-16 surrogates (VK_PACKET can generate these)
if (c < 0x10000)
- return decode_utf16(vo, c);
+ return decode_utf16(w32, c);
return c;
}
-static void handle_key_down(struct vo *vo, UINT vkey, UINT scancode)
+static void handle_key_down(struct vo_w32_state *w32, UINT vkey, UINT scancode)
{
// Ignore key repeat
if (scancode & KF_REPEAT)
@@ -408,15 +463,15 @@ static void handle_key_down(struct vo *vo, UINT vkey, UINT scancode)
int mpkey = mp_w32_vkey_to_mpkey(vkey, scancode & KF_EXTENDED);
if (!mpkey) {
- mpkey = decode_key(vo, vkey, scancode & (0xff | KF_EXTENDED));
+ mpkey = decode_key(w32, vkey, scancode & (0xff | KF_EXTENDED));
if (!mpkey)
return;
}
- mp_input_put_key(vo->input_ctx, mpkey | mod_state(vo) | MP_KEY_STATE_DOWN);
+ mp_input_put_key(w32->input_ctx, mpkey | mod_state(w32) | MP_KEY_STATE_DOWN);
}
-static void handle_key_up(struct vo *vo, UINT vkey, UINT scancode)
+static void handle_key_up(struct vo_w32_state *w32, UINT vkey, UINT scancode)
{
switch (vkey) {
case VK_MENU:
@@ -426,65 +481,75 @@ static void handle_key_up(struct vo *vo, UINT vkey, UINT scancode)
default:
// Releasing all keys on key-up is simpler and ensures no keys can be
// get "stuck." This matches the behaviour of other VOs.
- mp_input_put_key(vo->input_ctx, MP_INPUT_RELEASE_ALL);
+ mp_input_put_key(w32->input_ctx, MP_INPUT_RELEASE_ALL);
}
}
-static bool handle_char(struct vo *vo, wchar_t wc)
+static bool handle_char(struct vo_w32_state *w32, wchar_t wc)
{
- int c = decode_utf16(vo, wc);
+ int c = decode_utf16(w32, wc);
if (c == 0)
return true;
if (c < 0x20)
return false;
- mp_input_put_key(vo->input_ctx, c | mod_state(vo));
+ mp_input_put_key(w32->input_ctx, c | mod_state(w32));
return true;
}
+static void signal_events(struct vo_w32_state *w32, int events)
+{
+ w32->event_flags |= events;
+ mp_input_wakeup(w32->input_ctx);
+}
+
+static void wakeup_gui_thread(void *ctx)
+{
+ struct vo_w32_state *w32 = ctx;
+ PostMessage(w32->window, WM_USER, 0, 0);
+}
+
static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam)
{
- if (message == WM_NCCREATE) {
- CREATESTRUCT *cs = (void*)lParam;
- SetWindowLongPtrW(hWnd, GWLP_USERDATA, (LONG_PTR)cs->lpCreateParams);
- }
- struct vo *vo = (void*)GetWindowLongPtrW(hWnd, GWLP_USERDATA);
- // message before WM_NCCREATE, pray to Raymond Chen that it's not important
- if (!vo)
- return DefWindowProcW(hWnd, message, wParam, lParam);
- struct vo_w32_state *w32 = vo->w32;
+ assert(w32_thread_context);
+ struct vo_w32_state *w32 = w32_thread_context;
+ if (!w32->window)
+ w32->window = hWnd; // can happen during CreateWindow*!
+ assert(w32->window == hWnd);
int mouse_button = 0;
switch (message) {
- case WM_ERASEBKGND: // no need to erase background seperately
+ case WM_USER:
+ // This message is used to wakeup the GUI thread, see wakeup_gui_thread.
+ mp_dispatch_queue_process(w32->dispatch, 0);
+ break;
+ case WM_ERASEBKGND: // no need to erase background separately
return 1;
case WM_PAINT:
- w32->event_flags |= VO_EVENT_EXPOSE;
+ signal_events(w32, VO_EVENT_EXPOSE);
break;
case WM_MOVE: {
POINT p = {0};
ClientToScreen(w32->window, &p);
w32->window_x = p.x;
w32->window_y = p.y;
- MP_VERBOSE(vo, "move window: %d:%d\n",
- w32->window_x, w32->window_y);
+ MP_VERBOSE(w32, "move window: %d:%d\n", w32->window_x, w32->window_y);
break;
}
case WM_SIZE: {
- w32->event_flags |= VO_EVENT_RESIZE;
RECT r;
GetClientRect(w32->window, &r);
- vo->dwidth = r.right;
- vo->dheight = r.bottom;
- MP_VERBOSE(vo, "resize window: %d:%d\n",
- vo->dwidth, vo->dheight);
+ w32->dw = r.right;
+ w32->dh = r.bottom;
+ signal_events(w32, VO_EVENT_RESIZE);
+ MP_VERBOSE(w32, "resize window: %d:%d\n", w32->dw, w32->dh);
break;
}
case WM_SIZING:
- if (vo->opts->keepaspect && !vo->opts->fullscreen &&
- vo->opts->WinID < 0)
+ if (w32->opts->keepaspect && !w32->opts->fullscreen &&
+ w32->opts->WinID < 0)
{
RECT *rc = (RECT*)lParam;
// get client area of the windows if it had the rect rc
@@ -505,14 +570,16 @@ static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
}
break;
case WM_CLOSE:
- mp_input_put_key(vo->input_ctx, MP_KEY_CLOSE_WIN);
- break;
+ // Don't actually allow it to destroy the window, or whatever else it
+ // is that will make us lose WM_USER wakeups.
+ mp_input_put_key(w32->input_ctx, MP_KEY_CLOSE_WIN);
+ return 1;
case WM_SYSCOMMAND:
switch (wParam) {
case SC_SCREENSAVE:
case SC_MONITORPOWER:
if (w32->disable_screensaver) {
- MP_VERBOSE(vo, "win32: killing screensaver\n");
+ MP_VERBOSE(w32, "killing screensaver\n");
return 0;
}
break;
@@ -520,23 +587,23 @@ static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
break;
case WM_SYSKEYDOWN:
case WM_KEYDOWN:
- handle_key_down(vo, wParam, HIWORD(lParam));
+ handle_key_down(w32, wParam, HIWORD(lParam));
if (wParam == VK_F10)
return 0;
break;
case WM_SYSKEYUP:
case WM_KEYUP:
- handle_key_up(vo, wParam, HIWORD(lParam));
+ handle_key_up(w32, wParam, HIWORD(lParam));
if (wParam == VK_F10)
return 0;
break;
case WM_CHAR:
case WM_SYSCHAR:
- if (handle_char(vo, wParam))
+ if (handle_char(w32, wParam))
return 0;
break;
case WM_KILLFOCUS:
- mp_input_put_key(vo->input_ctx, MP_INPUT_RELEASE_ALL);
+ mp_input_put_key(w32->input_ctx, MP_INPUT_RELEASE_ALL);
break;
case WM_SETCURSOR:
if (LOWORD(lParam) == HTCLIENT && !w32->cursor_visible) {
@@ -546,7 +613,7 @@ static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
break;
case WM_MOUSELEAVE:
w32->tracking = FALSE;
- mp_input_put_key(vo->input_ctx, MP_KEY_MOUSE_LEAVE);
+ mp_input_put_key(w32->input_ctx, MP_KEY_MOUSE_LEAVE);
break;
case WM_MOUSEMOVE: {
if (!w32->tracking)
@@ -559,7 +626,7 @@ static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
if (x != w32->mouse_x || y != w32->mouse_y) {
w32->mouse_x = x;
w32->mouse_y = y;
- vo_mouse_movement(vo, x, y);
+ mp_input_set_mouse_pos(w32->input_ctx, x, y);
}
break;
}
@@ -597,22 +664,22 @@ static LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam,
}
if (mouse_button) {
- mouse_button |= mod_state(vo);
- mp_input_put_key(vo->input_ctx, mouse_button);
+ mouse_button |= mod_state(w32);
+ mp_input_put_key(w32->input_ctx, mouse_button);
- if (vo->opts->enable_mouse_movements) {
+ if (mp_input_mouse_enabled(w32->input_ctx)) {
int x = GET_X_LPARAM(lParam);
int y = GET_Y_LPARAM(lParam);
if (mouse_button == (MP_MOUSE_BTN0 | MP_KEY_STATE_DOWN) &&
- !vo->opts->fullscreen &&
- !mp_input_test_dragging(vo->input_ctx, x, y))
+ !w32->opts->fullscreen &&
+ !mp_input_test_dragging(w32->input_ctx, x, y))
{
// Window dragging hack
ReleaseCapture();
SendMessage(hWnd, WM_NCLBUTTONDOWN, HTCAPTION, 0);
- mp_input_put_key(vo->input_ctx, MP_MOUSE_BTN0 |
- MP_KEY_STATE_UP);
+ mp_input_put_key(w32->input_ctx, MP_MOUSE_BTN0 |
+ MP_KEY_STATE_UP);
return 0;
}
}
@@ -632,68 +699,40 @@ static bool is_key_message(UINT msg)
msg == WM_KEYUP || msg == WM_SYSKEYUP;
}
-/**
- * \brief Dispatch incoming window events and handle them.
- *
- * This function should be placed inside libvo's function "check_events".
- *
- * \return int with these flags possibly set, take care to handle in the right order
- * if it matters in your driver:
- *
- * VO_EVENT_RESIZE = The window was resized. If necessary reinit your
- * driver render context accordingly.
- * VO_EVENT_EXPOSE = The window was exposed. Call e.g. flip_frame() to redraw
- * the window if the movie is paused.
- */
-int vo_w32_check_events(struct vo *vo)
+// Dispatch incoming window events and handle them.
+// This returns only when the thread is asked to terminate.
+static void run_message_loop(struct vo_w32_state *w32)
{
- struct vo_w32_state *w32 = vo->w32;
MSG msg;
- w32->event_flags = 0;
-
- while (PeekMessageW(&msg, 0, 0, 0, PM_REMOVE)) {
+ while (GetMessageW(&msg, 0, 0, 0) > 0) {
// Only send IME messages to TranslateMessage
if (is_key_message(msg.message) && msg.wParam == VK_PROCESSKEY)
TranslateMessage(&msg);
DispatchMessageW(&msg);
- }
-
- if (vo->opts->WinID >= 0) {
- BOOL res;
- RECT r;
- POINT p;
- res = GetClientRect(w32->window, &r);
-
- if (res && (r.right != vo->dwidth || r.bottom != vo->dheight)) {
- vo->dwidth = r.right; vo->dheight = r.bottom;
- w32->event_flags |= VO_EVENT_RESIZE;
- }
-
- p.x = 0; p.y = 0;
- ClientToScreen(w32->window, &p);
-
- if (p.x != w32->window_x || p.y != w32->window_y) {
- w32->window_x = p.x; w32->window_y = p.y;
- }
-
- res = GetClientRect(WIN_ID_TO_HWND(vo->opts->WinID), &r);
-
- if (res && (r.right != vo->dwidth || r.bottom != vo->dheight))
- MoveWindow(w32->window, 0, 0, r.right, r.bottom, FALSE);
- if (!IsWindow(WIN_ID_TO_HWND(vo->opts->WinID))) {
- // Window has probably been closed, e.g. due to program crash
- mp_input_put_key(vo->input_ctx, MP_KEY_CLOSE_WIN);
+ if (w32->opts->WinID >= 0) {
+ HWND parent = WIN_ID_TO_HWND(w32->opts->WinID);
+ RECT r, rp;
+ BOOL res = GetClientRect(w32->window, &r);
+ res = res && GetClientRect(parent, &rp);
+ if (res && (r.right != rp.right || r.bottom != rp.bottom))
+ MoveWindow(w32->window, 0, 0, rp.right, rp.bottom, FALSE);
+
+ // Window has probably been closed, e.g. due to parent program crash
+ if (!IsWindow(parent))
+ mp_input_put_key(w32->input_ctx, MP_KEY_CLOSE_WIN);
}
}
- return w32->event_flags;
+ // Even if the message loop somehow exits, we still have to respond to
+ // external requests until termination is requested.
+ while (!w32->terminate)
+ mp_dispatch_queue_process(w32->dispatch, 1000);
}
static BOOL CALLBACK mon_enum(HMONITOR hmon, HDC hdc, LPRECT r, LPARAM p)
{
- struct vo *vo = (void*)p;
- struct vo_w32_state *w32 = vo->w32;
+ struct vo_w32_state *w32 = (void *)p;
// this defaults to the last screen if specified number does not exist
w32->screenrc = (struct mp_rect){r->left, r->top, r->right, r->bottom};
@@ -704,10 +743,9 @@ static BOOL CALLBACK mon_enum(HMONITOR hmon, HDC hdc, LPRECT r, LPARAM p)
return TRUE;
}
-static void w32_update_xinerama_info(struct vo *vo)
+static void w32_update_xinerama_info(struct vo_w32_state *w32)
{
- struct vo_w32_state *w32 = vo->w32;
- struct mp_vo_opts *opts = vo->opts;
+ struct mp_vo_opts *opts = w32->opts;
int screen = opts->fullscreen ? opts->fsscreen_id : opts->screen_id;
if (opts->fullscreen && screen == -2) {
@@ -737,97 +775,94 @@ static void w32_update_xinerama_info(struct vo *vo)
} else if (screen >= 0) {
w32->mon_cnt = 0;
w32->mon_id = screen;
- EnumDisplayMonitors(NULL, NULL, mon_enum, (LONG_PTR)vo);
+ EnumDisplayMonitors(NULL, NULL, mon_enum, (LONG_PTR)w32);
}
}
-static void updateScreenProperties(struct vo *vo)
+static void updateScreenProperties(struct vo_w32_state *w32)
{
- struct vo_w32_state *w32 = vo->w32;
-
DEVMODE dm;
dm.dmSize = sizeof dm;
dm.dmDriverExtra = 0;
dm.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;
if (!EnumDisplaySettings(0, ENUM_CURRENT_SETTINGS, &dm)) {
- MP_ERR(vo, "win32: unable to enumerate display settings!\n");
+ MP_ERR(w32, "unable to enumerate display settings!\n");
return;
}
w32->screenrc = (struct mp_rect){0, 0, dm.dmPelsWidth, dm.dmPelsHeight};
- w32_update_xinerama_info(vo);
+ w32_update_xinerama_info(w32);
}
-static DWORD update_style(struct vo *vo, DWORD style)
+static DWORD update_style(struct vo_w32_state *w32, DWORD style)
{
const DWORD NO_FRAME = WS_POPUP;
const DWORD FRAME = WS_OVERLAPPEDWINDOW | WS_SIZEBOX;
style &= ~(NO_FRAME | FRAME);
- style |= (vo->opts->border && !vo->opts->fullscreen) ? FRAME : NO_FRAME;
+ style |= (w32->opts->border && !w32->opts->fullscreen) ? FRAME : NO_FRAME;
return style;
}
-// Update the window title, position, size, and border style from vo_* values.
-static int reinit_window_state(struct vo *vo)
+// Update the window title, position, size, and border style.
+static int reinit_window_state(struct vo_w32_state *w32)
{
- struct vo_w32_state *w32 = vo->w32;
HWND layer = HWND_NOTOPMOST;
RECT r;
- if (vo->opts->WinID >= 0)
+ if (w32->opts->WinID >= 0)
return 1;
- bool toggle_fs = w32->current_fs != vo->opts->fullscreen;
- w32->current_fs = vo->opts->fullscreen;
+ bool toggle_fs = w32->current_fs != w32->opts->fullscreen;
+ w32->current_fs = w32->opts->fullscreen;
- DWORD style = update_style(vo, GetWindowLong(w32->window, GWL_STYLE));
+ DWORD style = update_style(w32, GetWindowLong(w32->window, GWL_STYLE));
- if (vo->opts->ontop)
+ if (w32->opts->ontop)
layer = HWND_TOPMOST;
// xxx not sure if this can trigger any unwanted messages (WM_MOVE/WM_SIZE)
- updateScreenProperties(vo);
+ updateScreenProperties(w32);
- if (vo->opts->fullscreen) {
+ if (w32->opts->fullscreen) {
// Save window position and size when switching to fullscreen.
if (toggle_fs) {
- w32->prev_width = vo->dwidth;
- w32->prev_height = vo->dheight;
+ w32->prev_width = w32->dw;
+ w32->prev_height = w32->dh;
w32->prev_x = w32->window_x;
w32->prev_y = w32->window_y;
- MP_VERBOSE(vo, "save window bounds: %d:%d:%d:%d\n",
+ MP_VERBOSE(w32, "save window bounds: %d:%d:%d:%d\n",
w32->prev_x, w32->prev_y, w32->prev_width, w32->prev_height);
}
w32->window_x = w32->screenrc.x0;
w32->window_y = w32->screenrc.y0;
- vo->dwidth = w32->screenrc.x1 - w32->screenrc.x0;
- vo->dheight = w32->screenrc.y1 - w32->screenrc.y0;
+ w32->dw = w32->screenrc.x1 - w32->screenrc.x0;
+ w32->dh = w32->screenrc.y1 - w32->screenrc.y0;
style &= ~WS_OVERLAPPEDWINDOW;
} else {
if (toggle_fs) {
// Restore window position and size when switching from fullscreen.
- MP_VERBOSE(vo, "restore window bounds: %d:%d:%d:%d\n",
+ MP_VERBOSE(w32, "restore window bounds: %d:%d:%d:%d\n",
w32->prev_x, w32->prev_y, w32->prev_width, w32->prev_height);
- vo->dwidth = w32->prev_width;
- vo->dheight = w32->prev_height;
+ w32->dw = w32->prev_width;
+ w32->dh = w32->prev_height;
w32->window_x = w32->prev_x;
w32->window_y = w32->prev_y;
}
}
r.left = w32->window_x;
- r.right = r.left + vo->dwidth;
+ r.right = r.left + w32->dw;
r.top = w32->window_y;
- r.bottom = r.top + vo->dheight;
+ r.bottom = r.top + w32->dh;
SetWindowLong(w32->window, GWL_STYLE, style);
add_window_borders(w32->window, &r);
- MP_VERBOSE(vo, "reset window bounds: %d:%d:%d:%d\n",
- (int) r.left, (int) r.top, (int)(r.right - r.left),
- (int)(r.bottom - r.top));
+ MP_VERBOSE(w32, "reset window bounds: %d:%d:%d:%d\n",
+ (int) r.left, (int) r.top, (int)(r.right - r.left),
+ (int)(r.bottom - r.top));
SetWindowPos(w32->window, layer, r.left, r.top, r.right - r.left,
r.bottom - r.top, SWP_FRAMECHANGED);
@@ -839,53 +874,31 @@ static int reinit_window_state(struct vo *vo)
SetWindowPos(w32->window, NULL, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_SHOWWINDOW);
+ signal_events(w32, VO_EVENT_RESIZE);
+
return 1;
}
-/**
- * \brief Configure and show window on the screen.
- *
- * This function should be called in libvo's "config" callback.
- * It configures a window and shows it on the screen.
- *
- * \return 1 - Success, 0 - Failure
- */
-int vo_w32_config(struct vo *vo, uint32_t flags)
+static void gui_thread_reconfig(void *ptr)
{
- struct vo_w32_state *w32 = vo->w32;
- PIXELFORMATDESCRIPTOR pfd;
- int pf;
- HDC vo_hdc = GetDC(w32->window);
-
- memset(&pfd, 0, sizeof pfd);
- pfd.nSize = sizeof pfd;
- pfd.nVersion = 1;
- pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
-
- if (flags & VOFLAG_STEREO)
- pfd.dwFlags |= PFD_STEREO;
-
- pfd.iPixelType = PFD_TYPE_RGBA;
- pfd.cColorBits = 24;
- pfd.iLayerType = PFD_MAIN_PLANE;
- pf = ChoosePixelFormat(vo_hdc, &pfd);
-
- if (!pf) {
- MP_ERR(vo, "win32: unable to select a valid pixel format!\n");
- ReleaseDC(w32->window, vo_hdc);
- return 0;
- }
+ void **p = ptr;
+ struct vo_w32_state *w32 = p[0];
+ uint32_t flags = *(uint32_t *)p[1];
+ int *res = p[2];
- SetPixelFormat(vo_hdc, pf, &pfd);
- ReleaseDC(w32->window, vo_hdc);
+ struct vo *vo = w32->vo;
// we already have a fully initialized window, so nothing needs to be done
- if (flags & VOFLAG_HIDDEN)
- return 1;
+ if (flags & VOFLAG_HIDDEN) {
+ *res = 1;
+ return;
+ }
struct vo_win_geometry geo;
vo_calc_window_geometry(vo, &w32->screenrc, &geo);
vo_apply_window_geometry(vo, &geo);
+ w32->dw = vo->dwidth;
+ w32->dh = vo->dheight;
bool reset_size = w32->o_dwidth != vo->dwidth || w32->o_dheight != vo->dheight;
@@ -893,7 +906,7 @@ int vo_w32_config(struct vo *vo, uint32_t flags)
w32->o_dheight = vo->dheight;
// the desired size is ignored in wid mode, it always matches the window size.
- if (vo->opts->WinID < 0) {
+ if (w32->opts->WinID < 0) {
if (w32->window_bounds_initialized) {
// restore vo_dwidth/vo_dheight, which are reset against our will
// in vo_config()
@@ -919,32 +932,30 @@ int vo_w32_config(struct vo *vo, uint32_t flags)
vo->dheight = r.bottom;
}
- return reinit_window_state(vo);
+ *res = reinit_window_state(w32);
}
-/**
- * \brief Initialize w32_common framework.
- *
- * The first function that should be called from the w32_common framework.
- * It handles window creation on the screen with proper title and attributes.
- * It also initializes the framework's internal variables. The function should
- * be called after your own preinit initialization and you shouldn't do any
- * window management on your own.
- *
- * \return 1 = Success, 0 = Failure
- */
-int vo_w32_init(struct vo *vo)
+// Resize the window. On the first non-VOFLAG_HIDDEN call, it's also made visible.
+int vo_w32_config(struct vo *vo, uint32_t flags)
{
- assert(!vo->w32);
+ struct vo_w32_state *w32 = vo->w32;
+ int r;
+ void *p[] = {w32, &flags, &r};
+ mp_dispatch_run(w32->dispatch, gui_thread_reconfig, p);
+ return r;
+}
- struct vo_w32_state *w32 = talloc_zero(vo, struct vo_w32_state);
- vo->w32 = w32;
+static void *gui_thread(void *ptr)
+{
+ struct vo_w32_state *w32 = ptr;
+ bool ole_ok = false;
+ int res = 0;
HINSTANCE hInstance = GetModuleHandleW(NULL);
WNDCLASSEXW wcex = {
.cbSize = sizeof wcex,
- .style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW,
+ .style = CS_HREDRAW | CS_VREDRAW,
.lpfnWndProc = WndProc,
.hInstance = hInstance,
.hIcon = LoadIconW(hInstance, L"IDI_ICON1"),
@@ -953,38 +964,40 @@ int vo_w32_init(struct vo *vo)
};
if (!RegisterClassExW(&wcex)) {
- MP_ERR(vo, "win32: unable to register window class!\n");
- return 0;
+ MP_ERR(w32, "unable to register window class!\n");
+ goto done;
}
- if (vo->opts->WinID >= 0) {
+ w32_thread_context = w32;
+
+ if (w32->opts->WinID >= 0) {
RECT r;
- GetClientRect(WIN_ID_TO_HWND(vo->opts->WinID), &r);
- vo->dwidth = r.right; vo->dheight = r.bottom;
+ GetClientRect(WIN_ID_TO_HWND(w32->opts->WinID), &r);
w32->window = CreateWindowExW(WS_EX_NOPARENTNOTIFY, classname,
classname,
WS_CHILD | WS_VISIBLE,
- 0, 0, vo->dwidth, vo->dheight,
- WIN_ID_TO_HWND(vo->opts->WinID),
- 0, hInstance, vo);
+ 0, 0, r.right, r.bottom,
+ WIN_ID_TO_HWND(w32->opts->WinID),
+ 0, hInstance, NULL);
} else {
w32->window = CreateWindowExW(0, classname,
classname,
- update_style(vo, 0),
- CW_USEDEFAULT, 0, 100, 100,
- 0, 0, hInstance, vo);
+ update_style(w32, 0),
+ CW_USEDEFAULT, SW_HIDE, 100, 100,
+ 0, 0, hInstance, NULL);
}
if (!w32->window) {
- MP_ERR(vo, "win32: unable to create window!\n");
- return 0;
+ MP_ERR(w32, "unable to create window!\n");
+ goto done;
}
if (OleInitialize(NULL) == S_OK) {
fmtetc_url.cfFormat = (CLIPFORMAT)RegisterClipboardFormat(TEXT("UniformResourceLocator"));
DropTarget* dropTarget = talloc(NULL, DropTarget);
- DropTarget_Init(dropTarget, vo);
+ DropTarget_Init(dropTarget, w32);
RegisterDragDrop(w32->window, &dropTarget->iface);
+ ole_ok = true;
}
w32->tracking = FALSE;
@@ -994,79 +1007,97 @@ int vo_w32_init(struct vo *vo)
.hwndTrack = w32->window,
};
- if (vo->opts->WinID >= 0)
+ if (w32->opts->WinID >= 0)
EnableWindow(w32->window, 0);
w32->cursor_visible = true;
- // we don't have proper event handling
- vo->wakeup_period = 0.02;
+ updateScreenProperties(w32);
- updateScreenProperties(vo);
+ mp_dispatch_set_wakeup_fn(w32->dispatch, wakeup_gui_thread, w32);
- return 1;
-}
+ // Microsoft-recommended way to create a message queue.
+ // Needed so that initial WM_USER wakeups are not lost.
+ PeekMessage(&(MSG){0}, NULL, WM_USER, WM_USER, PM_NOREMOVE);
-/**
- * \brief Toogle fullscreen / windowed mode.
- *
- * Should be called on VOCTRL_FULLSCREEN event. The window is
- * always resized during this call, so the rendering context
- * should be reinitialized with the new dimensions.
- * It is unspecified if vo_check_events will create a resize
- * event in addition or not.
- */
+ res = 1;
+done:
-static void vo_w32_fullscreen(struct vo *vo)
-{
- if (vo->opts->fullscreen != vo->w32->current_fs)
- reinit_window_state(vo);
-}
+ mp_rendezvous(w32, res); // init barrier
-/**
- * \brief Toogle window border attribute.
- *
- * Should be called on VOCTRL_BORDER event.
- */
-static void vo_w32_border(struct vo *vo)
-{
- vo->opts->border = !vo->opts->border;
- reinit_window_state(vo);
+ // This blocks until the GUI thread is to be exited.
+ if (res)
+ run_message_loop(w32);
+
+ MP_VERBOSE(w32, "uninit\n");
+
+ if (w32->window) {
+ RevokeDragDrop(w32->window);
+ DestroyWindow(w32->window);
+ }
+ if (ole_ok)
+ OleUninitialize();
+ SetThreadExecutionState(ES_CONTINUOUS);
+ UnregisterClassW(classname, 0);
+
+ w32_thread_context = NULL;
+ return NULL;
}
-/**
- * \brief Toogle window ontop attribute.
- *
- * Should be called on VOCTRL_ONTOP event.
- */
-static void vo_w32_ontop(struct vo *vo)
+// Returns: 1 = Success, 0 = Failure
+int vo_w32_init(struct vo *vo)
{
- vo->opts->ontop = !vo->opts->ontop;
- reinit_window_state(vo);
+ assert(!vo->w32);
+
+ struct vo_w32_state *w32 = talloc_ptrtype(vo, w32);
+ *w32 = (struct vo_w32_state){
+ .log = mp_log_new(w32, vo->log, "win32"),
+ .vo = vo,
+ .opts = vo->opts,
+ .input_ctx = vo->input_ctx,
+ .dispatch = mp_dispatch_create(w32),
+ };
+ vo->w32 = w32;
+
+ if (pthread_create(&w32->thread, NULL, gui_thread, w32))
+ goto fail;
+
+ if (!mp_rendezvous(w32, 0)) { // init barrier
+ pthread_join(w32->thread, NULL);
+ goto fail;
+ }
+
+ return 1;
+fail:
+ talloc_free(w32);
+ vo->w32 = NULL;
+ return 0;
}
-static bool vo_w32_is_cursor_in_client(struct vo *vo)
+static bool vo_w32_is_cursor_in_client(struct vo_w32_state *w32)
{
DWORD pos = GetMessagePos();
- return SendMessage(vo->w32->window, WM_NCHITTEST, 0, pos) == HTCLIENT;
+ return SendMessage(w32->window, WM_NCHITTEST, 0, pos) == HTCLIENT;
}
-int vo_w32_control(struct vo *vo, int *events, int request, void *arg)
+static int gui_thread_control(struct vo_w32_state *w32, int *events,
+ int request, void *arg)
{
- struct vo_w32_state *w32 = vo->w32;
+ *events |= w32->event_flags;
+ w32->event_flags = 0;
switch (request) {
- case VOCTRL_CHECK_EVENTS:
- *events |= vo_w32_check_events(vo);
- return VO_TRUE;
case VOCTRL_FULLSCREEN:
- vo_w32_fullscreen(vo);
+ if (w32->opts->fullscreen != w32->current_fs)
+ reinit_window_state(w32);
*events |= VO_EVENT_RESIZE;
return VO_TRUE;
case VOCTRL_ONTOP:
- vo_w32_ontop(vo);
+ w32->opts->ontop = !w32->opts->ontop;
+ reinit_window_state(w32);
return VO_TRUE;
case VOCTRL_BORDER:
- vo_w32_border(vo);
+ w32->opts->border = !w32->opts->border;
+ reinit_window_state(w32);
*events |= VO_EVENT_RESIZE;
return VO_TRUE;
case VOCTRL_GET_WINDOW_SIZE: {
@@ -1075,8 +1106,8 @@ int vo_w32_control(struct vo *vo, int *events, int request, void *arg)
if (!w32->window_bounds_initialized)
return VO_FALSE;
- s[0] = w32->current_fs ? w32->prev_width : vo->dwidth;
- s[1] = w32->current_fs ? w32->prev_height : vo->dheight;
+ s[0] = w32->current_fs ? w32->prev_width : w32->dw;
+ s[1] = w32->current_fs ? w32->prev_height : w32->dh;
return VO_TRUE;
}
case VOCTRL_SET_WINDOW_SIZE: {
@@ -1088,18 +1119,18 @@ int vo_w32_control(struct vo *vo, int *events, int request, void *arg)
w32->prev_width = s[0];
w32->prev_height = s[1];
} else {
- vo->dwidth = s[0];
- vo->dheight = s[1];
+ w32->dw = s[0];
+ w32->dh = s[1];
}
- reinit_window_state(vo);
+ reinit_window_state(w32);
*events |= VO_EVENT_RESIZE;
return VO_TRUE;
}
case VOCTRL_SET_CURSOR_VISIBILITY:
w32->cursor_visible = *(bool *)arg;
- if (vo_w32_is_cursor_in_client(vo)) {
+ if (vo_w32_is_cursor_in_client(w32)) {
if (w32->cursor_visible)
SetCursor(LoadCursor(NULL, IDC_ARROW));
else
@@ -1124,26 +1155,59 @@ int vo_w32_control(struct vo *vo, int *events, int request, void *arg)
return VO_NOTIMPL;
}
-/**
- * \brief Uninitialize w32_common framework.
- *
- * Should be called last in video driver's uninit function. First release
- * anything built on top of the created window e.g. rendering context inside
- * and call vo_w32_uninit at the end.
- */
-void vo_w32_uninit(struct vo *vo)
+static void do_control(void *ptr)
+{
+ void **p = ptr;
+ struct vo_w32_state *w32 = p[0];
+ int *events = p[1];
+ int request = *(int *)p[2];
+ void *arg = p[3];
+ int *ret = p[4];
+ *ret = gui_thread_control(w32, events, request, arg);
+ // Safe access, since caller (owner of vo) is blocked.
+ if (*events & VO_EVENT_RESIZE) {
+ w32->vo->dwidth = w32->dw;
+ w32->vo->dheight = w32->dh;
+ }
+}
+
+int vo_w32_control(struct vo *vo, int *events, int request, void *arg)
{
struct vo_w32_state *w32 = vo->w32;
- MP_VERBOSE(vo, "win32: uninit\n");
+ int r;
+ void *p[] = {w32, events, &request, arg, &r};
+ mp_dispatch_run(w32->dispatch, do_control, p);
+ return r;
+}
+static void do_terminate(void *ptr)
+{
+ struct vo_w32_state *w32 = ptr;
+ w32->terminate = true;
+ PostQuitMessage(0);
+}
+
+void vo_w32_uninit(struct vo *vo)
+{
+ struct vo_w32_state *w32 = vo->w32;
if (!w32)
return;
- RevokeDragDrop(w32->window);
- OleUninitialize();
- SetThreadExecutionState(ES_CONTINUOUS);
- DestroyWindow(w32->window);
- UnregisterClassW(classname, 0);
+ mp_dispatch_run(w32->dispatch, do_terminate, w32);
+ pthread_join(w32->thread, NULL);
+
talloc_free(w32);
vo->w32 = NULL;
}
+
+HWND vo_w32_hwnd(struct vo *vo)
+{
+ struct vo_w32_state *w32 = vo->w32;
+ return w32->window; // immutable, so no synchronization needed
+}
+
+void vo_w32_run_on_thread(struct vo *vo, void (*cb)(void *ctx), void *ctx)
+{
+ struct vo_w32_state *w32 = vo->w32;
+ mp_dispatch_run(w32->dispatch, cb, ctx);
+}
diff --git a/video/out/w32_common.h b/video/out/w32_common.h
index 89d4abf..d5c9f07 100644
--- a/video/out/w32_common.h
+++ b/video/out/w32_common.h
@@ -25,52 +25,13 @@
#include "common/common.h"
-struct vo_w32_state {
- HWND window;
-
- // Size and virtual position of the current screen.
- struct mp_rect screenrc;
-
- // last non-fullscreen extends (updated only on fullscreen or on initialization)
- int prev_width;
- int prev_height;
- int prev_x;
- int prev_y;
-
- // whether the window position and size were intialized
- bool window_bounds_initialized;
-
- bool current_fs;
-
- int window_x;
- int window_y;
-
- // video size
- uint32_t o_dwidth;
- uint32_t o_dheight;
-
- bool disable_screensaver;
- bool cursor_visible;
- int event_flags;
- int mon_cnt;
- int mon_id;
-
- BOOL tracking;
- TRACKMOUSEEVENT trackEvent;
-
- int mouse_x;
- int mouse_y;
-
- // UTF-16 decoding state for WM_CHAR and VK_PACKET
- int high_surrogate;
-};
-
struct vo;
int vo_w32_init(struct vo *vo);
void vo_w32_uninit(struct vo *vo);
int vo_w32_control(struct vo *vo, int *events, int request, void *arg);
-int vo_w32_check_events(struct vo *vo);
int vo_w32_config(struct vo *vo, uint32_t);
+HWND vo_w32_hwnd(struct vo *vo);
+void vo_w32_run_on_thread(struct vo *vo, void (*cb)(void *ctx), void *ctx);
#endif /* MPLAYER_W32_COMMON_H */
diff --git a/video/out/wayland_common.c b/video/out/wayland_common.c
index fe6142c..0a02ee2 100644
--- a/video/out/wayland_common.c
+++ b/video/out/wayland_common.c
@@ -54,6 +54,8 @@ static int lookupkey(int key);
static void hide_cursor(struct vo_wayland_state * wl);
static void show_cursor(struct vo_wayland_state * wl);
+static void window_move(struct vo_wayland_state * wl, uint32_t serial);
+static void window_set_title(struct vo_wayland_state * wl, const char *title);
static void schedule_resize(struct vo_wayland_state *wl,
uint32_t edges,
int32_t width,
@@ -340,8 +342,8 @@ static void pointer_handle_motion(void *data,
wl->window.mouse_x = wl_fixed_to_int(sx_w);
wl->window.mouse_y = wl_fixed_to_int(sy_w);
- vo_mouse_movement(wl->vo, wl->window.mouse_x,
- wl->window.mouse_y);
+ mp_input_set_mouse_pos(wl->vo->input_ctx, wl->window.mouse_x,
+ wl->window.mouse_y);
}
static void pointer_handle_button(void *data,
@@ -359,7 +361,7 @@ static void pointer_handle_button(void *data,
if (!mp_input_test_dragging(wl->vo->input_ctx, wl->window.mouse_x, wl->window.mouse_y) &&
(button == BTN_LEFT) && (state == WL_POINTER_BUTTON_STATE_PRESSED))
- wl_shell_surface_move(wl->window.shell_surface, wl->input.seat, serial);
+ window_move(wl, serial);
}
static void pointer_handle_axis(void *data,
@@ -638,6 +640,24 @@ static void show_cursor (struct vo_wayland_state *wl)
wl_surface_commit(wl->cursor.surface);
}
+static void window_move(struct vo_wayland_state *wl, uint32_t serial)
+{
+ if (wl->display.shell)
+ wl_shell_surface_move(wl->window.shell_surface, wl->input.seat, serial);
+}
+
+static void window_set_toplevel(struct vo_wayland_state *wl)
+{
+ if (wl->display.shell)
+ wl_shell_surface_set_toplevel(wl->window.shell_surface);
+}
+
+static void window_set_title(struct vo_wayland_state *wl, const char *title)
+{
+ if (wl->display.shell)
+ wl_shell_surface_set_title(wl->window.shell_surface, title);
+}
+
static void schedule_resize(struct vo_wayland_state *wl,
uint32_t edges,
int32_t width,
@@ -763,19 +783,22 @@ static bool create_window (struct vo_wayland_state *wl)
{
wl->window.video_surface =
wl_compositor_create_surface(wl->display.compositor);
- wl->window.shell_surface =
- wl_shell_get_shell_surface(wl->display.shell, wl->window.video_surface);
- if (!wl->window.shell_surface) {
- MP_ERR(wl, "creating shell surface failed\n");
- return false;
- }
+ if (wl->display.shell) {
+ wl->window.shell_surface = wl_shell_get_shell_surface(wl->display.shell,
+ wl->window.video_surface);
- wl_shell_surface_add_listener(wl->window.shell_surface,
- &shell_surface_listener, wl);
+ if (!wl->window.shell_surface) {
+ MP_ERR(wl, "creating shell surface failed\n");
+ return false;
+ }
- wl_shell_surface_set_toplevel(wl->window.shell_surface);
- wl_shell_surface_set_class(wl->window.shell_surface, "mpv");
+ wl_shell_surface_add_listener(wl->window.shell_surface,
+ &shell_surface_listener, wl);
+
+ wl_shell_surface_set_toplevel(wl->window.shell_surface);
+ wl_shell_surface_set_class(wl->window.shell_surface, "mpv");
+ }
return true;
}
@@ -796,15 +819,21 @@ static bool create_cursor (struct vo_wayland_state *wl)
return false;
}
- wl->cursor.surface =
- wl_compositor_create_surface(wl->display.compositor);
+ if (wl->cursor.pointer) {
+ // only create cursor surface if a pointer interface is available
+ // without this check it leads to problems with compositor which don't
+ // have pointer interfaces
+ wl->cursor.surface =
+ wl_compositor_create_surface(wl->display.compositor);
- if (!wl->cursor.surface)
- return false;
+ if (!wl->cursor.surface)
+ return false;
+
+ wl->cursor.theme = wl_cursor_theme_load(NULL, 32, wl->display.shm);
+ wl->cursor.default_cursor = wl_cursor_theme_get_cursor(wl->cursor.theme,
+ "left_ptr");
+ }
- wl->cursor.theme = wl_cursor_theme_load(NULL, 32, wl->display.shm);
- wl->cursor.default_cursor = wl_cursor_theme_get_cursor(wl->cursor.theme,
- "left_ptr");
return true;
}
@@ -896,7 +925,7 @@ static void vo_wayland_ontop (struct vo *vo)
struct vo_wayland_state *wl = vo->wayland;
MP_DBG(wl, "going ontop\n");
vo->opts->ontop = 1;
- wl_shell_surface_set_toplevel(wl->window.shell_surface);
+ window_set_toplevel(wl);
schedule_resize(wl, 0, wl->window.width, wl->window.height);
}
@@ -921,7 +950,7 @@ static void vo_wayland_fullscreen (struct vo *vo)
else {
MP_DBG(wl, "leaving fullscreen\n");
wl->window.is_fullscreen = false;
- wl_shell_surface_set_toplevel(wl->window.shell_surface);
+ window_set_toplevel(wl);
schedule_resize(wl, 0, wl->window.p_width, wl->window.p_height);
}
}
@@ -1112,7 +1141,7 @@ int vo_wayland_control (struct vo *vo, int *events, int request, void *arg)
wl->cursor.visible = *(bool *)arg;
return VO_TRUE;
case VOCTRL_UPDATE_WINDOW_TITLE:
- wl_shell_surface_set_title(wl->window.shell_surface, (char *) arg);
+ window_set_title(wl, (char*) arg);
return VO_TRUE;
}
return VO_NOTIMPL;
diff --git a/video/out/x11_common.c b/video/out/x11_common.c
index eb4fb15..539d66e 100644
--- a/video/out/x11_common.c
+++ b/video/out/x11_common.c
@@ -777,7 +777,7 @@ int vo_x11_check_events(struct vo *vo)
if (x11->window == None)
break;
vo_x11_update_geometry(vo);
- if (Event.xconfigure.window == vo->opts->WinID) {
+ if (Event.xconfigure.window == (Window)vo->opts->WinID) {
XMoveResizeWindow(x11->display, x11->window,
x11->winrc.x0, x11->winrc.y0,
RC_W(x11->winrc), RC_H(x11->winrc));
@@ -835,7 +835,8 @@ int vo_x11_check_events(struct vo *vo)
};
x11_send_ewmh_msg(x11, "_NET_WM_MOVERESIZE", params);
} else {
- vo_mouse_movement(vo, Event.xmotion.x, Event.xmotion.y);
+ mp_input_set_mouse_pos(vo->input_ctx, Event.xmotion.x,
+ Event.xmotion.y);
}
x11->win_drag_button1_down = false;
break;
@@ -1560,7 +1561,7 @@ static void vo_x11_selectinput_witherr(struct vo *vo,
Window w,
long event_mask)
{
- if (!vo->opts->enable_mouse_movements)
+ if (!mp_input_mouse_enabled(vo->input_ctx))
event_mask &= ~(PointerMotionMask | ButtonPressMask | ButtonReleaseMask);
XSelectInput(display, w, NoEventMask);
diff --git a/video/vdpau.c b/video/vdpau.c
index 90aba50..754b6d3 100644
--- a/video/vdpau.c
+++ b/video/vdpau.c
@@ -179,6 +179,7 @@ static struct mp_image *create_ref(struct mp_vdpau_ctx *ctx, int index)
struct surface_entry *e = &ctx->video_surfaces[index];
assert(!e->in_use);
e->in_use = true;
+ e->age = ctx->age_counter++;
struct surface_ref *ref = talloc_ptrtype(NULL, ref);
*ref = (struct surface_ref){ctx, index};
struct mp_image *res =
@@ -237,11 +238,18 @@ static struct mp_image *mp_vdpau_get_surface(struct mp_vdpau_ctx *ctx,
assert(e->chroma == chroma);
assert(e->rgb_format == rgb_format);
assert(e->rgb == rgb);
+ if (surface_index >= 0) {
+ struct surface_entry *other = &ctx->video_surfaces[surface_index];
+ if (other->age < e->age)
+ continue;
+ }
surface_index = n;
- goto done;
}
}
+ if (surface_index >= 0)
+ goto done;
+
// Allocate new surface
for (int n = 0; n < MAX_VIDEO_SURFACES; n++) {
struct surface_entry *e = &ctx->video_surfaces[n];
@@ -409,22 +417,29 @@ struct mp_image *mp_vdpau_upload_video_surface(struct mp_vdpau_ctx *ctx,
if (!hwmpi)
return NULL;
+ struct mp_image *src = mpi;
+ if (mpi->stride[0] < 0)
+ src = mp_image_new_copy(mpi); // unflips it when copying
+
if (hwmpi->imgfmt == IMGFMT_VDPAU) {
VdpVideoSurface surface = (intptr_t)hwmpi->planes[3];
- const void *destdata[3] = {mpi->planes[0], mpi->planes[2], mpi->planes[1]};
- if (mpi->imgfmt == IMGFMT_NV12)
+ const void *destdata[3] = {src->planes[0], src->planes[2], src->planes[1]};
+ if (src->imgfmt == IMGFMT_NV12)
destdata[1] = destdata[2];
vdp_st = vdp->video_surface_put_bits_y_cb_cr(surface,
- ycbcr, destdata, mpi->stride);
+ ycbcr, destdata, src->stride);
} else {
VdpOutputSurface rgb_surface = (intptr_t)hwmpi->planes[3];
vdp_st = vdp->output_surface_put_bits_native(rgb_surface,
- &(const void *){mpi->planes[0]},
- &(uint32_t){mpi->stride[0]},
+ &(const void *){src->planes[0]},
+ &(uint32_t){src->stride[0]},
NULL);
}
CHECK_VDP_WARNING(ctx, "Error when uploading surface");
+ if (src != mpi)
+ talloc_free(src);
+
mp_image_copy_attributes(hwmpi, mpi);
return hwmpi;
}
diff --git a/video/vdpau.h b/video/vdpau.h
index 7fdbbf4..6f60165 100644
--- a/video/vdpau.h
+++ b/video/vdpau.h
@@ -56,6 +56,7 @@ struct mp_vdpau_ctx {
// Surface pool
pthread_mutex_t pool_lock;
+ int64_t age_counter;
struct surface_entry {
VdpVideoSurface surface;
VdpOutputSurface osurface;
@@ -65,6 +66,7 @@ struct mp_vdpau_ctx {
VdpChromaType chroma;
bool rgb;
bool in_use;
+ int64_t age;
} video_surfaces[MAX_VIDEO_SURFACES];
};
diff --git a/waftools/detections/compiler.py b/waftools/detections/compiler.py
index ad1f843..b982188 100644
--- a/waftools/detections/compiler.py
+++ b/waftools/detections/compiler.py
@@ -22,6 +22,9 @@ def __add_generic_flags__(ctx):
"-D_LARGEFILE64_SOURCE",
"-std=c99", "-Wall"]
+ if ctx.is_optimization():
+ ctx.env.CFLAGS += ['-O2']
+
if ctx.is_debug_build():
ctx.env.CFLAGS += ['-g']
@@ -43,9 +46,6 @@ def __add_clang_flags__(ctx):
def __add_mingw_flags__(ctx):
ctx.env.CFLAGS += ['-D__USE_MINGW_ANSI_STDIO=1']
- ctx.env.CFLAGS += ['-DBYTE_ORDER=1234']
- ctx.env.CFLAGS += ['-DLITLE_ENDIAN=1234']
- ctx.env.CFLAGS += ['-DBIG_ENDIAN=4321']
ctx.env.LAST_LINKFLAGS += ['-mwindows']
def __add_cygwin_flags__(ctx):
diff --git a/waftools/detections/devices.py b/waftools/detections/devices.py
index cf1cca7..42c4c28 100644
--- a/waftools/detections/devices.py
+++ b/waftools/detections/devices.py
@@ -4,6 +4,7 @@ __cdrom_devices_map__ = {
'darwin': '/dev/disk1',
'freebsd': '/dev/cd0',
'openbsd': '/dev/rcd0c',
+ 'linux': '/dev/sr0',
'default': '/dev/cdrom'
}
@@ -13,6 +14,7 @@ __dvd_devices_map__ = {
'darwin': '/dev/rdiskN',
'freebsd': '/dev/cd0',
'openbsd': '/dev/rcd0c',
+ 'linux': '/dev/sr0',
'default': '/dev/dvd'
}
diff --git a/waftools/generators/headers.py b/waftools/generators/headers.py
index b38fcb8..bd28bef 100644
--- a/waftools/generators/headers.py
+++ b/waftools/generators/headers.py
@@ -1,3 +1,9 @@
+def __cp_to_variant__(ctx, variant, basename):
+ src = ctx.bldnode.search(basename).read()
+ node = ctx.bldnode.make_node("{0}/{1}".format(variant, basename))
+ node.parent.mkdir()
+ node.write(src)
+
def __get_version__(ctx):
import subprocess
process = subprocess.Popen(["sh", "./version.sh", "--print"],
@@ -17,6 +23,7 @@ def __get_build_date__():
def __write_config_h__(ctx):
ctx.start_msg("Writing configuration header:")
ctx.write_config_header('config.h')
+ __cp_to_variant__(ctx, ctx.options.variant, 'config.h')
ctx.end_msg("config.h", "PINK")
def __write_version_h__(ctx):
@@ -25,6 +32,7 @@ def __write_version_h__(ctx):
ctx.define("VERSION", ctx.env.VERSION)
ctx.define("BUILDDATE", __get_build_date__())
ctx.write_config_header("version.h")
+ __cp_to_variant__(ctx, ctx.options.variant, 'version.h')
ctx.end_msg("version.h", "PINK")
def __add_mplayer_defines__(ctx):
diff --git a/waftools/syms.py b/waftools/syms.py
index 4bef9a3..eff35e7 100644
--- a/waftools/syms.py
+++ b/waftools/syms.py
@@ -1,85 +1,52 @@
#! /usr/bin/env python
# encoding: utf-8
-# Source: waflib/extras/syms.py from waf git 610d0d59f (New BSD License)
+# Original source: waflib/extras/syms.py from waf git 610d0d59f (New BSD License)
"""
-this tool supports the export_symbols_regex to export the symbols in a shared library.
-by default, all symbols are exported by gcc, and nothing by msvc.
+set the list of symbols exported from a dynamic library
to use the tool, do something like:
def build(ctx):
- ctx(features='c cshlib syms', source='a.c b.c', export_symbols_regex='mylib_.*', target='testlib')
+ ctx(features='c cshlib syms', source='a.c b.c', export_symbols_def='syms.def', target='testlib')
-only the symbols starting with 'mylib_' will be exported.
+only the symbols listed in the file syms.def will be exported.
"""
-import os
-import re
from waflib.Context import STDOUT
from waflib.Task import Task
from waflib.Errors import WafError
from waflib.TaskGen import feature, after_method
-class gen_sym(Task):
- def run(self):
- obj = self.inputs[0]
- kw = {}
- if 'msvc' in (self.env.CC_NAME, self.env.CXX_NAME):
- re_nm = re.compile(r'External\s+\|\s+_(' + self.generator.export_symbols_regex + r')\b')
- cmd = [self.env.DUMPBIN or 'dumpbin', '/symbols', obj.abspath()]
-
- # Dumpbin requires custom environment sniffed out by msvc.py earlier
- if self.env['PATH']:
- env = dict(self.env.env or os.environ)
- env.update(PATH = os.pathsep.join(self.env['PATH']))
- kw['env'] = env
-
- else:
- if self.env.DEST_BINFMT in ('pe', 'mac-o'): #gcc uses nm, and has a preceding _ on windows and osx
- re_nm = re.compile(r'T\s+_(' + self.generator.export_symbols_regex + r')\b')
- else:
- re_nm = re.compile(r'T\s+(' + self.generator.export_symbols_regex + r')\b')
- cmd = [self.env.NM or 'nm', '-g', obj.abspath()]
- syms = re_nm.findall(self.generator.bld.cmd_and_log(cmd, quiet=STDOUT, **kw))
- self.outputs[0].write('%r' % syms)
-
class compile_sym(Task):
- def run(self):
- syms = {}
- for x in self.inputs:
- slist = eval(x.read())
- for s in slist:
- syms[s] = 1
- lsyms = list(syms.keys())
- lsyms.sort()
- if self.env.DEST_BINFMT == 'pe':
- self.outputs[0].write('EXPORTS\n' + '\n'.join(lsyms))
- elif self.env.DEST_BINFMT == 'elf':
- self.outputs[0].write('{ global:\n' + ';\n'.join(lsyms) + ";\nlocal: *; };\n")
- elif self.env.DEST_BINFMT == 'mac-o':
- self.outputs[0].write('\n'.join("_"+sym for sym in lsyms))
- else:
- raise WafError('NotImplemented')
-
-@feature('syms')
-@after_method('process_source', 'process_use', 'apply_link', 'process_uselib_local')
-def do_the_symbol_stuff(self):
- ins = [x.outputs[0] for x in self.compiled_tasks]
- self.gen_sym_tasks = [self.create_task('gen_sym', x, x.change_ext('.%d.sym' % self.idx)) for x in ins]
-
- tsk = self.create_task('compile_sym',
- [x.outputs[0] for x in self.gen_sym_tasks],
- self.path.find_or_declare(getattr(self, 'sym_filename', self.target + '.def')))
- self.link_task.set_run_after(tsk)
- self.link_task.dep_nodes.append(tsk.outputs[0])
- if 'msvc' in (self.env.CC_NAME, self.env.CXX_NAME):
- self.link_task.env.append_value('LINKFLAGS', ['/def:' + tsk.outputs[0].bldpath()])
- elif self.env.DEST_BINFMT == 'pe': #gcc on windows takes *.def as an additional input
- self.link_task.inputs.append(tsk.outputs[0])
+ def run(self):
+ lsyms = []
+ for line in self.inputs[0].read().split():
+ lsyms.append(line.strip())
+ lsyms.sort()
+ if self.env.DEST_BINFMT == 'pe':
+ self.outputs[0].write('EXPORTS\n' + '\n'.join(lsyms))
elif self.env.DEST_BINFMT == 'elf':
- self.link_task.env.append_value('LINKFLAGS', ['-Wl,-version-script', '-Wl,' + tsk.outputs[0].bldpath()])
+ self.outputs[0].write('{ global:\n' + ';\n'.join(lsyms) + ";\nlocal: *; };\n")
elif self.env.DEST_BINFMT == 'mac-o':
- self.link_task.env.append_value('LINKFLAGS', ['-exported_symbols_list', tsk.outputs[0].bldpath()])
+ self.outputs[0].write('\n'.join("_"+sym for sym in lsyms) + '\n')
else:
- raise WafError('NotImplemented')
+ raise WafError('NotImplemented')
+@feature('syms')
+@after_method('process_source', 'process_use', 'apply_link', 'process_uselib_local')
+def do_the_symbol_stuff(self):
+ tsk = self.create_task('compile_sym',
+ [self.path.find_node(self.export_symbols_def)],
+ self.path.find_or_declare(getattr(self, 'sym_filename', self.target + '.def')))
+ self.link_task.set_run_after(tsk)
+ self.link_task.dep_nodes.append(tsk.outputs[0])
+ if 'msvc' in (self.env.CC_NAME, self.env.CXX_NAME):
+ self.link_task.env.append_value('LINKFLAGS', ['/def:' + tsk.outputs[0].bldpath()])
+ elif self.env.DEST_BINFMT == 'pe': #gcc on windows takes *.def as an additional input
+ self.link_task.inputs.append(tsk.outputs[0])
+ elif self.env.DEST_BINFMT == 'elf':
+ self.link_task.env.append_value('LINKFLAGS', ['-Wl,-version-script', '-Wl,' + tsk.outputs[0].bldpath()])
+ elif self.env.DEST_BINFMT == 'mac-o':
+ self.link_task.env.append_value('LINKFLAGS', ['-exported_symbols_list', tsk.outputs[0].bldpath()])
+ else:
+ raise WafError('NotImplemented')
diff --git a/wscript b/wscript
index bb55ba4..7786ebf 100644
--- a/wscript
+++ b/wscript
@@ -36,6 +36,11 @@ build_options = [
'default': 'enable',
'func': check_true
}, {
+ 'name': '--optimize',
+ 'desc': 'whether to optimize',
+ 'default': 'enable',
+ 'func': check_true
+ }, {
'name': '--debug-build',
'desc': 'whether to compile-in debugging information',
'default': 'enable',
@@ -69,17 +74,6 @@ build_options = [
'func': check_true,
'default': 'disable',
}, {
- 'name': '--macosx-bundle',
- 'desc': 'compilation of a Mac OS X Application bundle',
- 'deps': [ 'os-darwin' ],
- 'default': 'disable',
- 'func': check_true
- }, {
- 'name': 'win32-executable',
- 'desc': 'w32 executable',
- 'deps_any': [ 'os-win32', 'os-cygwin'],
- 'func': check_ctx_vars('WINDRES')
- }, {
# does nothing - left for backward and forward compatibility
'name': '--asm',
'desc': 'inline assembly (currently without effect)',
@@ -474,7 +468,7 @@ audio_output_features = [
}, {
'name': '--pulse',
'desc': 'PulseAudio audio output',
- 'func': check_pkg_config('libpulse', '>= 0.9')
+ 'func': check_pkg_config('libpulse', '>= 1.0')
}, {
'name': '--portaudio',
'desc': 'PortAudio audio output',
@@ -678,27 +672,13 @@ hwaccel_features = [
} , {
'name': '--vda-hwaccel',
'desc': 'libavcodec VDA hwaccel',
- 'deps': [ 'corevideo'],
+ 'deps': [ 'corevideo' ],
'func': compose_checks(
check_headers('VideoDecodeAcceleration/VDADecoder.h'),
check_statement('libavcodec/vda.h',
- 'ff_vda_create_decoder(NULL, NULL, NULL)',
+ 'av_vda_alloc_context()',
framework='IOSurface',
use='libav')),
- } , {
- 'name': 'vda-libavcodec-refcounting',
- 'desc': "libavcodec VDA ref-counted CVPixelBuffers",
- 'deps': [ 'vda-hwaccel' ],
- 'func': check_statement ('libavcodec/vda.h',
- """struct vda_context a = (struct vda_context) {
- .use_ref_buffer = 1 }""", use='libav')
- }, {
- 'name': 'vda-av-vda-alloc-context',
- 'desc': "libavcodec VDA hwaccel 1.2",
- 'deps': [ 'vda-hwaccel' ],
- 'func': check_statement('libavcodec/vda.h',
- 'av_vda_alloc_context()',
- use='libav')
}, {
'name': '--vda-gl',
'desc': 'VDA with OpenGL',
@@ -746,6 +726,31 @@ scripting_features = [
}
]
+standalone_features = [
+ {
+ 'name': '--cplayer',
+ 'desc': 'mpv CLI player',
+ 'func': check_true
+ }, {
+ 'name': 'win32-executable',
+ 'desc': 'w32 executable',
+ 'deps_any': [ 'os-win32', 'os-cygwin'],
+ 'func': check_ctx_vars('WINDRES')
+ }, {
+ 'name': 'cocoa-application',
+ 'desc': 'standalone Cocoa application',
+ 'deps': [ 'cocoa' ],
+ 'deps_neg': [ 'libmpv-shared', 'libmpv-static' ],
+ 'func': check_true
+ }, {
+ 'name': '--macosx-bundle',
+ 'desc': 'compilation of a Mac OS X Application bundle',
+ 'deps': [ 'os-darwin' ],
+ 'default': 'disable',
+ 'func': check_true
+ }
+]
+
_INSTALL_DIRS_LIST = [
('bindir', '${PREFIX}/bin', 'binary files'),
('libdir', '${PREFIX}/lib', 'library files'),
@@ -772,6 +777,10 @@ def options(opt):
help = 'directory for installing {0} [{1}]' \
.format(desc, default))
+ group.add_option('--variant',
+ default = '',
+ help = 'variant name for saving configuration and build results')
+
opt.parse_features('build and install options', build_options)
optional_features = main_dependencies + libav_dependencies
opt.parse_features('optional feaures', optional_features)
@@ -780,6 +789,7 @@ def options(opt):
opt.parse_features('hwaccels', hwaccel_features)
opt.parse_features('tv features', radio_and_tv_features)
opt.parse_features('scripting', scripting_features)
+ opt.parse_features('standalone app', standalone_features)
group = opt.get_option_group("scripting")
group.add_option('--lua',
@@ -788,10 +798,15 @@ def options(opt):
help = "select Lua package which should be autodetected. Choices: 51 51deb 51fbsd 52 52deb 52fbsd luajit")
@conf
+def is_optimization(ctx):
+ return getattr(ctx.options, 'enable_optimize')
+
+@conf
def is_debug_build(ctx):
return getattr(ctx.options, 'enable_debug-build')
def configure(ctx):
+ ctx.resetenv(ctx.options.variant)
ctx.check_waf_version(mini='1.7.15')
target = os.environ.get('TARGET')
(cc, pkg_config, windres) = ('cc', 'pkg-config', 'windres')
@@ -834,6 +849,7 @@ def configure(ctx):
ctx.options.enable_lua = True
ctx.parse_dependencies(scripting_features)
+ ctx.parse_dependencies(standalone_features)
ctx.define('HAVE_SYS_SOUNDCARD_H',
'(HAVE_OSS_AUDIO_NATIVE || HAVE_OSS_AUDIO_4FRONT)',
@@ -851,5 +867,27 @@ def configure(ctx):
ctx.store_dependencies_lists()
def build(ctx):
+ if ctx.options.variant not in ctx.all_envs:
+ from waflib import Errors
+ raise Errors.WafError(
+ 'The project was not configured: run "waf --variant={0} configure" first!'
+ .format(ctx.options.variant))
ctx.unpack_dependencies_lists()
ctx.load('wscript_build')
+
+def init(ctx):
+ from waflib.Build import BuildContext, CleanContext, InstallContext, UninstallContext
+ for y in (BuildContext, CleanContext, InstallContext, UninstallContext):
+ class tmp(y):
+ variant = ctx.options.variant
+
+ # This is needed because waf initializes the ConfigurationContext with
+ # an arbitrary setenv('') which would rewrite the previous configuration
+ # cache for the default variant if the configure step finishes.
+ # Ideally ConfigurationContext should just let us override this at class
+ # level like the other Context subclasses do with variant
+ from waflib.Configure import ConfigurationContext
+ class cctx(ConfigurationContext):
+ def resetenv(self, name):
+ self.all_envs = {}
+ self.setenv(name)
diff --git a/wscript_build.py b/wscript_build.py
index ef480ab..090fe28 100644
--- a/wscript_build.py
+++ b/wscript_build.py
@@ -134,6 +134,7 @@ def build(ctx):
( "audio/out/ao.c" ),
( "audio/out/ao_alsa.c", "alsa" ),
( "audio/out/ao_coreaudio.c", "coreaudio" ),
+ ( "audio/out/ao_coreaudio_device.c", "coreaudio" ),
( "audio/out/ao_coreaudio_properties.c", "coreaudio" ),
( "audio/out/ao_coreaudio_utils.c", "coreaudio" ),
( "audio/out/ao_dsound.c", "dsound" ),
@@ -160,7 +161,6 @@ def build(ctx):
## Core
( "common/av_common.c" ),
( "common/av_log.c" ),
- ( "common/av_opts.c" ),
( "common/codecs.c" ),
( "common/encode_lavc.c", "encoding" ),
( "common/common.c" ),
@@ -173,6 +173,7 @@ def build(ctx):
( "demux/codec_tags.c" ),
( "demux/demux.c" ),
( "demux/demux_cue.c" ),
+ ( "demux/demux_disc.c" ),
( "demux/demux_edl.c" ),
( "demux/demux_lavf.c" ),
( "demux/demux_libass.c", "libass"),
@@ -181,8 +182,10 @@ def build(ctx):
( "demux/demux_playlist.c" ),
( "demux/demux_raw.c" ),
( "demux/demux_subreader.c" ),
+ ( "demux/demux_tv.c", "tv" ),
( "demux/ebml.c" ),
( "demux/mf.c" ),
+ ( "demux/packet.c" ),
## Input
( "input/cmd_list.c" ),
@@ -197,6 +200,7 @@ def build(ctx):
( "misc/charset_conv.c" ),
( "misc/dispatch.c" ),
( "misc/ring.c" ),
+ ( "misc/rendezvous.c" ),
## Options
( "options/m_config.c" ),
@@ -297,6 +301,7 @@ def build(ctx):
( "video/decode/vdpau.c", "vdpau-hwaccel" ),
( "video/filter/pullup.c" ),
( "video/filter/vf.c" ),
+ ( "video/filter/vf_buffer.c" ),
( "video/filter/vf_crop.c" ),
( "video/filter/vf_delogo.c" ),
( "video/filter/vf_divtc.c" ),
@@ -377,7 +382,7 @@ def build(ctx):
( "osdep/threads.c" ),
( "osdep/ar/HIDRemote.m", "cocoa" ),
- ( "osdep/macosx_application.m", "cocoa" ),
+ ( "osdep/macosx_application.m", "cocoa-application" ),
( "osdep/macosx_events.m", "cocoa" ),
( "osdep/path-macosx.m", "cocoa" ),
@@ -429,27 +434,28 @@ def build(ctx):
install_name = '/mpv.app/Contents/Resources/' + res_basename
ctx.install_as(ctx.env.BINDIR + install_name, resource)
- ctx(
- target = "mpv",
- source = ctx.filtered_sources(sources) + ["player/main_fn.c"],
- use = ctx.dependencies_use(),
- includes = [ctx.bldnode.abspath(), ctx.srcnode.abspath()] + \
- ctx.dependencies_includes(),
- features = "c cprogram",
- install_path = ctx.env.BINDIR,
- **cprog_kwargs
- )
+
+ if ctx.dependency_satisfied('cplayer'):
+ ctx(
+ target = "mpv",
+ source = ctx.filtered_sources(sources) + ["player/main_fn.c"],
+ use = ctx.dependencies_use(),
+ includes = [ctx.bldnode.abspath(), ctx.srcnode.abspath()] + \
+ ctx.dependencies_includes(),
+ features = "c cprogram",
+ install_path = ctx.env.BINDIR,
+ **cprog_kwargs
+ )
build_shared = ctx.dependency_satisfied('libmpv-shared')
build_static = ctx.dependency_satisfied('libmpv-static')
if build_shared or build_static:
if build_shared:
ctx.load("syms")
- vnum = int(re.search('^#define MPV_CLIENT_API_VERSION 0x(.*)UL$',
- ctx.path.find_node("libmpv/client.h").read(),
- re.M)
- .group(1), 16)
- libversion = str(vnum >> 16) + '.' + str(vnum & 0xffff) + '.0'
+ vre = '^#define MPV_CLIENT_API_VERSION MPV_MAKE_VERSION\((.*), (.*)\)$'
+ libmpv_header = ctx.path.find_node("libmpv/client.h").read()
+ major, minor = re.search(vre, libmpv_header, re.M).groups()
+ libversion = major + '.' + minor + '.0'
def _build_libmpv(shared):
features = "c "
@@ -464,7 +470,7 @@ def build(ctx):
includes = [ctx.bldnode.abspath(), ctx.srcnode.abspath()] + \
ctx.dependencies_includes(),
features = features,
- export_symbols_regex = 'mpv_.*',
+ export_symbols_def = "libmpv/mpv.def",
install_path = ctx.env.LIBDIR,
vnum = libversion,
)
@@ -473,6 +479,13 @@ def build(ctx):
if build_static:
_build_libmpv(False)
+ def get_deps():
+ res = ""
+ for k in ctx.env.keys():
+ if k.startswith("LIB_") and k != "LIB_ST":
+ res += " ".join(["-l" + x for x in ctx.env[k]]) + " "
+ return res
+
ctx(
target = 'libmpv/mpv.pc',
source = 'libmpv/mpv.pc.in',
@@ -481,6 +494,7 @@ def build(ctx):
LIBDIR = ctx.env.LIBDIR,
INCDIR = ctx.env.INCDIR,
VERSION = libversion,
+ PRIV_LIBS = get_deps(),
)
headers = ["client.h"]