Compare commits

..
11 Commits
Author SHA1 Message Date
Diogo Franco (Kovensky) e795a1781f Bump version to v0.9.0, remove Draft status from RELEASE_NOTES 2015-04-25 21:54:38 +09:00
Diogo Franco (Kovensky) 6e4abfb017 Fix typo in RELEASE_NOTES 2015-04-25 18:31:59 +09:00
Diogo Franco (Kovensky) 62195c174a Add v0.7.x RELEASE_NOTES to RELEASE_NOTES 2015-04-25 18:30:06 +09:00
Diogo Franco (Kovensky) 79efe85cf5 Update RELEASE_NOTES 2015-04-25 18:28:25 +09:00
Diogo Franco (Kovensky) 5f1d6b6e5a Merge branch 'master' into release/0.9
* master: (87 commits)
  manpage: move --autosync description
  player: add --window-scale option
  player: flush decoder even if cover art is decoded
  player: don't show A/V desync message in non-sense situations
  w32_common: add more rounded-down frame rates
  w32_common: use the current monitor's refresh rate
  dxva2: fix broken build with gcc 5.1
  terminal: printf() is not signal-safe
  man: fix PDF build
  DOCS/mplayer-changes: Eleborate on joystick input
  osc: add nil check for element.eventresponder
  mp_image: remove some unused interlacing flags
  vf_vapoursynth: update _FieldBased semantics
  options: remove unneeded hack from command line parser
  manpage: document ff-index sub-property
  demux_mkv: limit timestamp fixing to 1ms max
  demux_mkv: attempt to fix rounded timestamps
  demux_mkv: move global options to the demuxer
  demux_mkv: better seeking after video end
  lua: add utils.format_json() function
  ...
2015-04-25 18:28:17 +09:00
Diogo Franco (Kovensky) d64ff3aa51 Update RELEASE_NOTES 2015-04-13 20:05:18 +09:00
Diogo Franco (Kovensky) 3287825bd2 Merge branch 'master' into release/0.9
* master: (39 commits)
  Update license headers
  af_lavrresample: minor simplification
  af_lavrresample: allow resetting output sample format
  audio/filter: fully renegotiate audio formats on every reconfig
  DOCS/waf: Edit --enable-feature sentences
  vo_opengl: slightly simplify check_gl_features()
  vo_opengl: unify blend-subtitles-res and blend-subtitles
  vo_opengl: fix blend-subtitles-res=video & anamorphic video
  manpage: mention how pseudo-gui mode is enabled on win32
  main-fn-win: fix handle validity check for XP
  win32: use pseudo-gui profile when started without stdio
  win32: only attach to the console from mpv.com
  win32: use a platform-specific unicode entry-point
  vo_opengl: add blend-subtitles-res
  manpage: document pseudo-gui stuff
  mp_image: remove redundant flags field
  mp_image: remove redundant chroma_x/y_shift fields
  mp_image: remove redundant plane_w/h fields
  player: use config parser for setting up pseudo-gui profile
  player: change pseudo-gui settings
  ...
2015-04-13 19:55:48 +09:00
Diogo Franco (Kovensky) 9e65b5db0b Update RELEASE_NOTES 2015-04-13 19:51:35 +09:00
Diogo Franco (Kovensky) d9d8c9ce13 Update RELEASE_NOTES 2015-04-09 20:45:44 +09:00
Diogo Franco (Kovensky) 35e9d75083 Merge branch 'master' into release/0.9
All commits are bugfixes anyway, so just taking everything.

* master:
  sub: don't truncate timestamps to int
  sub: unprefer libavcodec's MicroDVD converter
  manpage: lua: clarify timer usage
  audio: automatically deatch filters if spdif prevents their use
  audio: change a detail about filter insertion
  ao_alsa: change log output
  audio: avoid one more redundant audio filter reinit
  ao_coreaudio: do not error if retrieving info for verbose mode fails
  travis: re-enable OSX
  video/out: fix screenshot image formats
  vdpau: don't use a transparent image format for screenshots
  screenshot: use GPU readback only for hardware decoded images
  manpage: remove confusing statement
  screenshots: select best image format the encoder supports
2015-04-09 20:42:14 +09:00
Diogo Franco (Kovensky) 4a84cd37f3 Add RELEASE_NOTES 2015-04-06 21:20:45 +09:00
551 changed files with 42814 additions and 55188 deletions

No files matched your search

-23
View File
@@ -1,23 +0,0 @@
### mpv version and platform
If you're not using git master or the latest release, update.
### Reproduction steps
### Expected behavior
### Actual behavior
### Log file
Make a log file made with -v or --log-file=output.txt, paste it to
http://sprunge.us or a similar site, and replace this text with a link to it.
Providing a log file is strongly encouraged. It is very helpful for reproducing
bugs or getting important technical context. Without a log it might not be
possible to analyze and fix certain bugs.
### Sample files
Sample files needed to reproduce this issue can be uploaded to https://0x0.st/
or similar sites. (Only needed if the issue cannot be reproduced without it.)
-7
View File
@@ -1,7 +0,0 @@
Ideally, you shouldn't need enter any text here, and your commit messages should
explain your changes sufficiently (especially why they are needed). Read
https://github.com/mpv-player/mpv/blob/master/DOCS/contribute.md for coding
style and development conventions. Remove this text block, but if you haven't
agreed to it before, leave the following sentence in place:
I agree that my changes can be relicensed to LGPL 2.1 or later.
-1
View File
@@ -19,7 +19,6 @@
/demux/ebml_types.h
/sub/osd_font.h
/player/lua/*.inc
/player/builtin_conf.inc
/DOCS/man/mpv.1
/DOCS/man/mpv.aux
/DOCS/man/mpv.log
+2 -5
View File
@@ -12,8 +12,6 @@ env:
global:
# Coverity token
- secure: "H21mSRlMhk4BKS0xHZvCFGJxteCP0hRVUxTuNfM2Z9HBsyutuLEYMtViLO86VtM+Tqla3xXPzUdS4ozLwI72Ax/5ZUDXACROj73yW6QhFB5D6rLut12+FjqC7M33Qv2hl0xwgNBmR5dsm1ToP37+Wn+ecJQNvN8fkTXF+HVzOEw="
# Travis token for mpv.io
- secure: "nlTVLJK6kRhtXvhKCoJ3YdFGHuKaq/eHowfPw25hqRWuBOZd+HjHY5KIYjV7SxuKFDpJE4GpNcvA3Q31nsqomxpkLYgrwjg6TSazN7ZP+x85ZgV1QGFebrPfGm2n5UR5CAPAwFoeF3pZheLi4bajVzwq1fWW+x3grS188P9OZso="
compiler:
- clang
- gcc
@@ -39,18 +37,17 @@ matrix:
- os: linux
compiler: clang
before_install: TOOLS/travis-deps libass-stable $LIBAV
before_install: ./travis-deps libass-stable $LIBAV
script:
- ./bootstrap.py
- ./waf configure
- ./waf build
after_script: TOOLS/travis-rebuild-website
notifications:
email: false
irc:
channels:
- "irc.freenode.org#mpv-devel"
- "irc.freenode.org#mpv-player-dev"
on_success: change
on_failure: always
+2 -10
View File
@@ -2,15 +2,9 @@ mpv is a fork of mplayer2, which is a fork of MPlayer.
mpv as a whole is licensed as GPL version 2 or later (see LICENSE). Most source
files are GPLv2+, but some files are available under a more liberal license,
such as LGPLv2.1+, BSD, MIT, ISC, and possibly others. Look at the copyright
such as LGPLv2+, BSD, MIT, ISC, and possibly others. Look at the copyright
header of each source file, and grep the sources for "Copyright" if you need
to know details. Files without Copyright notice are licensed as LGPLv2.1+.
All new contributions must be LGPLv2.1+ licensed, or if the changes are done on
GPL code, must come with the implicit agreement that the project can relicense
the code to LGPLv2.1+ at a later point without asking the contributor. (This
is a safeguard for making potential relicensing of the project to LGPLv2.1+
easier.) Using a more liberal license compatible to LGPLv2.1+ is also ok.
to know details. Files without Copyright notice are licensed as LGPLv2+.
For information about authors and contributors, consult the git log, which
contains the complete SVN and CVS history as well.
@@ -23,5 +17,3 @@ MPlayer as a whole is licensed under GPLv2 (incompatible to GPLv3!), because
some files are licensed to GPLv2 (and _not_ any later version of the license).
In particular, this affects the file libmpdemux/demux_ty_osd.c. It is disabled
under mplayer2, and has been removed from mpv.
"v2.1+" in this context means "version 2.1 or later".
+10 -74
View File
@@ -4,7 +4,9 @@ Introduction
This file lists all changes that can cause compatibility issues when using
mpv through the client API (libmpv and ``client.h``). Since the client API
interfaces to input handling (commands, properties) as well as command line
options, you should also look at ``interface-changes.rst``.
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),
@@ -18,87 +20,21 @@ The version number is the same as used for MPV_CLIENT_API_VERSION (see
Also, read the section ``Compatibility`` in ``client.h``.
Options, commands, properties
=============================
Changes to these are not listed here, but in ``interface-changes.rst``. (Before
client API version 1.17, they were listed here partially.)
This listing includes changes to the bare C API and behavior only, not what
you can access with them.
API changes
===========
::
--- mpv 0.21.0 ---
1.23 - deprecate setting "no-" options via mpv_set_option*(). For example,
instead of "no-video=" you should set "video=no".
- do not override the SIGPIPE signal handler anymore. This was done as
workaround for the FFmpeg TLS code, which has been fixed long ago.
- deprecate mpv_suspend() and mpv_resume(). They will be stubbed out
in mpv 0.22.0.
- make mpv_set_property() work to some degree before mpv_initialize().
It can now be used instead of mpv_set_option().
- semi-deprecate mpv_set_option()/mpv_set_option_string(). You should
use mpv_set_property() instead. There are some deprecated properties
which conflict with some options (see client.h remarks on
mpv_set_option()), for which mpv_set_option() might still be required.
In future mpv releases, the conflicting deprecated options/properties
will be removed, and mpv_set_option() will internally translate API
calls to mpv_set_property().
- qthelper.hpp: deprecate get_property_variant, set_property_variant,
mpv_set_option, command_variant, and replace them with get_property,
set_property, command.
--- mpv 0.19.0 ---
1.22 - add stream_cb API for custom protocols
--- mpv 0.18.1 ---
---- - remove "status" log level from mpv_request_log_messages() docs. This
is 100% equivalent to "v". The behavior is still the same, thus no
actual API change.
--- mpv 0.18.0 ---
1.21 - mpv_set_property() changes behavior with MPV_FORMAT_NODE. Before this
change it rejected mpv_nodes with format==MPV_FORMAT_STRING if the
property was not a string or did not have special mechanisms in place
the function failed. Now it always invokes the option string parser,
and mpv_node with a basic data type works exactly as if the function
is invoked with that type directly. This new behavior is equivalent
to mpv_set_option().
This also affects the mp.set_property_native() Lua function.
- generally, setting choice options/properties with "yes"/"no" options
can now be set as MPV_FORMAT_FLAG
- reading a choice property as MPV_FORMAT_NODE will now return a
MPV_FORMAT_FLAG value if the choice is "yes" (true) or "no" (false)
This implicitly affects Lua and JSON IPC interfaces as well.
- big changes to vo-cmdline on vo_opengl and vo_opengl_hq (but not
vo_opengl_cb): options are now normally not reset, but applied on top
of the current options. The special undocumented value "-" still
works, but now resets all options to before any vo-cmdline command
has been called.
--- mpv 0.12.0 ---
1.20 - deprecate "GL_MP_D3D_interfaces"/"glMPGetD3DInterface", and introduce
"GL_MP_MPGetNativeDisplay"/"glMPGetNativeDisplay" (this is a
backwards-compatible rename)
--- mpv 0.11.0 ---
--- mpv 0.10.0 ---
1.19 - add "GL_MP_D3D_interfaces" pseudo extension to make it possible to
use DXVA2 in OpenGL fullscreen mode in some situations
- mpv_request_log_messages() now accepts "terminal-default" as parameter
1.18 - add MPV_END_FILE_REASON_REDIRECT, and change behavior of
MPV_EVENT_END_FILE accordingly
- a bunch of interface-changes.rst changes
1.17 - mpv_initialize() now blocks SIGPIPE (details see client.h)
--- mpv 0.9.0 ---
1.17 - add MPV_FORMAT_BYTE_ARRAY
--- mpv 0.9.0 will be released ---
1.16 - add mpv_opengl_cb_report_flip()
- introduce mpv_opengl_cb_draw() and deprecate mpv_opengl_cb_render()
- add MPV_FORMAT_BYTE_ARRAY
1.15 - mpv_initialize() will now load config files. This requires setting
the "config" and "config-dir" options. In particular, it will load
mpv.conf.
- minor backwards-compatible change to the "seek" and "screenshot"
commands (new flag syntax, old additional args deprecated)
--- mpv 0.8.0 ---
--- mpv 0.8.0 is released ---
1.14 - add mpv_wait_async_requests()
- the --msg-level option changes its native type from a flat string to
a key-value list (setting/reading the option as string still works)
@@ -111,7 +47,7 @@ API changes
its own and mpv's OpenGL rendering
Warning: this API is not stable yet - anything in opengl_cb.h might
be changed in completely incompatible ways in minor API bumps
--- mpv 0.7.0 ---
--- mpv 0.7.0 is released ---
1.10 - deprecate/disable everything directly related to script_dispatch
(most likely affects nobody)
1.9 - add enum mpv_end_file_reason for mpv_event_end_file.reason
@@ -134,7 +70,7 @@ API changes
1.6 - modify "core-idle" property behavior
- MPV_EVENT_LOG_MESSAGE now always sends complete lines
- introduce numeric log levels (mpv_log_level)
--- mpv 0.6.0 ---
--- mpv 0.6.0 is released ---
1.5 - change in X11 and "--wid" behavior again. The previous change didn't
work as expected, and now the behavior can be explicitly controlled
with the "input-x11-keyboard" option. This is only a temporary
@@ -143,7 +79,7 @@ API changes
although the old option name still works.
1.4 - subtle change in X11 and "--wid" behavior
(this change was added to 0.5.2, and broke some things, see #1090)
--- mpv 0.5.0 ---
--- mpv 0.5.0 is released ---
1.3 - add MPV_MAKE_VERSION()
1.2 - remove "stream-time-pos" property (no replacement)
1.1 - remap dvdnav:// to dvd://
@@ -155,6 +91,6 @@ API changes
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 ---
--- mpv 0.4.0 is released ---
1.0 - the API is declared stable
+14
View File
@@ -0,0 +1,14 @@
All examples in this directory and its sub-directories are licensed
under one of the following licenses:
WTFPL, ISC, Ms-PL, AGPLv3, BSD (any)
Pick any license of your liking, and disregard the others.
(The full text of each license is available on this website:
http://opensource.org/licenses/alphabetical )
Additionally, you may consider the example code to be public domain.
You are free to use any of the example code without further
requirements or need for attribution.
+30
View File
@@ -0,0 +1,30 @@
Client API examples
===================
All these examples use the mpv client API through libmpv.
cocoa
-----
Shows how to embed the mpv video window in Objective-C/Cocoa.
qt
--
Shows how to embed the mpv video window in Qt (using normal desktop widgets).
qml
---
Shows how to use mpv's OpenGL video renderer in QtQuick2 with QML.
qml_direct
----------
Alternative example, which typically avoids a FBO indirection. Might be
slightly faster, but is less flexible and harder to use.
simple
------
Very primitive terminal-only example. Shows some most basic API usage.
+211
View File
@@ -0,0 +1,211 @@
// Plays a video from the command line in a window provided by mpv.
// You likely want to play the video in your own window instead,
// but that's not quite ready yet.
// You may need a basic Info.plist and MainMenu.xib to make this work.
// Build with: clang -o cocoabasic cocoabasic.m `pkg-config --libs --cflags mpv`
#include <mpv/client.h>
#include <stdio.h>
#include <stdlib.h>
static inline void check_error(int status)
{
if (status < 0) {
printf("mpv API error: %s\n", mpv_error_string(status));
exit(1);
}
}
#import <Cocoa/Cocoa.h>
@interface CocoaWindow : NSWindow
@end
@implementation CocoaWindow
- (BOOL)canBecomeMainWindow { return YES; }
- (BOOL)canBecomeKeyWindow { return YES; }
@end
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
mpv_handle *mpv;
dispatch_queue_t queue;
NSWindow *w;
NSView *wrapper;
}
@end
static void wakeup(void *);
@implementation AppDelegate
- (void)createWindow {
int mask = NSTitledWindowMask|NSClosableWindowMask|
NSMiniaturizableWindowMask|NSResizableWindowMask;
self->w = [[CocoaWindow alloc]
initWithContentRect:NSMakeRect(0,0, 1280, 720)
styleMask:mask
backing:NSBackingStoreBuffered
defer:NO];
[self->w setTitle:@"cocoabasic example"];
[self->w makeMainWindow];
[self->w makeKeyAndOrderFront:nil];
NSRect frame = [[self->w contentView] bounds];
self->wrapper = [[NSView alloc] initWithFrame:frame];
[self->wrapper setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
[[self->w contentView] addSubview:self->wrapper];
[self->wrapper release];
NSMenu *m = [[NSMenu alloc] initWithTitle:@"AMainMenu"];
NSMenuItem *item = [m addItemWithTitle:@"Apple" action:nil keyEquivalent:@""];
NSMenu *sm = [[NSMenu alloc] initWithTitle:@"Apple"];
[m setSubmenu:sm forItem:item];
[sm addItemWithTitle: @"mpv_command('stop')" action:@selector(mpv_stop) keyEquivalent:@""];
[sm addItemWithTitle: @"mpv_command('quit')" action:@selector(mpv_quit) keyEquivalent:@""];
[sm addItemWithTitle: @"quit" action:@selector(terminate:) keyEquivalent:@"q"];
[NSApp setMenu:m];
[NSApp activateIgnoringOtherApps:YES];
}
- (void) applicationDidFinishLaunching:(NSNotification *)notification {
[NSApp setActivationPolicy:NSApplicationActivationPolicyRegular];
atexit_b(^{
// Because activation policy has just been set to behave like a real
// application, that policy must be reset on exit to prevent, among
// other things, the menubar created here from remaining on screen.
[NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited];
});
// Read filename
NSArray *args = [NSProcessInfo processInfo].arguments;
if (args.count < 2) {
NSLog(@"Expected filename on command line");
exit(1);
}
NSString *filename = args[1];
[self createWindow];
// Deal with MPV in the background.
queue = dispatch_queue_create("mpv", DISPATCH_QUEUE_SERIAL);
dispatch_async(queue, ^{
mpv = mpv_create();
if (!mpv) {
printf("failed creating context\n");
exit(1);
}
int64_t wid = (intptr_t) self->wrapper;
check_error(mpv_set_option(mpv, "wid", MPV_FORMAT_INT64, &wid));
// Maybe set some options here, like default key bindings.
// NOTE: Interaction with the window seems to be broken for now.
check_error(mpv_set_option_string(mpv, "input-default-bindings", "yes"));
// for testing!
check_error(mpv_set_option_string(mpv, "input-media-keys", "yes"));
check_error(mpv_set_option_string(mpv, "input-cursor", "no"));
check_error(mpv_set_option_string(mpv, "input-vo-keyboard", "yes"));
// request important errors
check_error(mpv_request_log_messages(mpv, "warn"));
check_error(mpv_initialize(mpv));
// Register to be woken up whenever mpv generates new events.
mpv_set_wakeup_callback(mpv, wakeup, (__bridge void *) self);
// Load the indicated file
const char *cmd[] = {"loadfile", filename.UTF8String, NULL};
check_error(mpv_command(mpv, cmd));
});
}
- (void) handleEvent:(mpv_event *)event
{
switch (event->event_id) {
case MPV_EVENT_SHUTDOWN: {
mpv_detach_destroy(mpv);
mpv = NULL;
printf("event: shutdown\n");
break;
}
case MPV_EVENT_LOG_MESSAGE: {
struct mpv_event_log_message *msg = (struct mpv_event_log_message *)event->data;
printf("[%s] %s: %s", msg->prefix, msg->level, msg->text);
}
case MPV_EVENT_VIDEO_RECONFIG: {
dispatch_async(dispatch_get_main_queue(), ^{
NSArray *subviews = [self->wrapper subviews];
if ([subviews count] > 0) {
// mpv's events view
NSView *eview = [self->wrapper subviews][0];
[self->w makeFirstResponder:eview];
}
});
}
default:
printf("event: %s\n", mpv_event_name(event->event_id));
}
}
- (void) readEvents
{
dispatch_async(queue, ^{
while (mpv) {
mpv_event *event = mpv_wait_event(mpv, 0);
if (event->event_id == MPV_EVENT_NONE)
break;
[self handleEvent:event];
}
});
}
static void wakeup(void *context) {
AppDelegate *a = (__bridge AppDelegate *) context;
[a readEvents];
}
// Ostensibly, mpv's window would be hooked up to this.
- (BOOL) windowShouldClose:(id)sender
{
return NO;
}
- (void) mpv_stop
{
if (mpv) {
const char *args[] = {"stop", NULL};
mpv_command(mpv, args);
}
}
- (void) mpv_quit
{
if (mpv) {
const char *args[] = {"quit", NULL};
mpv_command(mpv, args);
}
}
@end
// Delete this if you already have a main.m.
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSApplication *app = [NSApplication sharedApplication];
AppDelegate *delegate = [AppDelegate new];
app.delegate = delegate;
[app run];
}
return EXIT_SUCCESS;
}
+136
View File
@@ -0,0 +1,136 @@
#include "main.h"
#include <stdexcept>
#include <clocale>
#include <QObject>
#include <QtGlobal>
#include <QOpenGLContext>
#include <QGuiApplication>
#include <QtGui/QOpenGLFramebufferObject>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QQuickView>
class MpvRenderer : public QQuickFramebufferObject::Renderer
{
static void *get_proc_address(void *ctx, const char *name) {
(void)ctx;
QOpenGLContext *glctx = QOpenGLContext::currentContext();
if (!glctx)
return NULL;
return (void *)glctx->getProcAddress(QByteArray(name));
}
mpv::qt::Handle mpv;
QQuickWindow *window;
mpv_opengl_cb_context *mpv_gl;
public:
MpvRenderer(const MpvObject *obj)
: mpv(obj->mpv), window(obj->window()), mpv_gl(obj->mpv_gl)
{
int r = mpv_opengl_cb_init_gl(mpv_gl, NULL, get_proc_address, NULL);
if (r < 0)
throw std::runtime_error("could not initialize OpenGL");
}
virtual ~MpvRenderer()
{
// Until this call is done, we need to make sure the player remains
// alive. This is done implicitly with the mpv::qt::Handle instance
// in this class.
mpv_opengl_cb_uninit_gl(mpv_gl);
}
void render()
{
QOpenGLFramebufferObject *fbo = framebufferObject();
window->resetOpenGLState();
mpv_opengl_cb_draw(mpv_gl, fbo->handle(), fbo->width(), fbo->height());
window->resetOpenGLState();
}
};
MpvObject::MpvObject(QQuickItem * parent)
: QQuickFramebufferObject(parent), mpv_gl(0)
{
mpv = mpv::qt::Handle::FromRawHandle(mpv_create());
if (!mpv)
throw std::runtime_error("could not create mpv context");
mpv_set_option_string(mpv, "terminal", "yes");
mpv_set_option_string(mpv, "msg-level", "all=v");
if (mpv_initialize(mpv) < 0)
throw std::runtime_error("could not initialize mpv context");
// Make use of the MPV_SUB_API_OPENGL_CB API.
mpv::qt::set_option_variant(mpv, "vo", "opengl-cb");
// Request hw decoding, just for testing.
mpv::qt::set_option_variant(mpv, "hwdec", "auto");
// Setup the callback that will make QtQuick update and redraw if there
// is a new video frame. Use a queued connection: this makes sure the
// doUpdate() function is run on the GUI thread.
mpv_gl = (mpv_opengl_cb_context *)mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB);
if (!mpv_gl)
throw std::runtime_error("OpenGL not compiled in");
mpv_opengl_cb_set_update_callback(mpv_gl, MpvObject::on_update, (void *)this);
connect(this, &MpvObject::onUpdate, this, &MpvObject::doUpdate,
Qt::QueuedConnection);
}
MpvObject::~MpvObject()
{
if (mpv_gl)
mpv_opengl_cb_set_update_callback(mpv_gl, NULL, NULL);
}
void MpvObject::on_update(void *ctx)
{
MpvObject *self = (MpvObject *)ctx;
emit self->onUpdate();
}
// connected to onUpdate(); signal makes sure it runs on the GUI thread
void MpvObject::doUpdate()
{
update();
}
void MpvObject::command(const QVariant& params)
{
mpv::qt::command_variant(mpv, params);
}
void MpvObject::setProperty(const QString& name, const QVariant& value)
{
mpv::qt::set_property_variant(mpv, name, value);
}
QQuickFramebufferObject::Renderer *MpvObject::createRenderer() const
{
window()->setPersistentOpenGLContext(true);
window()->setPersistentSceneGraph(true);
return new MpvRenderer(this);
}
int main(int argc, char **argv)
{
QGuiApplication app(argc, argv);
// Qt sets the locale in the QGuiApplication constructor, but libmpv
// requires the LC_NUMERIC category to be set to "C", so change it back.
std::setlocale(LC_NUMERIC, "C");
qmlRegisterType<MpvObject>("mpvtest", 1, 0, "MpvObject");
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
view.setSource(QUrl("qrc:///mpvtest/main.qml"));
view.show();
return app.exec();
}
+36
View File
@@ -0,0 +1,36 @@
#ifndef MPVRENDERER_H_
#define MPVRENDERER_H_
#include <QtQuick/QQuickFramebufferObject>
#include <mpv/client.h>
#include <mpv/opengl_cb.h>
#include <mpv/qthelper.hpp>
class MpvRenderer;
class MpvObject : public QQuickFramebufferObject
{
Q_OBJECT
mpv::qt::Handle mpv;
mpv_opengl_cb_context *mpv_gl;
friend class MpvRenderer;
public:
MpvObject(QQuickItem * parent = 0);
virtual ~MpvObject();
virtual Renderer *createRenderer() const;
public slots:
void command(const QVariant& params);
void setProperty(const QString& name, const QVariant& value);
signals:
void onUpdate();
private slots:
void doUpdate();
private:
static void on_update(void *ctx);
};
#endif
+71
View File
@@ -0,0 +1,71 @@
import QtQuick 2.0
import QtQuick.Controls 1.0
import mpvtest 1.0
Item {
width: 1280
height: 720
MpvObject {
id: renderer
anchors.fill: parent
MouseArea {
anchors.fill: parent
onClicked: renderer.command(["loadfile", "../../../test.mkv"])
}
}
Rectangle {
id: labelFrame
anchors.margins: -50
radius: 5
color: "white"
border.color: "black"
opacity: 0.8
anchors.fill: box
}
Row {
id: box
anchors.bottom: renderer.bottom
anchors.left: renderer.left
anchors.right: renderer.right
anchors.margins: 100
Text {
anchors.margins: 10
wrapMode: Text.WordWrap
text: "QtQuick and mpv are both rendering stuff.\n
Click to load ../../../test.mkv"
}
// Don't take these controls too seriously. They're for testing.
Column {
CheckBox {
id: checkbox
anchors.margins: 10
// Heavily filtered means good, right?
text: "Make video look like on a Smart TV"
onClicked: {
if (checkbox.checked) {
renderer.command(["vo_cmdline", "scale=sharpen3:scale-param1=5.0"])
} else {
renderer.command(["vo_cmdline", ""])
}
}
}
Slider {
id: slider
anchors.margins: 10
anchors.left: checkbox.left
anchors.right: checkbox.right
minimumValue: -100
maximumValue: 100
value: 0
onValueChanged: renderer.setProperty("gamma", slider.value | 0)
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
QT += qml quick
HEADERS += main.h
SOURCES += main.cpp
CONFIG += link_pkgconfig debug
PKGCONFIG += mpv
RESOURCES += mpvtest.qrc
OTHER_FILES += main.qml
+5
View File
@@ -0,0 +1,5 @@
<RCC>
<qresource prefix="/mpvtest">
<file>main.qml</file>
</qresource>
</RCC>
@@ -0,0 +1,159 @@
#include "main.h"
#include <stdexcept>
#include <clocale>
#include <QObject>
#include <QtGlobal>
#include <QOpenGLContext>
#include <QGuiApplication>
#include <QtQuick/QQuickWindow>
#include <QtQuick/QQuickView>
static void *get_proc_address(void *ctx, const char *name) {
(void)ctx;
QOpenGLContext *glctx = QOpenGLContext::currentContext();
if (!glctx)
return NULL;
return (void *)glctx->getProcAddress(QByteArray(name));
}
MpvRenderer::MpvRenderer(mpv::qt::Handle a_mpv, mpv_opengl_cb_context *a_mpv_gl)
: mpv(a_mpv), mpv_gl(a_mpv_gl), window(0), size()
{
int r = mpv_opengl_cb_init_gl(mpv_gl, NULL, get_proc_address, NULL);
if (r < 0)
throw std::runtime_error("could not initialize OpenGL");
}
MpvRenderer::~MpvRenderer()
{
// Until this call is done, we need to make sure the player remains
// alive. This is done implicitly with the mpv::qt::Handle instance
// in this class.
mpv_opengl_cb_uninit_gl(mpv_gl);
}
void MpvRenderer::paint()
{
window->resetOpenGLState();
// This uses 0 as framebuffer, which indicates that mpv will render directly
// to the frontbuffer. Note that mpv will always switch framebuffers
// explicitly. Some QWindow setups (such as using QQuickWidget) actually
// want you to render into a FBO in the beforeRendering() signal, and this
// code won't work there.
// The negation is used for rendering with OpenGL's flipped coordinates.
mpv_opengl_cb_draw(mpv_gl, 0, size.width(), -size.height());
window->resetOpenGLState();
}
MpvObject::MpvObject(QQuickItem * parent)
: QQuickItem(parent), mpv_gl(0), renderer(0)
{
mpv = mpv::qt::Handle::FromRawHandle(mpv_create());
if (!mpv)
throw std::runtime_error("could not create mpv context");
mpv_set_option_string(mpv, "terminal", "yes");
mpv_set_option_string(mpv, "msg-level", "all=v");
if (mpv_initialize(mpv) < 0)
throw std::runtime_error("could not initialize mpv context");
// Make use of the MPV_SUB_API_OPENGL_CB API.
mpv::qt::set_option_variant(mpv, "vo", "opengl-cb");
// Setup the callback that will make QtQuick update and redraw if there
// is a new video frame. Use a queued connection: this makes sure the
// doUpdate() function is run on the GUI thread.
mpv_gl = (mpv_opengl_cb_context *)mpv_get_sub_api(mpv, MPV_SUB_API_OPENGL_CB);
if (!mpv_gl)
throw std::runtime_error("OpenGL not compiled in");
mpv_opengl_cb_set_update_callback(mpv_gl, MpvObject::on_update, (void *)this);
connect(this, &MpvObject::onUpdate, this, &MpvObject::doUpdate,
Qt::QueuedConnection);
connect(this, &QQuickItem::windowChanged,
this, &MpvObject::handleWindowChanged);
}
MpvObject::~MpvObject()
{
if (mpv_gl)
mpv_opengl_cb_set_update_callback(mpv_gl, NULL, NULL);
}
void MpvObject::handleWindowChanged(QQuickWindow *win)
{
if (!win)
return;
connect(win, &QQuickWindow::beforeSynchronizing,
this, &MpvObject::sync, Qt::DirectConnection);
connect(win, &QQuickWindow::sceneGraphInvalidated,
this, &MpvObject::cleanup, Qt::DirectConnection);
connect(win, &QQuickWindow::frameSwapped,
this, &MpvObject::swapped, Qt::DirectConnection);
win->setClearBeforeRendering(false);
}
void MpvObject::sync()
{
if (!renderer) {
renderer = new MpvRenderer(mpv, mpv_gl);
connect(window(), &QQuickWindow::beforeRendering,
renderer, &MpvRenderer::paint, Qt::DirectConnection);
}
renderer->window = window();
renderer->size = window()->size() * window()->devicePixelRatio();
}
void MpvObject::swapped()
{
mpv_opengl_cb_report_flip(mpv_gl, 0);
}
void MpvObject::cleanup()
{
if (renderer) {
delete renderer;
renderer = 0;
}
}
void MpvObject::on_update(void *ctx)
{
MpvObject *self = (MpvObject *)ctx;
emit self->onUpdate();
}
// connected to onUpdate(); signal makes sure it runs on the GUI thread
void MpvObject::doUpdate()
{
window()->update();
}
void MpvObject::command(const QVariant& params)
{
mpv::qt::command_variant(mpv, params);
}
int main(int argc, char **argv)
{
QGuiApplication app(argc, argv);
// Qt sets the locale in the QGuiApplication constructor, but libmpv
// requires the LC_NUMERIC category to be set to "C", so change it back.
std::setlocale(LC_NUMERIC, "C");
qmlRegisterType<MpvObject>("mpvtest", 1, 0, "MpvObject");
QQuickView view;
view.setResizeMode(QQuickView::SizeRootObjectToView);
view.setSource(QUrl("qrc:///mpvtest/main.qml"));
view.show();
return app.exec();
}
@@ -0,0 +1,51 @@
#ifndef MPVRENDERER_H_
#define MPVRENDERER_H_
#include <QtQuick/QQuickItem>
#include <mpv/client.h>
#include <mpv/opengl_cb.h>
#include <mpv/qthelper.hpp>
class MpvRenderer : public QObject
{
Q_OBJECT
mpv::qt::Handle mpv;
mpv_opengl_cb_context *mpv_gl;
QQuickWindow *window;
QSize size;
friend class MpvObject;
public:
MpvRenderer(mpv::qt::Handle a_mpv, mpv_opengl_cb_context *a_mpv_gl);
virtual ~MpvRenderer();
public slots:
void paint();
};
class MpvObject : public QQuickItem
{
Q_OBJECT
mpv::qt::Handle mpv;
mpv_opengl_cb_context *mpv_gl;
MpvRenderer *renderer;
public:
MpvObject(QQuickItem * parent = 0);
virtual ~MpvObject();
public slots:
void command(const QVariant& params);
void sync();
void swapped();
void cleanup();
signals:
void onUpdate();
private slots:
void doUpdate();
void handleWindowChanged(QQuickWindow *win);
private:
static void on_update(void *ctx);
};
#endif
@@ -0,0 +1,49 @@
import QtQuick 2.0
import QtQuick.Controls 1.0
import mpvtest 1.0
Item {
width: 1280
height: 720
MpvObject {
id: renderer
// This object isn't real and not visible; it just renders into the
// background of the containing Window.
width: 0
height: 0
}
MouseArea {
anchors.fill: parent
onClicked: renderer.command(["loadfile", "../../../test.mkv"])
}
Rectangle {
id: labelFrame
anchors.margins: -50
radius: 5
color: "white"
border.color: "black"
opacity: 0.8
anchors.fill: box
}
Row {
id: box
anchors.bottom: parent.bottom
anchors.left: parent.left
anchors.right: parent.right
anchors.margins: 100
Text {
anchors.margins: 10
wrapMode: Text.WordWrap
text: "QtQuick and mpv are both rendering stuff.\n
In this example, mpv is always in the background.\n
Click to load ../../../test.mkv"
}
}
}
@@ -0,0 +1,11 @@
QT += qml quick
HEADERS += main.h
SOURCES += main.cpp
CONFIG += link_pkgconfig debug
PKGCONFIG += mpv
RESOURCES += mpvtest.qrc
OTHER_FILES += main.qml
@@ -0,0 +1,5 @@
<RCC>
<qresource prefix="/mpvtest">
<file>main.qml</file>
</qresource>
</RCC>
+225
View File
@@ -0,0 +1,225 @@
// This example can be built with: qmake && make
#include <clocale>
#include <sstream>
#include <stdexcept>
#include <QtGlobal>
#include <QFileDialog>
#include <QStatusBar>
#include <QMenuBar>
#include <QMenu>
#include <QGridLayout>
#include <QApplication>
#include <QTextEdit>
#if QT_VERSION >= 0x050000
#include <QJsonDocument>
#endif
#include <mpv/qthelper.hpp>
#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;
emit mainwindow->mpv_events();
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
setWindowTitle("Qt embedding demo");
setMinimumSize(640, 480);
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, &QAction::triggered, this, &MainWindow::on_file_open);
menu->addAction(on_open);
QAction *on_new = new QAction(tr("&New window"), this);
connect(on_new, &QAction::triggered, this, &MainWindow::on_new_window);
menu->addAction(on_new);
statusBar();
QMainWindow *log_window = new QMainWindow(this);
log = new QTextEdit(log_window);
log->setReadOnly(true);
log_window->setCentralWidget(log);
log_window->setWindowTitle("mpv log window");
log_window->setMinimumSize(500, 50);
log_window->show();
mpv = mpv_create();
if (!mpv)
throw std::runtime_error("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. Works on: X11, win32, Cocoa
mpv_container = new QWidget(this);
setCentralWidget(mpv_container);
mpv_container->setAttribute(Qt::WA_DontCreateNativeAncestors);
mpv_container->setAttribute(Qt::WA_NativeWindow);
// If you have a HWND, use: int64_t wid = (intptr_t)hwnd;
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");
// Enable keyboard input on the X11 window. For the messy details, see
// --input-vo-keyboard on the manpage.
mpv_set_option_string(mpv, "input-vo-keyboard", "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);
mpv_observe_property(mpv, 0, "track-list", MPV_FORMAT_NODE);
mpv_observe_property(mpv, 0, "chapter-list", MPV_FORMAT_NODE);
// Request log messages with level "info" or higher.
// They are received as MPV_EVENT_LOG_MESSAGE.
mpv_request_log_messages(mpv, "info");
// From this point on, the wakeup function will be called. The callback
// can come from any thread, so we use the QueuedConnection mechanism to
// relay the wakeup in a thread-safe way.
connect(this, &MainWindow::mpv_events, this, &MainWindow::on_mpv_events,
Qt::QueuedConnection);
mpv_set_wakeup_callback(mpv, wakeup, this);
if (mpv_initialize(mpv) < 0)
throw std::runtime_error("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("");
}
} else if (strcmp(prop->name, "chapter-list") == 0 ||
strcmp(prop->name, "track-list") == 0)
{
// Dump the properties as JSON for demo purposes.
#if QT_VERSION >= 0x050000
if (prop->format == MPV_FORMAT_NODE) {
QVariant v = mpv::qt::node_to_variant((mpv_node *)prop->data);
// Abuse JSON support for easily printing the mpv_node contents.
QJsonDocument d = QJsonDocument::fromVariant(v);
append_log("Change property " + QString(prop->name) + ":\n");
append_log(d.toJson().data());
}
#endif
}
break;
}
case MPV_EVENT_VIDEO_RECONFIG: {
// Retrieve the new video size.
int64_t w, h;
if (mpv_get_property(mpv, "dwidth", MPV_FORMAT_INT64, &w) >= 0 &&
mpv_get_property(mpv, "dheight", MPV_FORMAT_INT64, &h) >= 0 &&
w > 0 && h > 0)
{
// Note that the MPV_EVENT_VIDEO_RECONFIG event doesn't necessarily
// imply a resize, and you should check yourself if the video
// dimensions really changed.
// mpv itself will scale/letter box the video to the container size
// if the video doesn't fit.
std::stringstream ss;
ss << "Reconfig: " << w << " " << h;
statusBar()->showMessage(QString::fromStdString(ss.str()));
}
break;
}
case MPV_EVENT_LOG_MESSAGE: {
struct mpv_event_log_message *msg = (struct mpv_event_log_message *)event->data;
std::stringstream ss;
ss << "[" << msg->prefix << "] " << msg->level << ": " << msg->text;
append_log(QString::fromStdString(ss.str()));
break;
}
case MPV_EVENT_SHUTDOWN: {
mpv_terminate_destroy(mpv);
mpv = NULL;
break;
}
default: ;
// Ignore uninteresting or unknown events.
}
}
// This slot is invoked by wakeup() (through the mpv_events signal).
void MainWindow::on_mpv_events()
{
// 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);
}
}
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);
}
}
void MainWindow::on_new_window()
{
(new MainWindow())->show();
}
void MainWindow::append_log(const QString &text)
{
QTextCursor cursor = log->textCursor();
cursor.movePosition(QTextCursor::End);
cursor.insertText(text);
log->setTextCursor(cursor);
}
MainWindow::~MainWindow()
{
if (mpv)
mpv_terminate_destroy(mpv);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// Qt sets the locale in the QApplication constructor, but libmpv requires
// the LC_NUMERIC category to be set to "C", so change it back.
std::setlocale(LC_NUMERIC, "C");
MainWindow w;
w.show();
return a.exec();
}
+37
View File
@@ -0,0 +1,37 @@
#ifndef QTEXAMPLE_H
#define QTEXAMPLE_H
#include <QMainWindow>
#include <mpv/client.h>
class QTextEdit;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_file_open();
void on_new_window();
void on_mpv_events();
signals:
void mpv_events();
private:
QWidget *mpv_container;
mpv_handle *mpv;
QTextEdit *log;
void append_log(const QString &text);
void create_player();
void handle_mpv_event(mpv_event *event);
};
#endif // QTEXAMPLE_H
+12
View File
@@ -0,0 +1,12 @@
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = qtexample
TEMPLATE = app
CONFIG += link_pkgconfig debug
PKGCONFIG += mpv
SOURCES += qtexample.cpp
HEADERS += qtexample.h
+54
View File
@@ -0,0 +1,54 @@
// Build with: gcc -o simple simple.c `pkg-config --libs --cflags mpv`
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <mpv/client.h>
static inline void check_error(int status)
{
if (status < 0) {
printf("mpv API error: %s\n", mpv_error_string(status));
exit(1);
}
}
int main(int argc, char *argv[])
{
if (argc != 2) {
printf("pass a single media file as argument\n");
return 1;
}
mpv_handle *ctx = mpv_create();
if (!ctx) {
printf("failed creating context\n");
return 1;
}
// Enable default key bindings, so the user can actually interact with
// the player (and e.g. close the window).
check_error(mpv_set_option_string(ctx, "input-default-bindings", "yes"));
mpv_set_option_string(ctx, "input-vo-keyboard", "yes");
int val = 1;
check_error(mpv_set_option(ctx, "osc", MPV_FORMAT_FLAG, &val));
// Done setting up options.
check_error(mpv_initialize(ctx));
// Play this file.
const char *cmd[] = {"loadfile", argv[1], NULL};
check_error(mpv_command(ctx, cmd));
// Let it play, and wait until the user quits.
while (1) {
mpv_event *event = mpv_wait_event(ctx, 10000);
printf("event: %s\n", mpv_event_name(event->event_id));
if (event->event_id == MPV_EVENT_SHUTDOWN)
break;
}
mpv_terminate_destroy(ctx);
return 0;
}
+41 -47
View File
@@ -68,7 +68,7 @@ echo "MXE_TARGETS := i686-w64-mingw32.static" >> settings.mk
# Build required packages. The following provide a minimum required to build
# a reasonable mpv binary (though not an absolute minimum).
make gcc ffmpeg libass jpeg lua
make gcc ffmpeg libass jpeg pthreads lua
# Add MXE binaries to $PATH
export PATH=/opt/mxe/usr/bin/:$PATH
@@ -104,21 +104,22 @@ Installing MSYS2
It doesn't matter whether the i686 or the x86_64 version is used. Both can
build 32-bit and 64-bit binaries when running on a 64-bit version of Windows.
2. Start a MinGW-w64 shell (``mingw64.exe``). Note that this is different
from the MSYS2 shell that is started from the final installation dialog.
2. Add ``C:\msys64\mingw64\bin`` to your ``%PATH%``. mpv will depend on several
DLLs in this folder.
For a 32-bit build, use ``mingw32.exe``.
3. Start a MinGW-w64 shell (``mingw64_shell.bat``). For a 32-bit build, use
``mingw32_shell.bat``.
Updating MSYS2
--------------
To prevent errors during post-install, the MSYS2 core runtime must be updated
separately.
To prevent errors during post-install, ``msys2-runtime`` and ``pacman`` must be
updated first.
```bash
# Check for core updates. If instructed, close the shell window and reopen it
# before continuing.
pacman -Syu
# Check for updates to msys2-runtime and pacman. If there were updates, restart
# MSYS2 before continuing.
pacman -Sy --needed msys2-runtime pacman
# Update everything else
pacman -Su
@@ -129,14 +130,14 @@ Installing mpv dependencies
```bash
# Install MSYS2 build dependencies and a MinGW-w64 compiler
pacman -S git mingw-w64-x86_64-pkg-config python mingw-w64-x86_64-gcc
pacman -S git pkg-config python3 mingw-w64-x86_64-gcc
# Install the most important MinGW-w64 dependencies. libass, libbluray and
# lcms2 are also pulled in as dependencies of ffmpeg.
pacman -S mingw-w64-x86_64-ffmpeg mingw-w64-x86_64-libjpeg-turbo mingw-w64-x86_64-lua51
pacman -S mingw-w64-x86_64-ffmpeg mingw-w64-x86_64-libjpeg-turbo mingw-w64-x86_64-lua
# Install additional (optional) dependencies
pacman -S mingw-w64-x86_64-libdvdnav mingw-w64-x86_64-libguess mingw-w64-x86_64-angleproject-git
pacman -S mingw-w64-x86_64-libdvdnav mingw-w64-x86_64-mpg123 mingw-w64-x86_64-libguess
```
For a 32-bit build, install ``mingw-w64-i686-*`` packages instead.
@@ -156,14 +157,14 @@ Finally, compile and install mpv. Binaries will be installed to
```bash
# For a 32-bit build, use --prefix=/mingw32 instead
./waf configure CC=gcc.exe --check-c-compiler=gcc --prefix=/mingw64
./waf configure CC=gcc --prefix=/mingw64
./waf install
```
Or, compile and install both libmpv and mpv:
```bash
./waf configure CC=gcc.exe --check-c-compiler=gcc --enable-libmpv-shared --prefix=/mingw64
./waf configure CC=gcc --enable-libmpv-shared --prefix=/mingw64
./waf install
# waf installs libmpv to the wrong directory, so fix it up
@@ -173,46 +174,39 @@ sed -i 's_/mingw64/bin_/mingw64/lib_' /mingw64/lib/pkgconfig/mpv.pc
rmdir /mingw64/bin/pkgconfig
```
Linking libmpv with MSVC programs
---------------------------------
Additional dependencies
=======================
You can build C++ programs in Visual Studio and link them with libmpv. To do
this, you need a Visual Studio which supports ``stdint.h`` (recent ones do),
and you need to create a import library for the mpv DLL:
pthreads
--------
mpv will use a pthreads wrapper by default. Either pthreads-win32 or
winpthreads should work. The latter is packaged with most MinGW-w64
environments, including MSYS2, so it shouldn't be a problem. If you don't have
a pthreads wrapper or you want to build mpv without one, configure with:
```bash
lib /def:mpv.def /name:mpv-1.dll /out:mpv.lib /MACHINE:X64
./waf configure --enable-win32-internal-pthreads
```
The string in the ``/name:`` parameter must match the filename of the DLL (this
is simply the filename the MSVC linker will use). The ``mpv.def`` can be
retrieved from the mpv build directory, or can be produced by MingGW's
gendef.exe helper from the mpv DLL.
libwaio
-------
Static linking is not possible.
If you want to use ``--input-file``, you need libwaio. It's available from
git://midipix.org/waio
Running mpv
-----------
If you want to run mpv from the MinGW-w64 shell, you will find the experience
much more pleasant if you use the ``winpty`` utility
To compile libwaio in MSYS2, run:
```bash
pacman -S winpty
winpty mpv.com ToS-4k-1920.mov
git clone git://midipix.org/waio && cd waio
# 32-bit build, run from mingw32_shell.bat
./build-mingw-nt32 lib-static CC=gcc AR=ar
cp -r include/waio /mingw32/include
cp lib32/libwaio.a /mingw32/lib
# 64-bit build, run from mingw64_shell.bat
./build-mingw-nt64 lib-static CC=gcc AR=ar
cp -r include/waio /mingw64/include
cp lib64/libwaio.a /mingw64/lib
```
If you want to move / copy ``mpv.exe`` and ``mpv.com`` to somewhere other than
``/mingw64/bin/`` for use outside the MinGW-w64 shell, they will still depend on
DLLs in that folder. The simplest solution is to add ``C:\msys64\mingw64\bin``
to the windows system ``%PATH%``. Beware though that this can cause problems or
confusion in Cygwin if that is also installed on the machine.
Use of the ANGLE OpenGL backend requires a copy of ``d3dcompiler_43.dll`` (yes,
exactly 43) in the path or in the same folder as mpv. It must be of the same
architecture (x86_64 / i686) as the mpv you compiled. You can find a copy in the
official mpv builds:
https://mpv.srsfckn.biz/mpv-x86_64-20160118.7z
https://mpv.srsfckn.biz/mpv-i686-20160118.7z
+8 -13
View File
@@ -4,8 +4,8 @@ How to contribute
General
-------
The main contact for mpv development is IRC, specifically #mpv
and #mpv-devel on Freenode.
The main contact for mpv development is IRC, specifically #mpv-player
and #mpv-player-dev on Freenode.
Sending patches
---------------
@@ -14,11 +14,9 @@ Sending patches
``git format-patch``. diffs posted as pastebins (especially if the http link
returns HTML) just cause extra work for everyone, because they lack commit
message and authorship information.
- All new code must be LGPLv2.1+ licensed, or come with the implicit agreement
that it will be relicensed to LGPLv2.1+ later (see ``Copyright`` in the
repository root directory).
- When creating pull requests, be sure to test your changes. If you didn't,
please say so in the pull request message.
- When creating pull requests, be sure to test your changes. If you didn't, please
say so in the pull request message.
- Write informative commit messages. Use present tense to describe the
situation with the patch applied, and past tense for the situation before
the change.
@@ -29,8 +27,8 @@ Sending patches
For example, you fixed a crash in af_volume.c:
- Bad: ``fixed the bug (wtf?)``
- Good: ``af_volume: fix crash due to null pointer access``
Bad: ``fixed the bug (wtf?)``
Good: ``af_volume: fix crash due to null pointer access``
Having a prefix gives context, and is especially useful when trying to find
a specific change by looking at the history, or when running ``git blame``.
@@ -55,10 +53,7 @@ Sending patches
something like reformatting a whole file, and hiding an actual functional
change in the same commit.
- If you add a new command line option, document it in options.rst. If you
add a new input property, document it in input.rst. Changes to the user
interface (options, properties, commands) should be documented in
interface-changes.rst. Changes to libmpv should be documented in
client-api-changes.rst.
add a new input property, document it in input.rst.
Code formatting
---------------
+3 -2
View File
@@ -31,8 +31,9 @@ estimated remaining duration of the source file is used.
Note::
Usage of relative or absolute paths as well as any protocol prefixes may be
prevented for security reasons.
mpv can't use ordered chapter files in EDL entries. Usage of relative or
absolute paths as well as any protocol prefixes is prevented for security
reasons.
Syntax of mpv EDL files
-260
View File
@@ -1,260 +0,0 @@
Introduction
============
mpv provides access to its internals via the following means:
- options
- commands
- properties
- events
All of these are important for interfacing both with end users and API users
(which include Lua scripts, libmpv, and the JSON IPC). As such, they constitute
a large part of the user interface and APIs.
This document lists changes to them. New changes are added to the top.
Interface changes
=================
::
--- mpv 0.21.0 ---
- setting certain options at runtime will now take care of updating them
property (see for example issue #3281). On the other hand, it will also
do runtime verification and reject option changes that do not work
(example: setting the "vf" option to a filter during playback, which fails
to initialize - the option value will remain at its old value). In general,
"set name value" should be mostly equivalent to "set options/name value"
in cases where the "name" property is not deprecated and "options/name"
exists - deviations from this are either bugs, or documented as caveats
in the "Inconsistencies between options and properties" manpage section.
- deprecate _all_ --vo and --ao suboptions. Generally, all suboptions are
replaced by global options, which do exactly the same. For example,
"--vo=opengl:scale=nearest" turns into "--scale=nearest". In some cases,
the global option is prefixed, e.g. "--vo=opengl:pbo" turns into
"--opengl-pbo".
Most of the exact replacements are documented here:
https://github.com/mpv-player/mpv/wiki/Option-replacement-list
- remove --vo=opengl-hq. Set --profile=opengl-hq instead. Note that this
profile does not force the VO. This means if you use the --vo option to
set another VO, it won't work. But this also means it can be used with
opengl-cb.
- remove the --vo=opengl "pre-shaders", "post-shaders" and "scale-shader"
sub-options: they were deprecated in favor of "user-shaders"
- deprecate --vo-defaults (no replacement)
- remove the vo-cmdline command. You can set OpenGL renderer options
directly via properties instead.
- deprecate the device/sink options on all AOs. Use --audio-device instead.
- deprecate "--ao=wasapi:exclusive" and "--ao=coreaudio:exclusive",
use --audio-exclusive instead.
- subtle changes in how "--no-..." options are treated mean that they are
not accessible under "options/..." anymore (instead, these are resolved
at parsing time). This does not affect options which start with "--no-",
but do not use the mechanism for negation options.
(Also see client API change for API version 1.23.)
- rename the following properties
- "demuxer" -> "current-demuxer"
- "fps" -> "container-fps"
- "idle" -> "idle-active"
- "cache" -> "cache-percent"
the old names are deprecated and will change behavior in mpv 0.22.0.
- remove deprecated "hwdec-active" and "hwdec-detected" properties
- deprecate the ao and vo auto-profiles (they never made any sense)
- deprecate "--vo=direct3d_shaders" - use "--vo=direct3d" instead.
Change "--vo=direct3d" to always use shaders by default.
- deprecate --playlist-pos option, renamed to --playlist-start
- deprecate the --chapter option, as it is redundant with --start/--end,
and conflicts with the semantics of the "chapter" property
- rename --sub-text-* to --sub-* and --ass-* to --sub-ass-* (old options
deprecated)
- incompatible change to cdda:// protocol options: the part after cdda://
now always sets the device, not the span or speed to be played. No
separating extra "/" is needed. The hidden --cdda-device options is also
deleted (it was redundant with the documented --cdrom-device).
- deprecate --vo=rpi. It will be removed in mpv 0.22.0. Its functionality
was folded into --vo=opengl, which now uses RPI hardware decoding by
treating it as a hardware overlay (without applying GL filtering). Also
to be changed in 0.22.0: the --fs flag will be reset to "no" by default
(like on the other platforms).
- deprecate --mute=auto (informally has been since 0.18.1)
- deprecate "resume" and "suspend" IPC commands. They will be completely
removed in 0.22.0.
- deprecate mp.suspend(), mp.resume(), mp.resume_all() Lua scripting
commands, as well as setting mp.use_suspend. They will be completely
removed in 0.22.0.
- the "seek" command's absolute seek mode will now interpret negative
seek times as relative from the end of the file (and clamps seeks that
still go before 0)
- add almost all options to the property list, meaning you can change
options without adding "options/" to the property name (a new section
has been added to the manpage describing some conflicting behavior
between options and properties)
- implement changing sub-speed during playback
- make many previously fixed options changeable at runtime (for example
--terminal, --osc, --ytdl, can all be enable/disabled after
mpv_initialize() - this can be extended to other still fixed options
on user requests)
--- mpv 0.20.0 ---
- add --image-display-duration option - this also means that image duration
is not influenced by --mf-fps anymore in the general case (this is an
incompatible change)
--- mpv 0.19.0 ---
- deprecate "balance" option/property (no replacement)
--- mpv 0.18.1 ---
- deprecate --heartbeat-cmd
- remove --softvol=no capability:
- deprecate --softvol, it now does nothing
- --volume, --mute, and the corresponding properties now always control
softvol, and behave as expected without surprises (e.g. you can set
them normally while no audio is initialized)
- rename --softvol-max to --volume-max (deprecated alias is added)
- the --volume-restore-data option and property are removed without
replacement. They were _always_ internal, and used for watch-later
resume/restore. Now --volume/--mute are saved directly instead.
- the previous point means resuming files with older watch-later configs
will print an error about missing --volume-restore-data (which you can
ignore), and will not restore the previous value
- as a consequence, volume controls will no longer control PulseAudio
per-application value, or use the system mixer's per-application
volume processing
- system or per-application volume can still be controlled with the
ao-volume and ao-mute properties (there are no command line options)
--- mpv 0.18.0 ---
- now ab-loops are active even if one of the "ab-loop-a"/"-b" properties is
unset ("no"), in which case the start of the file is used if the A loop
point is unset, and the end of the file for an unset B loop point
- deprecate --sub-ass=no option by --ass-style-override=strip
(also needs --embeddedfonts=no)
- add "hwdec-interop" and "hwdec-current" properties
- deprecated "hwdec-active" and "hwdec-detected" properties (to be removed
in mpv 0.20.0)
- choice option/property values that are "yes" or "no" will now be returned
as booleans when using the mpv_node functions in the client API, the
"native" property accessors in Lua, and the JSON API. They can be set as
such as well.
- the VO opengl fbo-format sub-option does not accept "rgb" or "rgba"
anymore
- all VO opengl prescalers have been removed (replaced by user scripts)
--- mpv 0.17.0 ---
- deprecate "track-list/N/audio-channels" property (use
"track-list/N/demux-channel-count" instead)
- remove write access to "stream-pos", and change semantics for read access
- Lua scripts now don't suspend mpv by default while script code is run
- add "cache-speed" property
- rename --input-unix-socket to --input-ipc-server, and make it work on
Windows too
- change the exact behavior of the "video-zoom" property
- --video-unscaled no longer disables --video-zoom and --video-aspect
To force the old behavior, set --video-zoom=0 and --video-aspect=0
--- mpv 0.16.0 ---
- change --audio-channels default to stereo (use --audio-channels=auto to
get the old default)
- add --audio-normalize-downmix
- change the default downmix behavior (--audio-normalize-downmix=yes to get
the old default)
- VO opengl custom shaders must now use "sample_pixel" as function name,
instead of "sample"
- change VO opengl scaler-resizes-only default to enabled
- add VO opengl "interpolation-threshold" suboption (introduces new default
behavior, which can change e.g. ``--video-sync=display-vdrop`` to the
worse, but is usually what you want)
- make "volume" and "mute" properties changeable even if no audio output is
active (this gives not-ideal behavior if --softvol=no is used)
- add "volume-max" and "mixer-active" properties
- ignore --input-cursor option for events injected by input commands like
"mouse", "keydown", etc.
--- mpv 0.15.0 ---
- change "yadif" video filter defaults
--- mpv 0.14.0 ---
- vo_opengl interpolation now requires --video-sync=display-... to be set
- change some vo_opengl defaults (including changing tscale)
- add "vsync-ratio", "estimated-display-fps" properties
- add --rebase-start-time option
This is a breaking change to start time handling. Instead of making start
time handling an aspect of different options and properties (like
"time-pos" vs. "playback-time"), make it dependent on the new option. For
compatibility, the "time-start" property now always returns 0, so code
which attempted to handle rebasing manually will not break.
--- mpv 0.13.0 ---
- remove VO opengl-cb frame queue suboptions (no replacement)
--- mpv 0.12.0 ---
- remove --use-text-osd (useless; fontconfig isn't a requirement anymore,
and text rendering is also lazily initialized)
- some time properties (at least "playback-time", "time-pos",
"time-remaining", "playtime-remaining") now are unavailable if the time
is unknown, instead of just assuming that the internal playback position
is 0
- add --audio-fallback-to-null option
- replace vf_format outputlevels suboption with "video-output-levels" global
property/option; also remove "colormatrix-output-range" property
- vo_opengl: remove sharpen3/sharpen5 scale filters, add sharpen sub-option
--- mpv 0.11.0 ---
- add "af-metadata" property
--- mpv 0.10.0 ---
- add --video-aspect-method option
- add --playlist-pos option
- add --video-sync* options
"display-sync-active" property
"vo-missed-frame-count" property
"audio-speed-correction" and "video-speed-correction" properties
- remove --demuxer-readahead-packets and --demuxer-readahead-bytes
add --demuxer-max-packets and --demuxer-max-bytes
(the new options are not replacement and have very different semantics)
- change "video-aspect" property: always settable, even if no video is
running; always return the override - if no override is set, return
the video's aspect ratio
- remove disc-nav (DVD, BD) related properties and commands
- add "option-info/<name>/set-locally" property
- add --cache-backbuffer; change --cache-default default to 75MB
the new total cache size is the sum of backbuffer and the cache size
specified by --cache-default or --cache
- add ``track-list/N/audio-channels`` property
- change --screenshot-tag-colorspace default value
- add --stretch-image-subs-to-screen
- add "playlist/N/title" property
- add --video-stereo-mode=no to disable auto-conversions
- add --force-seekable, and change default seekability in some cases
- add vf yadif/vavpp/vdpaupp interlaced-only suboptions
Also, the option is enabled by default (Except vf_yadif, which has
it enabled only if it's inserted by the deinterlace property.)
- add --hwdec-preload
- add ao coreaudio exclusive suboption
- add ``track-list/N/forced`` property
- add audio-params/channel-count and ``audio-params-out/channel-count props.
- add af volume replaygain-fallback suboption
- add video-params/stereo-in property
- add "keypress", "keydown", and "keyup" commands
- deprecate --ad-spdif-dtshd and enabling passthrough via --ad
add --audio-spdif as replacement
- remove "get_property" command
- remove --slave-broken
- add vo opengl custom shader suboptions (source-shader, scale-shader,
pre-shaders, post-shaders)
- completely change how the hwdec properties work:
- "hwdec" now reflects the --hwdec option
- "hwdec-detected" does partially what the old "hwdec" property did
(and also, "detected-hwdec" is removed)
- "hwdec-active" is added
- add protocol-list property
- deprecate audio-samplerate and audio-channels properties
(audio-params sub-properties are the replacement)
- add audio-params and audio-out-params properties
- deprecate "audio-format" property, replaced with "audio-codec-name"
- deprecate --media-title, replaced with --force-media-title
- deprecate "length" property, replaced with "duration"
- change volume property:
- the value 100 is now always "unchanged volume" - with softvol, the
range is 0 to --softvol-max, without it is 0-100
- the minimum value of --softvol-max is raised to 100
- remove vo opengl npot suboption
- add relative seeking by percentage to "seek" command
- add playlist_shuffle command
- add --force-window=immediate
- add ao coreaudio change-physical-format suboption
- remove vo opengl icc-cache suboption, add icc-cache-dir suboption
- add --screenshot-directory
- add --screenshot-high-bit-depth
- add --screenshot-jpeg-source-chroma
- default action for "rescan_external_files" command changes
--- mpv 0.9.0 ---
+220 -34
View File
@@ -11,10 +11,6 @@ syntax is:
To get a full list of available audio filters, see ``--af=help``.
Also, keep in mind that most actual filters are available via the ``lavfi``
wrapper, which gives you access to most of libavfilter's filters. This
includes all filters that have been ported from MPlayer to libavfilter.
You can also set defaults for each filter. The defaults are applied before the
normal filter parameters.
@@ -63,14 +59,11 @@ Available filters are:
(If you just want to set defaults for this filter that will be used
even by automatically inserted lavrresample instances, you should
prefer setting them with ``--af-defaults=lavrresample:...``.)
``normalize=<yes|no|auto>``
Whether to normalize when remixing channel layouts (default: auto).
``auto`` uses the value set by ``--audio-normalize-downmix``.
``o=<string>``
Set AVOptions on the SwrContext or AVAudioResampleContext. These should
be documented by FFmpeg or Libav.
``lavcac3enc[=options]``
``lavcac3enc[=tospdif[:bitrate[:minch]]]``
Encode multi-channel audio to AC-3 at runtime using libavcodec. Supports
16-bit native-endian input format, maximum 6 channels. The output is
big-endian when outputting a raw AC-3 stream, native-endian when
@@ -103,9 +96,58 @@ Available filters are:
If the input channel number is less than ``<minch>``, the filter will
detach itself (default: 3).
``encoder=<name>``
Select the libavcodec encoder used. Currently, this should be an AC-3
encoder, and using another codec will fail horribly.
``sweep[=speed]``
Produces a sine sweep.
``<0.0-1.0>``
Sine function delta, use very low values to hear the sweep.
``sinesuppress[=freq:decay]``
Remove a sine at the specified frequency. Useful to get rid of the 50/60 Hz
noise on low quality audio equipment. It only works on mono input.
``<freq>``
The frequency of the sine which should be removed (in Hz) (default:
50)
``<decay>``
Controls the adaptivity (a larger value will make the filter adapt to
amplitude and phase changes quicker, a smaller value will make the
adaptation slower) (default: 0.0001). Reasonable values are around
0.001.
``bs2b[=option1:option2:...]``
Bauer stereophonic to binaural transformation using libbs2b. Improves the
headphone listening experience by making the sound similar to that from
loudspeakers, allowing each ear to hear both channels and taking into
account the distance difference and the head shadowing effect. It is
applicable only to 2-channel audio.
``fcut=<300-1000>``
Set cut frequency in Hz.
``feed=<10-150>``
Set feed level for low frequencies in 0.1*dB.
``profile=<value>``
Several profiles are available for convenience:
:default: will be used if nothing else was specified (fcut=700,
feed=45)
:cmoy: Chu Moy circuit implementation (fcut=700, feed=60)
:jmeier: Jan Meier circuit implementation (fcut=650, feed=95)
If ``fcut`` or ``feed`` options are specified together with a profile, they
will be applied on top of the selected profile.
``hrtf[=flag]``
Head-related transfer function: Converts multichannel audio to 2-channel
output for headphones, preserving the spatiality of the sound.
==== ===================================
Flag Meaning
==== ===================================
m matrix decoding of the rear channel
s 2-channel matrix decoding
0 no matrix decoding (default)
==== ===================================
``equalizer=g1:g2:g3:...:g10``
10 octave band graphic equalizer, implemented using 10 IIR band-pass
@@ -164,7 +206,7 @@ Available filters are:
.. admonition:: Examples
``mpv --af=channels=4:[0-1,1-0,2-2,3-3] media.avi``
``mpv --af=channels=4:[0-1,1-0,0-2,1-3] media.avi``
Would change the number of channels to 4 and set up 4 routes that
swap channel 0 and channel 1 and leave channel 2 and 3 intact.
Observe that if media containing two channels were played back,
@@ -221,6 +263,13 @@ Available filters are:
used to do conversion itself, unlike this one which lets the filter system
handle the conversion.
``convert24``
Filter for internal use only. Converts between 24-bit and 32-bit sample
formats.
``convertsign``
Filter for internal use only. Converts between signed/unsigned formats.
``volume[=<volumedb>[:...]]``
Implements software volume control. Use this filter with caution since it
can reduce the signal to noise ratio of the sound. In most cases it is
@@ -245,10 +294,6 @@ Available filters are:
``replaygain-clip=yes|no``
Prevent clipping caused by replaygain by automatically lowering the
gain (default). Use ``replaygain-clip=no`` to disable this.
``replaygain-fallback``
Gain in dB to apply if the file has no replay gain tags. This option
is always applied if the replaygain logic is somehow inactive. If this
is applied, no other replaygain options are applied.
``softclip``
Turns soft clipping on. Soft-clipping can make the
sound more smooth if very high volume levels are used. Enable this
@@ -312,12 +357,121 @@ Available filters are:
``mpv '--af=format=channels=5.1' '--audio-channels=5.1'`` would always force
remixing audio to 5.1 and output it like this.
This filter supports the following ``af-command`` commands:
``sub[=fc:ch]``
Adds a subwoofer channel to the audio stream. The audio data used for
creating the subwoofer channel is an average of the sound in channel 0 and
channel 1. The resulting sound is then low-pass filtered by a 4th order
Butterworth filter with a default cutoff frequency of 60Hz and added to a
separate channel in the audio stream.
``set-matrix``
Set the ``<matrix>`` argument dynamically. This can be used to change
the mixing matrix at runtime, without reinitializing the entire filter
chain.
.. warning::
Disable this filter when you are playing media with an LFE channel
(e.g. 5.1 surround sound), otherwise this filter will disrupt the sound
to the subwoofer.
``<fc>``
cutoff frequency in Hz for the low-pass filter (20 Hz to 300 Hz)
(default: 60 Hz) For the best result try setting the cutoff frequency
as low as possible. This will improve the stereo or surround sound
experience.
``<ch>``
Determines the channel number in which to insert the sub-channel
audio. Channel number can be between 0 and 7 (default: 5). Observe
that the number of channels will automatically be increased to <ch> if
necessary.
.. admonition:: Example
``mpv --af=sub=100:4 --audio-channels=5 media.avi``
Would add a subwoofer channel with a cutoff frequency of 100 Hz to
output channel 4.
``center``
Creates a center channel from the front channels. May currently be low
quality as it does not implement a high-pass filter for proper extraction
yet, but averages and halves the channels instead.
``<ch>``
Determines the channel number in which to insert the center channel.
Channel number can be between 0 and 7 (default: 5). Observe that the
number of channels will automatically be increased to ``<ch>`` if
necessary.
``surround[=delay]``
Decoder for matrix encoded surround sound like Dolby Surround. Some files
with 2-channel audio actually contain matrix encoded surround sound.
``<delay>``
delay time in ms for the rear speakers (0 to 1000) (default: 20) This
delay should be set as follows: If d1 is the distance from the
listening position to the front speakers and d2 is the distance from
the listening position to the rear speakers, then the delay should be
set to 15ms if d1 <= d2 and to 15 + 5*(d1-d2) if d1 > d2.
.. admonition:: Example
``mpv --af=surround=15 --audio-channels=4 media.avi``
Would add surround sound decoding with 15 ms delay for the sound to
the rear speakers.
``delay[=[ch1,ch2,...]]``
Delays the sound to the loudspeakers such that the sound from the
different channels arrives at the listening position simultaneously. It is
only useful if you have more than 2 loudspeakers.
``[ch1,ch2,...]``
The delay in ms that should be imposed on each channel (floating point
number between 0 and 1000).
To calculate the required delay for the different channels, do as follows:
1. Measure the distance to the loudspeakers in meters in relation to your
listening position, giving you the distances s1 to s5 (for a 5.1
system). There is no point in compensating for the subwoofer (you will
not hear the difference anyway).
2. Subtract the distances s1 to s5 from the maximum distance, i.e.
``s[i] = max(s) - s[i]; i = 1...5``.
3. Calculate the required delays in ms as ``d[i] = 1000*s[i]/342; i =
1...5``.
.. admonition:: Example
``mpv --af=delay=[10.5,10.5,0,0,7,0] media.avi``
Would delay front left and right by 10.5 ms, the two rear channels
and the subwoofer by 0 ms and the center channel by 7 ms.
``export=mmapped_file:nsamples]``
Exports the incoming signal to other processes using memory mapping
(``mmap()``). Memory mapped areas contain a header::
int nch /* number of channels */
int size /* buffer size */
unsigned long long counter /* Used to keep sync, updated every time
new data is exported. */
The rest is payload (non-interleaved) 16-bit data.
``<mmapped_file>``
File to map data to (required)
``<nsamples>``
number of samples per channel (default: 512).
.. admonition:: Example
``mpv --af=export=/tmp/mpv-af_export:1024 media.avi``
Would export 1024 samples per channel to ``/tmp/mpv-af_export``.
``extrastereo[=mul]``
(Linearly) increases the difference between left and right channels which
adds some sort of "live" effect to playback.
``<mul>``
Sets the difference coefficient (default: 2.5). 0.0 means mono sound
(average of both channels), with 1.0 sound will be unchanged, with
-1.0 left and right channels will be swapped.
``drc[=method:target]``
Applies dynamic range compression. This maximizes the volume by compressing
@@ -342,6 +496,45 @@ Available filters are:
This filter can cause distortion with audio signals that have a very
large dynamic range.
``ladspa=file:label:[<control0>,<control1>,...]``
Load a LADSPA (Linux Audio Developer's Simple Plugin API) plugin. This
filter is reentrant, so multiple LADSPA plugins can be used at once.
``<file>``
Specifies the LADSPA plugin library file.
.. note::
See also the note about the ``LADSPA_PATH`` variable in the
`ENVIRONMENT VARIABLES`_ section.
``<label>``
Specifies the filter within the library. Some libraries contain only
one filter, but others contain many of them. Entering 'help' here
will list all available filters within the specified library, which
eliminates the use of 'listplugins' from the LADSPA SDK.
``[<control0>,<control1>,...]``
Controls are zero or more ``,`` separated floating point values that
determine the behavior of the loaded plugin (for example delay,
threshold or gain).
In verbose mode (add ``-v`` to the mpv command line), all
available controls and their valid ranges are printed. This eliminates
the use of 'analyseplugin' from the LADSPA SDK.
Note that ``,`` is already used by the option parser to separate
filters, so you must quote the list of values with ``[...]`` or
similar.
.. admonition:: Example
``mpv --af=ladspa='/usr/lib/ladspa/delay.so':delay_5s:[0.5,0.2] media.avi``
Does something.
``karaoke``
Simple voice removal filter exploiting the fact that voice is usually
recorded with mono gear and later 'center' mixed onto the final audio
stream. Beware that this filter will turn your signal into mono. Works
well for 2 channel tracks; do not bother trying it on anything but 2
channel stereo.
``scaletempo[=option1:option2:...]``
Scales audio tempo without altering pitch, optionally synced to playback
speed (default).
@@ -401,6 +594,10 @@ Available filters are:
``mpv --af=scaletempo=stride=30:overlap=.50:search=10 media.ogg``
Would tweak the quality and performance parameters.
``mpv --af=format=float,scaletempo media.ogg``
Would make scaletempo use float code. Maybe faster on some
platforms.
``mpv --af=scaletempo=scale=1.2:speed=pitch audio.ogg``
Would play media at 1.2x normal speed, with audio at normal pitch.
Changing playback speed would change pitch, leaving audio tempo at
@@ -409,13 +606,9 @@ Available filters are:
``rubberband``
High quality pitch correction with librubberband. This can be used in place
of ``scaletempo``, and will be used to adjust audio pitch when playing
at speed different from normal. It can also be used to adjust audio pitch
without changing playback speed.
at speed different from normal.
``<pitch-scale>``
Sets the pitch scaling factor. Frequencies are multiplied by this value.
This filter has a number of additional sub-options. You can list them with
This filter has a number of sub-options. You can list them with
``mpv --af=rubberband=help``. This will also show the default values
for each option. The options are not documented here, because they are
merely passed to librubberband. Look at the librubberband documentation
@@ -424,13 +617,6 @@ Available filters are:
(The mapping of the mpv rubberband filter sub-option names and values to
those of librubberband follows a simple pattern: ``"Option" + Name + Value``.)
This filter supports the following ``af-command`` commands:
``set-pitch``
Set the ``<pitch-scale>`` argument dynamically. This can be used to
change the playback pitch at runtime. Note that speed is controlled
using the standard ``speed`` property, not ``af-command``.
``lavfi=graph``
Filter audio using FFmpeg's libavfilter.
+140 -95
View File
@@ -4,37 +4,108 @@ AUDIO OUTPUT DRIVERS
Audio output drivers are interfaces to different audio output facilities. The
syntax is:
``--ao=<driver1,driver2,...[,]>``
``--ao=<driver1[:suboption1[=value]:...],driver2,...[,]>``
Specify a priority list of audio output drivers to be used.
If the list has a trailing ',', mpv will fall back on drivers not contained
in the list.
in the list. Suboptions are optional and can mostly be omitted.
You can also set defaults for each driver. The defaults are applied before the
normal driver parameters.
``--ao-defaults=<driver1[:parameter1:parameter2:...],driver2,...>``
Set defaults for each driver.
Deprecated. No replacement.
.. note::
See ``--ao=help`` for a list of compiled-in audio output drivers. The
driver ``--ao=alsa`` is preferred. ``--ao=pulse`` is preferred on systems
where PulseAudio is used. On BSD systems, ``--ao=oss`` or ``--ao=sndio``
may work (the latter being experimental).
where PulseAudio is used. On Windows, ``--ao=wasapi`` is preferred,
though it might cause trouble sometimes, in which case ``--ao=dsound``
should be used. On BSD systems, ``--ao=oss`` or `--ao=sndio`` may work
(the latter being experimental). On OS X systems, use ``--ao=coreaudio``.
.. admonition:: Examples
- ``--ao=alsa,oss,`` Try the ALSA driver, then the OSS driver, then others.
- ``--ao=alsa:resample=yes:device=[plughw:0,3]`` Lets ALSA resample and
sets the device-name as first card, fourth device.
Available audio output drivers are:
``alsa`` (Linux only)
ALSA audio output driver
See `ALSA audio output options`_ for options specific to this AO.
``device=<device>``
Sets the device name. For ac3 output via S/PDIF, use an "iec958" or
"spdif" device, unless you really know how to set it correctly.
``resample=yes``
Enable ALSA resampling plugin. (This is disabled by default, because
some drivers report incorrect audio delay in some cases.)
``mixer-device=<device>``
Set the mixer device used with ``--no-softvol`` (default: ``default``).
``mixer-name=<name>``
Set the name of the mixer element (default: ``Master``). This is for
example ``PCM`` or ``Master``.
``mixer-index=<number>``
Set the index of the mixer channel (default: 0). Consider the output of
"``amixer scontrols``", then the index is the number that follows the
name of the element.
``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.
``ingore-chmap``
Don't read or set the channel map of the ALSA device - only request the
required number of channels, and then pass the audio as-is to it. This
option most likely should not be used. It can be useful for debugging,
or for static setups with a specially engineered ALSA configuration (in
this case you should always force the same layout with ``--audio-channels``,
or it will work only for files which use the layout implicit to your
ALSA device).
.. note::
MPlayer and mplayer2 required you to replace any ',' with '.' and
any ':' with '=' in the ALSA device name. mpv does not do this anymore.
Instead, quote the device name:
``--ao=alsa:device=[plug:surround50]``
Note that the ``[`` and ``]`` simply quote the device name. With some
shells (like zsh), you have to quote the option string to prevent the
shell from interpreting the brackets instead of passing them to mpv.
Actually, you should use the ``--audio-device`` option, instead of
setting the device directly.
.. warning::
To get multichannel/surround audio, use ``--audio-channels=auto``. The
default for this option is ``auto-safe``, which makes this audio otuput
explicitly reject multichannel output, as there is no way to detect
whether a certain channel layout is actually supported.
Handling of multichannel/surround audio changed in mpv 0.8.0 from the
behavior in MPlayer/mplayer2 and older versions of mpv.
The old behavior is that the player always downmixed to stereo by
default. The ``--audio-channels`` (or ``--channels`` before that) option
had to be set to get multichannel audio. Then playing stereo would
use the ``default`` device (which typically allows multiple programs
to play audio at the same time via dmix), while playing anything with
more channels would open one of the hardware devices, e.g. via the
``surround51`` alias (typically with exclusive access). Whether the
player would use exclusive access or not would depend on the file
being played.
The new behavior since mpv 0.8.0 always enables multichannel audio,
i.e. ``--audio-channels=auto`` is the default. However, since ALSA
provides no good way to play multichannel audio in a non-exclusive
way (without blocking other applications from using audio), the player
is restricted to the capabilities of the ``default`` device by default,
which means it supports only stereo and mono (at least with current
typical ALSA configurations). But if a hardware device is selected,
then multichannel audio will typically work.
The short story is: if you want multichannel audio with ALSA, use
``--audio-device`` to select the device (use ``--audio-device=help``
to get a list of all devices and their mpv name).
You can also try `using the upmix plugin <http://git.io/vfuAy>`_.
This setup enables multichannel audio on the ``default`` device
@@ -44,42 +115,40 @@ Available audio output drivers are:
``oss``
OSS audio output driver
The following global options are supported by this audio output:
``--oss-device``
``<dsp-device>``
Sets the audio output device (default: ``/dev/dsp``).
Deprecated, use ``--audio-device``.
``--oss-mixer-device``
``<mixer-device>``
Sets the audio mixer device (default: ``/dev/mixer``).
``--oss-mixer-channel``
``<mixer-channel>``
Sets the audio mixer channel (default: ``pcm``). Other valid values
include **vol, pcm, line**. For a complete list of options look for
``SOUND_DEVICE_NAMES`` in ``/usr/include/linux/soundcard.h``.
``jack``
JACK (Jack Audio Connection Kit) audio output driver.
JACK (Jack Audio Connection Kit) audio output driver
The following global options are supported by this audio output:
``--jack-port=<name>``
``port=<name>``
Connects to the ports with the given name (default: physical ports).
``--jack-name=<client>``
``name=<client>``
Client name that is passed to JACK (default: ``mpv``). Useful
if you want to have certain connections established automatically.
``--jack-autostart=<yes|no>``
``(no-)autostart``
Automatically start jackd if necessary (default: disabled). Note that
this tends to be unreliable and will flood stdout with server messages.
``--jack-connect=<yes|no>``
``(no-)connect``
Automatically create connections to output ports (default: enabled).
When enabled, the maximum number of output channels will be limited to
the number of available output ports.
``--jack-std-channel-layout=<waveext|any>``
Select the standard channel layout (default: waveext). JACK itself has no
``std-channel-layout=alsa|waveext|any``
Select the standard channel layout (default: alsa). JACK itself has no
notion of channel layouts (i.e. assigning which speaker a given
channel is supposed to map to) - it just takes whatever the application
outputs, and reroutes it to whatever the user defines. This means the
user and the application are in charge of dealing with the channel
layout. ``waveext`` uses WAVE_FORMAT_EXTENSIBLE order, which, even
layout. ``alsa`` uses the old MPlayer layout, which is inspired by
ALSA's standard layouts. In this mode, ao_jack will refuse to play 3
or 7 channels (because these do not really have a defined meaning in
MPlayer). ``waveext`` uses WAVE_FORMAT_EXTENSIBLE order, which, even
though it was defined by Microsoft, is the standard on many systems.
The value ``any`` makes JACK accept whatever comes from the audio
filter chain, regardless of channel layout and without reordering. This
@@ -93,27 +162,12 @@ Available audio output drivers are:
Automatically redirects to ``coreaudio_exclusive`` when playing compressed
formats.
The following global options are supported by this audio output:
``--coreaudio-change-physical-format=<yes|no>``
Change the physical format to one similar to the requested audio format
(default: no). This has the advantage that multichannel audio output
will actually work. The disadvantage is that it will change the
system-wide audio settings. This is equivalent to changing the ``Format``
setting in the ``Audio Devices`` dialog in the ``Audio MIDI Setup``
utility. Note that this does not affect the selected speaker setup.
``--coreaudio-exclusive``
Deprecated, use ``--audio-exclusive``.
Use exclusive mode access. This merely redirects to
``coreaudio_exclusive``, but should be preferred over using that AO
directly.
``coreaudio_exclusive`` (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).
``openal``
Experimental OpenAL audio output driver
@@ -123,21 +177,18 @@ Available audio output drivers are:
``pulse``
PulseAudio audio output driver
The following global options are supported by this audio output:
``--pulse-host=<host>``, ``--pulse-sink=<sink>``
``[<host>][:<output sink>]``
Specify the host and optionally output sink to use. An empty <host>
string uses a local connection, "localhost" uses network transfer
(most likely not what you want).
Deprecated, use ``--audio-device``.
``--pulse-buffer=<1-2000|native>``
``buffer=<1-2000|native>``
Set the audio buffer size in milliseconds. A higher value buffers
more data, and has a lower probability of buffer underruns. A smaller
value makes the audio stream react faster, e.g. to playback speed
changes. Default: 250.
``--pulse-latency-hacks=<yes|no>``
``latency-hacks=<yes|no>``
Enable hacks to workaround PulseAudio timing bugs (default: no). If
enabled, mpv will do elaborate latency calculations on its own. If
disabled, it will use PulseAudio automatically updated timing
@@ -146,7 +197,19 @@ Available audio output drivers are:
(it used to be required to get good behavior on old PulseAudio versions).
If you have stuttering video when using pulse, try to enable this
option. (Or try to update PulseAudio.)
option. (Or alternatively, try to update PulseAudio.)
``dsound`` (Windows only)
DirectX DirectSound audio output driver
.. note:: This driver is for compatibility with old systems.
``device=<devicenum>``
Sets the device number to use. Playing a file with ``-v`` will show a
list of available devices.
``buffersize=<ms>``
DirectSound buffer size in milliseconds (default: 200).
``sdl``
SDL 1.2+ audio output driver. Should work on any platform supported by SDL
@@ -157,67 +220,57 @@ Available audio output drivers are:
environments, such as systems where none of the other drivers
are available.
The following global options are supported by this audio output:
``--sdl-buflen=<length>``
``buflen=<length>``
Sets the audio buffer length in seconds. Is used only as a hint by the
sound system. Playing a file with ``-v`` will show the requested and
obtained exact buffer size. A value of 0 selects the sound system
default.
``--sdl-bufcnt=<count>``
``bufcnt=<count>``
Sets the number of extra audio buffers in mpv. Usually needs not be
changed.
``null``
Produces no audio output but maintains video playback speed. You can use
``--ao=null --ao-null-untimed`` for benchmarking.
Produces no audio output but maintains video playback speed. Use
``--ao=null:untimed`` for benchmarking.
The following global options are supported by this audio output:
``--ao-null-untimed``
``untimed``
Do not simulate timing of a perfect audio device. This means audio
decoding will go as fast as possible, instead of timing it to the
system clock.
``--ao-null-buffer``
``buffer``
Simulated buffer length in seconds.
``--ao-null-outburst``
``outburst``
Simulated chunk size in samples.
``--ao-null-speed``
``speed``
Simulated audio playback speed as a multiplier. Usually, a real audio
device will not go exactly as fast as the system clock. It will deviate
just a little, and this option helps to simulate this.
just a little, and this option helps simulating this.
``--ao-null-latency``
``latency``
Simulated device latency. This is additional to EOF.
``--ao-null-broken-eof``
``broken-eof``
Simulate broken audio drivers, which always add the fixed device
latency to the reported audio playback position.
``--ao-null-broken-delay``
``broken-delay``
Simulate broken audio drivers, which don't report latency correctly.
``--ao-null-channel-layouts``
If not empty, this is a ``,`` separated list of channel layouts the
AO allows. This can be used to test channel layout selection.
``pcm``
Raw PCM/WAVE file writer audio output
The following global options are supported by this audio output:
``--ao-pcm-waveheader=<yes|no>``
``(no-)waveheader``
Include or do not include the WAVE header (default: included). When
not included, raw PCM will be generated.
``--ao-pcm-file=<filename>``
``file=<filename>``
Write the sound to ``<filename>`` instead of the default
``audiodump.wav``. If ``no-waveheader`` is specified, the default is
``audiodump.pcm``.
``--ao-pcm-append=<yes|no>``
``(no-)append``
Append to the file, instead of overwriting it. Always use this with the
``no-waveheader`` option - with ``waveheader`` it's broken, because
it will write a WAVE header every time the file is opened.
@@ -229,19 +282,14 @@ Available audio output drivers are:
confused with RoarAudio, which is something completely
different.
The following global options are supported by this audio output:
``--rsound-host=<name/path>``
``host=<name/path>``
Set the address of the server (default: localhost). Can be either a
network hostname for TCP connections or a Unix domain socket path
starting with '/'.
``--rsound-port=<number>``
``port=<number>``
Set the TCP port used for connecting to the server (default: 12345).
Not used if connecting to a Unix domain socket.
These options are deprecated. If anyone cares enough, their functionality
can be added back using ``--audio-device``.
``sndio``
Audio output to the OpenBSD sndio sound system
@@ -250,28 +298,25 @@ Available audio output drivers are:
(Note: only supports mono, stereo, 4.0, 5.1 and 7.1 channel
layouts.)
The following global options are supported by this audio output:
``--ao-sndio-device=<device>``
``device=<device>``
sndio device to use (default: ``$AUDIODEVICE``, resp. ``snd0``).
Deprecated, use ``--audio-device``.
``wasapi``
Audio output to the Windows Audio Session API.
The following global options are supported by this audio output:
``--ao-wasapi-exclusive``
Deprecated, use ``--audio-exclusive``.
``exclusive``
Requests exclusive, direct hardware access. By definition prevents
sound playback of any other program until mpv exits.
``--ao-wasapi-device=<id>``
Deprecated, use ``--audio-device``.
``device=<id>``
Uses the requested endpoint instead of the system's default audio
endpoint. Both an ordinal number (0,1,2,...) and the GUID
String are valid; the GUID string is guaranteed to not change
unless the driver is uninstalled.
Also supports searching active devices by human-readable name. If more
Also supports searching active devices by human readable name. If more
than one device matches the name, refuses loading it.
This option is mostly deprecated in favour of the more general
``--audio-device`` option. That said, ``--audio-device=help`` will give
a list of valid device GUIDs (prefixed with ``wasapi/``), as well as
their human readable names, which should work here.
+1 -6
View File
@@ -8,11 +8,6 @@ There is no real changelog, but you can look at the following things:
https://github.com/mpv-player/mpv/releases
* The git log, which is the "real" changelog
* The files ``client-api-changes.rst`` and ``interface-changes.rst`` in the
``DOCS`` sub directoryon the git repository, which document API and user
interface changes (the latter usually documents breaking changes only, rather
than additions).
* The file ``mplayer-changes.rst`` in the ``DOCS`` sub directory on the git
repository, which used to be in place of this section. It documents some
changes that happened since mplayer2 forked off MPlayer. (Not updated
anymore.)
changes that happened since mplayer2 forked off MPlayer.
+5 -5
View File
@@ -93,8 +93,8 @@ You can encode files from one format/codec to another using this facility.
Completely empties the options list.
``--oafirst``
Force the audio stream to become the first stream in the output.
By default, the order is unspecified.
Force the audio stream to become the first stream in the output. By default
the order is unspecified.
``--ovc=<codec>``
Specifies the output video codec. This can be a comma separated list of
@@ -111,7 +111,7 @@ You can encode files from one format/codec to another using this facility.
.. admonition:: Examples
``"--ovc=mpeg4 --ovcopts=qscale=5"``
``"--ovc=mpeg4 --oacopts=qscale=5"``
selects constant quantizer scale 5 for MPEG-4 encoding.
``"--ovc=libx264 --ovcopts=crf=23"``
@@ -134,8 +134,8 @@ You can encode files from one format/codec to another using this facility.
Completely empties the options list.
``--ovfirst``
Force the video stream to become the first stream in the output.
By default, the order is unspecified.
Force the video stream to become the first stream in the output. By default
the order is unspecified.
``--ocopyts``
Copies input pts to the output video (not supported by some output
+332 -685
View File
File diff suppressed because it is too large. Load diff
+11 -60
View File
@@ -1,10 +1,10 @@
JSON IPC
========
mpv can be controlled by external programs using the JSON-based IPC protocol.
It can be enabled by specifying the path to a unix socket or a named pipe using
the option ``--input-ipc-server``. Clients can connect to this socket and send
commands to the player or receive events from it.
mpv can be controlled by external programs using the JSON-based IPC protocol. It
can be enabled by specifying the path to a unix socket using the option
``--input-unix-socket``. Clients can connect to this socket and send commands to
the player or receive events from it.
.. warning::
@@ -17,12 +17,12 @@ commands to the player or receive events from it.
Socat example
-------------
You can use the ``socat`` tool to send commands (and receive replies) from the
You can use the ``socat`` tool to send commands (and receive reply) from the
shell. Assuming mpv was started with:
::
mpv file.mkv --input-ipc-server=/tmp/mpvsocket
mpv file.mkv --input-unix-socket=/tmp/mpvsocket
Then you can control it using socat:
@@ -41,36 +41,11 @@ It's also possible to send input.conf style text-only commands:
::
> echo 'show-text ${playback-time}' | socat - /tmp/mpvsocket
> echo 'show_text ${playback-time}' | socat - /tmp/mpvsocket
But you won't get a reply over the socket. (This particular command shows the
playback time on the player's OSD.)
Command Prompt example
----------------------
Unfortunately, it's not as easy to test the IPC protocol on Windows, since
Windows ports of socat (in Cygwin and MSYS2) don't understand named pipes. In
the absence of a simple tool to send and receive from bidirectional pipes, the
``echo`` command can be used to send commands, but not receive replies from the
command prompt.
Assuming mpv was started with:
::
mpv file.mkv --input-ipc-server=\\.\pipe\mpvsocket
You can send commands from a command prompt:
::
echo show-text ${playback-time} >\\.\pipe\mpvsocket
To be able to simultaneously read and write from the IPC pipe, like on Linux,
it's necessary to write an external program that uses overlapped file I/O (or
some wrapper like .NET's NamedPipeClientStream.)
Protocol
--------
@@ -104,30 +79,12 @@ mpv will also send events to clients with JSON messages of the following form:
where ``event_name`` is the name of the event. Additional event-specific fields
can also be present. See `List of events`_ for a list of all supported events.
Because events can occur at any time, it may be difficult at times to determine
which response goes with which command. Commands may optionally include a
``request_id`` which, if provided in the command request, will be copied
verbatim into the response. mpv does not intrepret the ``request_id`` in any
way; it is solely for the use of the requester.
For example, this request:
::
{ "command": ["get_property", "time-pos"], "request_id": 100 }
Would generate this response:
::
{ "error": "success", "data": 1.468135, "request_id": 100 }
All commands, replies, and events are separated from each other with a line
break character (``\n``).
If the first character (after skipping whitespace) is not ``{``, the command
will be interpreted as non-JSON text command, as they are used in input.conf
(or ``mpv_command_string()`` in the client API). Additionally, lines starting
(or ``mpv_command_string()`` in the client API). Additionally, line starting
with ``#`` and empty lines are ignored.
Currently, embedded 0 bytes terminate the current line, but you should not
@@ -136,7 +93,7 @@ rely on this.
Commands
--------
In addition to the commands described in `List of Input Commands`_, a few
Additionally to the commands described in `List of Input Commands`_, a few
extra commands can also be used as part of the protocol:
``client_name``
@@ -214,7 +171,7 @@ extra commands can also be used as part of the protocol:
``unobserve_property``
Undo ``observe_property`` or ``observe_property_string``. This requires the
numeric id passed to the observed command as argument.
numeric id passed to the observe command as argument.
Example:
@@ -242,24 +199,18 @@ extra commands can also be used as part of the protocol:
command.
``suspend``
Deprecated, will be removed completely in 0.21.0.
Suspend the mpv main loop. There is a long-winded explanation of this in
the C API function ``mpv_suspend()``. In short, this prevents the player
from displaying the next video frame, so that you don't get blocked when
trying to access the player.
``resume``
Deprecated, will be removed completely in 0.21.0.
Undo one ``suspend`` call. ``suspend`` increments an internal counter, and
``resume`` decrements it. When 0 is reached, the player is actually resumed.
``get_version``
Returns the client API version the C API of the remote mpv instance
provides.
See also: ``DOCS/client-api-changes.rst``.
provides. (Also see ``DOCS/client-api-changes.rst``.)
UTF-8
-----
-16
View File
@@ -1,16 +0,0 @@
EMBEDDING INTO OTHER PROGRAMS (LIBMPV)
======================================
mpv can be embedded into other programs as video/audio playback backend. The
recommended way to do so is using libmpv. See ``libmpv/client.h`` in the mpv
source code repository. This provides a C API. Bindings for other languages
might be available (see wiki).
Since libmpv merely allows access to underlying mechanisms that can control
mpv, further documentation is spread over a few places:
- https://github.com/mpv-player/mpv/blob/master/libmpv/client.h
- http://mpv.io/manual/master/#options
- http://mpv.io/manual/master/#list-of-input-commands
- http://mpv.io/manual/master/#properties
- https://github.com/mpv-player/mpv-examples/tree/master/libmpv
+21 -80
View File
@@ -73,10 +73,6 @@ The ``mp`` module is preloaded, although it can be loaded manually with
Run the given command. This is similar to the commands used in input.conf.
See `List of Input Commands`_.
By default, this will show something on the OSD (depending on the command),
as if it was used in ``input.conf``. See `Input Command Prefixes`_ how
to influence OSD usage per command.
Returns ``true`` on success, or ``nil, error`` on error.
``mp.commandv(arg1, arg2, ...)``
@@ -98,9 +94,6 @@ The ``mp`` module is preloaded, although it can be loaded manually with
the ``expand-properties`` prefix, or the ``mp.get_property`` family of
functions.
Unlike ``mp.command``, this will not use OSD by default either (except
for some OSD-specific commands).
``mp.command_native(table [,def])``
Similar to ``mp.commandv``, but pass the argument list as table. This has
the advantage that in at least some cases, arguments can be passed as
@@ -175,7 +168,7 @@ The ``mp`` module is preloaded, although it can be loaded manually with
Similar to ``mp.set_property``, but set the given property using its native
type.
Since there are several data types which cannot represented natively in
Since there are several data types which can not represented natively in
Lua, this might not always work as expected. For example, while the Lua
wrapper can do some guesswork to decide whether a Lua table is an array
or a map, this would fail with empty tables. Also, there are not many
@@ -192,14 +185,13 @@ The ``mp`` module is preloaded, although it can be loaded manually with
Register callback to be run on a key binding. The binding will be mapped to
the given ``key``, which is a string describing the physical key. This uses
the same key names as in input.conf, and also allows combinations
(e.g. ``ctrl+a``). If the key is empty or ``nil``, no physical key is
registered, but the user still can create own bindings (see below).
(e.g. ``ctrl+a``).
After calling this function, key presses will cause the function ``fn`` to
be called (unless the user remapped the key with another binding).
The ``name`` argument should be a short symbolic string. It allows the user
to remap the key binding via input.conf using the ``script-message``
to remap the key binding via input.conf using the ``script_message``
command, and the name of the key binding (see below for
an example). The name should be unique across other bindings in the same
script - if not, the previous binding with the same name will be
@@ -221,8 +213,8 @@ The ``mp`` module is preloaded, although it can be loaded manually with
has an ``is_mouse`` entry, which tells whether the event was caused
by a mouse button.
Internally, key bindings are dispatched via the ``script-message-to`` or
``script-binding`` input commands and ``mp.register_script_message``.
Internally, key bindings are dispatched via the ``script_message_to`` or
``script_binding`` input commands and ``mp.register_script_message``.
Trying to map multiple commands to a key will essentially prefer a random
binding, while the other bindings are not called. It is guaranteed that
@@ -245,7 +237,7 @@ The ``mp`` module is preloaded, although it can be loaded manually with
::
y script-binding something
y script_binding something
This will print the message when the key ``y`` is pressed. (``x`` will
@@ -256,7 +248,7 @@ The ``mp`` module is preloaded, although it can be loaded manually with
::
y script-binding fooscript/something
y script_binding fooscript.something
``mp.add_forced_key_binding(...)``
This works almost the same as ``mp.add_key_binding``, but registers the
@@ -350,10 +342,6 @@ 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.
``is_enabled()``
Whether the timer is currently enabled or was previously disabled
(e.g. by ``stop()`` or ``kill()``).
``timeout`` (RW)
This field contains the current timeout period. This value is not
updated as time progresses. It's only used to calculate when the
@@ -394,7 +382,7 @@ The ``mp`` module is preloaded, although it can be loaded manually with
``mp.get_script_name()``
Return the name of the current script. The name is usually made of the
filename of the script, with directory and file extension removed. If
there are several scripts which would have the same name, it's made unique
there are several script which would have the same name, it's made unique
by appending a number.
.. admonition:: Example
@@ -412,28 +400,26 @@ These also live in the ``mp`` module, but are documented separately as they
are useful only in special situations.
``mp.suspend()``
This function has been deprecated in mpv 0.21.0 (no replacement).
Suspend the mpv main loop. There is a long-winded explanation of this in
the C API function ``mpv_suspend()``. In short, this prevents the player
from displaying the next video frame, so that you don't get blocked when
trying to access the player.
Before mpv 0.17.0, this was automatically called by the event handler.
This is automatically called by the event handler.
``mp.resume()``
This function has been deprecated in mpv 0.21.0 (no replacement).
Undo one ``mp.suspend()`` call. ``mp.suspend()`` increments an internal
counter, and ``mp.resume()`` decrements it. When 0 is reached, the player
is actually resumed.
``mp.resume_all()``
This function has been deprecated in mpv 0.21.0 (no replacement).
This resets the internal suspend counter and resumes the player. (It's
like calling ``mp.resume()`` until the player is actually resumed.)
You might want to call this if you're about to do something that takes a
long time, but doesn't really need access to the player (like a network
operation). Note that you still can access the player at any time.
``mp.get_wakeup_pipe()``
Calls ``mpv_get_wakeup_pipe()`` and returns the read end of the wakeup
pipe. (See ``client.h`` for details.)
@@ -456,12 +442,7 @@ are useful only in special situations.
``mp.get_wakeup_pipe()`` if you're interested in properly working
notification of new events and working timers.
``mp.register_idle(fn)``
Register an event loop idle handler. Idle handlers are called before the
script goes to sleep after handling all new events. This can be used for
example to delay processing of property change events: if you're observing
multiple properties at once, you might not want to act on each property
change, but only when all change notifications have been received.
This function calls ``mp.suspend()`` and ``mp.resume_all()`` on its own.
``mp.enable_messages(level)``
Set the minimum log level of which mpv message output to receive. These
@@ -471,9 +452,9 @@ are useful only in special situations.
The level is a string, see ``msg.log`` for allowed log levels.
``mp.register_script_message(name, fn)``
This is a helper to dispatch ``script-message`` or ``script-message-to``
invocations to Lua functions. ``fn`` is called if ``script-message`` or
``script-message-to`` (with this script as destination) is run
This is a helper to dispatch ``script_message`` or ``script_message_to``
invocations to Lua functions. ``fn`` is called if ``script_message`` or
``script_message_to`` (with this script as destination) is run
with ``name`` as first parameter. The other parameters are passed to ``fn``.
If a message with the given name is already registered, it's overwritten.
@@ -531,7 +512,7 @@ Example implementation::
optionC = true,
}
read_options(options, "myscript")
print(options.optionA)
print(option.optionA)
The config file will be stored in ``lua-settings/identifier.conf`` in mpv's user
@@ -554,8 +535,8 @@ Example command-line::
--script-opts=myscript-optionA=TEST,myscript-optionB=0,myscript-optionC=yes
mp.utils functions
------------------
mp.utils options
----------------
This built-in module provides generic helper functions for Lua, and have
strictly speaking nothing to do with mpv or video/audio playback. They are
@@ -642,20 +623,7 @@ strictly part of the guaranteed API.
On Windows, ``killed`` is only returned when the process has been
killed by mpv as a result of ``cancellable`` being set to ``true``.
``killed_by_us``
Set to ``true`` if the process has been killed by mpv as a result
of ``cancellable`` being set to ``true``.
``utils.subprocess_detached(t)``
Runs an external process and detaches it from mpv's control.
The parameter ``t`` is a table. The function reads the following entries:
``args``
Array of strings of the same semantics as the ``args`` used in the
``subprocess`` function.
The function returns ``nil``.
In all cases, ``mp.resume_all()`` is implicitly called.
``utils.parse_json(str [, trail])``
Parses the given string argument as JSON, and returns it as a Lua table. On
@@ -715,33 +683,6 @@ List of events
Happens after a file was unloaded. Typically, the player will load the
next file right away, or quit if this was the last file.
The event has the ``reason`` field, which takes one of these values:
``eof``
The file has ended. This can (but doesn't have to) include
incomplete files or broken network connections under
circumstances.
``stop``
Playback was ended by a command.
``quit``
Playback was ended by sending the quit command.
``error``
An error happened. In this case, an ``error`` field is present with
the error string.
``redirect``
Happens with playlists and similar. Details see
``MPV_END_FILE_REASON_REDIRECT`` in the C API.
``unknown``
Unknown. Normally doesn't happen, unless the Lua API is out of sync
with the C API. (Likewise, it could happen that your script gets
reason strings that did not exist yet at the time your script was
written.)
``file-loaded``
Happens after a file was loaded and begins playback.
+123 -209
View File
@@ -37,10 +37,6 @@ LIRC support - configure remotes as input devices instead).
See the ``--input-`` options for ways to customize it.
The following listings are not necessarily complete. See ``etc/input.conf`` for
a list of default bindings. User ``input.conf`` files and Lua scripts can
define additional key bindings.
Keyboard Control
----------------
@@ -54,7 +50,7 @@ UP and DOWN
Ctrl+LEFT and Ctrl+RIGHT
Seek to the previous/next subtitle. Subject to some restrictions and
might not always work; see ``sub-seek`` command.
might not work always; see ``sub_seek`` command.
[ and ]
Decrease/increase current playback speed by 10%.
@@ -120,7 +116,11 @@ o (also P)
Show progression bar, elapsed time and total duration on the OSD.
O
Toggle OSD states between normal and playback time/duration.
Toggle OSD states: none / seek / seek + timer / seek + timer + total time.
d
Toggle frame dropping states: none / skip display / skip decoding (see
``--framedrop``).
v
Toggle subtitle visibility.
@@ -132,10 +132,7 @@ x and z
Adjust subtitle delay by +/- 0.1 seconds.
l
Set/clear A-B loop points. See ``ab-loop`` command for details.
L
Toggle infinite looping.
Set/clear A-B loop points. See ``ab_loop`` command for details.
Ctrl + and Ctrl -
Adjust audio delay by +/- 0.1 seconds.
@@ -143,11 +140,11 @@ Ctrl + and Ctrl -
u
Switch between applying no style overrides to SSA/ASS subtitles, and
overriding them almost completely with the normal subtitle style. See
``--sub-ass-style-override`` for more info.
``--ass-style-override`` for more info.
V
Toggle subtitle VSFilter aspect compatibility mode. See
``--sub-ass-vsfilter-aspect-compat`` for more info.
``--ass-vsfilter-aspect-compat`` for more info.
r and t
Move subtitles up/down.
@@ -159,10 +156,6 @@ S
Take a screenshot, without subtitles. (Whether this works depends on VO
driver support.)
Ctrl s
Take a screenshot, as the window shows it (with subtitles, OSD, and scaled
video).
I
Show filename on the OSD.
@@ -175,7 +168,7 @@ Shift+PGUP and Shift+PGDWN
Seek backward or forward by 10 minutes. (This used to be mapped to
PGUP/PGDWN without Shift.)
d
D
Activate/deactivate deinterlacer.
A
@@ -196,19 +189,23 @@ corresponding adjustment, or the software equalizer (``--vf=eq``).)
7 and 8
Adjust saturation.
Alt+0 (and command+0 on OSX)
Resize video window to half its original size.
(The following keys are valid only on OS X.)
Alt+1 (and command+1 on OSX)
command + 0
Resize video window to half its original size.
(On other platforms, you can bind keys to change the ``window-scale``
property.)
command + 1
Resize video window to its original size.
Alt+2 (and command+2 on OSX)
command + 2
Resize video window to double its original size.
command + f (OSX only)
command + f
Toggle fullscreen (see also ``--fs``).
command + [ and command + ] (OSX only)
command + [ and command + ]
Set video window alpha.
(The following keys are valid if you have a keyboard with multimedia keys.)
@@ -226,10 +223,7 @@ PREVIOUS and NEXT
support.)
h and k
Select previous/next tv-channel.
H and K
Select previous/next dvb-channel.
Select previous/next channel.
Mouse Control
-------------
@@ -265,22 +259,21 @@ parser puts several options into a single string, and passes them to a
component at once, instead of using multiple options on the level of the
command line.
The suboption parser can quote strings with ``"`` and ``[...]``.
The suboption parser can quote strings with ``"``, ``'``, and ``[...]``.
Additionally, there is a special form of quoting with ``%n%`` described below.
For example, assume the hypothetical ``foo`` filter can take multiple options:
For example, the ``opengl`` VO can take multiple options:
``mpv test.mkv --vf=foo:option1=value1:option2:option3=value3,bar``
``mpv test.mkv --vo=opengl:scale=lanczos:icc-profile=file.icc,xv``
This passes ``option1`` and ``option3`` to the ``foo`` filter, with ``option2``
as flag (implicitly ``option2=yes``), and adds a ``bar`` filter after that. If
an option contains spaces or characters like ``,`` or ``:``, you need to quote
them:
This passes ``scale=lanczos`` and ``icc-profile=file.icc`` to ``opengl``,
and also specifies ``xv`` as fallback VO. If the icc-profile path contains
spaces or characters like ``,`` or ``:``, you need to quote them:
``mpv '--vf=foo:option1="option value with spaces",bar'``
``mpv '--vo=opengl:icc-profile="file with spaces.icc",xv'``
Shells may actually strip some quotes from the string passed to the commandline,
so the example quotes the string twice, ensuring that mpv receives the ``"``
so the example quotes the string twice, ensuring that mpv recieves the ``"``
quotes.
The ``[...]`` form of quotes wraps everything between ``[`` and ``]``. It's
@@ -298,19 +291,20 @@ It is started with ``%`` and has the following format::
.. admonition:: Examples
``mpv '--vf=foo:option1=%11%quoted text' test.avi``
``mpv --ao=pcm:file=%10%C:test.wav test.avi``
Or in a script:
``mpv --vf=foo:option1=%`expr length "$NAME"`%"$NAME" test.avi``
``mpv --ao=pcm:file=%`expr length "$NAME"`%"$NAME" test.avi``
Suboptions passed to the client API are also subject to escaping. Using
``mpv_set_option_string()`` is exactly like passing ``--name=data`` to the
command line (but without shell processing of the string). Some options
support passing values in a more structured way instead of flat strings, and
can avoid the suboption parsing mess. For example, ``--vf`` supports
``MPV_FORMAT_NODE``, which lets you pass suboptions as a nested data structure
of maps and arrays.
``MPV_FORMAT_NODE``, which let's you pass suboptions as a nested data structure
of maps and arrays. (``--vo`` supports this in the same way, although this
fact is undocumented.)
Paths
-----
@@ -320,22 +314,11 @@ example, paths starting with ``-`` will be interpreted as options. Likewise,
if a path contains the sequence ``://``, the string before that might be
interpreted as protocol prefix, even though ``://`` can be part of a legal
UNIX path. To avoid problems with arbitrary paths, you should be sure that
absolute paths passed to mpv start with ``/``, and prefix relative paths with
``./``.
Using the ``file://`` pseudo-protocol is discouraged, because it involves
strange URL unescaping rules.
absolute paths passed to mpv start with ``/``, and relative paths with ``./``.
The name ``-`` itself is interpreted as stdin, and will cause mpv to disable
console controls. (Which makes it suitable for playing data piped to stdin.)
The special argument ``--`` can be used to stop mpv from interpreting the
following arguments as options.
When using the client API, you should strictly avoid using ``mpv_command_string``
for invoking the ``loadfile`` command, and instead prefer e.g. ``mpv_command``
to avoid the need for filename escaping.
For paths passed to suboptions, the situation is further complicated by the
need to escape special characters. To work this around, the path can be
additionally wrapped in the fixed-length syntax, e.g. ``%n%string_of_length_n``
@@ -344,17 +327,7 @@ additionally wrapped in the fixed-length syntax, e.g. ``%n%string_of_length_n``
Some mpv options interpret paths starting with ``~``. Currently, the prefix
``~~/`` expands to the mpv configuration directory (usually ``~/.config/mpv/``).
``~/`` expands to the user's home directory. (The trailing ``/`` is always
required.) There are the following paths as well:
================ ===============================================================
Name Meaning
================ ===============================================================
``~~home/`` same as ``~~/``
``~~global/`` the global config path, if available (not on win32)
``~~osxbundle/`` the OSX bundle resource path (OSX only)
``~~desktop/`` the path to the desktop (win32, OSX)
================ ===============================================================
required.)
Per-File Options
----------------
@@ -396,45 +369,6 @@ file stops playing. If option ``--c`` is changed during playback of
``file2.mkv``, it is reset when advancing to ``file3.mkv``. This only affects
file-local options. The option ``--a`` is never reset here.
Playing DVDs
------------
DVDs can be played with the ``dvd://[title]`` syntax. The optional
title specifier is a number which selects between separate video
streams on the DVD. If no title is given (``dvd://``) then the longest
title is selected automatically by the library. This is usually what
you want. mpv does not support DVD menus.
DVDs which have been copied on to a hard drive or other mounted
filesystem (by e.g. the ``dvdbackup`` tool) are accommodated by
specifying the path to the local copy: ``--dvd-device=PATH``.
Alternatively, running ``mpv PATH`` should auto-detect a DVD directory
tree and play the longest title.
.. note::
mpv uses a different default DVD library than MPlayer. MPlayer
uses libdvdread by default, and mpv uses libdvdnav by default.
Both libraries are developed in parallel, but libdvdnav is
intended to support more sophisticated DVD features such as menus
and multi-angle playback. mpv uses libdvdnav for files specified
as either ``dvd://...`` or ``dvdnav://...``. To use libdvdread,
which will produce behavior more like MPlayer, specify
``dvdread://...`` instead. Some users have experienced problems
when using libdvdnav, in which playback gets stuck in a DVD menu
stream. These problems are reported to go away when auto-selecting
the title (``dvd://`` rather than ``dvd://1``) or when using
libdvdread (e.g. ``dvdread://0``).
DVDs use image-based subtitles. Image subtitles are implemented as
a bitmap video stream which can be superimposed over the main
movie. mpv's subtitle styling and positioning options and keyboard
shortcuts generally do not work with image-based subtitles.
Exceptions include options like ``--stretch-dvd-subs`` and
``--stretch-image-subs-to-screen``.
CONFIGURATION FILES
===================
@@ -444,12 +378,10 @@ 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 ``~/.config/mpv/mpv.conf``. For details and platform
specifics (in particular Windows paths) see the `FILES`_ section.
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
``option=<value>``; everything after a *#* is considered a comment. Options
that work without values can be enabled by setting them to *yes* and disabled by
setting them to *no*. Even suboptions can be specified in this way.
@@ -467,10 +399,10 @@ Escaping spaces and special characters
This is done like with command line options. The shell is not involved here,
but option values still need to be quoted as a whole if it contains certain
characters like spaces. A config entry can be quoted with ``"``,
characters like spaces. A config entry can be quoted with ``"`` and ``'``,
as well as with the fixed-length syntax (``%n%``) mentioned before. This is like
passing the exact contents of the quoted string as command line option. C-style
escapes are currently _not_ interpreted on this level, although some options do
escapes are currently _not_ interpreted on this level, although some options to
this manually. (This is a mess and should probably be changed at some point.)
Putting Command Line Options into the Configuration File
@@ -514,41 +446,13 @@ description (shown by ``--profile=help``) can be defined with the
``profile-desc`` option. To end the profile, start another one or use the
profile name ``default`` to continue with normal options.
.. admonition:: Example mpv config file with profiles
.. admonition:: Example mpv profile
::
# normal top-level option
fullscreen=yes
# a profile that can be enabled with --profile=big-cache
[big-cache]
cache=123400
demuxer-readahead-secs=20
[slow]
profile-desc="some profile name"
# reference a builtin profile
profile=opengl-hq
[fast]
vo=vdpau
# using a profile again extends it
[slow]
framedrop=no
# you can also include other profiles
profile=big-cache
Auto profiles
-------------
Some profiles are loaded automatically. The following example demonstrates this:
.. admonition:: Auto profile loading
::
[vo.vdpau]
# Use hardware decoding
hwdec=vdpau
[protocol.dvd]
profile-desc="profile for dvd:// streams"
@@ -558,21 +462,17 @@ Some profiles are loaded automatically. The following example demonstrates this:
profile-desc="profile for .flv files"
vf=flip
The profile name follows the schema ``type.name``, where type can be
``protocol`` for the input/output protocol in use (see ``--list-protocols``),
and ``extension`` for the extension of the path of the currently played file
(*not* the file format).
[ao.alsa]
device=spdif
This feature is very limited, and there are no other auto profiles.
TAKING SCREENSHOTS
==================
Screenshots of the currently played file can be taken using the 'screenshot'
input mode command, which is by default bound to the ``s`` key. Files named
``mpv-shotNNNN.jpg`` will be saved in the working directory, using the first
available number - no files will be overwritten. In pseudo-GUI mode, the
screenshot will be saved somewhere else. See `PSEUDO GUI MODE`_.
``shotNNNN.jpg`` will be saved in the working directory, using the first
available number - no files will be overwritten.
A screenshot will usually contain the unscaled video contents at the end of the
video filter chain and subtitles. By default, ``S`` takes screenshots without
@@ -612,21 +512,13 @@ listed.
if there is audio "missing", or not enough frames can be dropped. Usually
this will indicate a problem. (``total-avsync-change`` property.)
- Encoding state in ``{...}``, only shown in encoding mode.
- Display sync state. If display sync is active (``display-sync-active``
property), this shows ``DS: 2.500/13``, where the first number is average
number of vsyncs per video frame (e.g. 2.5 when playing 24Hz videos on 60Hz
screens), which might jitter if the ratio doesn't round off, or there are
mistimed frames (``vsync-ratio``), and the second number of estimated number
of vsyncs which took too long (``vo-delayed-frame-count`` property). The
latter is a heuristic, as it's generally not possible to determine this with
certainty.
- Dropped frames, e.g. ``Dropped: 4``. Shows up only if the count is not 0. Can
grow if the video framerate is higher than that of the display, or if video
rendering is too slow. May also be incremented on "hiccups" and when the video
rendering is too slow. Also can be incremented on "hiccups" and when the video
frame couldn't be displayed on time. (``vo-drop-frame-count`` property.)
If the decoder drops frames, the number of decoder-dropped frames is appended
to the display as well, e.g.: ``Dropped: 4/34``. This happens only if
decoder frame dropping is enabled with the ``--framedrop`` options.
decoder-framedropping is enabled with the ``--framedrop`` options.
(``drop-frame-count`` property.)
- Cache state, e.g. ``Cache: 2s+134KB``. Visible if the stream cache is enabled.
The first value shows the amount of video buffered in the demuxer in seconds,
@@ -653,13 +545,17 @@ PROTOCOLS
Play a path from Samba share.
``bd://[title][/device]`` ``--bluray-device=PATH``
Play a Blu-ray disc. Currently, this does not accept ISO files. Instead,
Play a Blu-Ray disc. Currently, this does not accept ISO files. Instead,
you must mount the ISO file as filesystem, and point ``--bluray-device``
to the mounted directory directly.
``bdnav://[title][/device]``
Play a Blu-Ray disc, with navigation features enabled. This feature is
permanently experimental.
``dvd://[title|[starttitle]-endtitle][/device]`` ``--dvd-device=PATH``
Play a DVD. DVD menus are not supported. If no title is given, the longest
title is auto-selected.
Play a DVD. If you want dvdnav menus, use ``dvd://menu``. If no title
is given, the longest title is auto-selected.
``dvdnav://`` is an old alias for ``dvd://`` and does exactly the same
thing.
@@ -681,7 +577,7 @@ PROTOCOLS
``mf://[filemask|@listfile]`` ``--mf-...``
Play a series of images as video.
``cdda://[device]`` ``--cdrom-device=PATH`` ``--cdda-...``
``cdda://track[-endtrack][:speed][/device]`` ``--cdrom-device=PATH`` ``--cdda-...``
Play CD.
``lavf://...``
@@ -704,24 +600,15 @@ PROTOCOLS
``PATH`` itself should start with a third ``/`` to make the path an
absolute path.
``fd://123``
Read data from the given file descriptor (for example 123). This is similar
to piping data to stdin via ``-``, but can use an arbitrary file descriptor.
``edl://[edl specification as in edl-mpv.rst]``
Stitch together parts of multiple files and play them.
``null://``
Simulate an empty file. If opened for writing, it will discard all data.
The ``null`` demuxer will specifically pass autoprobing if this protocol
is used (while it's not automatically invoked for empty files).
Simulate an empty file.
``memory://data``
Use the ``data`` part as source data.
``hex://data``
Like ``memory://``, but the string is interpreted as hexdump.
PSEUDO GUI MODE
===============
@@ -736,32 +623,23 @@ Currently this happens only in the following cases:
or file associations provided by desktop environments)
- if started from explorer.exe on Windows (technically, if it was started on
Windows, and all of the stdout/stderr/stdin handles are unset)
- started out of the bundle on OSX
- if you manually use ``--player-operation-mode=pseudo-gui`` on the command line
- manually adding ``--profile=pseudo-gui`` to the command line
This mode applies options from the builtin profile ``builtin-pseudo-gui``, but
only if these haven't been set in the user's config file or on the command line.
Also, for compatibility with the old pseudo-gui behavior, the options in the
``pseudo-gui`` profile are applied unconditionally. In addition, the profile
makes sure to enable the pseudo-GUI mode, so that ``--profile=pseudo-gui``
works like in older mpv releases. The profiles are currently defined as follows:
This mode implicitly adds ``--profile=pseudo-gui`` to the command line, with
the ``pseudo-gui`` profile being predefined with the following contents:
::
[builtin-pseudo-gui]
[pseudo-gui]
terminal=no
force-window=yes
idle=once
screenshot-directory=~~desktop/
[pseudo-gui]
player-operation-mode=pseudo-gui
.. warning::
This follows the mpv config file format. To customize pseudo-GUI mode, you can
put your own ``pseudo-gui`` profile into your ``mpv.conf``. This profile will
enhance the default profile, rather than overwrite it.
Currently, you can extend the ``pseudo-gui`` profile in the config file the
normal way. This is deprecated. In future mpv releases, the behavior might
change, and not apply your additional settings, and/or use a different
profile name.
The profile always overrides other settings in ``mpv.conf``.
.. include:: options.rst
@@ -786,8 +664,6 @@ works like in older mpv releases. The profiles are currently defined as follows:
.. include:: changes.rst
.. include:: libmpv.rst
ENVIRONMENT VARIABLES
=====================
@@ -805,6 +681,9 @@ behavior of mpv.
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/mpv.conf``.
@@ -815,7 +694,8 @@ behavior of mpv.
of ``--v`` options passed to the command line.
``MPV_LEAK_REPORT``
If set to ``1``, enable internal talloc leak reporting.
If set to ``1``, enable internal talloc leak reporting. Note that this can
cause trouble with multithreading, so only developers should use this.
``LADSPA_PATH``
Specifies the search path for LADSPA plugins. If it is unset, fully
@@ -855,7 +735,7 @@ libdvdcss:
key
is the default method. libdvdcss will use a set of calculated
player keys to try to get the disc key. This can fail if the drive
player keys to try and get the disc key. This can fail if the drive
does not recognize any of the player keys.
disc
@@ -908,8 +788,6 @@ If errors happen, the following exit codes can be returned:
immediately after initialization.
:3: There were some files that could be played, and some files which
couldn't (using the definition of success from above).
:4: Quit due to a signal, Ctrl+c in a VO window (by default), or from the
default quit key bindings in encoding mode.
Note that quitting the player manually will always lead to exit code 0,
overriding the exit code that would be returned normally. Also, the ``quit``
@@ -918,8 +796,6 @@ input command can take an exit code: in this case, that exit code is returned.
FILES
=====
For Windows-specifics, see `FILES ON WINDOWS`_ section.
``/usr/local/etc/mpv/mpv.conf``
mpv system-wide settings (depends on ``--prefix`` passed to configure - mpv
in default configuration will use ``/usr/local/etc/mpv/`` as config
@@ -940,7 +816,7 @@ For Windows-specifics, see `FILES ON WINDOWS`_ section.
``~/.config/mpv/watch_later/``
Contains temporary config files needed for resuming playback of files with
the watch later feature. See for example the ``Q`` key binding, or the
``quit-watch-later`` input command.
``quit_watch_later`` input command.
Each file is a small config file which is loaded if the corresponding media
file is loaded. It contains the playback position and some (not necessarily
@@ -971,7 +847,7 @@ locations are different. They are generally located under ``%APPDATA%/mpv/``.
For example, the path to mpv.conf is ``%APPDATA%/mpv/mpv.conf``, which maps to
a system and user-specific path, for example
``C:\users\USERNAME\AppData\Roaming\mpv\mpv.conf``
``C:\users\USERNAME\Application Data\mpv\mpv.conf``
You can find the exact path by running ``echo %APPDATA%\mpv\mpv.conf`` in cmd.exe.
@@ -981,23 +857,61 @@ Other config files (such as ``input.conf``) are in the same directory. See the
The environment variable ``$MPV_HOME`` completely overrides these, like on
UNIX.
If a directory named ``portable_config`` next to the mpv.exe exists, all
config will be loaded from this directory only. Watch later config files are
written to this directory as well. (This exists on Windows only and is redundant
with ``$MPV_HOME``. However, since Windows is very scripting unfriendly, a
wrapper script just setting ``$MPV_HOME``, like you could do it on other
systems, won't work. ``portable_config`` is provided for convenience to get
around this restriction.)
Config files located in the same directory as ``mpv.exe`` are loaded with
lower priority. Some config files are loaded only once, which means that
e.g. of 2 ``input.conf`` files located in two config directories, only the
one from the directory with higher priority will be loaded.
A third config directory with the lowest priority is the directory named ``mpv``
in the same directory as ``mpv.exe``. This used to be the directory with the
A third config directory with lowest priority is the directory named ``mpv``
in the same directory as ``mpv.exe``. This used to be the directory with
highest priority, but is now discouraged to use and might be removed in the
future.
Note that mpv likes to mix ``/`` and ``\`` path separators for simplicity.
kernel32.dll accepts this, but cmd.exe does not.
EXAMPLES OF MPV USAGE
=====================
Blu-ray playback:
- ``mpv bd:////path/to/disc``
- ``mpv bd:// --bluray-device=/path/to/disc``
Play in Japanese with English subtitles:
``mpv dvd://1 --alang=ja --slang=en``
Play only chapters 5, 6, 7:
``mpv dvd://1 --chapter=5-7``
Play only titles 5, 6, 7:
``mpv dvd://5-7``
Play a multi-angle DVD:
``mpv dvd://1 --dvd-angle=2``
Play from a different DVD device:
``mpv dvd://1 --dvd-device=/dev/dvd2``
Play DVD video from a directory with VOB files:
``mpv dvd://1 --dvd-device=/path/to/directory/``
Stream from HTTP:
``mpv http://example.com/example.avi``
Stream using RTSP:
``mpv rtsp://server.example.com/streamName``
Play a libavfilter graph:
``mpv avdevice://lavfi:mandelbrot``
AUTHORS
=======
mpv is a MPlayer fork based on mplayer2, which in turn is a fork of MPlayer.
MPlayer was initially written by Arpad Gereoffy. See the ``AUTHORS`` file for
a list of some of the many other contributors.
MPlayer is (C) 2000-2013 The MPlayer Team
This man page was written mainly by Gabucino, Jonas Jermann and Diego Biurrun.
+434 -1923
View File
File diff suppressed because it is too large. Load diff
+103 -103
View File
@@ -5,7 +5,7 @@ The On Screen Controller (short: OSC) is a minimal GUI integrated with mpv to
offer basic mouse-controllability. It is intended to make interaction easier
for new users and to enable precise and direct seeking.
The OSC is enabled by default if mpv was compiled with Lua support. It can be
The OSC is enabled by default if mpv was compiled with lua support. It can be
disabled entirely using the ``--osc=no`` option.
Using the OSC
@@ -20,25 +20,22 @@ The Interface
::
+---------+----------+----------------------------+-------------+
| pl prev | pl next | title | cache |
+------+--+---+------+---------+-----------+------+-------+-----+
| play | skip | skip | time | seekbar | time | audio | sub |
| | back | frwd | elapsed | | left | | |
+------+------+------+---------+-----------+------+-------+-----+
+------------------+-----------+--------------------+
| playlist prev | title | playlist next |
+-------+------+---+--+------+-+----+------+--------+
| audio | skip | seek | | seek | skip | full |
+-------+ back | back | play | frwd | frwd | screen |
| sub | | | | | | |
+-------+------+------+------+------+------+--------+
| seekbar |
+----------------+--------------+-------------------+
| time passed | cache status | time remaining |
+----------------+--------------+-------------------+
pl prev
playlist prev
============= ================================================
left-click play previous file in playlist
right-click show playlist
shift+L-click show playlist
============= ================================================
pl next
============= ================================================
left-click play next file in playlist
right-click show playlist
shift+L-click show playlist
============= ================================================
@@ -50,47 +47,10 @@ title
right-click show filename
============= ================================================
cache
| Shows current cache fill status
play
playlist next
============= ================================================
left-click toggle play/pause
============= ================================================
skip back
============= ================================================
left-click go to beginning of chapter / previous chapter
right-click show chapters
shift+L-click show chapters
============= ================================================
skip frwd
============= ================================================
left-click go to next chapter
right-click show chapters
shift+L-click show chapters
============= ================================================
time elapsed
| Shows current playback position timestamp
============= ================================================
left-click toggle displaying timecodes with milliseconds
============= ================================================
seekbar
| Indicates current playback position and position of chapters
============= ================================================
left-click seek to position
============= ================================================
time left
| Shows remaining playback time timestamp
============= ================================================
left-click toggle between total and remaining time
left-click play next file in playlist
shift+L-click show playlist
============= ================================================
audio and sub
@@ -102,6 +62,66 @@ audio and sub
shift+L-click show available audio/sub tracks
============= ================================================
skip back
============= ================================================
left-click go to beginning of chapter / previous chapter
shift+L-click show chapters
============= ================================================
seek back
============= ================================================
left-click skip back 5 seconds
right-click skip back 30 seconds
shift-L-click skip back 1 frame
============= ================================================
play
============= ================================================
left-click toggle play/pause
============= ================================================
seek frwd
============= ================================================
left-click skip forward 10 seconds
right-click skip forward 60 seconds
shift-L-click skip forward 1 frame
============= ================================================
skip frwd
============= ================================================
left-click go to next chapter
shift+L-click show chapters
============= ================================================
fullscreen
============= ================================================
left-click toggle fullscreen
============= ================================================
seekbar
| Indicates current playback position and position of chapters
============= ================================================
left-click seek to position
============= ================================================
time passed
| Shows current playback position timestamp
============= ================================================
left-click toggle displaying timecodes with milliseconds
============= ================================================
cache status
| Shows current cache fill status (only visible when below 45%)
time remaining
| Shows remaining playback time timestamp
============= ================================================
left-click toggle between total and remaining time
============= ================================================
Key Bindings
~~~~~~~~~~~~
@@ -110,7 +130,7 @@ these keys. In case of collision, the function needs to be bound to a
different key. See the `Script Commands`_ section.
============= ================================================
del Cycles visibility between never / auto (mouse-move) / always
del Hide the OSC permanently until mpv is restarted.
============= ================================================
Configuration
@@ -149,40 +169,35 @@ Configurable Options
``showwindowed``
| Default: yes
| Enable the OSC when windowed
| Show OSC when windowed?
``showfullscreen``
| Default: yes
| Enable the OSC when fullscreen
| Show OSC when fullscreen?
``scalewindowed``
| Default: 1.5
| Scale factor of the OSC when windowed
| Default: 1
| Scaling of the controller when windowed
``scalefullscreen``
| Default: 1.5
| Scale factor of the OSC when fullscreen
| Default: 1
| Scaling of the controller when fullscreen
``scaleforcedwindow``
| Default: 2.0
| Scale factor of the OSC when rendered on a forced (dummy) window
| Default: 2
| Scaling of the controller when rendered on a forced (dummy) window
``vidscale``
| Default: yes
| Scale the OSC with the video
| ``no`` tries to keep the OSC size constant as much as the window size allows
| Scale the controller with the video?
``valign``
| Default: 0.8
| Vertical alignment, -1 (top) to 1 (bottom)
``halign``
| Default: 0.0
| Horizontal alignment, -1 (left) to 1 (right)
``barmargin``
| Default: 0
| Margin from bottom (bottombar) or top (topbar), in pixels
| Horizontal alignment, -1 (left) to 1 (right)
``boxalpha``
| Default: 80
@@ -190,72 +205,57 @@ Configurable Options
``hidetimeout``
| Default: 500
| Duration in ms until the OSC hides if no mouse movement, must not be
negative
| Duration in ms until the OSC hides if no mouse movement, negative value
disables auto-hide
``fadeduration``
| Default: 200
| Duration of fade out in ms, 0 = no fade
``deadzonesize``
| Default: 1
| Default: 0
| Size of the deadzone. The deadzone is an area that makes the mouse act
like leaving the window. Movement there won't make the OSC show up and
it will hide immediately if the mouse enters it. The deadzone starts
at the window border opposite to the OSC and the size controls how much
of the window it will span. Values between 0 and 1, where 0 means the
OSC will always popup with mouse movement in the window, and 1 means the
OSC will only show up when the mouse hovers it.
of the window it will span. Values between 0 and 1.
``minmousemove``
| Default: 0
| Default: 3
| Minimum amount of pixels the mouse has to move between ticks to make
the OSC show up
``layout``
| Default: bottombar
| Default: box
| The layout for the OSC. Currently available are: box, slimbox,
bottombar and topbar.
``seekbarstyle``
| Default: bar
| Default: slider
| Sets the style of the seekbar, slider (diamond marker) or bar (fill)
``tooltipborder``
| Default: 1
| Size of the tooltip outline when using bottombar or topbar layouts
``timetotal``
| Default: no
| Show total time instead of time remaining
``timems``
| Default: no
| Display timecodes with milliseconds
``visibility``
| Default: auto (auto hide/show on mouse move)
| Also supports ``never`` and ``always``
Script Commands
~~~~~~~~~~~~~~~
The OSC script listens to certain script commands. These commands can bound
in ``input.conf``, or sent by other scripts.
``enable-osc``
Undoes ``disable-osc`` or the effect of the ``del`` key.
``disable-osc``
Hide the OSC permanently. This is also what the ``del`` key does.
``osc-message``
Show a message on screen using the OSC. First argument is the message,
second the duration in seconds.
``osc-visibility``
Controls visibility mode ``never`` / ``auto`` (on mouse move) / ``always``
and also ``cycle`` to cycle between the modes
Example
You could put this into ``input.conf`` to hide the OSC with the ``a`` key and
to set auto mode (the default) with ``b``::
to unhide it with ``b``::
a script-message osc-visibility never
b script-message osc-visibility auto
a script_message disable-osc
b script_message enable-osc
+133 -91
View File
@@ -17,10 +17,6 @@ normal filter parameters.
To get a full list of available video filters, see ``--vf=help``.
Also, keep in mind that most actual filters are available via the ``lavfi``
wrapper, which gives you access to most of libavfilter's filters. This
includes all filters that have been ported from MPlayer to libavfilter.
Video filters are managed in lists. There are a few commands to manage the
filter list.
@@ -101,7 +97,7 @@ Available filters are:
All parameters are optional.
``<w>:<h>``
``<w>,<h>``
scaled width/height (default: original width/height)
:0: scaled d_width/d_height
@@ -151,15 +147,15 @@ Available filters are:
:yes: Enable accurate rounding.
``dsize[=w:h:aspect-method:r:aspect]``
Changes the intended display aspect at an arbitrary point in the
Changes the intended display size/aspect at an arbitrary point in the
filter chain. Aspect can be given as a fraction (4/3) or floating point
number (1.33). Note that this filter does *not* do any scaling itself; it
number (1.33). Alternatively, you may specify the exact display width and
height desired. Note that this filter does *not* do any scaling itself; it
just affects what later scalers (software or hardware) will do when
auto-scaling to the correct aspect.
auto-scaling to correct aspect.
``<w>,<h>``
New aspect ratio given by a display width and height. Unlike older mpv
versions or MPlayer, this does not set the display size.
New display width and height.
Can also be these special values:
@@ -202,7 +198,7 @@ Available filters are:
``<aspect>``
Force an aspect ratio.
``format=fmt=<value>:colormatrix=<value>:...``
``format[=fmt[:outfmt]]``
Restricts the color space for the next filter without doing any conversion.
Use together with the scale filter for a real conversion.
@@ -214,7 +210,7 @@ Available filters are:
Format name, e.g. rgb15, bgr24, 420p, etc. (default: don't change).
``<outfmt>``
Format name that should be substituted for the output. If they do not
have the same bytes per pixel and chroma subsampling, it will fail.
have the same bytes per pixel and chroma subsamplimg, it will fail.
``<colormatrix>``
Controls the YUV to RGB color space conversion when playing video. There
are various standards. Normally, BT.601 should be used for SD video, and
@@ -259,6 +255,26 @@ Available filters are:
:limited: limited range (16-235 for luma, 16-240 for chroma)
:full: full range (0-255 for both luma and chroma)
``<outputlevels>``
RGB color levels used with YUV to RGB conversion. Normally, output devices
such as PC monitors use full range color levels. However, some TVs and
video monitors expect studio RGB levels. Providing full range output to a
device expecting studio level input results in crushed blacks and whites,
the reverse in dim gray blacks and dim whites.
The same limitations as with ``<colormatrix>`` apply.
Available color ranges are:
:auto: automatic selection (equals to full range) (default)
:limited: limited range (16-235 per component), studio levels
:full: full range (0-255 per component), PC levels
.. note::
It is advisable to use your graphics driver's color range option
instead, if available.
``<primaries>``
RGB primaries the source file was encoded with. Normally this should be set
in the file header, but when playing broken or mistagged files this can be
@@ -288,41 +304,28 @@ Available filters are:
:adobe: Adobe RGB (1998)
:prophoto: ProPhoto RGB (ROMM)
:cie1931: CIE 1931 RGB
:dci-p3: DCI-P3 (Digital Cinema)
:v-gamut: Panasonic V-Gamut primaries
``<gamma>``
Gamma function the source file was encoded with. Normally this should be set
in the file header, but when playing broken or mistagged files this can be
used to override the setting.
``<gamma>``
Gamma function the source file was encoded with. Normally this should be set
in the file header, but when playing broken or mistagged files this can be
used to override the setting.
This option only affects video output drivers that perform color management.
This option only affects video output drivers that perform color management.
If this option is set to ``auto`` (which is the default), the gamma will
be set to BT.1886 for YCbCr content, sRGB for RGB content and Linear for
XYZ content.
If this option is set to ``auto`` (which is the default), the gamma will
be set to BT.1886 for YCbCr content, sRGB for RGB content and Linear for
XYZ content.
Available gamma functions are:
Available gamma functions are:
:auto: automatic selection (default)
:bt.1886: ITU-R BT.1886 (EOTF corresponding to BT.601/BT.709/BT.2020)
:srgb: IEC 61966-2-4 (sRGB)
:linear: Linear light
:gamma1.8: Pure power curve (gamma 1.8)
:gamma2.2: Pure power curve (gamma 2.2)
:gamma2.8: Pure power curve (gamma 2.8)
:prophoto: ProPhoto RGB (ROMM) curve
:st2084: SMPTE ST2084 (HDR) curve
:std-b67: ARIB STD-B67 (Hybrid Log-gamma) curve
:v-log: Panasonic V-Log transfer curve
``<peak>``
Reference peak illumination for the video file. This is mostly
interesting for HDR, but it can also be used tone map SDR content
to a darker or brighter exposure.
The default of 0.0 will default to the display's reference brightness
for SDR and the source's reference brightness for HDR.
:auto: automatic selection (default)
:bt.1886: ITU-R BT.1886 (approximation of BT.601/BT.709/BT.2020 curve)
:srgb: IEC 61966-2-4 (sRGB)
:linear: Linear light
:gamma1.8: Pure power curve (gamma 1.8)
:gamma2.2: Pure power curve (gamma 2.2)
:gamma2.8: Pure power curve (gamma 2.8)
:prophoto: ProPhoto RGB (ROMM) curve
``<stereo-in>``
Set the stereo mode the video is assumed to be encoded in. Takes the
@@ -406,6 +409,41 @@ Available filters are:
``'--vf=lavfi=yadif:o="threads=2,thread_type=slice"'``
forces a specific threading configuration.
``noise[=<strength>[:averaged][:pattern][:temporal][:uniform][:hq]``
Adds noise.
``strength``
Set the noise for all components. If you want different strength
values for luma and chroma, use libavfilter's noise filter directly
(using ``--vf=lavfi=[noise=...]``), or tell the libavfilter developers
to stop being stupid.
``averaged``
averaged temporal noise (smoother, but a lot slower)
``pattern``
mix random noise with a (semi)regular pattern
``temporal``
temporal noise (noise pattern changes between frames)
``uniform``
uniform noise (Gaussian otherwise)
``hqdn3d[=luma_spatial:chroma_spatial:luma_tmp:chroma_tmp]``
This filter aims to reduce image noise producing smooth images and making
still images really still (This should enhance compressibility.).
``<luma_spatial>``
spatial luma strength (default: 4)
``<chroma_spatial>``
spatial chroma strength (default: 3)
``<luma_tmp>``
luma temporal strength (default: 6)
``<chroma_tmp>``
chroma temporal strength (default:
``luma_tmp*chroma_spatial/luma_spatial``)
``eq[=gamma:contrast:brightness:saturation:rg:gg:bg:weight]``
Software equalizer that uses lookup tables (slow), allowing gamma correction
in addition to simple brightness and contrast adjustment. The parameters are
@@ -432,6 +470,23 @@ Available filters are:
and just plain white. A value of 0.0 turns the gamma correction all
the way down while 1.0 leaves it at its full strength (default: 1.0).
``unsharp[=lx:ly:la:cx:cy:ca]``
unsharp mask / Gaussian blur
``l`` is for the luma component, ``c`` for the chroma component. ``x``/``y``
is the filter size. ``a`` is the amount.
``lx``, ``ly``, ``cx``, ``cy``
width and height of the matrix, odd sized in both directions (min =
3:3, max = 13:11 or 11:13, usually something between 3:3 and 7:7)
``la``, ``ca``
Relative amount of sharpness/blur to add to the image (a sane range
should be -1.5-1.5).
:<0: blur
:>0: sharpen
``pullup[=jl:jr:jt:jb:sb:mp]``
Pulldown reversal (inverse telecine) filter, capable of handling mixed
hard-telecine, 24000/1001 fps progressive, and 30000/1001 fps progressive
@@ -451,8 +506,9 @@ Available filters are:
generating an occasional mismatched frame, but it may also cause an
excessive number of frames to be dropped during high motion sequences.
Conversely, setting it to -1 will make ``pullup`` match fields more
easily. This may help process video with slight blurring between the
fields, but may also cause interlaced frames in the output.
easily. This may help processing of video where there is slight
blurring between the fields, but may also cause there to be interlaced
frames in the output.
``mp`` (metric plane)
This option may be set to ``u`` or ``v`` to use a chroma plane instead of the
@@ -462,32 +518,49 @@ Available filters are:
video. The main purpose of setting ``mp`` to a chroma plane is to reduce
CPU load and make pullup usable in realtime on slow machines.
``yadif=[mode:interlaced-only]``
``yadif=[mode[:enabled=yes|no]]``
Yet another deinterlacing filter
``<mode>``
:frame: Output 1 frame for each frame.
:field: Output 1 frame for each field (default).
:field: Output 1 frame for each field.
:frame-nospatial: Like ``frame`` but skips spatial interlacing check.
:field-nospatial: Like ``field`` but skips spatial interlacing check.
``<interlaced-only>``
:no: Deinterlace all frames.
:yes: Only deinterlace frames marked as interlaced (default).
``<enabled>``
:yes: Filter is active (default).
:no: Filter is not active, but can be activated with the ``D`` key
(or any other key that toggles the ``deinterlace`` property).
This filter is automatically inserted when using the ``d`` key (or any
This filter, is automatically inserted when using the ``D`` key (or any
other key that toggles the ``deinterlace`` property or when using the
``--deinterlace`` switch), assuming the video output does not have native
deinterlacing support.
If you just want to set the default mode, put this filter and its options
into ``--vf-defaults`` instead, and enable deinterlacing with ``d`` or
into ``--vf-defaults`` instead, and enable deinterlacing with ``D`` or
``--deinterlace``.
Also, note that the ``d`` key is stupid enough to insert a deinterlacer twice
Also note that the ``D`` key is stupid enough to insert an interlacer twice
when inserting yadif with ``--vf``, so using the above methods is
recommended.
``delogo[=x:y:w:h:t:show]``
Suppresses a TV station logo by a simple interpolation of the surrounding
pixels. Just set a rectangle covering the logo and watch it disappear (and
sometimes something even uglier appear - your mileage may vary).
``<x>,<y>``
top left corner of the logo
``<w>,<h>``
width and height of the cleared rectangle
``<t>``
Thickness of the fuzzy edge of the rectangle (added to ``w`` and
``h``). When set to -1, a green rectangle is drawn on the screen to
simplify finding the right ``x``,``y``,``w``,``h`` parameters.
``show``
Draw a rectangle showing the area defined by x/y/w/h.
``sub=[=bottom-margin:top-margin]``
Moves subtitle rendering to an arbitrary point in the filter chain, or force
subtitle rendering in the video filter as opposed to using video output OSD
@@ -596,8 +669,6 @@ Available filters are:
Loads an external library to filter the image. The library interface
is the ``vf_dlopen`` interface specified using ``libmpcodecs/vf_dlopen.h``.
.. warning:: This filter is deprecated.
``dll=<library>``
Specify the library to load. This may require a full file system path
in some cases. This argument is required.
@@ -656,11 +727,10 @@ Available filters are:
``buffered-frames``
Maximum number of decoded video frames that should be buffered before
the filter (default: 4). This specifies the maximum number of frames
the script can request in reverse direction.
E.g. if ``buffered-frames=5``, and the script just requested frame 15,
it can still request frame 10, but frame 9 is not available anymore.
If it requests frame 30, mpv will decode 15 more frames, and keep only
frames 25-30.
the script can requests backwards. E.g. if ``buffered-frames=5``, and
the script just requested frame 15, it can still request frame 10, but
frame 9 is not available anymore. If it requests frame 30, mpv will
decode 15 more frames, and keep only frames 25-30.
The actual number of buffered frames also depends on the value of the
``concurrent-frames`` option. Currently, both option values are
@@ -708,7 +778,7 @@ Available filters are:
``vapoursynth-lazy``
The same as ``vapoursynth``, but doesn't load Python scripts. Instead, a
custom backend using Lua and the raw VapourSynth API is used. The syntax
is completely different, and absolutely no convenience features are
is completely different, and absolutely no conveniencve features are
provided. There's no type checking either, and you can trigger crashes.
.. admonition:: Example:
@@ -733,7 +803,7 @@ Available filters are:
``vavpp``
VA-AP-API video post processing. Works with ``--vo=vaapi`` and ``--vo=opengl``
only. Currently deinterlaces. This filter is automatically inserted if
deinterlacing is requested (either using the ``d`` key, by default mapped to
deinterlacing is requested (either using the ``D`` key, by default mapped to
the command ``cycle deinterlace``, or the ``--deinterlace`` option).
``deint=<method>``
@@ -750,14 +820,10 @@ Available filters are:
depends on the GPU hardware, the GPU drivers, driver bugs, and
mpv bugs.
``<interlaced-only>``
:no: Deinterlace all frames.
:yes: Only deinterlace frames marked as interlaced (default).
``vdpaupp``
VDPAU video post processing. Works with ``--vo=vdpau`` and ``--vo=opengl``
only. This filter is automatically inserted if deinterlacing is requested
(either using the ``d`` key, by default mapped to the command
(either using the ``D`` key, by default mapped to the command
``cycle deinterlace``, or the ``--deinterlace`` option). When enabling
deinterlacing, it is always preferred over software deinterlacer filters
if the ``vdpau`` VO is used, and also if ``opengl`` is used and hardware
@@ -798,38 +864,14 @@ Available filters are:
``pullup``
Try to apply inverse telecine, needs motion adaptive temporal
deinterlacing.
``interlaced-only=<yes|no>``
If ``yes`` (default), only deinterlace frames marked as interlaced.
``hqscaling=<0-9>``
0
Use default VDPAU scaling (default).
1-9
Apply high quality VDPAU scaling (needs capable hardware).
``vdpaurb``
VDPAU video read back. Works with ``--vo=vdpau`` and ``--vo=opengl`` only.
This filter will read back frames decoded by VDPAU so that other filters,
which are not normally compatible with VDPAU, can be used like normal.
This filter must be specified before ``vdpaupp`` in the filter chain if
``vdpaupp`` is used.
``d3d11vpp``
Direct3D 11 video post processing. Currently requires D3D11 hardware
decoding for use.
``deint=<yes|no>``
Whether deinterlacing is enabled (default: no).
``interlaced-only=<yes|no>``
If ``yes`` (default), only deinterlace frames marked as interlaced.
``mode=<blend|bob|adaptive|mocomp|ivctc|none>``
Tries to select a video processor with the given processing capability.
If a video processor supports multiple capabilities, it is not clear
which algorithm is actually selected. ``none`` always falls back. On
most if not all hardware, this option will probably do nothing, because
a video processor usually supports all modes or none.
``buffer=<num>``
Buffer ``<num>`` frames in the filter chain. This filter is probably pretty
useless, except for debugging. (Note that this won't help to smooth out
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.)
+571 -145
View File
@@ -4,25 +4,29 @@ VIDEO OUTPUT DRIVERS
Video output drivers are interfaces to different video output facilities. The
syntax is:
``--vo=<driver1,driver2,...[,]>``
``--vo=<driver1[:suboption1[=value]:...],driver2,...[,]>``
Specify a priority list of video output drivers to be used.
If the list has a trailing ``,``, mpv will fall back on drivers not contained
in the list.
If the list has a trailing ',', mpv will fall back on drivers not contained
in the list. Suboptions are optional and can mostly be omitted.
You can also set defaults for each driver. The defaults are applied before the
normal driver parameters.
``--vo-defaults=<driver1[:parameter1:parameter2:...],driver2,...>``
Set defaults for each driver.
Deprecated. No replacement.
.. note::
See ``--vo=help`` for a list of compiled-in video output drivers.
The recommended output driver is ``--vo=opengl``, which is the default. All
other drivers are for compatibility or special purposes. If the default
does not work, it will fallback to other drivers (in the same order as
listed by ``--vo=help``).
The recommended output drivers are ``--vo=vdpau`` and ``--vo=opengl-hq``.
All other drivers are just for compatibility or special purposes.
.. admonition:: Example
``--vo=opengl,xv,``
Try the ``opengl`` driver, then the ``xv`` driver, then others.
Available video output drivers are:
@@ -33,13 +37,11 @@ Available video output drivers are:
.. note:: This driver is for compatibility with old systems.
The following global options are supported by this video output:
``--xv-adaptor=<number>``
``adaptor=<number>``
Select a specific XVideo adapter (check xvinfo results).
``--xv-port=<number>``
``port=<number>``
Select a specific XVideo port.
``--xv-ck=<cur|use|set>``
``ck=<cur|use|set>``
Select the source from which the color key is taken (default: cur).
cur
@@ -50,11 +52,9 @@ Available video output drivers are:
set
Same as use but also sets the supplied color key.
``--xv-ck-method=<none|man|bg|auto>``
``ck-method=<man|bg|auto>``
Sets the color key drawing method (default: man).
none
Disables color-keying.
man
Draw the color key manually (reduces flicker in some cases).
bg
@@ -62,15 +62,12 @@ Available video output drivers are:
auto
Let Xv draw the color key.
``--xv-colorkey=<number>``
``colorkey=<number>``
Changes the color key to an RGB value of your choice. ``0x000000`` is
black and ``0xffffff`` is white.
``--xv-buffers=<number>``
Number of image buffers to use for the internal ringbuffer (default: 2).
Increasing this will use more memory, but might help with the X server
not responding quickly enough if video FPS is close to or higher than
the display refresh rate.
``no-colorkey``
Disables color-keying.
``x11`` (X11 only)
Shared memory video output driver without hardware acceleration that works
@@ -89,25 +86,23 @@ Available video output drivers are:
``chroma-deint``, ``pullup``, ``hqscaling``. These sub-options are
deprecated, and you should use the ``vdpaupp`` video filter instead.
The following global options are supported by this video output:
``--vo-vdpau-sharpen=<-1-1>``
``sharpen=<-1-1>``
(Deprecated. See note about ``vdpaupp``.)
For positive values, apply a sharpening algorithm to the video, for
negative values a blurring algorithm (default: 0).
``--vo-vdpau-denoise=<0-1>``
``denoise=<0-1>``
(Deprecated. See note about ``vdpaupp``.)
Apply a noise reduction algorithm to the video (default: 0; no noise
reduction).
``--vo-vdpau-deint=<-4-4>``
``deint=<-4-4>``
(Deprecated. See note about ``vdpaupp``.)
Select deinterlacing mode (default: 0). In older versions (as well as
MPlayer/mplayer2) you could use this option to enable deinterlacing.
This doesn't work anymore, and deinterlacing is enabled with either
the ``d`` key (by default mapped to the command ``cycle deinterlace``),
the ``D`` key (by default mapped to the command ``cycle deinterlace``),
or the ``--deinterlace`` option. Also, to select the default deint mode,
you should use something like ``--vf-defaults=vdpaupp:deint-mode=temporal``
instead of this sub-option.
@@ -124,32 +119,32 @@ Available video output drivers are:
4
Motion-adaptive temporal deinterlacing with edge-guided spatial
interpolation. Needs fast video hardware.
``--vo-vdpau-chroma-deint``
``chroma-deint``
(Deprecated. See note about ``vdpaupp``.)
Makes temporal deinterlacers operate both on luma and chroma (default).
Use no-chroma-deint to solely use luma and speed up advanced
deinterlacing. Useful with slow video memory.
``--vo-vdpau-pullup``
``pullup``
(Deprecated. See note about ``vdpaupp``.)
Try to apply inverse telecine, needs motion adaptive temporal
deinterlacing.
``--vo-vdpau-hqscaling=<0-9>``
``hqscaling=<0-9>``
(Deprecated. See note about ``vdpaupp``.)
0
Use default VDPAU scaling (default).
1-9
Apply high quality VDPAU scaling (needs capable hardware).
``--vo-vdpau-fps=<number>``
``fps=<number>``
Override autodetected display refresh rate value (the value is needed
for framedrop to allow video playback rates higher than display
refresh rate, and for vsync-aware frame timing adjustments). Default 0
means use autodetected value. A positive value is interpreted as a
refresh rate in Hz and overrides the autodetected value. A negative
value disables all timing adjustment and framedrop logic.
``--vo-vdpau-composite-detect``
``composite-detect``
NVIDIA's current VDPAU implementation behaves somewhat differently
under a compositing window manager and does not give accurate frame
timing information. With this option enabled, the player tries to
@@ -160,20 +155,20 @@ Available video output drivers are:
with the composited mode behavior of the NVIDIA driver, there is no
hard playback speed limit even without the disabled logic. Enabled by
default, use ``no-composite-detect`` to disable.
``--vo-vdpau-queuetime-windowed=<number>`` and ``queuetime-fs=<number>``
``queuetime_windowed=<number>`` and ``queuetime_fs=<number>``
Use VDPAU's presentation queue functionality to queue future video
frame changes at most this many milliseconds in advance (default: 50).
See below for additional information.
``--vo-vdpau-output-surfaces=<2-15>``
``output_surfaces=<2-15>``
Allocate this many output surfaces to display video frames (default:
3). See below for additional information.
``--vo-vdpau-colorkey=<#RRGGBB|#AARRGGBB>``
``colorkey=<#RRGGBB|#AARRGGBB>``
Set the VDPAU presentation queue background color, which in practice
is the colorkey used if VDPAU operates in overlay mode (default:
``#020507``, some shade of black). If the alpha component of this value
is 0, the default VDPAU colorkey will be used instead (which is usually
green).
``--vo-vdpau-force-yuv``
``force-yuv``
Never accept RGBA input. This means mpv will insert a filter to convert
to a YUV format before the VO. Sometimes useful to force availability
of certain YUV-only features, like video equalizer or deinterlacing.
@@ -200,40 +195,31 @@ Available video output drivers are:
driver implementation may also have limits on the length of maximum
queuing time or number of queued surfaces that work well or at all.
``direct3d`` (Windows only)
``direct3d_shaders`` (Windows only)
Video output driver that uses the Direct3D interface.
.. note:: This driver is for compatibility with systems that don't provide
proper OpenGL drivers, and where ANGLE does not perform well.
proper OpenGL drivers.
.. note:: Before to 0.21.0, ``direct3d_shaders`` and ``direct3d`` were
different, with ``direct3d`` not using shader by default. Now
both use shaders by default, and ``direct3d_shaders`` is a
deprecated alias. Use the ``--vo-direct3d-prefer-stretchrect``
or the ``--vo-direct3d-disable-shaders`` options to get the old
behavior of ``direct3d``.
The following global options are supported by this video output:
``--vo-direct3d-prefer-stretchrect``
``prefer-stretchrect``
Use ``IDirect3DDevice9::StretchRect`` over other methods if possible.
``--vo-direct3d-disable-stretchrect``
``disable-stretchrect``
Never render the video using ``IDirect3DDevice9::StretchRect``.
``--vo-direct3d-disable-textures``
``disable-textures``
Never render the video using D3D texture rendering. Rendering with
textures + shader will still be allowed. Add ``disable-shaders`` to
completely disable video rendering with textures.
``--vo-direct3d-disable-shaders``
``disable-shaders``
Never use shaders when rendering video.
``--vo-direct3d-only-8bit``
``only-8bit``
Never render YUV video with more than 8 bits per component.
Using this flag will force software conversion to 8-bit.
``--vo-direct3d-disable-texture-align``
``disable-texture-align``
Normally texture sizes are always aligned to 16. With this option
enabled, the video texture will always have exactly the same size as
the video itself.
@@ -243,11 +229,11 @@ Available video output drivers are:
might crash, might cause slow downs, etc. Contact the developers if you
actually need any of these for performance or proper operation.
``--vo-direct3d-force-power-of-2``
``force-power-of-2``
Always force textures to power of 2, even if the device reports
non-power-of-2 texture sizes as supported.
``--vo-direct3d-texture-memory=<mode>``
``texture-memory=<mode>``
Only affects operation with shaders/texturing enabled, and (E)OSD.
Possible values:
@@ -271,24 +257,26 @@ Available video output drivers are:
Use ``D3DPOOL_SCRATCH``, with a ``D3DPOOL_SYSTEMMEM`` texture for
locking.
``--vo-direct3d-swap-discard``
``swap-discard``
Use ``D3DSWAPEFFECT_DISCARD``, which might be faster.
Might be slower too, as it must(?) clear every frame.
``--vo-direct3d-exact-backbuffer``
``exact-backbuffer``
Always resize the backbuffer to window size.
``direct3d`` (Windows only)
Same as ``direct3d_shaders``, but with the options ``disable-textures``
and ``disable-shaders`` forced.
.. note:: This driver is for compatibility with old systems.
``opengl``
OpenGL video output driver. It supports extended scaling methods, dithering
and color management.
See `OpenGL renderer options`_ for options specific to this VO.
By default, it tries to use fast and fail-safe settings. Use the
``opengl-hq`` profile to use this driver with defaults set to high
quality rendering. (This profile is also the replacement for
``--vo=opengl-hq``.) The profile can be applied with ``--profile=opengl-hq``
and its contents can be viewed with ``--show-profile=opengl-hq``.
By default, it tries to use fast and fail-safe settings. Use the alias
``opengl-hq`` to use this driver with defaults set to high quality
rendering.
Requires at least OpenGL 2.1.
@@ -302,13 +290,471 @@ Available video output drivers are:
color space conversion and chroma upsampling is generally in the hand of
the hardware decoder APIs.
``opengl`` makes use of FBOs by default. Sometimes you can achieve better
quality or performance by changing the ``--opengl-fbo-format`` option to
``rgb16f``, ``rgb32f`` or ``rgb``. Known problems include Mesa/Intel not
accepting ``rgb16``, Mesa sometimes not being compiled with float texture
support, and some OS X setups being very slow with ``rgb16`` but fast
with ``rgb32f``. If you have problems, you can also try enabling the
``--opengl-dumb-mode=yes`` option.
``scale=<filter>``
``bilinear``
Bilinear hardware texture filtering (fastest, very low quality).
This is the default for compatibility reasons.
``spline36``
Mid quality and speed. This is the default when using ``opengl-hq``.
``lanczos``
Lanczos scaling. Provides mid quality and speed. Generally worse
than ``spline36``, but it results in a slightly sharper image
which is good for some content types. The number of taps can be
controlled with ``scale-radius``, but is best left unchanged.
This filter corresponds to the old ``lanczos3`` alias if the default
radius is used, while ``lanczos2`` corresponds to a radius of 2.
(This filter is an alias for ``sinc``-windowed ``sinc``)
``ewa_lanczos``
Elliptic weighted average Lanczos scaling. Also known as Jinc.
Relatively slow, but very good quality. The radius can be
controlled with ``scale-radius``. Increasing the radius makes the
filter sharper but adds more ringing.
(This filter is an alias for ``jinc``-windowed ``jinc``)
``ewa_lanczossharp``
A slightly sharpened version of ewa_lanczos, preconfigured to use
an ideal radius and parameter. If your hardware can run it, this is
probably what you should use by default.
``mitchell``
Mitchell-Netravali. The ``B`` and ``C`` parameters can be set with
``scale-param1`` and ``scale-param2``. This filter is very good at
downscaling (see ``dscale``).
``oversample``
A version of nearest neighbour that (naively) oversamples pixels,
so that pixels overlapping edges get linearly interpolated instead
of rounded. This essentially removes the small imperfections and
judder artifacts caused by nearest-neighbour interpolation, in
exchange for adding some blur. This filter is good at temporal
interpolation, and also known as "smoothmotion" (see ``tscale``).
There are some more filters, but most are not as useful. For a complete
list, pass ``help`` as value, e.g.::
mpv --vo=opengl:scale=help
``scale-param1=<value>``, ``scale-param2=<value>``
Set filter parameters. Ignored if the filter is not tunable.
Currently, this affects the following filter parameters:
bcspline
Spline parameters (``B`` and ``C``). Defaults to 0.5 for both.
gaussian
Scale parameter (``t``). Increasing this makes the result blurrier.
Defaults to 1.
sharpen3, sharpen5
Sharpening strength. Increasing this makes the image sharper but
adds more ringing and aliasing. Defaults to 0.5.
oversample
Minimum distance to an edge before interpolation is used. Setting
this to 0 will always interpolate edges, whereas setting it to 0.5
will never interpolate, thus behaving as if the regular nearest
neighbour algorithm was used. Defaults to 0.0.
``scale-blur=<value>``
Kernel scaling factor (also known as a blur factor). Decreasing this
makes the result sharper, increasing it makes it blurrier (default 0).
If set to 0, the kernel's preferred blur factor is used. Note that
setting this too low (eg. 0.5) leads to bad results. It's generally
recommended to stick to values between 0.8 and 1.2.
``scale-radius=<value>``
Set radius for filters listed below, must be a float number between 0.5
and 16.0. Defaults to the filter's preferred radius if not specified.
``sinc`` and derivatives, ``jinc`` and derivatives, ``gaussian``, ``box`` and ``triangle``
Note that depending on filter implementation details and video scaling
ratio, the radius that actually being used might be different
(most likely being increased a bit).
``scale-antiring=<value>``
Set the antiringing strength. This tries to eliminate ringing, but can
introduce other artifacts in the process. Must be a float number
between 0.0 and 1.0. The default value of 0.0 disables antiringing
entirely.
Note that this doesn't affect the special filters ``bilinear``,
``bicubic_fast`` or ``sharpen``.
``scale-window=<window>``
(Advanced users only) Choose a custom windowing function for the kernel.
Defaults to the filter's preferred window if unset. Use
``scale-window=help`` to get a list of supported windowing functions.
``scale-wparam=<window>``
(Advanced users only) Configure the parameter for the window function
given by ``scale-window``. Ignored if the window is not tunable.
Currently, this affects the following window parameters:
kaiser
Window parameter (alpha). Defaults to 6.33.
blackman
Window parameter (alpha). Defaults to 0.16.
gaussian
Scale parameter (t). Increasing this makes the window wider.
Defaults to 1.
``scaler-resizes-only``
Disable the scaler if the video image is not resized. In that case,
``bilinear`` is used instead whatever is set with ``scale``. Bilinear
will reproduce the source image perfectly if no scaling is performed.
Note that this option never affects ``cscale``.
``pbo``
Enable use of PBOs. This is slightly faster, but can sometimes lead to
sporadic and temporary image corruption (in theory, because reupload
is not retried when it fails), and perhaps actually triggers slower
paths with drivers that don't support PBOs properly.
``dither-depth=<N|no|auto>``
Set dither target depth to N. Default: no.
no
Disable any dithering done by mpv.
auto
Automatic selection. If output bit depth cannot be detected,
8 bits per component are assumed.
8
Dither to 8 bit output.
Note that the depth of the connected video display device can not be
detected. Often, LCD panels will do dithering on their own, which
conflicts with ``opengl``'s dithering and leads to ugly output.
``dither-size-fruit=<2-8>``
Set the size of the dither matrix (default: 6). The actual size of
the matrix is ``(2^N) x (2^N)`` for an option value of ``N``, so a
value of 6 gives a size of 64x64. The matrix is generated at startup
time, and a large matrix can take rather long to compute (seconds).
Used in ``dither=fruit`` mode only.
``dither=<fruit|ordered|no>``
Select dithering algorithm (default: fruit). (Normally, the
``dither-depth`` option controls whether dithering is enabled.)
``temporal-dither``
Enable temporal dithering. (Only active if dithering is enabled in
general.) This changes between 8 different dithering pattern on each
frame by changing the orientation of the tiled dithering matrix.
Unfortunately, this can lead to flicker on LCD displays, since these
have a high reaction time.
``debug``
Check for OpenGL errors, i.e. call ``glGetError()``. Also request a
debug OpenGL context (which does nothing with current graphics drivers
as of this writing).
``interpolation``
Reduce stuttering caused by mismatches in the video fps and display
refresh rate (also known as judder).
This essentially attempts to interpolate the missing frames by
convoluting the video along the temporal axis. The filter used can be
controlled using the ``tscale`` setting.
Note that this relies on vsync to work, see ``swapinterval`` for more
information.
``swapinterval=<n>``
Interval in displayed frames between two buffer swaps.
1 is equivalent to enable VSYNC, 0 to disable VSYNC. Defaults to 1 if
not specified.
Note that this depends on proper OpenGL vsync support. On some platforms
and drivers, this only works reliably when in fullscreen mode. It may
also require driver-specific hacks if using multiple monitors, to
ensure mpv syncs to the right one. Compositing window managers can
also lead to bad results, as can missing or incorrect display FPS
information (see ``--display-fps``).
``dscale=<filter>``
Like ``scale``, but apply these filters on downscaling instead. If this
option is unset, the filter implied by ``scale`` will be applied.
``cscale=<filter>``
As ``scale``, but for interpolating chroma information. If the image
is not subsampled, this option is ignored entirely.
``tscale=<filter>``
The filter used for interpolating the temporal axis (frames). This is
only used if ``interpolation`` is enabled. The only valid choices
for ``tscale`` are separable convolution filters (use ``tscale=help``
to get a list). The default is ``oversample``.
Note that the maximum supported filter radius is currently 3, and that
using filters with larger radius may introduce issues when pausing or
framestepping, proportional to the radius used. It is recommended to
stick to a radius of 1 or 2.
``dscale-radius``, ``cscale-radius``, ``tscale-radius``, etc.
Set filter parameters for ``dscale``, ``cscale`` and ``tscale``,
respectively.
See the corresponding options for ``scale``.
``linear-scaling``
Scale in linear light. This is automatically enabled if
``target-prim``, ``target-trc``, ``icc-profile`` or
``sigmoid-upscaling`` is set. It should only be used with a
``fbo-format`` that has at least 16 bit precision.
``fancy-downscaling``
When using convolution based filters, extend the filter size
when downscaling. Trades quality for reduced downscaling performance.
This is automatically disabled for anamorphic video, because this
feature doesn't work correctly with different scale factors in
different directions.
``sigmoid-upscaling``
When upscaling, use a sigmoidal color transform to avoid emphasizing
ringing artifacts. This also enables ``linear-scaling``.
``sigmoid-center``
The center of the sigmoid curve used for ``sigmoid-upscaling``, must
be a float between 0.0 and 1.0. Defaults to 0.75 if not specified.
``sigmoid-slope``
The slope of the sigmoid curve used for ``sigmoid-upscaling``, must
be a float between 1.0 and 20.0. Defaults to 6.5 if not specified.
``no-npot``
Force use of power-of-2 texture sizes. For debugging only.
Borders will be distorted due to filtering.
``glfinish``
Call ``glFinish()`` before and after swapping buffers (default: disabled).
Slower, but might help getting better results when doing framedropping.
Can completely ruin performance. The details depend entirely on the
OpenGL driver.
``waitvsync``
Call ``glXWaitVideoSyncSGI`` after each buffer swap (default: disabled).
This may or may not help with video timing accuracy and frame drop. It's
possible that this makes video output slower, or has no effect at all.
X11/GLX only.
``dwmflush=<no|windowed|yes>``
Calls ``DwmFlush`` after swapping buffers on Windows (default: no).
It also sets ``SwapInterval(0)`` to ignore the OpenGL timing. Values
are: no (disabled), windowed (only in windowed mode), yes (also in
full screen).
This may help getting more consistent frame intervals, especially with
high-fps clips - which might also reduce dropped frames. Typically a
value of 1 should be enough since full screen may bypass the DWM.
Windows only.
``sw``
Continue even if a software renderer is detected.
``backend=<sys>``
The value ``auto`` (the default) selects the windowing backend. You
can also pass ``help`` to get a complete list of compiled in backends
(sorted by autoprobe order).
auto
auto-select (default)
cocoa
Cocoa/OS X
win
Win32/WGL
x11, x11es
X11/GLX (the ``es`` variant forces GLES)
wayland
Wayland/EGL
x11egl, x11egles
X11/EGL (the ``es`` variant forces GLES)
``fbo-format=<fmt>``
Selects the internal format of textures used for FBOs. The format can
influence performance and quality of the video output. (FBOs are not
always used, and typically only when using extended scalers.)
``fmt`` can be one of: rgb, rgba, rgb8, rgb10, rgb10_a2, rgb16, rgb16f,
rgb32f, rgba12, rgba16, rgba16f, rgba32f.
Default: rgba.
``gamma=<0.1..2.0>``
Set a gamma value (default: 1.0). If gamma is adjusted in other ways
(like with the ``--gamma`` option or key bindings and the ``gamma``
property), the value is multiplied with the other gamma value.
Recommended values based on the environmental brightness:
1.0
Brightly illuminated (default)
0.9
Slightly dim
0.8
Pitch black room
``gamma-auto``
Automatically corrects the gamma value depending on ambient lighting
conditions (adding a gamma boost for dark rooms).
With ambient illuminance of 64lux, mpv will pick the 1.0 gamma value
(no boost), and slightly increase the boost up until 0.8 for 16lux.
NOTE: Only implemented on OS X.
``target-prim=<value>``
Specifies the primaries of the display. Video colors will be adapted
to this colorspace if necessary. Valid values are:
auto
Disable any adaptation (default)
bt.470m
ITU-R BT.470 M
bt.601-525
ITU-R BT.601 (525-line SD systems, eg. NTSC), SMPTE 170M/240M
bt.601-625
ITU-R BT.601 (625-line SD systems, eg. PAL/SECAM), ITU-R BT.470 B/G
bt.709
ITU-R BT.709 (HD), IEC 61966-2-4 (sRGB), SMPTE RP177 Annex B
bt.2020
ITU-R BT.2020 (UHD)
apple
Apple RGB
adobe
Adobe RGB (1998)
prophoto
ProPhoto RGB (ROMM)
cie1931
CIE 1931 RGB (not to be confused with CIE XYZ)
``target-trc=<value>``
Specifies the transfer characteristics (gamma) of the display. Video
colors will be adjusted to this curve. Valid values are:
auto
Disable any adaptation (default)
bt.1886
ITU-R BT.1886 curve, without the brightness drop (approx. 1.961)
srgb
IEC 61966-2-4 (sRGB)
linear
Linear light output
gamma1.8
Pure power curve (gamma 1.8), also used for Apple RGB
gamma2.2
Pure power curve (gamma 2.2)
gamma2.8
Pure power curve (gamma 2.8), also used for BT.470-BG
prophoto
ProPhoto RGB (ROMM)
``icc-profile=<file>``
Load an ICC profile and use it to transform linear RGB to screen output.
Needs LittleCMS 2 support compiled in. This option overrides the
``target-prim`` and ``target-trc`` options. It also enables
``linear-scaling``.
``icc-profile-auto``
Automatically select the ICC display profile currently specified by
the display settings of the operating system.
NOTE: Only implemented on OS X and X11
``icc-cache=<file>``
Store and load the 3D LUT created from the ICC profile in this file.
This can be used to speed up loading, since LittleCMS 2 can take a while
to create the 3D LUT. Note that this file contains an uncompressed LUT.
Its size depends on the ``3dlut-size``, and can be very big.
``icc-intent=<value>``
Specifies the ICC intent used for the color transformation (when using
``icc-profile``).
0
perceptual
1
relative colorimetric (default)
2
saturation
3
absolute colorimetric
``3dlut-size=<r>x<g>x<b>``
Size of the 3D LUT generated from the ICC profile in each dimension.
Default is 128x256x64.
Sizes must be a power of two, and 512 at most.
``blend-subtitles=<yes|video|no>``
Blend subtitles directly onto upscaled video frames, before
interpolation and/or color management (default: no). Enabling this
causes subtitles to be affected by ``icc-profile``, ``target-prim``,
``target-trc``, ``interpolation``, ``gamma`` and ``linear-scaling``.
It also increases subtitle performance when using ``interpolation``.
The downside of enabling this is that it restricts subtitles to the
visible portion of the video, so you can't have subtitles exist in the
black margins below a video (for example).
If ``video`` is selected, the behavior is similar to ``yes``, but subs
are drawn at the video's native resolution, and scaled along with the
video.
.. warning:: This changes the way subtitle colors are handled. Normally,
subtitle colors are assumed to be in sRGB and color managed
as such. Enabling this makes them treated as being in the
video's color space instead. This is good if you want
things like softsubbed ASS signs to match the video colors,
but may cause SRT subtitles or similar to look slightly off.
``alpha=<blend|yes|no>``
Decides what to do if the input has an alpha component (default: blend).
blend
Blend the frame against a black background.
yes
Try to create a framebuffer with alpha component. This only makes sense
if the video contains alpha information (which is extremely rare). May
not be supported on all platforms. If alpha framebuffers are
unavailable, it silently falls back on a normal framebuffer. Note
that if you set the ``fbo-format`` option to a non-default value,
a format with alpha must be specified, or this won't work.
no
Ignore alpha component.
``rectangle-textures``
Force use of rectangle textures (default: no). Normally this shouldn't
have any advantages over normal textures. Note that hardware decoding
overrides this flag.
``background=<color>``
Color used to draw parts of the mpv window not covered by video.
See ``--osd-color`` option how colors are defined.
``opengl-hq``
Same as ``opengl``, but with default settings for high quality rendering.
This is equivalent to::
--vo=opengl:scale=spline36:cscale=spline36:dscale=mitchell:dither-depth=auto:fbo-format=rgba16:fancy-downscaling:sigmoid-upscaling
Note that some cheaper LCDs do dithering that gravely interferes with
``opengl``'s dithering. Disabling dithering with ``dither-depth=no`` helps.
Unlike ``opengl``, ``opengl-hq`` makes use of FBOs by default. Sometimes you
can achieve better quality or performance by changing the ``fbo-format``
suboption to ``rgb16f``, ``rgb32f`` or ``rgb``. Known problems include
Mesa/Intel not accepting ``rgb16``, Mesa sometimes not being compiled with
float texture support, and some OS X setups being very slow with ``rgb16``
but fast with ``rgb32f``.
``sdl``
SDL 2.0+ Render video output driver, depending on system with or without
@@ -318,12 +764,10 @@ Available video output drivers are:
.. note:: This driver is for compatibility with systems that don't provide
proper graphics drivers, or which support GLES only.
The following global options are supported by this video output:
``--sdl-sw``
``sw``
Continue even if a software renderer is detected.
``--sdl-switch-mode``
``switch-mode``
Instruct SDL to switch the monitor video mode when going fullscreen.
``vaapi``
@@ -335,9 +779,7 @@ Available video output drivers are:
.. note:: This driver is for compatibility with crappy systems. You can
use vaapi hardware decoding with ``--vo=opengl`` too.
The following global options are supported by this video output:
``--vo-vaapi-scaling=<algorithm>``
``scaling=<algorithm>``
default
Driver default (mpv default as well).
fast
@@ -347,9 +789,9 @@ Available video output drivers are:
nla
``non-linear anamorphic scaling``
``--vo-vaapi-deint-mode=<mode>``
``deint-mode=<mode>``
Select deinterlacing algorithm. Note that by default deinterlacing is
initially always off, and needs to be enabled with the ``d`` key
initially always off, and needs to be enabled with the ``D`` key
(default key binding for ``cycle deinterlace``).
This option doesn't apply if libva supports video post processing (vpp).
@@ -366,7 +808,7 @@ Available video output drivers are:
bob
bob deinterlacing (default for older libva).
``--vo-vaapi-scaled-osd=<yes|no>``
``scaled-osd=<yes|no>``
If enabled, then the OSD is rendered at video resolution and scaled to
display resolution. By default, this is disabled, and the OSD is
rendered at display resolution if the driver supports it.
@@ -374,14 +816,6 @@ Available video output drivers are:
``null``
Produces no video output. Useful for benchmarking.
Usually, it's better to disable video with ``--no-video`` instead.
The following global options are supported by this video output:
``--vo-null-fps=<value>``
Simulate display FPS. This artificially limits how many frames the
VO accepts per second.
``caca``
Color ASCII art video output driver that works on a text console.
@@ -391,9 +825,7 @@ Available video output drivers are:
Output each frame into an image file in the current directory. Each file
takes the frame number padded with leading zeros as name.
The following global options are supported by this video output:
``--vo-image-format=<format>``
``format=<format>``
Select the image file format.
jpg
@@ -411,24 +843,24 @@ Available video output drivers are:
tga
Truevision TGA.
``--vo-image-png-compression=<0-9>``
``png-compression=<0-9>``
PNG compression factor (speed vs. file size tradeoff) (default: 7)
``--vo-image-png-filter=<0-5>``
``png-filter=<0-5>``
Filter applied prior to PNG compression (0 = none; 1 = sub; 2 = up;
3 = average; 4 = Paeth; 5 = mixed) (default: 5)
``--vo-image-jpeg-quality=<0-100>``
``jpeg-quality=<0-100>``
JPEG quality factor (default: 90)
``--vo-image-jpeg-progressive=<yes|no>``
``(no-)jpeg-progressive``
Specify standard or progressive JPEG (default: no).
``--vo-image-jpeg-baseline=<yes|no>``
``(no-)jpeg-baseline``
Specify use of JPEG baseline or not (default: yes).
``--vo-image-jpeg-optimize=<0-100>``
``jpeg-optimize=<0-100>``
JPEG optimization factor (default: 100)
``--vo-image-jpeg-smooth=<0-100>``
``jpeg-smooth=<0-100>``
smooth factor (default: 0)
``--vo-image-jpeg-dpi=<1->``
``jpeg-dpi=<1->``
JPEG DPI (default: 72)
``--vo-image-outdir=<dirname>``
``outdir=<dirname>``
Specify the directory to save the image files to (default: ``./``).
``wayland`` (Wayland only)
@@ -437,73 +869,67 @@ Available video output drivers are:
.. note:: This driver is for compatibility with systems that don't provide
working OpenGL drivers.
The following global options are supported by this video output:
``--vo-wayland-alpha``
``alpha``
Use a buffer format that supports videos and images with alpha
information
``--vo-wayland-rgb565``
``rgb565``
Use RGB565 as buffer format. This format is implemented on most
platforms, especially on embedded where it is far more efficient then
RGB8888.
``--vo-wayland-triple-buffering``
``triple-buffering``
Use 3 buffers instead of 2. This can lead to more fluid playback, but
uses more memory.
``opengl-cb``
For use with libmpv direct OpenGL embedding; useless in any other contexts.
(See ``<mpv/opengl_cb.h>``.)
Usually, ``opengl-cb`` renders frames asynchronously by client and this
can cause some frame drops. In order to provide a way to handle this
situation, ``opengl-cb`` has its own frame queue and calls update callback
more frequently if the queue is not empty regardless of existence of new frame.
Once the queue is filled, ``opengl-cb`` drops frames automatically.
This also supports many of the options the ``opengl`` VO has.
With default options, ``opengl-cb`` renders only the latest frame and drops
all frames handed over while waiting render function after update callback.
``frame-queue-size=<1..100>``
The maximum count of frames which the frame queue can hold (default: 1)
``frame-drop-mode=<pop|clear>``
Select the behavior when the frame queue is full.
pop
Drop the oldest frame in the frame queue. (default)
clear
Drop all frames in the frame queue.
This also supports many of the suboptions the ``opengl`` VO has. Run
``mpv --vo=opengl-cb:help`` for a list.
This also supports the ``vo_cmdline`` command.
``rpi`` (Raspberry Pi)
Native video output on the Raspberry Pi using the MMAL API.
This is deprecated. Use ``--vo=opengl`` instead, which is the default and
provides the same functionality. The ``rpi`` VO will be removed in
mpv 0.22.0. Its functionality was folded into --vo=opengl, which now uses
RPI hardware decoding by treating it as a hardware overlay (without applying
GL filtering). Also to be changed in 0.22.0: the --fs flag will be reset to
"no" by default (like on the other platforms).
The following deprecated global options are supported by this video output:
``--rpi-display=<number>``
``display=<number>``
Select the display number on which the video overlay should be shown
(default: 0).
``--rpi-layer=<number>``
``layer=<number>``
Select the dispmanx layer on which the video overlay should be shown
(default: -10). Note that mpv will also use the 2 layers above the
selected layer, to handle the window background and OSD. Actual video
rendering will happen on the layer above the selected layer.
``--rpi-background=<yes|no>``
Whether to render a black background behind the video (default: no).
Normally it's better to kill the console framebuffer instead, which
gives better performance.
``--rpi-osd=<yes|no>``
Enabled by default. If disabled with ``no``, no OSD layer is created.
This also means there will be no subtitles rendered.
``drm`` (Direct Rendering Manager)
Video output driver using Kernel Mode Setting / Direct Rendering Manager.
Should be used when one doesn't want to install full-blown graphical
environment (e.g. no X). Does not support hardware acceleration (if you
need this, check the ``drm-egl`` backend for ``opengl`` VO).
Does not support hardware acceleration. Should be used when one doesn't
want to install full-blown graphical environment (e.g. no X).
The following global options are supported by this video output:
``--drm-connector=[<gpu_number>.]<name>``
Select the connector to use (usually this is a monitor.) If ``<name>``
is empty or ``auto``, mpv renders the output on the first available
connector. Use ``--drm-connector=help`` to get list of available
connectors. When using multiple graphic cards, use the ``<gpu_number>``
argument to disambiguate.
(default: empty)
``--drm-mode=<number>``
Mode ID to use (resolution, bit depth and frame rate).
(default: 0)
``connector=<number>``
Select the connector to use (usually this is a monitor.) If set to -1,
mpv renders the output on the first available connector. (default: -1)
``devpath=<filename>``
Path to graphic card device.
(default: /dev/dri/card0)
+13 -20
View File
@@ -7,8 +7,8 @@ large part of which is incompatible or completely changes how the player
behaves. Although there are still many similarities to its ancestors, **mpv**
should generally be treated as a completely different program.
.. admonition:: Warning
This document is not updated anymore, and is incomplete and outdated.
.. note::
These lists are incomplete.
General Changes from MPlayer to mpv
-----------------------------------
@@ -30,7 +30,7 @@ Player
* Slave mode compatibility broken (see below).
* Re-enable screensaver while the player is paused.
* Allow resuming playback at a later point with ``Shift+q``, also see the
``quit-watch-later`` input command.
``quit_watch_later`` input command.
* ``--keep-open`` option to stop the player from closing the window and
exiting after playback ends.
* A client API, that allows embedding **mpv** into applications
@@ -49,10 +49,8 @@ Input
* Classic LIRC support was removed. Install remotes as input devices instead.
This way they will send X11 key events to the mpv window, which can be bound
using the normal ``input.conf``.
Also see: http://github.com/mpv-player/mpv/wiki/IR-remotes
* Joystick support was removed. It was considered useless and was the cause
of some problems (e.g. a laptop's accelerator being recognized as joystick).
* Support for relative seeking by percentage.
Audio
~~~~~
@@ -79,8 +77,7 @@ Video
using most of FFmpeg's filters, which improve greatly on the old MPlayer
filters in features, performance, and correctness.
* More correct color reproduction (color matrix generation), including support
for BT.2020 (Ultra HD). linear XYZ (Digital Cinema) and SMPTE ST2084 (HDR)
inputs.
for BT.2020 (Ultra HD) and linear XYZ (Digital Cinema) inputs.
* Support for color managed displays, via ICC profiles.
* High-quality image resamplers (see the ``opengl`` ``scale`` suboption).
* Support for scaling in (sigmoidized) linear light.
@@ -95,8 +92,6 @@ Video
* Image subtitles (DVDs etc.) are rendered in color and use more correct
positioning (color for image subs can be disabled with ``--sub-gray``).
* Support for the X11 video output is removed, since it was considered
deprecated. SDL video output can still be used as a fallback.
OSD and terminal
~~~~~~~~~~~~~~~~
@@ -262,14 +257,13 @@ Command Line Switches
``-ssf <sub>`` ``--sws-...``
``-stop-xscreensaver`` ``--stop-screensaver``
``-sub-fuzziness`` ``--sub-auto``
``-sub-text-*`` ``--sub-*``
``-sub`` ``--sub-file``
``-subcp`` ``--sub-codepage``
``-subdelay`` ``--sub-delay``
``-subfile`` ``--sub-file``
``-subfont-*`` ``--sub-*``, ``--osd-*``
``-subfont-*`` ``--sub-text-*``, ``--osd-*``
``-subfont-text-scale`` ``--sub-scale``
``-subfont`` ``--sub-font``
``-subfont`` ``--sub-text-font``
``-subfps`` ``--sub-fps``
``-subpos`` ``--sub-pos``
``-sws`` ``--sws-scaler``
@@ -281,7 +275,7 @@ Command Line Switches
``-xineramascreen`` ``--screen`` (different values)
``-xy W`` ``--autofit=W``
``-zoom`` Inverse available as ``--video-unscaled``
``dvdnav://`` Removed.
``dvdnav://`` ``dvdnav://menu``
``dvd://1`` ``dvd://0`` (0-based offset)
=========================== ========================================
@@ -313,11 +307,11 @@ input.conf and Slave Commands
+--------------------------------+----------------------------------------+
| Old | New |
+================================+========================================+
| ``pt_step 1 [0|1]`` | ``playlist-next [weak|force]`` |
| ``pt_step 1 [0|1]`` | ``playlist_next [weak|force]`` |
| | (translation layer cannot deal with |
| | whitespace) |
+--------------------------------+----------------------------------------+
| ``pt_step -1 [0|1]`` | ``playlist-prev [weak|force] (same)`` |
| ``pt_step -1 [0|1]`` | ``playlist_prev [weak|force] (same)`` |
+--------------------------------+----------------------------------------+
| ``switch_ratio [<ratio>]`` | ``set video-aspect <ratio>`` |
| | |
@@ -332,7 +326,7 @@ input.conf and Slave Commands
| ``<step> <dir>`` | ``no-osd``: ``no-osd cycle <prop>`` |
| | ``<step>`` |
+--------------------------------+----------------------------------------+
| ``osd_show_property_text`` | ``show-text <text>`` |
| ``osd_show_property_text`` | ``show_text <text>`` |
| ``<text>`` | The property expansion format string |
| | syntax slightly changed. |
+--------------------------------+----------------------------------------+
@@ -341,9 +335,9 @@ input.conf and Slave Commands
| | ``raw`` prefix to disable property |
| | expansion. |
+--------------------------------+----------------------------------------+
| ``show_tracks`` | ``show-text ${track-list}`` |
| ``show_tracks`` | ``show_text ${track-list}`` |
+--------------------------------+----------------------------------------+
| ``show_chapters`` | ``show-text ${chapter-list}`` |
| ``show_chapters`` | ``show_text ${chapter-list}`` |
+--------------------------------+----------------------------------------+
| ``af_switch``, ``af_add``, ... | ``af set|add|...`` |
+--------------------------------+----------------------------------------+
@@ -401,8 +395,7 @@ Slave mode
Assuming the system supports ``/dev/stdin``.
(The option was added back in 0.5.1 and sets exactly these options. It was
removed in 0.10.x again.)
(The option was readded in 0.5.1 and sets exactly these options.)
* A JSON RPC protocol giving access to the client API is also supported. See
`JSON IPC`_ for more information.
+27 -70
View File
@@ -1,107 +1,64 @@
Release Policy
==============
Once or twice a month, a new release is cut off of the master branch and is
assigned a 0.X.Y version number, where X is incremented each time a release
contains breaking changes, such as changed options or added/removed features,
and Y is incremented if a release contains only bugfixes and other minor
changes.
Every few months, a new release is cut off of the master branch and is assigned
a 0.X.0 version number.
There is only one release branch that keeps track of the latest version and
will not be maintained separately.
As part of the maintenance process, minor releases are made, which are assigned
0.X.Y version numbers. Minor releases contain bug fixes only. They never merge
the master branch, and no features are added to it. Only the latest release is
maintained.
The goal of releases is to provide Linux distributions with something to
package. If you want the newest features, just use the master branch.
We try our best to keep it deployable at all times.
The goal of releases is to provide stability and an unchanged base for the sake
of Linux distributions. If you want the newest features, just use the master
branch, which is stable most of the time, except sometimes, when it's not.
Releases other than the latest release are unsupported and unmaintained.
Release procedure
-----------------
- Merge master into branch release/current.
- Create branch release/0.X or cherry-pick commits to the relevant branch.
- Create and/or update the `RELEASE_NOTES` file.
- Create and/or update the ``RELEASE_NOTES`` file.
- Create and/or update the `VERSION` file.
- Create and/or update the ``VERSION`` file.
- Update `DOCS/client-api-changes.rst` and `DOCS/interface-changes.rst`
(in particular, update the last version numbers if necessary)
- Update ``DOCS/client-api-changes.rst`` (on major releases).
- Create tag v0.X.Y.
- Push branch and tag to GitHub.
- Create a new GitHub release using the content of `RELEASE_NOTES` related to
- Create a new GitHub release using the content of ``RELEASE_NOTES`` related to
the new version.
Release notes template
----------------------
Here is a template that can be used for writing the `RELEASE_NOTES` file.
Here is a template that can be used for writing the ``RELEASE_NOTES`` file.
```markdown
Release 0.X.Y
=============
Features
--------
Changes
-------
New
~~~
- List of changes.
- List of new features
Bug fixes
---------
Removed
~~~~~~~
- List of bug fixes.
- List of removed features
New features
------------
Deprecated
~~~~~~~~~~
- List of deprecated features
Behavior
--------
- List of user-visible changes in behavior
Options and Commands
--------------------
Added
~~~~~
- List of added options and commands
Changed
~~~~~~~
- List of changed options and commands
Renamed
~~~~~~~
- List of renamed options and commands
Deprecated
~~~~~~~~~~
- List of deprecated options and commands
Removed
~~~~~~~
- List of removed options and commands
Fixes and Minor Enhancements
----------------------------
- List of fixes and minor enhancements
- List of new features.
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
complete change log can be viewed by running ``git log <start>..<end>`` in
the git repository.
```
@@ -109,6 +66,6 @@ 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
``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.
+3 -2
View File
@@ -75,7 +75,8 @@ talloc.h & talloc.c:
allocation call will never return NULL.
One very useful feature of talloc is fast tracking of memory leaks. ("Fast"
as in it doesn't require valgrind.) You can enable it by setting the
as in it doesn't require valgrind.) You can enable it by passing the option
--leak-report as first parameter, or better, setting the
MPV_LEAK_REPORT environment variable to "1":
export MPV_LEAK_REPORT=1
This will list all unfree'd allocations on exit.
@@ -123,7 +124,7 @@ options/options.h, options/options.c
parser-mpcmd.c, and uses the option table in options.c.
input/input.c:
This translates keyboard input coming from VOs and other sources (such
This translates keyboard input comming from VOs and other sources (such
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
+2 -2
View File
@@ -1,7 +1,7 @@
waf build system overview
=========================
mpv's new build system is based on waf and it should completely replace the
mpv's new build system is based on waf and it should completly replace the
custom ./configure + Makefile based system inherited from MPlayer.
Goals and the choice of waf
@@ -65,7 +65,7 @@ This defines a feature called ``vdpau`` which can be enabled or disabled by
the users with configure flags (that's the meaning of ``--``). This feature
depends on another feature whose name is ``x11``, and the autodetection check
consists of running ``pkg-config`` and looking for ``vdpau`` with version
``>= 0.2``. If the check succeeds a ``#define HAVE_VDPAU 1`` will be added to
``>= 0.2``. If the check succeds a ``#define HAVE_VDPAU 1`` will be added to
``config.h``, if not ``#define HAVE_VDPAU 0`` will be added.
The defines names are automatically prepended with ``HAVE_``, capitalized and
+28 -55
View File
@@ -26,21 +26,6 @@ variety of video file formats, audio and video codecs, and subtitle types.
Releases can be found on the [release list][releases].
## System requirements
- A not too ancient Linux, or Windows Vista or later, or OSX 10.8 or later.
- A somewhat capable CPU. Hardware decoding might sometimes help if the CPU
is too slow to decode video realtime, but must be explicitly enabled with
the `--hwdec` option. On Windows, a CPU with SSE4 instruction set is required
to get decent hardware decoding performance.
- A not too crappy GPU. mpv is not intended to be used with bad GPUs. There are
many caveats with drivers or system compositors causing tearing, stutter,
etc. On Windows, you might want to make sure the graphics drivers are
current, especially OpenGL. In some cases, ancient fallback video output
methods can help (such as `--vo=xv` on Linux), but this use is not
recommended or supported.
## Downloads
@@ -72,6 +57,9 @@ To build the software you can use `./waf build`: the result of the compilation
will be located in `build/mpv`. You can use `./waf install` to install mpv
to the *prefix* after it is compiled.
NOTE: Using the old build system (with `./old-configure`) should still work,
but will be removed in a future version of mpv.
Essential dependencies (incomplete list):
- gcc or clang
@@ -85,7 +73,7 @@ Essential dependencies (incomplete list):
- libass (OSD, OSC, text subtitles)
- Lua (optional, required for the OSC pseudo-GUI and youtube-dl integration)
- libjpeg (optional, used for screenshots only)
- uchardet (optional, for subtitle charset detection)
- Enca (optional, for subtitle charset detection)
- vdpau and vaapi libraries for hardware decoding on Linux (optional)
Libass dependencies:
@@ -111,10 +99,13 @@ the separately available build wrapper ([mpv-build][mpv-build]) that first compi
libraries and libass, and then compiles the player statically linked against
those.
If you are running Mac OSX and using homebrew we provide [homebrew-mpv][homebrew-mpv], an up
to date formula that compiles mpv with sensible dependencies and defaults for
OSX.
If you want to build a Windows binary, you either have to use MSYS2 and MinGW,
or cross-compile from Linux with MinGW. See [Windows compilation][windows_compilation].
## FFmpeg vs. Libav
@@ -123,42 +114,20 @@ of both FFmpeg and Libav. But FFmpeg is preferred, and some mpv features work
with FFmpeg only (subtitle formats in particular).
## Preferred FFmpeg version
Using the latest FFmpeg release (or FFmpeg git master) is strongly recommended.
Older versions are unsupported, even if the build system still happens to
accept them. The main reason mpv still builds with older FFmpeg versions is to
evade arguing with people (users, distros) who insist on using older FFmpeg
versions for no rational reason.
If you want to use a stable FFmpeg release, use the latest release, which has
most likely the best maintenance out of all stable releases. Older releases
are for distros, and at best receive basic changes like fixing critical security
issues or build fixes, and at worst are completely abandoned.
## FFmpeg ABI compatibility
mpv does not support linking against FFmpeg versions it was not built with, even
if the linked version is supposedly ABI-compatible with the version it was
compiled against. Expect malfunctions, crashes, and security issues if you
do it anyway.
The reason for not supporting this is because it creates far too much complexity
with little to no benefit, coupled with absurd and unusable FFmpeg API
artifacts.
Newer mpv versions will refuse to start if runtime and compile time FFmpeg
library versions mismatch.
## Release cycle
Every other month, an arbitrary git snapshot is made, and is assigned
a 0.X.0 version number. No further maintenance is done.
The goal of releases is to make Linux distributions happy. Linux distributions
are also expected to apply their own patches in case of bugs and security
issues.
Every few months, a new release is cut off of the master branch and is assigned
a 0.X.0 version number.
As part of the maintenance process, minor releases are made, which are assigned
0.X.Y version numbers. Minor releases contain bug fixes only. They never merge
the master branch, and no features are added to it. Only the latest release is
maintained.
The goal of releases is to provide stability and an unchanged base for the sake
of Linux distributions. If you want the newest features, just use the master
branch, which is stable most of the time, except sometimes, when it's not.
Releases other than the latest release are unsupported and unmaintained.
@@ -205,9 +174,11 @@ list of changes is located [here][mplayer-changes].
Most activity happens on the IRC channel and the github issue tracker. The
mailing lists are mostly unused.
- **GitHub issue tracker**: [issue tracker][issue-tracker] (report bugs here)
- **User IRC Channel**: `#mpv` on `irc.freenode.net`
- **Developer IRC Channel**: `#mpv-devel` on `irc.freenode.net`
- **Github issue tracker**: [issue tracker][issue-tracker] (report bugs here)
- **User IRC Channel**: `#mpv-player` on `irc.freenode.net`
- **Developer IRC Channel**: `#mpv-player-dev` on `irc.freenode.net`
- **Users Mailing List**: `mpv-users@googlegroups.com` ([Archive / Subscribe][mpv-users]).
- **Devel Mailing List**: `mpv-devel@googlegroups.com` ([Archive / Subscribe][mpv-devel])
To contact the `mpv` team in private write to `mpv-team@googlegroups.com`. Use
only if discretion is required.
@@ -216,12 +187,14 @@ only if discretion is required.
[mpv-build]: https://github.com/mpv-player/mpv-build
[homebrew-mpv]: https://github.com/mpv-player/homebrew-mpv
[issue-tracker]: https://github.com/mpv-player/mpv/issues
[mpv-users]: https://groups.google.com/forum/?hl=en#!forum/mpv-users
[mpv-devel]: https://groups.google.com/forum/?hl=en#!forum/mpv-devel
[ffmpeg_vs_libav]: https://github.com/mpv-player/mpv/wiki/FFmpeg-versus-Libav
[release-policy]: https://github.com/mpv-player/mpv/blob/master/DOCS/release-policy.md
[windows_compilation]: https://github.com/mpv-player/mpv/blob/master/DOCS/compile-windows.md
[mplayer-changes]: https://github.com/mpv-player/mpv/blob/master/DOCS/mplayer-changes.rst
## License
## License
Mostly GPLv2 or later. See [details.](https://github.com/mpv-player/mpv/blob/master/Copyright)
[GPLv2](https://github.com/mpv-player/mpv/blob/master/LICENSE)
+9 -1550
View File
File diff suppressed because it is too large. Load diff
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/bash
set -e
export DEST_OS=win32
export CC=gcc
export PKG_CONFIG=/usr/bin/pkg-config
export PERL=/usr/bin/perl
export PYTHON=/usr/bin/python3
"$PYTHON" bootstrap.py
"$PYTHON" waf configure \
--check-c-compiler=gcc \
--disable-cdda \
--enable-egl-angle \
--enable-jpeg \
--enable-lcms2 \
--enable-libarchive \
--enable-libass \
--enable-lua \
--enable-rubberband \
--enable-uchardet
"$PYTHON" waf build
-35
View File
@@ -1,35 +0,0 @@
#!/usr/bin/bash
set -e
case $MSYSTEM in
MINGW32)
export MINGW_PACKAGE_PREFIX=mingw-w64-i686
;;
MINGW64)
export MINGW_PACKAGE_PREFIX=mingw-w64-x86_64
;;
esac
# Write an empty fonts.conf to speed up fc-cache
export FONTCONFIG_FILE=/dummy-fonts.conf
cat >"$FONTCONFIG_FILE" <<EOF
<?xml version="1.0"?>
<!DOCTYPE fontconfig SYSTEM "fonts.dtd">
<fontconfig></fontconfig>
EOF
# Install build dependencies for mpv
pacman -S --noconfirm --needed \
$MINGW_PACKAGE_PREFIX-gcc \
$MINGW_PACKAGE_PREFIX-angleproject-git \
$MINGW_PACKAGE_PREFIX-ffmpeg \
$MINGW_PACKAGE_PREFIX-lcms2 \
$MINGW_PACKAGE_PREFIX-libarchive \
$MINGW_PACKAGE_PREFIX-libass \
$MINGW_PACKAGE_PREFIX-libjpeg-turbo \
$MINGW_PACKAGE_PREFIX-lua51 \
$MINGW_PACKAGE_PREFIX-rubberband \
$MINGW_PACKAGE_PREFIX-uchardet-git
# Delete unused packages to reduce space used in the Appveyor cache
pacman -Sc --noconfirm
+2 -2
View File
@@ -9,8 +9,8 @@ use warnings;
# the exact contents of the original file.
# FIXME: why not a char array?
# treat only alphanumeric and punctuations (excluding " and ?) as safe
my $unsafe_chars = qr{[^][A-Za-z0-9!#%&'()*+,./:;<=>^_{|}~ -]};
# treat only alphanumeric and not-" punctuation as safe
my $unsafe_chars = qr{[^][A-Za-z0-9!#%&'()*+,./:;<=>?^_{|}~ -]};
for my $file (@ARGV) {
open my $fh, '<:raw', $file or next;
Executable → Regular
+1 -1
View File
@@ -5,7 +5,7 @@
conv() {
echo
echo `identify -format "icon: %w %h" "$1"`
identify -format "icon: %w %h" "$1"
convert "$1" -depth 8 rgba:-
}
+7 -7
View File
@@ -47,7 +47,7 @@ judge()
progressive=$((progressive + progressive1))
undetermined=$((undetermined + undetermined1))
done <<EOF
$(testfun "$@" | sed 's/:/: /g')
$(testfun "$@")
EOF
interlaced=$((bff + tff))
@@ -95,18 +95,18 @@ case "$verdict" in
exit 0
;;
interlaced-tff)
judge "$@" --vf-clr --vf-pre=lavfi=\[setfield=tff\],pullup
judge "$@" --vf-clr --vf-pre=pullup --field-dominance=top
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=lavfi=\[setfield=tff\],pullup
$ILDETECT_MPV "$@" --vf-pre=pullup --field-dominance=top
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 1
;;
*)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=lavfi=\[setfield=tff\],yadif
$ILDETECT_MPV "$@" --vf-pre=yadif --field-dominance=top
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 2
@@ -114,18 +114,18 @@ case "$verdict" in
esac
;;
interlaced-bff)
judge "$@" --vf-clr --vf-pre=lavfi=\[setfield=bff\],pullup
judge "$@" --vf-clr --vf-pre=pullup --field-dominance=bottom
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=lavfi=\[setfield=bff\],pullup
$ILDETECT_MPV "$@" --vf-pre=pullup --field-dominance=bottom
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 1
;;
*)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=lavfi=\[setfield=bff\],yadif
$ILDETECT_MPV "$@" --vf-pre=yadif --field-dominance=bottom
r=$?
[ $r -eq 0 ] || exit $((r | 16))
exit 2
+1 -1
View File
@@ -84,7 +84,7 @@ sub elem_by_hexid {
# used by elem when setting the 'valname' key
use constant TYPE_MAP => {
uint => 'uint64_t',
str => 'char *',
str => 'struct bstr',
binary => 'struct bstr',
ebml_id => 'uint32_t',
float => 'double',
+1 -7
View File
@@ -11,10 +11,4 @@ to mpv's command line.
Where appropriate, they may also be placed in ~/.config/mpv/scripts/ from
where they will be automatically loaded when mpv starts.
This is only a small selection of internally maintained scripts. Some of them
are just for testing mpv internals, or serve as examples. An extensive
user-edited list of 3rd party scripts is available here:
https://github.com/mpv-player/mpv/wiki/User-Scripts
(Anyone can add their own scripts to that list.)
Some of these are just for testing mpv internals.
-20
View File
@@ -1,20 +0,0 @@
-- Handles the edge case where previous attempts to init audio have failed, but
-- might start working due to a newly added device. This is required in
-- particular for ao=wasapi, since the internal IMMNotificationClient code that
-- normally triggers ao-reload will not be running in this case.
function do_reload()
mp.command("ao-reload")
reloading = nil
end
function on_audio_device_list_change()
if mp.get_property("current-ao") == "null" and not reloading then
mp.msg.verbose("audio-device-list changed: reloading audio")
-- avoid calling ao-reload too often
reloading = mp.add_timeout(0.5, do_reload)
end
end
mp.set_property("options/audio-fallback-to-null", "yes")
mp.observe_property("audio-device-list", "native", on_audio_device_list_change)
+45 -26
View File
@@ -2,16 +2,21 @@
-- appropriate deinterlacing filter based on a short section of the
-- currently playing video.
--
-- It registers the key-binding ctrl+d, which when pressed, inserts the filters
-- ``vf=lavfi=idet,pullup,vf=lavfi=idet``. After 4 seconds, it removes these
-- filters and decides whether the content is progressive, interlaced, or
-- telecined and the interlacing field dominance.
-- It registers the key-binding ctrl+d, which when pressed, inserts
-- the filter vf=lavfi=idet. After 4 second, it examines the results
-- to determine whether the content progressive or interlaced and the
-- interlacing field dominance. It immediately sets the latter within
-- mpv.
--
-- Based on this information, it may set mpv's ``deinterlace`` property (which
-- usually inserts the yadif filter), or insert the ``pullup`` filter if the
-- content is telecined. It also sets mpv's ``field-dominance`` property.
-- If the content is judged not to be progressive, it may be either
-- interlaced or telecined. To determine which one, the video is
-- seeked back to the detection starting point with the "pullup"
-- filter inserted. After another four seconds, if idet thinks that
-- the pulled up viedo is "progressive", then pullup is the correct
-- filter and this script leaves it in places while removing the idet
-- filter. Otherwise, the content plain interlaced and mpv's deinterlace
-- property is set. This will usually insert the yadif deinterlacing filter.
--
-- OPTIONS:
-- The default detection time may be overridden by adding
--
-- --script-opts=autodeint.detect_seconds=<number of seconds>
@@ -32,7 +37,6 @@ require "mp.msg"
script_name = mp.get_script_name()
detect_label = string.format("%s-detect", script_name)
pullup_label = string.format("%s", script_name)
ivtc_detect_label = string.format("%s-ivtc-detect", script_name)
-- number of seconds to gather cropdetect data
detect_seconds = tonumber(mp.get_opt(string.format("%s.detect_seconds", script_name)))
@@ -65,29 +69,30 @@ function start_detect()
mp.set_property("deinterlace","no")
del_filter_if_present(pullup_label)
percent_pos = mp.get_property("percent-pos")
-- insert the detection filter
local cmd = string.format('vf add @%s:lavfi=graph="idet",@%s:pullup,@%s:lavfi=graph="idet"',
detect_label, pullup_label, ivtc_detect_label)
local cmd = string.format('vf add @%s:lavfi=graph="idet"', detect_label)
if not mp.command(cmd) then
mp.msg.error("failed to insert detection filters")
mp.msg.error("failed to insert detection filter")
return
end
-- wait to gather data
timer = mp.add_timeout(detect_seconds, select_filter)
timer = mp.add_timeout(detect_seconds, judge_field_dominance)
end
function stop_detect()
del_filter_if_present(detect_label)
del_filter_if_present(ivtc_detect_label)
timer = nil
mp.set_property("playback-pos", percent_pos)
end
progressive, interlaced_tff, interlaced_bff, interlaced = 0, 1, 2, 3, 4
function judge(label)
function judge()
-- get the metadata
local result = mp.get_property_native(string.format("vf-metadata/%s", label))
local result = mp.get_property_native(string.format("vf-metadata/%s", detect_label))
num_tff = tonumber(result["lavfi.idet.multiple.tff"])
num_bff = tonumber(result["lavfi.idet.multiple.bff"])
num_progressive = tonumber(result["lavfi.idet.multiple.progressive"])
@@ -95,10 +100,10 @@ function judge(label)
num_interlaced = num_tff + num_bff
num_determined = num_interlaced + num_progressive
mp.msg.verbose(label.." progressive = "..num_progressive)
mp.msg.verbose(label.." interlaced-tff = "..num_tff)
mp.msg.verbose(label.." interlaced-bff = "..num_bff)
mp.msg.verbose(label.." undetermined = "..num_undetermined)
mp.msg.verbose("progressive = "..num_progressive)
mp.msg.verbose("interlaced-tff = "..num_tff)
mp.msg.verbose("interlaced-bff = "..num_bff)
mp.msg.verbose("undetermined = "..num_undetermined)
if num_determined < num_undetermined then
mp.msg.warn("majority undetermined frames")
@@ -114,12 +119,11 @@ function judge(label)
end
end
function select_filter()
-- handle the first detection filter results
verdict = judge(detect_label)
function judge_field_dominance()
verdict = judge()
if verdict == progressive then
mp.msg.info("progressive: doing nothing")
stop_detect()
mp.msg.info("progressive: doing nothing")
return
elseif verdict == interlaced_tff then
mp.set_property("field-dominance", "top")
@@ -129,8 +133,21 @@ function select_filter()
mp.set_property("field-dominance", "auto")
end
-- handle the ivtc detection filter results
verdict = judge(ivtc_detect_label)
local cmd = string.format("vf pre @%s:pullup", pullup_label)
if not mp.command(cmd) then
mp.msg.error("failed to insert pullup filter")
stop_detect()
return
end
-- redo the detection with the pullup filter to see if it's telecined
mp.set_property("percent-pos", percent_pos)
timer = mp.add_timeout(detect_seconds, judge_ivtc)
end
function judge_ivtc()
verdict = judge()
if verdict == progressive then
mp.msg.info(string.format("telecinied with %s field dominance: using pullup", mp.get_property("field-dominance")))
stop_detect()
@@ -140,6 +157,8 @@ function select_filter()
mp.set_property("deinterlace","yes")
stop_detect()
end
return
end
mp.add_key_binding("ctrl+d", script_name, start_detect)
+4 -21
View File
@@ -4,8 +4,8 @@
-- alphabetically, and adds entries before and after the current file to
-- the internal playlist. (It stops if the it would add an already existing
-- playlist entry at the same position - this makes it "stable".)
-- Add at most 5000 * 2 files when starting a file (before + after).
MAXENTRIES = 5000
-- Add at most 5 * 2 files when starting a file (before + after).
MAXENTRIES = 5
function Set (t)
local set = {}
@@ -25,17 +25,12 @@ function add_files_at(index, files)
local oldcount = mp.get_property_number("playlist-count", 1)
for i = 1, #files do
mp.commandv("loadfile", files[i], "append")
mp.commandv("playlist-move", oldcount + i - 1, index + i - 1)
mp.commandv("playlist_move", oldcount + i - 1, index + i - 1)
end
end
function get_extension(path)
match = string.match(path, "%.([^%.]+)$" )
if match == nil then
return "nomatch"
else
return match
end
return string.match(path, "%.([^%.]+)$" )
end
table.filter = function(t, iter)
@@ -52,13 +47,6 @@ function find_and_add_entries()
if #dir == 0 then
return
end
local pl_count = mp.get_property_number("playlist-count", 1)
if (pl_count > 1 and autoload == nil) or
(pl_count == 1 and EXTENSIONS[string.lower(get_extension(filename))] == nil) then
return
else
autoload = true
end
local files = mputils.readdir(dir, "files")
if files == nil then
@@ -72,11 +60,6 @@ function find_and_add_entries()
return EXTENSIONS[string.lower(ext)]
end)
table.sort(files, function (a, b)
local len = string.len(a) - string.len(b)
if len ~= 0 then -- case for ordering filename ending with such as X.Y.Z
local ext = string.len(get_extension(a)) + 1
return string.sub(a, 1, -ext) < string.sub(b, 1, -ext)
end
return string.lower(a) < string.lower(b)
end)
+2 -2
View File
@@ -4,7 +4,7 @@
-- parameters. See the entry for "drc" under the "AUDIO FILTERS"
-- section of the man page for a complete description of the filter.
--
-- This script registers the key-binding "\" to toggle the filter between
-- This script registers the key-binding "\" to toggle the filter between
--
-- * off
-- * method=1 (single-sample smoothing)
@@ -92,7 +92,7 @@ function drc_quieter_handler()
drc_scale_target(0.5)
end
-- toggle between off, method 1 and method 2
-- toggle between off, method 1 and method 2
mp.add_key_binding("\\", "drc_toggle_method", drc_toggle_method_handler)
-- increase or decrease target volume
mp.add_key_binding("ctrl+9", "drc_quieter", drc_quieter_handler)
+1 -9
View File
@@ -6,17 +6,9 @@
local utils = require("mp.utils")
function observe(name)
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 '" ..
utils.to_string(val) .. "'")
end)
end
for i,name in ipairs(mp.get_property_native("property-list")) do
observe(name)
end
for i,name in ipairs(mp.get_property_native("options")) do
observe("options/" .. name)
end
+1 -3
View File
@@ -1,7 +1,5 @@
-- Rebuild the terminal status line as a lua script
-- Be aware that this will require more cpu power!
-- Also, this is based on a rather old version of the
-- builtin mpv status line.
-- Add a string to the status line
function atsl(s)
@@ -30,7 +28,7 @@ function update_status_line()
atsl(mp.get_property_osd("time-pos"))
atsl(" / ");
atsl(mp.get_property_osd("duration"));
atsl(mp.get_property_osd("length"));
atsl(" (")
atsl(mp.get_property_osd("percent-pos", -1))
+34
View File
@@ -0,0 +1,34 @@
--sets the startime of a youtube video as specified in the "t=HHhMMmSSs" part of the url
--NOTE: This might become obsolete once youtube-dl adds the functionality
local msg = require 'mp.msg'
function youtube_starttime()
url = mp.get_property("path", "")
start = 0
if string.find(url, "youtu%.?be") and
((url:find("http://") == 1) or (url:find("https://") == 1)) then
time = string.match(url, "[#&%?]t=%d*h?%d*m?%d+s?m?h?")
--the time-string can start with #, & or ? followed by t= and the timing parameters
--at least one number needs to be present after t=, followed by h, m, s or nothing (>implies s)
if time then
for pos in string.gmatch(time,"%d+%a?") do
if string.match(pos,"%d+h") then --find out multiplier for
multiplier = 60*60 --hours
elseif string.match(pos,"%d+m") then
multiplier = 60 --minutes
else multiplier = 1 end --seconds
start = start + (string.match(pos,"%d+") * multiplier)
end
msg.info("parsed '" .. time .. "' into '" .. start .. "' seconds")
end
mp.set_property("file-local-options/start",start)
end
end
mp.add_hook("on_load", 50, youtube_starttime)
+1 -10
View File
@@ -39,17 +39,8 @@ def apply_plist_template(plist_file, version):
for line in fileinput.input(plist_file, inplace=1):
print (line.rstrip().replace('${VERSION}', version))
def bundle_version():
if os.path.exists('VERSION'):
x = open('VERSION')
version = x.read()
x.close()
else:
version = sh("./version.sh").strip()
return version
def main():
version = bundle_version().rstrip()
version = sh("./version.sh --print").strip()
usage = "usage: %prog [options] arg"
parser = OptionParser(usage)
@@ -1 +1,2 @@
player-operation-mode=pseudo-gui
screenshot-template=~/Desktop/shot%n
profile=pseudo-gui
+17 -48
View File
@@ -1,15 +1,11 @@
#!/usr/bin/env python3
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph as pg
import matplotlib.pyplot as plot
import sys
import re
filename = sys.argv[1]
events = ".*"
if len(sys.argv) > 2:
events = sys.argv[2]
event_regex = re.compile(events)
event_regex = re.compile(".*")
"""
This script is meant to display stats written by mpv --dump-stats=filename.
@@ -30,8 +26,8 @@ Currently, the following event types are supported:
'end' <name> end of the named event
'value' <float> <name> a normal value (as opposed to event)
'event-timed' <ts> <name> singular event at the given timestamp
'value-timed' <ts> <float> <name> a value for an event at the given timestamp
'range-timed' <ts1> <ts2> <name> like start/end, but explicit times
'value-timed' <ts> <float> <name>
a value for an event at the given timestamp
<name> singular event (same as 'signal')
"""
@@ -39,8 +35,8 @@ Currently, the following event types are supported:
class G:
events = {}
start = None
markers = ["o", "s", "t", "d"]
curveno = {}
# http://matplotlib.org/api/markers_api.html#module-matplotlib.markers
markers = ["o", "8", "s", "p", "*", "h", "+", "x", "D"]
def find_marker():
if len(G.markers) == 0:
@@ -66,10 +62,6 @@ def get_event(event, evtype):
G.events[event] = e
return G.events[event]
colors = [(0.0, 0.5, 0.0), (0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.75, 0.75, 0), (0.0, 0.75, 0.75), (0.75, 0, 0.75)]
def mkColor(t):
return pg.mkColor(int(t[0] * 255), int(t[1] * 255), int(t[2] * 255))
SCALE = 1e6 # microseconds to seconds
for line in [line.split("#")[0].strip() for line in open(filename, "r")]:
@@ -99,15 +91,6 @@ for line in [line.split("#")[0].strip() for line in open(filename, "r")]:
val = int(val) / SCALE - G.start
e = get_event(name, "event-signal")
e.vals.append((val, 1))
elif event.startswith("range-timed "):
_, ts1, ts2, name = event.split(" ", 3)
ts1 = int(ts1) / SCALE - G.start
ts2 = int(ts2) / SCALE - G.start
e = get_event(name, "event")
e.vals.append((ts1, 0))
e.vals.append((ts1, 1))
e.vals.append((ts2, 1))
e.vals.append((ts2, 0))
elif event.startswith("value-timed "):
_, tsval, val, name = event.split(" ", 3)
tsval = int(tsval) / SCALE - G.start
@@ -133,34 +116,20 @@ for e, index in zip(G.sevents, range(len(G.sevents))):
else:
e.vals = [(x, y * (m - index) / m) for (x, y) in e.vals]
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
app = QtGui.QApplication([])
win = pg.GraphicsWindow()
#win.resize(1500, 900)
fig = plot.figure()
fig.hold(True)
ax = [None, None]
plots = 2 if hasval else 1
ax[0] = win.addPlot()
ax[0] = fig.add_subplot(plots, 1, 1)
if hasval:
win.nextRow()
ax[1] = win.addPlot()
ax[1].setXLink(ax[0])
for cur in ax:
if cur is not None:
cur.addLegend(offset = (-1, 1))
ax[1] = fig.add_subplot(plots, 1, 2, sharex=ax[0])
legends = [[], []]
for e in G.sevents:
cur = ax[1 if e.type == "value" else 0]
if not cur in G.curveno:
G.curveno[cur] = 0
args = {'name': e.name,'antialias':True}
color = mkColor(colors[G.curveno[cur] % len(colors)])
pl, = cur.plot([x for x,y in e.vals], [y for x,y in e.vals], label=e.name)
if e.type == "event-signal":
args['symbol'] = e.marker
args['symbolBrush'] = pg.mkBrush(color, width=0)
else:
args['pen'] = pg.mkPen(color, width=0)
G.curveno[cur] += 1
n = cur.plot([x for x,y in e.vals], [y for x,y in e.vals], **args)
QtGui.QApplication.instance().exec_()
plot.setp(pl, marker = e.marker, linestyle = "None")
for cur in ax:
if cur is not None:
cur.legend()
plot.show()
-29
View File
@@ -1,29 +0,0 @@
#!/bin/sh
if [ "x$LIBAV" != "xffmpeg-git" ] || [ "x$TRAVIS_OS_NAME" != "xlinux" ]; then
# trigger build only on one of the matrix nodes
exit;
fi
if [ "x$TRAVIS_BRANCH" != "xmaster" ]; then
# only rebuild website with pushes to master
exit;
fi
TRAVIS_COMMIT_RANGE=${TRAVIS_COMMIT_RANGE:-HEAD^..}
if git diff --quiet --name-only --exit-code "$TRAVIS_COMMIT_RANGE" DOCS/; then
exit;
fi
body='{
"request": {
"branch":"master"
}}'
curl -s -X POST \
-H "Content-Type: application/json" \
-H "Accept: application/json" \
-H "Travis-API-Version: 3" \
-H "Authorization: token $WEBSITE_TRAVIS_TOKEN" \
-d "$body" \
https://api.travis-ci.org/repo/mpv-player%2Fmpv.io/requests
+11 -46
View File
@@ -4,14 +4,11 @@
use strict;
use warnings;
use warnings FATAL => 'uninitialized';
my $mpv = $ARGV[0] || 'mpv';
my @opts = parse_main_opts('--list-options', '^ (\-\-[^\s\*]*)\*?\s*(.*)');
die "Couldn't find any options" unless (@opts);
my @ao = parse_opts('--ao=help', '^ ([^\s\:]*)\s*: (.*)');
my @vo = parse_opts('--vo=help', '^ ([^\s\:]*)\s*: (.*)');
@@ -39,8 +36,7 @@ chomp $vf_str;
$protos_str = join(' ', @protos);
my $runtime_completions = <<'EOS';
profile|show-profile)
my $profile_comp = <<'EOS';
local -a profiles
local current
for current in "${(@f)$($words[1] --profile=help)}"; do
@@ -67,40 +63,17 @@ my $runtime_completions = <<'EOS';
profiles=($profiles 'help[list profiles]')
_values -s , 'profile(s)' $profiles && rc=0
fi
;;
audio-device)
local -a audio_devices
local current
for current in "${(@f)$($words[1] --audio-device=help)}"; do
current=${current//\*/\\\*}
current=${current//\:/\\\:}
current=${current//\[/\\\[}
current=${current//\]/\\\]}
if [[ $current =~ ' '\'([^\']*)\'' \('(.*)'\)' ]]; then
audio_devices=($audio_devices "$match[1][$match[2]]")
fi
done
audio_devices=($audio_devices 'help[list audio devices]')
_values 'audio device' $audio_devices && rc=0
;;
EOS
chomp $runtime_completions;
chomp $profile_comp;
my $tmpl = <<"EOS";
#compdef mpv
# For customization, see:
# https://github.com/mpv-player/mpv/wiki/Zsh-completion-customization
# mpv zsh completion
local curcontext="\$curcontext" state state_descr line
typeset -A opt_args
# By default, don't complete URLs unless no files match
local -a tag_order
zstyle -a ":completion:*:*:\$service:*" tag-order tag_order || \
zstyle ":completion:*:*:\$service:*" tag-order '!urls'
local rc=1
_arguments -C -S \\
@@ -132,7 +105,9 @@ $vf_str
&& rc=0
;;
$runtime_completions
profile|show-profile)
$profile_comp
;;
files)
compset -P '*,'
@@ -144,7 +119,8 @@ $runtime_completions
local expl
_tags files urls
while _tags; do
_requested files expl 'media file' _files && rc=0
_requested files expl 'media file' _files -g \\
"*.(#i)(asf|asx|avi|flac|flv|m1v|m2p|m2v|m4v|mjpg|mka|mkv|mov|mp3|mp4|mpe|mpeg|mpg|ogg|ogm|ogv|qt|rm|ts|vob|wav|webm|wma|wmv)(-.)" && rc=0
if _requested urls; then
while _next_label urls expl URL; do
_urls "\$expl[@]" && rc=0
@@ -165,7 +141,7 @@ sub parse_main_opts {
my ($cmd, $regex) = @_;
my @list;
my @lines = call_mpv($cmd);
my @lines = split /\n/, `"$mpv" --no-config $cmd`;
foreach my $line (@lines) {
my ($name, $desc) = ($line =~ /^$regex/) or next;
@@ -207,7 +183,7 @@ sub parse_main_opts {
}
} elsif ($line =~ /\[file\]/) {
$entry .= '->files';
} elsif ($name =~ /^--(ao|vo|af|vf|profile|show-profile|audio-device)$/) {
} elsif ($name =~ /^--(ao|vo|af|vf|profile|show-profile)$/) {
$entry .= "->$1";
}
push @list, $entry;
@@ -230,7 +206,7 @@ sub parse_opts {
my ($cmd, $regex) = @_;
my @list;
my @lines = call_mpv($cmd);
my @lines = split /\n/, `"$mpv" --no-config $cmd`;
foreach my $line (@lines) {
if ($line !~ /^$regex/) {
@@ -250,14 +226,3 @@ sub parse_opts {
return @list;
}
sub call_mpv {
my ($cmd) = @_;
my $output = `"$mpv" --no-config $cmd`;
if ($? == -1) {
die "Could not run mpv: $!";
} elsif ((my $exit_code = $? >> 8) != 0) {
die "mpv returned $exit_code with output:\n$output";
}
return split /\n/, $output;
}
+1 -1
View File
@@ -1 +1 @@
0.21.0
0.9.0
-29
View File
@@ -1,29 +0,0 @@
branches:
only:
- master
- appveyor
environment:
matrix:
- MSYSTEM: MINGW64
- MSYSTEM: MINGW32
shallow_clone: true
test: off
install:
# Update core packages
- C:\msys64\usr\bin\pacman -Syyuu --noconfirm
# Update non-core packages
- C:\msys64\usr\bin\pacman -Suu --noconfirm
# Install required MSYS2 packages
- C:\msys64\usr\bin\pacman -S --noconfirm --needed perl python pkg-config
# Now MSYS2 is up to date, do the rest of the install from a bash script
- C:\msys64\usr\bin\bash -lc "cd \"$APPVEYOR_BUILD_FOLDER\" && exec ./TOOLS/appveyor-install.sh"
build_script:
- C:\msys64\usr\bin\bash -lc "cd \"$APPVEYOR_BUILD_FOLDER\" && exec ./TOOLS/appveyor-build.sh"
on_failure:
- type "%APPVEYOR_BUILD_FOLDER%\build\config.log"
cache:
- C:\msys64\var\cache\pacman\pkg
+25 -173
View File
@@ -22,10 +22,9 @@
#include <libavutil/buffer.h>
#include <libavutil/frame.h>
#include <libavutil/mem.h>
#include <libavutil/version.h>
#include "mpv_talloc.h"
#include "talloc.h"
#include "common/common.h"
#include "fmt-conversion.h"
#include "audio.h"
@@ -35,8 +34,8 @@ static void update_redundant_info(struct mp_audio *mpa)
assert(mp_chmap_is_empty(&mpa->channels) ||
mp_chmap_is_valid(&mpa->channels));
mpa->nch = mpa->channels.num;
mpa->bps = af_fmt_to_bytes(mpa->format);
if (af_fmt_is_planar(mpa->format)) {
mpa->bps = af_fmt2bps(mpa->format);
if (AF_FORMAT_IS_PLANAR(mpa->format)) {
mpa->spf = 1;
mpa->num_planes = mpa->nch;
mpa->sstride = mpa->bps;
@@ -59,6 +58,13 @@ void mp_audio_set_num_channels(struct mp_audio *mpa, int num_channels)
update_redundant_info(mpa);
}
// Use old MPlayer/ALSA channel layout.
void mp_audio_set_channels_old(struct mp_audio *mpa, int num_channels)
{
mp_chmap_from_channels_alsa(&mpa->channels, num_channels);
update_redundant_info(mpa);
}
void mp_audio_set_channels(struct mp_audio *mpa, const struct mp_chmap *chmap)
{
mpa->channels = *chmap;
@@ -87,19 +93,15 @@ bool mp_audio_config_valid(const struct mp_audio *mpa)
char *mp_audio_config_to_str_buf(char *buf, size_t buf_sz, struct mp_audio *mpa)
{
char ch[128];
mp_chmap_to_str_buf(ch, sizeof(ch), &mpa->channels);
char *hr_ch = mp_chmap_to_str_hr(&mpa->channels);
if (strcmp(hr_ch, ch) != 0)
mp_snprintf_cat(ch, sizeof(ch), " (%s)", hr_ch);
snprintf(buf, buf_sz, "%dHz %s %dch %s", mpa->rate,
ch, mpa->channels.num, af_fmt_to_str(mpa->format));
mp_chmap_to_str(&mpa->channels), mpa->channels.num,
af_fmt_to_str(mpa->format));
return buf;
}
void mp_audio_force_interleaved_format(struct mp_audio *mpa)
{
if (af_fmt_is_planar(mpa->format))
if (AF_FORMAT_IS_PLANAR(mpa->format))
mp_audio_set_format(mpa, af_fmt_from_planar(mpa->format));
}
@@ -138,9 +140,6 @@ static void mp_audio_destructor(void *ptr)
* available on every plane. The previous data is kept (for the smallest
* common number of samples before/after resize).
*
* This also makes sure the resulting buffer is writable (even in the case
* the buffer has the correct size).
*
* mpa->samples is not set or used.
*
* This function is flexible enough to handle format and channel layout
@@ -156,18 +155,12 @@ void mp_audio_realloc(struct mp_audio *mpa, int samples)
int size = get_plane_size(mpa, samples);
if (size < 0)
abort(); // oom or invalid parameters
if (!mp_audio_is_writeable(mpa)) {
for (int n = 0; n < MP_NUM_CHANNELS; n++) {
av_buffer_unref(&mpa->allocated[n]);
mpa->planes[n] = NULL;
}
}
for (int n = 0; n < mpa->num_planes; n++) {
if (!mpa->allocated[n] || size != mpa->allocated[n]->size) {
if (av_buffer_realloc(&mpa->allocated[n], size) < 0)
abort(); // OOM
mpa->planes[n] = mpa->allocated[n]->data;
}
mpa->planes[n] = mpa->allocated[n]->data;
}
for (int n = mpa->num_planes; n < MP_NUM_CHANNELS; n++) {
av_buffer_unref(&mpa->allocated[n]);
@@ -180,7 +173,7 @@ void mp_audio_realloc(struct mp_audio *mpa, int samples)
// If the buffer is reallocated, also preallocate.
void mp_audio_realloc_min(struct mp_audio *mpa, int samples)
{
if (samples > mp_audio_get_allocated_size(mpa) || !mp_audio_is_writeable(mpa)) {
if (samples > mp_audio_get_allocated_size(mpa)) {
size_t alloc = ta_calc_prealloc_elems(samples);
if (alloc > INT_MAX)
abort(); // oom
@@ -198,18 +191,8 @@ int mp_audio_get_allocated_size(struct mp_audio *mpa)
{
int size = 0;
for (int n = 0; n < mpa->num_planes; n++) {
for (int i = 0; i < MP_NUM_CHANNELS && mpa->allocated[i]; i++) {
uint8_t *start = mpa->allocated[i]->data;
uint8_t *end = start + mpa->allocated[i]->size;
uint8_t *plane = mpa->planes[n];
if (plane >= start && plane < end) {
int s = MPMIN((end - plane) / mpa->sstride, INT_MAX);
size = n == 0 ? s : MPMIN(size, s);
goto next;
}
}
return 0; // plane is not covered by any buffer
next: ;
int s = mpa->allocated[n] ? mpa->allocated[n]->size / mpa->sstride : 0;
size = n == 0 ? s : MPMIN(size, s);
}
return size;
}
@@ -261,51 +244,8 @@ void mp_audio_skip_samples(struct mp_audio *data, int samples)
data->planes[n] = (uint8_t *)data->planes[n] + samples * data->sstride;
data->samples -= samples;
if (data->pts != MP_NOPTS_VALUE)
data->pts += samples / (double)data->rate;
}
// Return the timestamp of the sample just after the end of this frame.
double mp_audio_end_pts(struct mp_audio *f)
{
if (f->pts == MP_NOPTS_VALUE || f->rate < 1)
return MP_NOPTS_VALUE;
return f->pts + f->samples / (double)f->rate;
}
// Clip the given frame to the given timestamp range. Adjusts the frame size
// and timestamp.
void mp_audio_clip_timestamps(struct mp_audio *f, double start, double end)
{
double f_end = mp_audio_end_pts(f);
if (f_end == MP_NOPTS_VALUE)
return;
if (end != MP_NOPTS_VALUE) {
if (f_end >= end) {
if (f->pts >= end) {
f->samples = 0;
} else {
int new = (end - f->pts) * f->rate;
f->samples = MPCLAMP(new, 0, f->samples);
}
}
}
if (start != MP_NOPTS_VALUE) {
if (f->pts < start) {
if (f_end <= start) {
f->samples = 0;
f->pts = f_end;
} else {
int skip = (start - f->pts) * f->rate;
skip = MPCLAMP(skip, 0, f->samples);
mp_audio_skip_samples(f, skip);
}
}
}
}
// Return false if the frame data is shared, true otherwise.
// Will return true for non-refcounted frames.
bool mp_audio_is_writeable(struct mp_audio *data)
@@ -356,9 +296,9 @@ struct mp_audio *mp_audio_from_avframe(struct AVFrame *avframe)
mp_chmap_from_lavc(&lavc_chmap, avframe->channel_layout);
#if LIBAVUTIL_VERSION_MICRO >= 100
// FFmpeg being stupid POS again
if (lavc_chmap.num != av_frame_get_channels(avframe))
mp_chmap_from_channels(&lavc_chmap, av_frame_get_channels(avframe));
// FFmpeg being special again
if (lavc_chmap.num != avframe->channels)
mp_chmap_from_channels(&lavc_chmap, avframe->channels);
#endif
new->rate = avframe->sample_rate;
@@ -376,23 +316,21 @@ struct mp_audio *mp_audio_from_avframe(struct AVFrame *avframe)
}
// If we can't handle the format (e.g. too many channels), bail out.
if (!mp_audio_config_valid(new))
if (!mp_audio_config_valid(new) || avframe->nb_extended_buf)
goto fail;
for (int n = 0; n < AV_NUM_DATA_POINTERS + avframe->nb_extended_buf; n++) {
AVBufferRef *buf = n < AV_NUM_DATA_POINTERS ? avframe->buf[n]
: avframe->extended_buf[n - AV_NUM_DATA_POINTERS];
if (!buf)
for (int n = 0; n < AV_NUM_DATA_POINTERS; n++) {
if (!avframe->buf[n])
break;
if (n >= MP_NUM_CHANNELS)
goto fail;
new->allocated[n] = av_buffer_ref(buf);
new->allocated[n] = av_buffer_ref(avframe->buf[n]);
if (!new->allocated[n])
goto fail;
}
for (int n = 0; n < new->num_planes; n++)
new->planes[n] = avframe->extended_data[n];
new->planes[n] = avframe->data[n];
new->samples = avframe->nb_samples;
return new;
@@ -403,92 +341,6 @@ fail:
return NULL;
}
int mp_audio_to_avframe(struct mp_audio *frame, struct AVFrame *avframe)
{
av_frame_unref(avframe);
avframe->nb_samples = frame->samples;
avframe->format = af_to_avformat(frame->format);
if (avframe->format == AV_SAMPLE_FMT_NONE)
goto fail;
avframe->channel_layout = mp_chmap_to_lavc(&frame->channels);
if (!avframe->channel_layout)
goto fail;
#if LIBAVUTIL_VERSION_MICRO >= 100
// FFmpeg being a stupid POS again
av_frame_set_channels(avframe, frame->channels.num);
#endif
avframe->sample_rate = frame->rate;
if (frame->num_planes > AV_NUM_DATA_POINTERS) {
avframe->extended_data =
av_mallocz_array(frame->num_planes, sizeof(avframe->extended_data[0]));
int extbufs = frame->num_planes - AV_NUM_DATA_POINTERS;
avframe->extended_buf =
av_mallocz_array(extbufs, sizeof(avframe->extended_buf[0]));
if (!avframe->extended_data || !avframe->extended_buf)
goto fail;
avframe->nb_extended_buf = extbufs;
}
for (int p = 0; p < frame->num_planes; p++)
avframe->extended_data[p] = frame->planes[p];
avframe->linesize[0] = frame->samples * frame->sstride;
for (int p = 0; p < AV_NUM_DATA_POINTERS; p++)
avframe->data[p] = avframe->extended_data[p];
for (int p = 0; p < frame->num_planes; p++) {
if (!frame->allocated[p])
break;
AVBufferRef *nref = av_buffer_ref(frame->allocated[p]);
if (!nref)
goto fail;
if (p < AV_NUM_DATA_POINTERS) {
avframe->buf[p] = nref;
} else {
avframe->extended_buf[p - AV_NUM_DATA_POINTERS] = nref;
}
}
// Force refcounted frame.
if (!avframe->buf[0]) {
AVFrame *tmp = av_frame_alloc();
if (!tmp)
goto fail;
if (av_frame_ref(tmp, avframe) < 0)
goto fail;
av_frame_free(&avframe);
avframe = tmp;
}
return 0;
fail:
av_frame_unref(avframe);
return -1;
}
// Returns NULL on failure. The input is always unreffed.
struct AVFrame *mp_audio_to_avframe_and_unref(struct mp_audio *frame)
{
struct AVFrame *avframe = av_frame_alloc();
if (!avframe)
goto fail;
if (mp_audio_to_avframe(frame, avframe) < 0)
goto fail;
talloc_free(frame);
return avframe;
fail:
av_frame_free(&avframe);
talloc_free(frame);
return NULL;
}
struct mp_audio_pool {
AVBufferPool *avpool;
int element_size;
+3 -11
View File
@@ -35,19 +35,15 @@ struct mp_audio {
int nch; // number of channels (redundant with chmap)
int spf; // sub-samples per sample on each plane
int num_planes; // number of planes
int bps; // size of sub-samples (af_fmt_to_bytes(format))
int bps; // size of sub-samples (af_fmt2bps(format))
double pts; // currently invalid within the filter chain
// --- private
// These do not necessarily map directly to planes[]. They can have
// different order or count. There shouldn't be more buffers than planes.
// If allocated[n] is NULL, allocated[n+1] must also be NULL.
// private
struct AVBufferRef *allocated[MP_NUM_CHANNELS];
};
void mp_audio_set_format(struct mp_audio *mpa, int format);
void mp_audio_set_num_channels(struct mp_audio *mpa, int num_channels);
void mp_audio_set_channels_old(struct mp_audio *mpa, int num_channels);
void mp_audio_set_channels(struct mp_audio *mpa, const struct mp_chmap *chmap);
void mp_audio_copy_config(struct mp_audio *dst, const struct mp_audio *src);
bool mp_audio_config_equals(const struct mp_audio *a, const struct mp_audio *b);
@@ -72,16 +68,12 @@ void mp_audio_copy(struct mp_audio *dst, int dst_offset,
struct mp_audio *src, int src_offset, int length);
void mp_audio_copy_attributes(struct mp_audio *dst, struct mp_audio *src);
void mp_audio_skip_samples(struct mp_audio *data, int samples);
void mp_audio_clip_timestamps(struct mp_audio *f, double start, double end);
double mp_audio_end_pts(struct mp_audio *data);
bool mp_audio_is_writeable(struct mp_audio *data);
int mp_audio_make_writeable(struct mp_audio *data);
struct AVFrame;
struct mp_audio *mp_audio_from_avframe(struct AVFrame *avframe);
struct AVFrame *mp_audio_to_avframe_and_unref(struct mp_audio *frame);
int mp_audio_to_avframe(struct mp_audio *frame, struct AVFrame *avframe);
struct mp_audio_pool;
struct mp_audio_pool *mp_audio_pool_create(void *ta_parent);
+7 -16
View File
@@ -1,18 +1,18 @@
/*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* mpv is 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 Lesser General Public License for more details.
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU General Public License along
* with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
#include <stddef.h>
@@ -119,15 +119,6 @@ void mp_audio_buffer_prepend_silence(struct mp_audio_buffer *ab, int samples)
mp_audio_fill_silence(ab->buffer, 0, samples);
}
void mp_audio_buffer_duplicate(struct mp_audio_buffer *ab, int samples)
{
assert(samples >= 0 && samples <= ab->buffer->samples);
int oldlen = ab->buffer->samples;
ab->buffer->samples += samples;
mp_audio_realloc_min(ab->buffer, ab->buffer->samples);
mp_audio_copy(ab->buffer, oldlen, ab->buffer, oldlen - samples, samples);
}
// Get the start of the current readable buffer.
void mp_audio_buffer_peek(struct mp_audio_buffer *ab, struct mp_audio *out_mpa)
{
+7 -8
View File
@@ -1,18 +1,18 @@
/*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* mpv is 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 Lesser General Public License for more details.
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU General Public License along
* with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MP_AUDIO_BUFFER_H
@@ -35,7 +35,6 @@ void mp_audio_buffer_get_write_buffer(struct mp_audio_buffer *ab, int minsamples
void mp_audio_buffer_finish_write(struct mp_audio_buffer *ab, int samples);
void mp_audio_buffer_append(struct mp_audio_buffer *ab, struct mp_audio *mpa);
void mp_audio_buffer_prepend_silence(struct mp_audio_buffer *ab, int samples);
void mp_audio_buffer_duplicate(struct mp_audio_buffer *ab, int samples);
void mp_audio_buffer_peek(struct mp_audio_buffer *ab, struct mp_audio *out_mpa);
void mp_audio_buffer_skip(struct mp_audio_buffer *ab, int samples);
void mp_audio_buffer_clear(struct mp_audio_buffer *ab);
+133 -104
View File
@@ -1,25 +1,23 @@
/*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* mpv is 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 Lesser General Public License for more details.
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
* 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 <assert.h>
#include <libavutil/common.h>
#include "common/common.h"
#include "common/msg.h"
#include "chmap.h"
@@ -52,7 +50,6 @@ static const char *const speaker_names[MP_SPEAKER_ID_COUNT][2] = {
[MP_SPEAKER_ID_SDL] = {"sdl", "surround direct left"},
[MP_SPEAKER_ID_SDR] = {"sdr", "surround direct right"},
[MP_SPEAKER_ID_LFE2] = {"lfe2", "low frequency 2"},
[MP_SPEAKER_ID_NA] = {"na", "not available"},
};
// Names taken from libavutil/channel_layout.c (Not accessible by API.)
@@ -70,7 +67,6 @@ static const char *const std_layout_names[][2] = {
{"quad", "fl-fr-bl-br"},
{"quad(side)", "fl-fr-sl-sr"},
{"3.1", "fl-fr-fc-lfe"},
{"3.1(back)", "fl-fr-lfe-bc"}, // not in lavc
{"5.0", "fl-fr-fc-bl-br"},
{"5.0(alsa)", "fl-fr-bl-br-fc"}, // not in lavc
{"5.0(side)", "fl-fr-fc-sl-sr"},
@@ -84,23 +80,21 @@ static const char *const std_layout_names[][2] = {
{"hexagonal", "fl-fr-fc-bl-br-bc"},
{"6.1", "fl-fr-fc-lfe-bc-sl-sr"},
{"6.1(back)", "fl-fr-fc-lfe-bl-br-bc"}, // lavc calls this "6.1" too
{"6.1(top)", "fl-fr-fc-lfe-bl-br-tc"}, // not in lavc
{"6.1(front)", "fl-fr-lfe-flc-frc-sl-sr"},
{"7.0", "fl-fr-fc-bl-br-sl-sr"},
{"7.0(front)", "fl-fr-fc-flc-frc-sl-sr"},
{"7.0(rear)", "fl-fr-fc-bl-br-sdl-sdr"}, // not in lavc
{"7.1", "fl-fr-fc-lfe-bl-br-sl-sr"},
{"7.1(alsa)", "fl-fr-bl-br-fc-lfe-sl-sr"}, // not in lavc
{"7.1(wide)", "fl-fr-fc-lfe-bl-br-flc-frc"},
{"7.1(wide-side)", "fl-fr-fc-lfe-flc-frc-sl-sr"},
{"7.1(rear)", "fl-fr-fc-lfe-bl-br-sdl-sdr"}, // not in lavc
{"7.1(rear)", "fl-fr-fc-lfe-bl-br-sdl-sdr"},
{"octagonal", "fl-fr-fc-bl-br-bc-sl-sr"},
{"downmix", "dl-dr"},
{"auto", ""}, // not in lavc
{0}
};
static const struct mp_chmap default_layouts[] = {
static const struct mp_chmap default_layouts[MP_NUM_CHANNELS + 1] = {
{0}, // empty
MP_CHMAP_INIT_MONO, // mono
MP_CHMAP2(FL, FR), // stereo
@@ -112,6 +106,19 @@ static const struct mp_chmap default_layouts[] = {
MP_CHMAP8(FL, FR, FC, LFE, BL, BR, SL, SR), // 7.1
};
// The channel order was lavc/waveex, but differs from lavc for 5, 6 and 8
// channels. 3 and 7 channels were likely undefined (no ALSA support).
// I'm not sure about the 4 channel case: ALSA uses "quad", while the ffmpeg
// default layout is "4.0".
static const char *const mplayer_layouts[MP_NUM_CHANNELS + 1] = {
[1] = "mono",
[2] = "stereo",
[4] = "quad",
[5] = "5.0(alsa)",
[6] = "5.1(alsa)",
[8] = "7.1(alsa)",
};
// Returns true if speakers are mapped uniquely, and there's at least 1 channel.
bool mp_chmap_is_valid(const struct mp_chmap *src)
{
@@ -120,8 +127,7 @@ bool mp_chmap_is_valid(const struct mp_chmap *src)
int sp = src->speaker[n];
if (sp >= MP_SPEAKER_ID_COUNT || mapped[sp])
return false;
if (sp != MP_SPEAKER_ID_NA)
mapped[sp] = true;
mapped[sp] = true;
}
return src->num > 0;
}
@@ -136,10 +142,12 @@ bool mp_chmap_is_empty(const struct mp_chmap *src)
bool mp_chmap_is_unknown(const struct mp_chmap *src)
{
for (int n = 0; n < src->num; n++) {
if (src->speaker[n] != MP_SPEAKER_ID_NA)
return false;
int speaker = src->speaker[n];
if (speaker >= MP_SPEAKER_ID_UNKNOWN0 &&
speaker <= MP_SPEAKER_ID_UNKNOWN_LAST)
return true;
}
return mp_chmap_is_valid(src);
return false;
}
// Note: empty channel maps compare as equal. Invalid ones can equal too.
@@ -163,6 +171,15 @@ bool mp_chmap_equals_reordered(const struct mp_chmap *a, const struct mp_chmap *
return mp_chmap_equals(&t1, &t2);
}
bool mp_chmap_is_compatible(const struct mp_chmap *a, const struct mp_chmap *b)
{
if (mp_chmap_equals(a, b))
return true;
if (a->num == b->num && (mp_chmap_is_unknown(a) || mp_chmap_is_unknown(b)))
return true;
return false;
}
bool mp_chmap_is_stereo(const struct mp_chmap *src)
{
static const struct mp_chmap stereo = MP_CHMAP_INIT_STEREO;
@@ -182,43 +199,34 @@ void mp_chmap_reorder_norm(struct mp_chmap *map)
qsort(arr, map->num, 1, comp_uint8);
}
// Remove silent (NA) channels, if any.
void mp_chmap_remove_na(struct mp_chmap *map)
{
struct mp_chmap new = {0};
for (int n = 0; n < map->num; n++) {
int sp = map->speaker[n];
if (sp != MP_SPEAKER_ID_NA)
new.speaker[new.num++] = map->speaker[n];
}
*map = new;
}
// Add silent (NA) channels to map until map->num >= num.
void mp_chmap_fill_na(struct mp_chmap *map, int num)
{
assert(num <= MP_NUM_CHANNELS);
while (map->num < num)
map->speaker[map->num++] = MP_SPEAKER_ID_NA;
}
// Set *dst to a standard layout with the given number of channels.
// If the number of channels is invalid, an invalid map is set, and
// mp_chmap_is_valid(dst) will return false.
void mp_chmap_from_channels(struct mp_chmap *dst, int num_channels)
{
*dst = (struct mp_chmap) {0};
if (num_channels >= 0 && num_channels < MP_ARRAY_SIZE(default_layouts))
if (num_channels < 0 || num_channels > MP_NUM_CHANNELS) {
*dst = (struct mp_chmap) {0};
} else {
*dst = default_layouts[num_channels];
if (!dst->num)
mp_chmap_set_unknown(dst, num_channels);
}
}
// Try to do what mplayer/mplayer2/mpv did before channel layouts were
// introduced, i.e. get the old default channel order.
void mp_chmap_from_channels_alsa(struct mp_chmap *dst, int num_channels)
{
if (num_channels < 0 || num_channels > MP_NUM_CHANNELS) {
*dst = (struct mp_chmap) {0};
} else {
mp_chmap_from_str(dst, bstr0(mplayer_layouts[num_channels]));
if (!dst->num)
mp_chmap_from_channels(dst, num_channels);
}
}
// Set *dst to an unknown layout for the given numbers of channels.
// If the number of channels is invalid, an invalid map is set, and
// mp_chmap_is_valid(dst) will return false.
// A mp_chmap with all entries set to NA is treated specially in some
// contexts (watch out for mp_chmap_is_unknown()).
void mp_chmap_set_unknown(struct mp_chmap *dst, int num_channels)
{
if (num_channels < 0 || num_channels > MP_NUM_CHANNELS) {
@@ -226,31 +234,60 @@ void mp_chmap_set_unknown(struct mp_chmap *dst, int num_channels)
} else {
dst->num = num_channels;
for (int n = 0; n < dst->num; n++)
dst->speaker[n] = MP_SPEAKER_ID_NA;
dst->speaker[n] = MP_SPEAKER_ID_UNKNOWN0 + n;
}
}
// Return channel index of the given speaker, or -1.
static int mp_chmap_find_speaker(const struct mp_chmap *map, int speaker)
{
for (int n = 0; n < map->num; n++) {
if (map->speaker[n] == speaker)
return n;
}
return -1;
}
static void mp_chmap_remove_speaker(struct mp_chmap *map, int speaker)
{
int index = mp_chmap_find_speaker(map, speaker);
if (index >= 0) {
for (int n = index; n < map->num - 1; n++)
map->speaker[n] = map->speaker[n + 1];
map->num--;
}
}
// Some decoders output additional, redundant channels, which are usually
// useless and will mess up proper audio output channel handling.
// map: channel map from which the channels should be removed
// requested: if not NULL, and if it contains any of the "useless" channels,
// don't remove them (this is for convenience)
void mp_chmap_remove_useless_channels(struct mp_chmap *map,
const struct mp_chmap *requested)
{
if (requested &&
mp_chmap_find_speaker(requested, MP_SPEAKER_ID_DL) >= 0)
return;
if (map->num > 2) {
mp_chmap_remove_speaker(map, MP_SPEAKER_ID_DL);
mp_chmap_remove_speaker(map, MP_SPEAKER_ID_DR);
}
}
// Return the ffmpeg/libav channel layout as in <libavutil/channel_layout.h>.
// Speakers not representable by ffmpeg/libav are dropped.
// Warning: this ignores the order of the channels, and will return a channel
// mask even if the order is different from libavcodec's.
// Also, "unknown" channel maps are translated to non-sense channel
// maps with the same number of channels.
uint64_t mp_chmap_to_lavc_unchecked(const struct mp_chmap *src)
{
// lavc has no concept for unknown layouts yet, so pick a default
struct mp_chmap t = *src;
if (t.num > 64)
return 0;
// lavc has no concept for unknown layouts yet, so pick something that does
// the job of signaling the number of channels, even if it makes no sense
// as a proper layout.
if (mp_chmap_is_unknown(&t))
return t.num == 64 ? (uint64_t)-1 : (1ULL << t.num) - 1;
mp_chmap_from_channels(&t, t.num);
uint64_t mask = 0;
for (int n = 0; n < t.num; n++) {
if (t.speaker[n] < 64) // ignore MP_SPEAKER_ID_NA etc.
mask |= 1ULL << t.speaker[n];
}
for (int n = 0; n < t.num; n++)
mask |= 1ULL << t.speaker[n];
return mask;
}
@@ -301,8 +338,6 @@ bool mp_chmap_is_lavc(const struct mp_chmap *src)
return true;
}
// Warning: for "unknown" channel maps, this returns something that may not
// make sense. Invalid channel maps are not changed.
void mp_chmap_reorder_to_lavc(struct mp_chmap *map)
{
if (!mp_chmap_is_valid(map))
@@ -313,43 +348,56 @@ void mp_chmap_reorder_to_lavc(struct mp_chmap *map)
// Get reordering array for from->to reordering. from->to must have the same set
// of speakers (i.e. same number and speaker IDs, just different order). Then,
// for each speaker n, src[n] will be set such that:
// to->speaker[n] = from->speaker[src[n]]
// (src[n] gives the source channel for destination channel n)
// If *from and *to don't contain the same set of speakers, then the above
// invariant is not guaranteed. Instead, src[n] can be set to -1 if the channel
// at to->speaker[n] is unmapped.
void mp_chmap_get_reorder(int src[MP_NUM_CHANNELS], const struct mp_chmap *from,
// for each speaker n, dst[n] will be set such that:
// to->speaker[dst[n]] = from->speaker[n]
// (dst[n] gives the source channel for destination channel n)
void mp_chmap_get_reorder(int dst[MP_NUM_CHANNELS], const struct mp_chmap *from,
const struct mp_chmap *to)
{
for (int n = 0; n < MP_NUM_CHANNELS; n++)
src[n] = -1;
assert(from->num == to->num);
if (mp_chmap_is_unknown(from) || mp_chmap_is_unknown(to)) {
for (int n = 0; n < to->num; n++)
src[n] = n < from->num ? n : -1;
for (int n = 0; n < from->num; n++)
dst[n] = n;
return;
}
for (int n = 0; n < to->num; n++) {
for (int i = 0; i < from->num; i++) {
if (to->speaker[n] == from->speaker[i]) {
src[n] = i;
// Same set of speakers required
assert(mp_chmap_equals_reordered(from, to));
for (int n = 0; n < from->num; n++) {
int src = from->speaker[n];
dst[n] = -1;
for (int i = 0; i < to->num; i++) {
if (src == to->speaker[i]) {
dst[n] = i;
break;
}
}
assert(dst[n] != -1);
}
for (int n = 0; n < to->num; n++)
assert(src[n] < 0 || (to->speaker[n] == from->speaker[src[n]]));
for (int n = 0; n < from->num; n++)
assert(to->speaker[dst[n]] == from->speaker[n]);
}
// Return the number of channels only in a.
int mp_chmap_diffn(const struct mp_chmap *a, const struct mp_chmap *b)
// Performs the difference between a and b, and store it in diff. If b has
// channels that do not appear in a, those will not appear in the difference.
// To get to those the argument ordering in the function call has to be
// inverted. For the same reason, the diff with a superset will return no
// speakers.
void mp_chmap_diff(const struct mp_chmap *a, const struct mp_chmap *b,
struct mp_chmap *diff)
{
uint64_t a_mask = mp_chmap_to_lavc_unchecked(a);
uint64_t b_mask = mp_chmap_to_lavc_unchecked(b);
return av_popcount64((a_mask ^ b_mask) & a_mask);
mp_chmap_from_lavc(diff, (a_mask ^ b_mask) & a_mask);
}
// Checks whether a contains all the speakers in b
bool mp_chmap_contains(const struct mp_chmap *a, const struct mp_chmap *b)
{
struct mp_chmap d1;
struct mp_chmap d2;
mp_chmap_diff(a, b, &d1);
mp_chmap_diff(b, a, &d2);
return a->num >= b->num && d1.num >= 0 && d2.num == 0;
}
// Returns something like "fl-fr-fc". If there's a standard layout in lavc
@@ -452,25 +500,6 @@ bool mp_chmap_from_str(struct mp_chmap *dst, bstr src)
return true;
}
// Output a human readable "canonical" channel map string. Converting this from
// a string back to a channel map can yield a different map, but the string
// looks nicer. E.g. "fc-fl-fr-na" becomes "3.0".
char *mp_chmap_to_str_hr_buf(char *buf, size_t buf_size, const struct mp_chmap *src)
{
struct mp_chmap map = *src;
mp_chmap_remove_na(&map);
for (int n = 0; std_layout_names[n][0]; n++) {
struct mp_chmap s;
if (mp_chmap_from_str(&s, bstr0(std_layout_names[n][0])) &&
mp_chmap_equals_reordered(&s, &map))
{
map = s;
break;
}
}
return mp_chmap_to_str_buf(buf, buf_size, &map);
}
void mp_chmap_print_help(struct mp_log *log)
{
mp_info(log, "Speakers:\n");
+23 -22
View File
@@ -1,18 +1,18 @@
/*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* mpv is 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 Lesser General Public License for more details.
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU General Public License along
* with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MP_CHMAP_H
@@ -22,7 +22,7 @@
#include <stdbool.h>
#include "misc/bstr.h"
#define MP_NUM_CHANNELS 16
#define MP_NUM_CHANNELS 8
// Speaker a channel can be assigned to.
// This corresponds to WAVEFORMATEXTENSIBLE channel mask bit indexes.
@@ -47,7 +47,7 @@ enum mp_speaker_id {
MP_SPEAKER_ID_TBL, // TOP_BACK_LEFT
MP_SPEAKER_ID_TBC, // TOP_BACK_CENTER
MP_SPEAKER_ID_TBR, // TOP_BACK_RIGHT
// Unofficial/libav* extensions
// Inofficial/libav* extensions
MP_SPEAKER_ID_DL = 29, // STEREO_LEFT (stereo downmix special speakers)
MP_SPEAKER_ID_DR, // STEREO_RIGHT
MP_SPEAKER_ID_WL, // WIDE_LEFT
@@ -56,12 +56,10 @@ enum mp_speaker_id {
MP_SPEAKER_ID_SDR, // SURROUND_DIRECT_RIGHT
MP_SPEAKER_ID_LFE2, // LOW_FREQUENCY_2
// Speaker IDs >= 64 are not representable in WAVEFORMATEXTENSIBLE or libav*.
// "Silent" channels. These are sometimes used to insert padding for
// unused channels. Unlike other speaker types, multiple of these can
// occur in a single mp_chmap.
MP_SPEAKER_ID_NA = 64,
// Special mpv-specific speaker entries reserved for channels which have no
// known meaning.
MP_SPEAKER_ID_UNKNOWN0 = 64,
MP_SPEAKER_ID_UNKNOWN_LAST = MP_SPEAKER_ID_UNKNOWN0 + MP_NUM_CHANNELS - 1,
// Including the unassigned IDs in between. This is not a valid ID anymore,
// but is still within uint8_t.
@@ -100,14 +98,17 @@ bool mp_chmap_is_empty(const struct mp_chmap *src);
bool mp_chmap_is_unknown(const struct mp_chmap *src);
bool mp_chmap_equals(const struct mp_chmap *a, const struct mp_chmap *b);
bool mp_chmap_equals_reordered(const struct mp_chmap *a, const struct mp_chmap *b);
bool mp_chmap_is_compatible(const struct mp_chmap *a, const struct mp_chmap *b);
bool mp_chmap_is_stereo(const struct mp_chmap *src);
void mp_chmap_reorder_norm(struct mp_chmap *map);
void mp_chmap_remove_na(struct mp_chmap *map);
void mp_chmap_fill_na(struct mp_chmap *map, int num);
void mp_chmap_from_channels(struct mp_chmap *dst, int num_channels);
void mp_chmap_set_unknown(struct mp_chmap *dst, int num_channels);
void mp_chmap_from_channels_alsa(struct mp_chmap *dst, int num_channels);
void mp_chmap_remove_useless_channels(struct mp_chmap *map,
const struct mp_chmap *requested);
uint64_t mp_chmap_to_lavc(const struct mp_chmap *src);
uint64_t mp_chmap_to_lavc_unchecked(const struct mp_chmap *src);
@@ -116,17 +117,17 @@ void mp_chmap_from_lavc(struct mp_chmap *dst, uint64_t src);
bool mp_chmap_is_lavc(const struct mp_chmap *src);
void mp_chmap_reorder_to_lavc(struct mp_chmap *map);
void mp_chmap_get_reorder(int src[MP_NUM_CHANNELS], const struct mp_chmap *from,
void mp_chmap_get_reorder(int dst[MP_NUM_CHANNELS], const struct mp_chmap *from,
const struct mp_chmap *to);
int mp_chmap_diffn(const struct mp_chmap *a, const struct mp_chmap *b);
void mp_chmap_diff(const struct mp_chmap *a, const struct mp_chmap *b,
struct mp_chmap *diff);
bool mp_chmap_contains(const struct mp_chmap *a, const struct mp_chmap *b);
char *mp_chmap_to_str_buf(char *buf, size_t buf_size, const struct mp_chmap *src);
#define mp_chmap_to_str(m) mp_chmap_to_str_buf((char[64]){0}, 64, (m))
char *mp_chmap_to_str_hr_buf(char *buf, size_t buf_size, const struct mp_chmap *src);
#define mp_chmap_to_str_hr(m) mp_chmap_to_str_hr_buf((char[128]){0}, 128, (m))
bool mp_chmap_from_str(struct mp_chmap *dst, bstr src);
struct mp_log;
+88 -161
View File
@@ -1,18 +1,18 @@
/*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* mpv is 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 Lesser General Public License for more details.
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
* 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>
@@ -20,7 +20,6 @@
#include <limits.h>
#include "common/common.h"
#include "common/msg.h"
#include "chmap_sel.h"
static const struct mp_chmap speaker_replacements[][2] = {
@@ -59,29 +58,6 @@ static bool replace_speakers(struct mp_chmap *map, struct mp_chmap list[2])
return false;
}
// These go strictly from the first to the second entry and always use the
// full layout (possibly reordered and/or padding channels added).
static const struct mp_chmap preferred_remix[][2] = {
// mono can be perfectly played as stereo
{ MP_CHMAP_INIT_MONO, MP_CHMAP_INIT_STEREO },
};
// Conversion from src to dst is explicitly encouraged and should be preferred
// over "mathematical" upmixes or downmixes (which minimize lost channels).
static bool test_preferred_remix(const struct mp_chmap *src,
const struct mp_chmap *dst)
{
struct mp_chmap src_p = *src, dst_p = *dst;
mp_chmap_remove_na(&src_p);
mp_chmap_remove_na(&dst_p);
for (int n = 0; n < MP_ARRAY_SIZE(preferred_remix); n++) {
if (mp_chmap_equals_reordered(&src_p, &preferred_remix[n][0]) &&
mp_chmap_equals_reordered(&dst_p, &preferred_remix[n][1]))
return true;
}
return false;
}
// Allow all channel layouts that can be expressed with mp_chmap.
// (By default, all layouts are rejected.)
void mp_chmap_sel_add_any(struct mp_chmap_sel *s)
@@ -95,6 +71,17 @@ void mp_chmap_sel_add_waveext(struct mp_chmap_sel *s)
s->allow_waveext = true;
}
// Classic ALSA-based MPlayer layouts.
void mp_chmap_sel_add_alsa_def(struct mp_chmap_sel *s)
{
for (int n = 1; n <= MP_NUM_CHANNELS; n++) {
struct mp_chmap t;
mp_chmap_from_channels_alsa(&t, n);
if (t.num)
mp_chmap_sel_add_map(s, &t);
}
}
// Add a channel map that should be allowed.
void mp_chmap_sel_add_map(struct mp_chmap_sel *s, const struct mp_chmap *map)
{
@@ -189,10 +176,6 @@ bool mp_chmap_sel_adjust(const struct mp_chmap_sel *s, struct mp_chmap *map)
return true;
}
}
if (mp_chmap_sel_fallback(s, map))
return true;
for (int i = 0; i < MP_ARRAY_SIZE(speaker_replacements); i++) {
struct mp_chmap t = *map;
struct mp_chmap *r = (struct mp_chmap *)speaker_replacements[i];
@@ -202,6 +185,9 @@ bool mp_chmap_sel_adjust(const struct mp_chmap_sel *s, struct mp_chmap *map)
}
}
if (mp_chmap_sel_fallback(s, map))
return true;
// Fallback to mono/stereo as last resort
*map = (struct mp_chmap) MP_CHMAP_INIT_STEREO;
if (test_layout(s, map))
@@ -213,101 +199,64 @@ bool mp_chmap_sel_adjust(const struct mp_chmap_sel *s, struct mp_chmap *map)
return false;
}
// Like mp_chmap_diffn(), but find the minimum difference with all possible
// speaker replacements considered.
static int mp_chmap_diffn_r(const struct mp_chmap *a, const struct mp_chmap *b)
{
int mindiff = INT_MAX;
#define UPMIX_IDX 0
#define DOWNMIX_IDX 1
#define FALLBACK_IDX 2
for (int i = -1; i < (int)MP_ARRAY_SIZE(speaker_replacements); i++) {
struct mp_chmap ar = *a;
if (i >= 0) {
struct mp_chmap *r = (struct mp_chmap *)speaker_replacements[i];
if (!replace_speakers(&ar, r))
continue;
}
int d = mp_chmap_diffn(&ar, b);
if (d < mindiff)
mindiff = d;
static bool test_fallbacks(struct mp_chmap *a, struct mp_chmap *b,
int best_diffs[2], struct mp_chmap best[2])
{
struct mp_chmap diff1, diff2;
mp_chmap_diff(a, b, &diff1);
if (mp_chmap_contains(a, b) && best_diffs[UPMIX_IDX] > diff1.num) {
best[UPMIX_IDX] = *a;
best_diffs[UPMIX_IDX] = diff1.num;
return true;
}
// Special-case: we consider stereo a replacement for mono. (This is not
// true in the other direction. Also, fl-fr is generally not a replacement
// for fc. Thus it's not part of the speaker replacement list.)
struct mp_chmap mono = MP_CHMAP_INIT_MONO;
struct mp_chmap stereo = MP_CHMAP_INIT_STEREO;
if (mp_chmap_equals(&mono, b) && mp_chmap_equals(&stereo, a))
mindiff = 0;
mp_chmap_diff(b, a, &diff2);
if (mp_chmap_contains(b, a) && best_diffs[DOWNMIX_IDX] > diff2.num) {
best[DOWNMIX_IDX] = *a;
best_diffs[DOWNMIX_IDX] = diff2.num;
return true;
}
return mindiff;
if (diff1.num > 0 && best_diffs[FALLBACK_IDX] > diff1.num) {
best[FALLBACK_IDX] = *a;
best_diffs[FALLBACK_IDX] = diff1.num;
return true;
}
if (diff2.num > 0 && best_diffs[FALLBACK_IDX] > diff2.num) {
best[FALLBACK_IDX] = *a;
best_diffs[FALLBACK_IDX] = diff2.num;
return true;
}
return false;
}
// Decide whether we should prefer old or new for the requested layout.
// Return true if new should be used, false if old should be used.
// If old is empty, always return new (initial case).
static bool mp_chmap_is_better(struct mp_chmap *req, struct mp_chmap *old,
struct mp_chmap *new)
{
// Initial case
if (!old->num)
return true;
// Exact pick - this also ensures that the best layout is chosen if the
// layouts are the same, but with different order of channels.
if (mp_chmap_equals(req, old))
return false;
if (mp_chmap_equals(req, new))
return true;
// If there's no exact match, strictly do a preferred conversion.
bool old_pref = test_preferred_remix(req, old);
bool new_pref = test_preferred_remix(req, new);
if (old_pref && !new_pref)
return false;
if (!old_pref && new_pref)
return true;
int old_lost_r = mp_chmap_diffn_r(req, old); // num. channels only in req
int new_lost_r = mp_chmap_diffn_r(req, new);
// Imperfect upmix (no real superset) - minimize lost channels
if (new_lost_r != old_lost_r)
return new_lost_r < old_lost_r;
struct mp_chmap old_p = *old, new_p = *new;
mp_chmap_remove_na(&old_p);
mp_chmap_remove_na(&new_p);
// If the situation is equal with replaced speakers, but the replacement is
// perfect for only one of them, let the better one win. This prefers
// inexact equivalents over exact supersets.
bool perfect_r_new = !new_lost_r && new_p.num <= old_p.num;
bool perfect_r_old = !old_lost_r && old_p.num <= new_p.num;
if (perfect_r_new != perfect_r_old)
return perfect_r_new;
int old_lost = mp_chmap_diffn(req, old);
int new_lost = mp_chmap_diffn(req, new);
// If the situation is equal with replaced speakers, pick the better one,
// even if it means an upmix.
if (new_lost != old_lost)
return new_lost < old_lost;
// Some kind of upmix. If it's perfect, prefer the smaller one. Even if not,
// both have equal loss, so also prefer the smaller one.
// Drop padding channels (NA) for the sake of this check, as the number of
// padding channels isn't really meaningful.
if (new_p.num != old_p.num)
return new_p.num < old_p.num;
// Again, with physical channels (minimizes number of NA channels).
return new->num < old->num;
}
// Determine which channel map to fallback to given a source channel map.
// Determine which channel map to fallback to given a source channel map. It
// uses the following heuristic:
// 1) If mono is required always prefer stereo to a multichannel upmix.
// 2) Search for an upmix that is an exact superset of the required chmap.
// 3) Search for a downmix that is the exact subset of the required chmap.
// 4) Search for either an upmix or downmix that is the closest (minimum
// difference of speakers) to the required chmap.
bool mp_chmap_sel_fallback(const struct mp_chmap_sel *s, struct mp_chmap *map)
{
struct mp_chmap best = {0};
// special case: if possible always fallback mono to stereo (instead of
// looking for a multichannel upmix)
struct mp_chmap mono = MP_CHMAP_INIT_MONO;
struct mp_chmap stereo = MP_CHMAP_INIT_STEREO;
if (mp_chmap_equals(&mono, map) && test_layout(s, &stereo)) {
*map = stereo;
return true;
}
int best_diffs[] = { INT_MAX, INT_MAX, INT_MAX };
struct mp_chmap best[] = { {0}, {0}, {0} };
for (int n = 0; n < s->num_chmaps; n++) {
struct mp_chmap e = s->chmaps[n];
@@ -315,13 +264,25 @@ bool mp_chmap_sel_fallback(const struct mp_chmap_sel *s, struct mp_chmap *map)
if (mp_chmap_is_unknown(&e))
continue;
if (mp_chmap_is_better(map, &best, &e))
best = e;
if (test_fallbacks(&e, map, best_diffs, best))
continue;
// in case we didn't match any fallback retry after replacing speakers
for (int i = 0; i < MP_ARRAY_SIZE(speaker_replacements); i++) {
struct mp_chmap t = e;
struct mp_chmap *r = (struct mp_chmap *)speaker_replacements[i];
if (replace_speakers(&t, r)) {
if (test_fallbacks(&t, map, best_diffs, best))
continue;
}
}
}
if (best.num) {
*map = best;
return true;
for (int i = UPMIX_IDX; i < MP_ARRAY_SIZE(best); i++) {
if (best_diffs[i] < INT_MAX) {
*map = best[i];
return true;
}
}
return false;
@@ -353,37 +314,3 @@ bool mp_chmap_sel_get_def(const struct mp_chmap_sel *s, struct mp_chmap *map,
}
return map->num > 0;
}
// Print the set of allowed channel layouts.
void mp_chmal_sel_log(const struct mp_chmap_sel *s, struct mp_log *log, int lev)
{
if (!mp_msg_test(log, lev))
return;
for (int i = 0; i < s->num_chmaps; i++)
mp_msg(log, lev, " - %s\n", mp_chmap_to_str(&s->chmaps[i]));
for (int i = 0; i < MP_SPEAKER_ID_COUNT; i++) {
if (!s->speakers[i])
continue;
struct mp_chmap l = {.num = 1, .speaker = { i }};
mp_msg(log, lev, " - #%s\n",
i == MP_SPEAKER_ID_FC ? "fc" : mp_chmap_to_str_hr(&l));
}
if (s->allow_waveext)
mp_msg(log, lev, " - waveext\n");
if (s->allow_any)
mp_msg(log, lev, " - anything\n");
}
// Select a channel map from the given list that fits best to c. Don't change
// *c if there's no match, or the list is empty.
void mp_chmap_sel_list(struct mp_chmap *c, struct mp_chmap *maps, int num_maps)
{
// This is a separate function to keep messing with mp_chmap_sel internals
// within this source file.
struct mp_chmap_sel sel = {
.chmaps = maps,
.num_chmaps = num_maps,
};
mp_chmap_sel_fallback(&sel, c);
}
+8 -12
View File
@@ -1,18 +1,18 @@
/*
* This file is part of mpv.
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* mpv is 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 Lesser General Public License for more details.
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU General Public License along
* with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MP_CHMAP_SEL_H
@@ -37,6 +37,7 @@ struct mp_chmap_sel {
void mp_chmap_sel_add_any(struct mp_chmap_sel *s);
void mp_chmap_sel_add_waveext(struct mp_chmap_sel *s);
void mp_chmap_sel_add_waveext_def(struct mp_chmap_sel *s);
void mp_chmap_sel_add_alsa_def(struct mp_chmap_sel *s);
void mp_chmap_sel_add_map(struct mp_chmap_sel *s, const struct mp_chmap *map);
void mp_chmap_sel_add_speaker(struct mp_chmap_sel *s, int id);
bool mp_chmap_sel_adjust(const struct mp_chmap_sel *s, struct mp_chmap *map);
@@ -44,9 +45,4 @@ bool mp_chmap_sel_fallback(const struct mp_chmap_sel *s, struct mp_chmap *map);
bool mp_chmap_sel_get_def(const struct mp_chmap_sel *s, struct mp_chmap *map,
int num);
struct mp_log;
void mp_chmal_sel_log(const struct mp_chmap_sel *s, struct mp_log *log, int lev);
void mp_chmap_sel_list(struct mp_chmap *c, struct mp_chmap *maps, int num_maps);
#endif
+1 -2
View File
@@ -35,8 +35,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_packet)(struct dec_audio *da, struct demux_packet *pkt,
struct mp_audio **out);
int (*decode_packet)(struct dec_audio *da, struct mp_audio **out);
};
enum ad_ctrl {
+67 -97
View File
@@ -26,7 +26,7 @@
#include <libavutil/common.h>
#include <libavutil/intreadwrite.h>
#include "mpv_talloc.h"
#include "talloc.h"
#include "config.h"
#include "common/av_common.h"
@@ -42,11 +42,8 @@ struct priv {
AVFrame *avframe;
struct mp_audio frame;
bool force_channel_map;
uint32_t skip_samples, trim_samples;
bool preroll_done;
double next_pts;
bool needs_reset;
AVRational codec_timebase;
struct demux_packet *packet;
uint32_t skip_samples;
};
static void uninit(struct dec_audio *da);
@@ -63,7 +60,7 @@ const struct m_sub_options ad_lavc_conf = {
.opts = (const m_option_t[]) {
OPT_FLOATRANGE("ac3drc", ac3drc, 0, 0, 6),
OPT_FLAG("downmix", downmix, 0),
OPT_INTRANGE("threads", threads, 0, 0, 16),
OPT_INTRANGE("threads", threads, 0, 1, 16),
OPT_KEYVALUELIST("o", avopts, 0),
{0}
},
@@ -81,14 +78,13 @@ static int init(struct dec_audio *da, const char *decoder)
struct ad_lavc_params *opts = mpopts->ad_lavc_params;
AVCodecContext *lavc_context;
AVCodec *lavc_codec;
struct mp_codec_params *c = da->codec;
struct sh_stream *sh = da->header;
struct sh_audio *sh_audio = sh->audio;
struct priv *ctx = talloc_zero(NULL, struct priv);
da->priv = ctx;
ctx->codec_timebase = mp_get_codec_timebase(da->codec);
ctx->force_channel_map = c->force_channels;
ctx->force_channel_map = sh_audio->force_channels;
lavc_codec = avcodec_find_decoder_by_name(decoder);
if (!lavc_codec) {
@@ -104,13 +100,9 @@ static int init(struct dec_audio *da, const char *decoder)
lavc_context->codec_type = AVMEDIA_TYPE_AUDIO;
lavc_context->codec_id = lavc_codec->id;
#if LIBAVCODEC_VERSION_MICRO >= 100
lavc_context->pkt_timebase = ctx->codec_timebase;
#endif
if (opts->downmix && mpopts->audio_output_channels.num_chmaps == 1) {
if (opts->downmix) {
lavc_context->request_channel_layout =
mp_chmap_to_lavc(&mpopts->audio_output_channels.chmaps[0]);
mp_chmap_to_lavc(&mpopts->audio_output_channels);
}
// Always try to set - option only exists for AC3 at the moment
@@ -124,19 +116,24 @@ static int init(struct dec_audio *da, const char *decoder)
mp_set_avopts(da->log, lavc_context, opts->avopts);
lavc_context->codec_tag = c->codec_tag;
lavc_context->sample_rate = c->samplerate;
lavc_context->bit_rate = c->bitrate;
lavc_context->block_align = c->block_align;
lavc_context->bits_per_coded_sample = c->bits_per_coded_sample;
lavc_context->channels = c->channels.num;
if (!mp_chmap_is_unknown(&c->channels))
lavc_context->channel_layout = mp_chmap_to_lavc(&c->channels);
lavc_context->codec_tag = sh->format;
lavc_context->sample_rate = sh_audio->samplerate;
lavc_context->bit_rate = sh_audio->bitrate;
lavc_context->block_align = sh_audio->block_align;
lavc_context->bits_per_coded_sample = sh_audio->bits_per_coded_sample;
lavc_context->channels = sh_audio->channels.num;
if (!mp_chmap_is_unknown(&sh_audio->channels))
lavc_context->channel_layout = mp_chmap_to_lavc(&sh_audio->channels);
// demux_mkv
mp_lavc_set_extradata(lavc_context, c->extradata, c->extradata_size);
if (sh_audio->codecdata_len && sh_audio->codecdata &&
!lavc_context->extradata) {
mp_lavc_set_extradata(lavc_context, sh_audio->codecdata,
sh_audio->codecdata_len);
}
mp_set_lav_codec_headers(lavc_context, c);
if (sh->lav_headers)
mp_copy_lav_codec_headers(lavc_context, sh->lav_headers);
mp_set_avcodec_threads(da->log, lavc_context, opts->threads);
@@ -147,8 +144,6 @@ static int init(struct dec_audio *da, const char *decoder)
return 0;
}
ctx->next_pts = MP_NOPTS_VALUE;
return 1;
}
@@ -174,53 +169,40 @@ static int control(struct dec_audio *da, int cmd, void *arg)
switch (cmd) {
case ADCTRL_RESET:
avcodec_flush_buffers(ctx->avctx);
talloc_free(ctx->packet);
ctx->packet = NULL;
ctx->skip_samples = 0;
ctx->trim_samples = 0;
ctx->preroll_done = false;
ctx->next_pts = MP_NOPTS_VALUE;
ctx->needs_reset = false;
return CONTROL_TRUE;
}
return CONTROL_UNKNOWN;
}
static int decode_packet(struct dec_audio *da, struct demux_packet *mpkt,
struct mp_audio **out)
static int decode_packet(struct dec_audio *da, struct mp_audio **out)
{
struct priv *priv = da->priv;
AVCodecContext *avctx = priv->avctx;
// If the decoder discards the timestamp for some reason, we use the
// interpolated PTS. Initialize it so that it works for the initial
// packet as well.
if (mpkt && priv->next_pts == MP_NOPTS_VALUE)
priv->next_pts = mpkt->pts;
struct demux_packet *mpkt = priv->packet;
if (!mpkt) {
if (demux_read_packet_async(da->header, &mpkt) == 0)
return AD_WAIT;
}
priv->packet = talloc_steal(priv, mpkt);
int in_len = mpkt ? mpkt->len : 0;
AVPacket pkt;
mp_set_av_packet(&pkt, mpkt, &priv->codec_timebase);
mp_set_av_packet(&pkt, mpkt, NULL);
// If we don't have a PTS yet, use the first packet PTS we can get.
if (da->pts == MP_NOPTS_VALUE && mpkt && mpkt->pts != MP_NOPTS_VALUE) {
da->pts = mpkt->pts;
da->pts_offset = 0;
}
int got_frame = 0;
av_frame_unref(priv->avframe);
if (priv->needs_reset)
control(da, ADCTRL_RESET, NULL);
#if HAVE_AVCODEC_NEW_CODEC_API
int ret = avcodec_send_packet(avctx, &pkt);
if (ret >= 0 || ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
if (ret >= 0 && mpkt)
mpkt->len = 0;
ret = avcodec_receive_frame(avctx, priv->avframe);
if (ret >= 0)
got_frame = 1;
if (ret == AVERROR_EOF)
priv->needs_reset = true;
if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF)
ret = 0;
}
#else
int ret = avcodec_decode_audio4(avctx, priv->avframe, &got_frame, &pkt);
if (mpkt) {
// At least "shorten" decodes sub-frames, instead of the whole packet.
@@ -231,71 +213,59 @@ static int decode_packet(struct dec_audio *da, struct demux_packet *mpkt,
mpkt->len -= ret;
mpkt->pts = MP_NOPTS_VALUE; // don't reset PTS next time
}
// LATM may need many packets to find mux info
if (ret == AVERROR(EAGAIN)) {
mpkt->len = 0;
return 0;
if (mpkt->len == 0 || ret < 0) {
talloc_free(mpkt);
priv->packet = NULL;
}
// LATM may need many packets to find mux info
if (ret == AVERROR(EAGAIN))
return AD_OK;
}
#endif
if (ret < 0) {
MP_ERR(da, "Error decoding audio.\n");
return -1;
return AD_ERR;
}
if (!got_frame)
return 0;
return mpkt ? AD_OK : AD_EOF;
double out_pts = mp_pts_from_av(MP_AVFRAME_DEC_PTS(priv->avframe),
&priv->codec_timebase);
double out_pts = mp_pts_from_av(priv->avframe->pkt_pts, NULL);
if (out_pts != MP_NOPTS_VALUE) {
da->pts = out_pts;
da->pts_offset = 0;
}
struct mp_audio *mpframe = mp_audio_from_avframe(priv->avframe);
if (!mpframe)
return -1;
return AD_ERR;
struct mp_chmap lavc_chmap = mpframe->channels;
if (lavc_chmap.num != avctx->channels)
mp_chmap_from_channels(&lavc_chmap, avctx->channels);
if (priv->force_channel_map) {
if (lavc_chmap.num == da->codec->channels.num)
lavc_chmap = da->codec->channels;
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(mpframe, &lavc_chmap);
mpframe->pts = out_pts;
if (mpframe->pts == MP_NOPTS_VALUE)
mpframe->pts = priv->next_pts;
if (mpframe->pts != MP_NOPTS_VALUE)
priv->next_pts = mpframe->pts + mpframe->samples / (double)mpframe->rate;
#if HAVE_AVFRAME_SKIP_SAMPLES
AVFrameSideData *sd =
av_frame_get_side_data(priv->avframe, AV_FRAME_DATA_SKIP_SAMPLES);
if (sd && sd->size >= 10) {
char *d = sd->data;
priv->skip_samples += AV_RL32(d + 0);
priv->trim_samples += AV_RL32(d + 4);
uint32_t pad = AV_RL32(d + 4);
uint32_t skip = MPMIN(priv->skip_samples, mpframe->samples);
if (skip) {
mp_audio_skip_samples(mpframe, skip);
da->pts_offset += skip;
priv->skip_samples -= skip;
}
if (pad <= mpframe->samples)
mpframe->samples -= pad;
}
#endif
if (!priv->preroll_done) {
// Skip only if this isn't already handled by AV_FRAME_DATA_SKIP_SAMPLES.
if (!priv->skip_samples)
priv->skip_samples = avctx->delay;
priv->preroll_done = true;
}
uint32_t skip = MPMIN(priv->skip_samples, mpframe->samples);
if (skip) {
mp_audio_skip_samples(mpframe, skip);
priv->skip_samples -= skip;
}
uint32_t trim = MPMIN(priv->trim_samples, mpframe->samples);
if (trim) {
mpframe->samples -= trim;
priv->trim_samples -= trim;
}
*out = mpframe;
av_frame_unref(priv->avframe);
+30 -111
View File
@@ -34,14 +34,11 @@
struct spdifContext {
struct mp_log *log;
enum AVCodecID codec_id;
AVFormatContext *lavf_ctx;
int out_buffer_len;
uint8_t out_buffer[OUTBUF_SIZE];
bool need_close;
bool use_dts_hd;
struct mp_audio fmt;
struct mp_audio_pool *pool;
};
static int write_packet(void *p, uint8_t *buf, int buf_size)
@@ -79,86 +76,17 @@ static int init(struct dec_audio *da, const char *decoder)
struct spdifContext *spdif_ctx = talloc_zero(NULL, struct spdifContext);
da->priv = spdif_ctx;
spdif_ctx->log = da->log;
spdif_ctx->use_dts_hd = da->opts->dtshd;
spdif_ctx->pool = mp_audio_pool_create(spdif_ctx);
if (strcmp(decoder, "dts-hd") == 0) {
decoder = "dts";
spdif_ctx->use_dts_hd = true;
}
spdif_ctx->codec_id = mp_codec_to_av_codec_id(decoder);
return spdif_ctx->codec_id != AV_CODEC_ID_NONE;
}
static int determine_codec_profile(struct dec_audio *da, AVPacket *pkt)
{
struct spdifContext *spdif_ctx = da->priv;
int profile = FF_PROFILE_UNKNOWN;
AVCodecContext *ctx = NULL;
AVFrame *frame = NULL;
AVCodec *codec = avcodec_find_decoder(spdif_ctx->codec_id);
if (!codec)
goto done;
frame = av_frame_alloc();
if (!frame)
goto done;
ctx = avcodec_alloc_context3(codec);
if (!ctx)
goto done;
if (avcodec_open2(ctx, codec, NULL) < 0) {
av_free(ctx); // don't attempt to avcodec_close() an unopened ctx
ctx = NULL;
goto done;
}
#if HAVE_AVCODEC_NEW_CODEC_API
if (avcodec_send_packet(ctx, pkt) < 0)
goto done;
if (avcodec_receive_frame(ctx, frame) < 0)
goto done;
#else
int got_frame = 0;
if (avcodec_decode_audio4(ctx, frame, &got_frame, pkt) < 1 || !got_frame)
goto done;
#endif
profile = ctx->profile;
done:
av_frame_free(&frame);
if (ctx)
avcodec_close(ctx);
avcodec_free_context(&ctx);
if (profile == FF_PROFILE_UNKNOWN)
MP_WARN(da, "Failed to parse codec profile.\n");
return profile;
}
static int init_filter(struct dec_audio *da, AVPacket *pkt)
{
struct spdifContext *spdif_ctx = da->priv;
int profile = FF_PROFILE_UNKNOWN;
if (spdif_ctx->codec_id == AV_CODEC_ID_DTS)
profile = determine_codec_profile(da, pkt);
AVFormatContext *lavf_ctx = avformat_alloc_context();
if (!lavf_ctx)
goto fail;
spdif_ctx->lavf_ctx = lavf_ctx;
lavf_ctx->oformat = av_guess_format("spdif", NULL, NULL);
if (!lavf_ctx->oformat)
goto fail;
spdif_ctx->lavf_ctx = lavf_ctx;
void *buffer = av_mallocz(OUTBUF_SIZE);
if (!buffer)
abort();
@@ -178,18 +106,14 @@ static int init_filter(struct dec_audio *da, AVPacket *pkt)
if (!stream)
goto fail;
#if HAVE_AVCODEC_HAS_CODECPAR
stream->codecpar->codec_id = spdif_ctx->codec_id;
#else
stream->codec->codec_id = spdif_ctx->codec_id;
#endif
stream->codec->codec_id = mp_codec_to_av_codec_id(decoder);
AVDictionary *format_opts = NULL;
int num_channels = 0;
int sample_format = 0;
int samplerate = 0;
switch (spdif_ctx->codec_id) {
switch (stream->codec->codec_id) {
case AV_CODEC_ID_AAC:
sample_format = AF_FORMAT_S_AAC;
samplerate = 48000;
@@ -200,22 +124,18 @@ static int init_filter(struct dec_audio *da, AVPacket *pkt)
samplerate = 48000;
num_channels = 2;
break;
case AV_CODEC_ID_DTS: {
bool is_hd = profile == FF_PROFILE_DTS_HD_HRA ||
profile == FF_PROFILE_DTS_HD_MA ||
profile == FF_PROFILE_UNKNOWN;
if (spdif_ctx->use_dts_hd && is_hd) {
case AV_CODEC_ID_DTS:
if (da->opts->dtshd) {
av_dict_set(&format_opts, "dtshd_rate", "768000", 0); // 4*192000
sample_format = AF_FORMAT_S_DTSHD;
samplerate = 192000;
num_channels = 2*4;
sample_format = AF_FORMAT_S_DTSHD;
samplerate = 192000;
num_channels = 2*4;
} else {
sample_format = AF_FORMAT_S_DTS;
samplerate = 48000;
num_channels = 2;
sample_format = AF_FORMAT_S_DTS;
samplerate = 48000;
num_channels = 2;
}
break;
}
case AV_CODEC_ID_EAC3:
sample_format = AF_FORMAT_S_EAC3;
samplerate = 192000;
@@ -247,45 +167,46 @@ static int init_filter(struct dec_audio *da, AVPacket *pkt)
spdif_ctx->need_close = true;
return 0;
return 1;
fail:
uninit(da);
return -1;
return 0;
}
static int decode_packet(struct dec_audio *da, struct demux_packet *mpkt,
struct mp_audio **out)
static int decode_packet(struct dec_audio *da, struct mp_audio **out)
{
struct spdifContext *spdif_ctx = da->priv;
AVFormatContext *lavf_ctx = spdif_ctx->lavf_ctx;
spdif_ctx->out_buffer_len = 0;
if (!mpkt)
return 0;
struct demux_packet *mpkt;
if (demux_read_packet_async(da->header, &mpkt) == 0)
return AD_WAIT;
double pts = mpkt->pts;
if (!mpkt)
return AD_EOF;
AVPacket pkt;
mp_set_av_packet(&pkt, mpkt, NULL);
mpkt->len = 0; // will be fully consumed
pkt.pts = pkt.dts = 0;
if (!spdif_ctx->lavf_ctx) {
if (init_filter(da, &pkt) < 0)
return -1;
if (mpkt->pts != MP_NOPTS_VALUE) {
da->pts = mpkt->pts;
da->pts_offset = 0;
}
int ret = av_write_frame(spdif_ctx->lavf_ctx, &pkt);
avio_flush(spdif_ctx->lavf_ctx->pb);
int ret = av_write_frame(lavf_ctx, &pkt);
talloc_free(mpkt);
avio_flush(lavf_ctx->pb);
if (ret < 0)
return -1;
return AD_ERR;
int samples = spdif_ctx->out_buffer_len / spdif_ctx->fmt.sstride;
*out = mp_audio_pool_get(spdif_ctx->pool, &spdif_ctx->fmt, samples);
*out = mp_audio_pool_get(da->pool, &spdif_ctx->fmt, samples);
if (!*out)
return -1;
return AD_ERR;
memcpy((*out)->planes[0], spdif_ctx->out_buffer, spdif_ctx->out_buffer_len);
(*out)->pts = pts;
return 0;
}
@@ -314,8 +235,6 @@ static void add_decoders(struct mp_decoder_list *list)
"libavformat/spdifenc audio pass-through decoder");
}
}
mp_add_decoder(list, "spdif", "dts", "dts-hd",
"libavformat/spdifenc audio pass-through decoder");
}
const struct ad_functions ad_spdif = {
+105 -144
View File
@@ -18,7 +18,6 @@
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <math.h>
#include <assert.h>
#include <libavutil/mem.h>
@@ -53,7 +52,6 @@ static const struct ad_functions * const ad_drivers[] = {
static void uninit_decoder(struct dec_audio *d_audio)
{
audio_reset_decoding(d_audio);
if (d_audio->ad_driver) {
MP_VERBOSE(d_audio, "Uninit audio decoder.\n");
d_audio->ad_driver->uninit(d_audio);
@@ -83,21 +81,11 @@ struct mp_decoder_list *audio_decoder_list(void)
return list;
}
static struct mp_decoder_list *audio_select_decoders(struct dec_audio *d_audio)
static struct mp_decoder_list *audio_select_decoders(const char *codec,
char *selection)
{
struct MPOpts *opts = d_audio->opts;
const char *codec = d_audio->codec->codec;
struct mp_decoder_list *list = audio_decoder_list();
struct mp_decoder_list *new =
mp_select_decoders(list, codec, opts->audio_decoders);
if (d_audio->try_spdif) {
struct mp_decoder_list *spdif =
mp_select_decoder_list(list, codec, "spdif", opts->audio_spdif);
mp_append_decoders(spdif, new);
talloc_free(new);
new = spdif;
}
struct mp_decoder_list *new = mp_select_decoders(list, codec, selection);
talloc_free(list);
return new;
}
@@ -111,13 +99,14 @@ static const struct ad_functions *find_driver(const char *name)
return NULL;
}
int audio_init_best_codec(struct dec_audio *d_audio)
int audio_init_best_codec(struct dec_audio *d_audio, char *audio_decoders)
{
uninit_decoder(d_audio);
assert(!d_audio->ad_driver);
audio_reset_decoding(d_audio);
struct mp_decoder_entry *decoder = NULL;
struct mp_decoder_list *list = audio_select_decoders(d_audio);
struct mp_decoder_list *list =
audio_select_decoders(d_audio->header->codec, audio_decoders);
mp_print_decoders(d_audio->log, MSGL_V, "Codec list:", list);
@@ -144,7 +133,7 @@ int audio_init_best_codec(struct dec_audio *d_audio)
MP_VERBOSE(d_audio, "Selected audio codec: %s\n", d_audio->decoder_desc);
} else {
MP_ERR(d_audio, "Failed to initialize an audio decoder for codec '%s'.\n",
d_audio->codec->codec);
d_audio->header->codec ? d_audio->header->codec : "<unknown>");
}
talloc_free(list);
@@ -155,139 +144,111 @@ void audio_uninit(struct dec_audio *d_audio)
{
if (!d_audio)
return;
MP_VERBOSE(d_audio, "Uninit audio filters...\n");
af_destroy(d_audio->afilter);
uninit_decoder(d_audio);
talloc_free(d_audio->waiting);
talloc_free(d_audio);
}
static int decode_new_frame(struct dec_audio *da)
{
while (!da->waiting) {
int ret = da->ad_driver->decode_packet(da, &da->waiting);
if (ret < 0)
return ret;
if (da->pts == MP_NOPTS_VALUE && da->header->missing_timestamps)
da->pts = 0;
if (da->waiting) {
da->pts_offset += da->waiting->samples;
da->decode_format = *da->waiting;
mp_audio_set_null_data(&da->decode_format);
}
}
return mp_audio_config_valid(da->waiting) ? AD_OK : AD_ERR;
}
/* 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)
{
return decode_new_frame(da);
}
static bool copy_output(struct af_stream *afs, struct mp_audio_buffer *outbuf,
int minsamples, bool eof)
{
while (mp_audio_buffer_samples(outbuf) < minsamples) {
if (af_output_frame(afs, eof) < 0)
return true; // error, stop doing stuff
struct mp_audio *mpa = af_read_output_frame(afs);
if (!mpa)
return false; // out of data
mp_audio_buffer_append(outbuf, mpa);
talloc_free(mpa);
}
return true;
}
/* Try to get at least minsamples decoded+filtered samples in outbuf
* (total length including possible existing data).
* 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 *da, struct mp_audio_buffer *outbuf,
int minsamples)
{
struct af_stream *afs = da->afilter;
if (afs->initialized < 1)
return AD_ERR;
MP_STATS(da, "start audio");
int res;
while (1) {
res = 0;
if (copy_output(afs, outbuf, minsamples, false))
break;
res = decode_new_frame(da);
if (res < 0) {
// drain filters first (especially for true EOF case)
copy_output(afs, outbuf, minsamples, true);
break;
}
// On format change, make sure to drain the filter chain.
if (!mp_audio_config_equals(&afs->input, da->waiting)) {
copy_output(afs, outbuf, minsamples, true);
res = AD_NEW_FMT;
break;
}
struct mp_audio *mpa = da->waiting;
da->waiting = NULL;
if (af_filter_frame(afs, mpa) < 0)
return AD_ERR;
}
MP_STATS(da, "end audio");
return res;
}
void audio_reset_decoding(struct dec_audio *d_audio)
{
if (d_audio->ad_driver)
d_audio->ad_driver->control(d_audio, ADCTRL_RESET, NULL);
af_seek_reset(d_audio->afilter);
d_audio->pts = MP_NOPTS_VALUE;
talloc_free(d_audio->current_frame);
d_audio->current_frame = NULL;
talloc_free(d_audio->packet);
d_audio->packet = NULL;
talloc_free(d_audio->new_segment);
d_audio->new_segment = NULL;
d_audio->start = d_audio->end = MP_NOPTS_VALUE;
}
static void fix_audio_pts(struct dec_audio *da)
{
if (!da->current_frame)
return;
if (da->current_frame->pts != MP_NOPTS_VALUE) {
double newpts = da->current_frame->pts;
if (da->pts != MP_NOPTS_VALUE)
MP_STATS(da, "value %f audio-pts-err", da->pts - newpts);
// Keep the interpolated timestamp if it doesn't deviate more
// than 1 ms from the real one. (MKV rounded timestamps.)
if (da->pts == MP_NOPTS_VALUE || fabs(da->pts - newpts) > 0.001)
da->pts = newpts;
}
if (da->pts == MP_NOPTS_VALUE && da->header->missing_timestamps)
da->pts = 0;
da->current_frame->pts = da->pts;
if (da->pts != MP_NOPTS_VALUE)
da->pts += da->current_frame->samples / (double)da->current_frame->rate;
}
void audio_work(struct dec_audio *da)
{
if (da->current_frame)
return;
if (!da->packet && !da->new_segment &&
demux_read_packet_async(da->header, &da->packet) == 0)
{
da->current_state = DATA_WAIT;
return;
}
if (da->packet && da->packet->new_segment) {
assert(!da->new_segment);
da->new_segment = da->packet;
da->packet = NULL;
}
bool had_input_packet = !!da->packet;
bool had_packet = da->packet || da->new_segment;
int ret = da->ad_driver->decode_packet(da, da->packet, &da->current_frame);
if (ret < 0 || (da->packet && da->packet->len == 0)) {
talloc_free(da->packet);
da->packet = NULL;
}
if (da->current_frame && !mp_audio_config_valid(da->current_frame)) {
talloc_free(da->current_frame);
da->current_frame = NULL;
}
da->current_state = DATA_OK;
if (!da->current_frame) {
da->current_state = DATA_EOF;
if (had_packet)
da->current_state = DATA_AGAIN;
}
fix_audio_pts(da);
bool segment_end = !da->current_frame && !had_input_packet;
if (da->current_frame) {
mp_audio_clip_timestamps(da->current_frame, da->start, da->end);
if (da->current_frame->pts != MP_NOPTS_VALUE && da->start != MP_NOPTS_VALUE)
segment_end = da->current_frame->pts >= da->end;
if (da->current_frame->samples == 0) {
talloc_free(da->current_frame);
da->current_frame = NULL;
}
}
// If there's a new segment, start it as soon as we're drained/finished.
if (segment_end && da->new_segment) {
struct demux_packet *new_segment = da->new_segment;
da->new_segment = NULL;
// Could avoid decoder reinit; would still need flush.
da->codec = new_segment->codec;
if (da->ad_driver)
da->ad_driver->uninit(da);
da->ad_driver = NULL;
audio_init_best_codec(da);
da->start = new_segment->start;
da->end = new_segment->end;
new_segment->new_segment = false;
da->packet = new_segment;
da->current_state = DATA_AGAIN;
d_audio->pts_offset = 0;
if (d_audio->waiting) {
talloc_free(d_audio->waiting);
d_audio->waiting = NULL;
}
}
// Fetch an audio frame decoded with audio_work(). Returns one of:
// DATA_OK: *out_frame is set to a new image
// DATA_WAIT: waiting for demuxer; will receive a wakeup signal
// DATA_EOF: end of file, no more frames to be expected
// DATA_AGAIN: dropped frame or something similar
int audio_get_frame(struct dec_audio *da, struct mp_audio **out_frame)
{
*out_frame = NULL;
if (da->current_frame) {
*out_frame = da->current_frame;
da->current_frame = NULL;
return DATA_OK;
}
if (da->current_state == DATA_OK)
return DATA_AGAIN;
return da->current_state;
}
+23 -18
View File
@@ -32,31 +32,36 @@ struct dec_audio {
struct mpv_global *global;
const struct ad_functions *ad_driver;
struct sh_stream *header;
struct mp_codec_params *codec;
struct af_stream *afilter;
char *decoder_desc;
bool try_spdif;
int init_retries;
struct mp_audio_pool *pool;
struct mp_audio decode_format;
struct mp_audio *waiting; // used on format-change
// set by decoder
int bitrate; // input bitrate, can change with VBR sources
// last known pts value in output from decoder
double pts;
// number of samples output by decoder after last known pts
int pts_offset;
// For free use by the ad_driver
void *priv;
};
// Strictly internal (dec_audio.c).
double pts; // endpts of previous frame
double start, end;
struct demux_packet *packet;
struct demux_packet *new_segment;
struct mp_audio *current_frame;
int current_state;
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);
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);
void audio_work(struct dec_audio *d_audio);
int audio_get_frame(struct dec_audio *d_audio, struct mp_audio **out_frame);
void audio_reset_decoding(struct dec_audio *d_audio);
#endif /* MPLAYER_DEC_AUDIO_H */
+299 -189
View File
@@ -31,33 +31,70 @@
#include "af.h"
// Static list of filters
extern const struct af_info af_info_dummy;
extern const struct af_info af_info_delay;
extern const struct af_info af_info_channels;
extern const struct af_info af_info_format;
extern const struct af_info af_info_force;
extern const struct af_info af_info_volume;
extern const struct af_info af_info_equalizer;
extern const struct af_info af_info_pan;
extern const struct af_info af_info_surround;
extern const struct af_info af_info_sub;
extern const struct af_info af_info_export;
extern const struct af_info af_info_drc;
extern const struct af_info af_info_extrastereo;
extern const struct af_info af_info_lavcac3enc;
extern const struct af_info af_info_lavrresample;
extern const struct af_info af_info_sweep;
extern const struct af_info af_info_hrtf;
extern const struct af_info af_info_ladspa;
extern const struct af_info af_info_center;
extern const struct af_info af_info_sinesuppress;
extern const struct af_info af_info_karaoke;
extern const struct af_info af_info_scaletempo;
extern const struct af_info af_info_bs2b;
extern const struct af_info af_info_lavfi;
extern const struct af_info af_info_convert24;
extern const struct af_info af_info_convertsignendian;
extern const struct af_info af_info_rubberband;
static const struct af_info *const filter_list[] = {
&af_info_dummy,
&af_info_delay,
&af_info_channels,
&af_info_format,
&af_info_volume,
&af_info_equalizer,
&af_info_pan,
&af_info_surround,
&af_info_sub,
&af_info_export,
&af_info_drc,
&af_info_extrastereo,
&af_info_lavcac3enc,
&af_info_lavrresample,
&af_info_sweep,
&af_info_hrtf,
#if HAVE_LADSPA
&af_info_ladspa,
#endif
#if HAVE_RUBBERBAND
&af_info_rubberband,
#endif
&af_info_center,
&af_info_sinesuppress,
&af_info_karaoke,
&af_info_scaletempo,
#if HAVE_LIBBS2B
&af_info_bs2b,
#endif
#if HAVE_LIBAVFILTER
&af_info_lavfi,
#endif
// Must come last, because they're fallback format conversion filter
&af_info_convert24,
&af_info_convertsignendian,
NULL
};
@@ -155,21 +192,33 @@ static struct af_instance *af_create(struct af_stream *s, char *name,
MP_ERR(s, "Couldn't find audio filter '%s'.\n", name);
return NULL;
}
const struct af_info *info = desc.p;
/* Make sure that the filter is not already in the list if it is
non-reentrant */
if (info->flags & AF_FLAGS_NOT_REENTRANT) {
for (struct af_instance *cur = s->first; cur; cur = cur->next) {
if (cur->info == info) {
MP_ERR(s, "There can only be one "
"instance of the filter '%s' in each stream\n", name);
return NULL;
}
}
}
MP_VERBOSE(s, "Adding filter %s \n", name);
struct af_instance *af = talloc_zero(NULL, struct af_instance);
*af = (struct af_instance) {
.info = desc.p,
.info = info,
.data = talloc_zero(af, struct mp_audio),
.log = mp_log_new(af, s->log, name),
.opts = s->opts,
.replaygain_data = s->replaygain_data,
.out_pool = mp_audio_pool_create(af),
};
struct m_config *config =
m_config_from_obj_desc_and_args(af, s->log, NULL, &desc,
name, s->opts->af_defs, args);
if (!config)
struct m_config *config = m_config_from_obj_desc(af, s->log, &desc);
if (m_config_apply_defaults(config, name, s->opts->af_defs) < 0)
goto error;
if (m_config_set_obj_params(config, args) < 0)
goto error;
af->priv = config->optstruct;
@@ -208,6 +257,29 @@ static struct af_instance *af_prepend(struct af_stream *s,
return new;
}
/* Create and insert a new filter of type name after the filter in the
argument. This function can be called during runtime, the return
value is the new filter */
static struct af_instance *af_append(struct af_stream *s,
struct af_instance *af,
char *name, char **args)
{
if (!af)
af = s->first;
if (af == s->last)
af = s->last->prev;
// Create the new filter and make sure it is OK
struct af_instance *new = af_create(s, name, args);
if (!new)
return NULL;
// Update pointers
new->prev = af;
new->next = af->next;
af->next = new;
new->next->prev = new;
return new;
}
// Uninit and remove the filter "af"
static void af_remove(struct af_stream *s, struct af_instance *af)
{
@@ -250,12 +322,8 @@ static void af_print_filter_chain(struct af_stream *s, struct af_instance *at,
while (af) {
char b[128] = {0};
mp_snprintf_cat(b, sizeof(b), " [%s] ", af->info->name);
if (af->label)
mp_snprintf_cat(b, sizeof(b), "\"%s\" ", af->label);
if (af->data)
mp_snprintf_cat(b, sizeof(b), "%s", mp_audio_config_to_str(af->data));
if (af->auto_inserted)
mp_snprintf_cat(b, sizeof(b), " [a]");
if (af == at)
mp_snprintf_cat(b, sizeof(b), " <-");
MP_MSG(s, msg_level, "%s\n", b);
@@ -266,167 +334,257 @@ static void af_print_filter_chain(struct af_stream *s, struct af_instance *at,
MP_MSG(s, msg_level, " [ao] %s\n", mp_audio_config_to_str(&s->output));
}
static void reset_formats(struct af_stream *s)
static int af_count_filters(struct af_stream *s)
{
struct mp_audio none = {0};
for (struct af_instance *af = s->first; af; af = af->next) {
if (af != s->first && af != s->last)
mp_audio_copy_config(af->data, &none);
}
int count = 0;
for (struct af_instance *af = s->first; af; af = af->next)
count++;
return count;
}
static int filter_reinit(struct af_instance *af)
// Finds the first conversion filter on the way from srcfmt to dstfmt.
// Conversions form a DAG: each node is a format/filter pair, and possible
// conversions are edges. We search the DAG for the shortest path.
// Some cases visit the same filter multiple times, but with different formats
// (like u24le->s8), so one node per format or filter separate is not enough.
// Returns the filter and dest. format for the first conversion step.
// (So we know what conversion filter with what format to insert next.)
static char *af_find_conversion_filter(int srcfmt, int *dstfmt)
{
#define MAX_NODES (64 * 32)
int num_fmt = 0, num_filt = 0;
for (int n = 0; filter_list[n]; n++)
num_filt = n + 1;
for (int n = 0; af_fmtstr_table[n].format; n++)
num_fmt = n + 1;
int num_nodes = num_fmt * num_filt;
assert(num_nodes < MAX_NODES);
bool visited[MAX_NODES] = {0};
unsigned char distance[MAX_NODES];
short previous[MAX_NODES] = {0};
for (int n = 0; n < num_nodes; n++) {
distance[n] = 255;
if (af_fmtstr_table[n % num_fmt].format == srcfmt)
distance[n] = 0;
}
while (1) {
int next = -1;
for (int n = 0; n < num_nodes; n++) {
if (!visited[n] && (next < 0 || (distance[n] < distance[next])))
next = n;
}
if (next < 0 || distance[next] == 255)
return NULL;
visited[next] = true;
int fmt = next % num_fmt;
if (af_fmtstr_table[fmt].format == *dstfmt) {
// Best match found
for (int cur = next; cur >= 0; cur = previous[cur] - 1) {
if (distance[cur] == 1) {
*dstfmt = af_fmtstr_table[cur % num_fmt].format;
return (char *)filter_list[cur / num_fmt]->name;
}
}
return NULL;
}
for (int n = 0; filter_list[n]; n++) {
const struct af_info *af = filter_list[n];
if (!af->test_conversion)
continue;
for (int i = 0; af_fmtstr_table[i].format; i++) {
if (i != fmt && af->test_conversion(af_fmtstr_table[fmt].format,
af_fmtstr_table[i].format))
{
int other = n * num_fmt + i;
int ndist = distance[next] + 1;
if (ndist < distance[other]) {
distance[other] = ndist;
previous[other] = next + 1;
}
}
}
}
}
assert(0);
#undef MAX_NODES
}
static bool af_is_conversion_filter(struct af_instance *af)
{
return af && af->info->test_conversion != NULL;
}
// in is what af can take as input - insert a conversion filter if the actual
// input format doesn't match what af expects.
// Returns:
// AF_OK: must call af_reinit() or equivalent, format matches (or is closer)
// AF_FALSE: nothing was changed, format matches
// else: error
static int af_fix_format_conversion(struct af_stream *s,
struct af_instance **p_af,
struct mp_audio in)
{
int rv;
struct af_instance *af = *p_af;
struct af_instance *prev = af->prev;
assert(prev);
// Check if this is the first filter
struct mp_audio in = *prev->data;
// Reset just in case...
mp_audio_set_null_data(&in);
if (!mp_audio_config_valid(&in))
struct mp_audio actual = *prev->data;
if (actual.format == in.format)
return AF_FALSE;
int dstfmt = in.format;
char *filter = af_find_conversion_filter(actual.format, &dstfmt);
if (!filter)
return AF_ERROR;
af->fmt_in = in;
int rv = af->control(af, AF_CONTROL_REINIT, &in);
if (rv == AF_OK && !mp_audio_config_equals(&in, prev->data))
rv = AF_FALSE; // conversion filter needed
if (rv == AF_FALSE)
af->fmt_in = in;
if (rv == AF_OK) {
if (!mp_audio_config_valid(af->data))
return AF_ERROR;
af->fmt_out = *af->data;
}
return rv;
}
static int filter_reinit_with_conversion(struct af_stream *s, struct af_instance *af)
{
int rv = filter_reinit(af);
// Conversion filter is needed
if (rv == AF_FALSE) {
// First try if we can change the output format of the previous
// filter to the input format the current filter is expecting.
struct mp_audio in = af->fmt_in;
if (af->prev != s->first && !mp_audio_config_equals(af->prev->data, &in)) {
// This should have been successful (because it succeeded
// before), even if just reverting to the old output format.
mp_audio_copy_config(af->prev->data, &in);
rv = filter_reinit(af->prev);
if (rv != AF_OK)
return rv;
if (strcmp(filter, prev->info->name) == 0) {
if (prev->control(prev, AF_CONTROL_SET_FORMAT, &dstfmt) == AF_OK) {
*p_af = prev;
return AF_OK;
}
if (!mp_audio_config_equals(af->prev->data, &in)) {
// Retry with conversion filter added.
struct af_instance *new =
af_prepend(s, af, "lavrresample", NULL);
if (!new)
return AF_ERROR;
new->auto_inserted = true;
mp_audio_copy_config(new->data, &in);
rv = filter_reinit(new);
if (rv != AF_OK)
af_remove(s, new);
}
if (rv == AF_OK)
rv = filter_reinit(af);
}
return rv;
}
static int af_find_output_conversion(struct af_stream *s, struct mp_audio *cfg)
{
assert(mp_audio_config_valid(&s->output));
assert(s->initialized > 0);
if (mp_chmap_equals_reordered(&s->input.channels, &s->output.channels))
struct af_instance *new = af_prepend(s, af, filter, NULL);
if (new == NULL)
return AF_ERROR;
// Heuristic to detect point of conversion. If it looks like something
// more complicated is going on, better bail out.
// We expect that the last filter converts channels.
struct af_instance *conv = s->last->prev;
if (!conv->auto_inserted)
return AF_ERROR;
if (!(mp_chmap_equals_reordered(&conv->fmt_in.channels, &s->input.channels) &&
mp_chmap_equals_reordered(&conv->fmt_out.channels, &s->output.channels)))
return AF_ERROR;
// Also, should be the only one which does auto conversion.
for (struct af_instance *af = s->first->next; af != s->last; af = af->next)
{
if (af != conv && af->auto_inserted &&
!mp_chmap_equals_reordered(&af->fmt_in.channels, &af->fmt_out.channels))
return AF_ERROR;
}
// And not if it's the only filter.
if (conv->prev == s->first && conv->next == s->last)
return AF_ERROR;
*cfg = s->output;
new->auto_inserted = true;
if (AF_OK != (rv = new->control(new, AF_CONTROL_SET_FORMAT, &dstfmt)))
return rv;
*p_af = new;
return AF_OK;
}
// Return AF_OK on success or AF_ERROR on failure.
static int af_do_reinit(struct af_stream *s, bool second_pass)
// same as af_fix_format_conversion - only wrt. channels
static int af_fix_channels(struct af_stream *s, struct af_instance **p_af,
struct mp_audio in)
{
struct mp_audio convert_early = {0};
if (second_pass) {
// If a channel conversion happens, and it is done by an auto-inserted
// filter, then insert a filter to convert it early. Otherwise, do
// nothing and return immediately.
if (af_find_output_conversion(s, &convert_early) != AF_OK)
return AF_OK;
int rv;
struct af_instance *af = *p_af;
struct af_instance *prev = af->prev;
struct mp_audio actual = *prev->data;
if (mp_chmap_equals(&actual.channels, &in.channels))
return AF_FALSE;
if (prev->control(prev, AF_CONTROL_SET_CHANNELS, &in.channels) == AF_OK) {
*p_af = prev;
return AF_OK;
}
char *filter = "lavrresample";
struct af_instance *new = af_prepend(s, af, filter, NULL);
if (new == NULL)
return AF_ERROR;
new->auto_inserted = true;
if (AF_OK != (rv = new->control(new, AF_CONTROL_SET_CHANNELS, &in.channels)))
return rv;
*p_af = new;
return AF_OK;
}
static int af_fix_rate(struct af_stream *s, struct af_instance **p_af,
struct mp_audio in)
{
int rv;
struct af_instance *af = *p_af;
struct af_instance *prev = af->prev;
struct mp_audio actual = *prev->data;
if (actual.rate == in.rate)
return AF_FALSE;
if (prev->control(prev, AF_CONTROL_SET_RESAMPLE_RATE, &in.rate) == AF_OK) {
*p_af = prev;
return AF_OK;
}
char *filter = "lavrresample";
struct af_instance *new = af_prepend(s, af, filter, NULL);
if (new == NULL)
return AF_ERROR;
new->auto_inserted = true;
if (AF_OK != (rv = new->control(new, AF_CONTROL_SET_RESAMPLE_RATE, &in.rate)))
return rv;
*p_af = new;
return AF_OK;
}
static void reset_formats(struct af_stream *s)
{
for (struct af_instance *af = s->first; af; af = af->next) {
af->control(af, AF_CONTROL_SET_RESAMPLE_RATE, &(int){0});
af->control(af, AF_CONTROL_SET_CHANNELS, &(struct mp_chmap){0});
af->control(af, AF_CONTROL_SET_FORMAT, &(int){0});
}
}
// Return AF_OK on success or AF_ERROR on failure.
// Warning:
// A failed af_reinit() leaves the audio chain behind in a useless, broken
// state (for example, format filters that were tentatively inserted stay
// inserted).
// In that case, you should always rebuild the filter chain, or abort.
static int af_reinit(struct af_stream *s)
{
remove_auto_inserted_filters(s);
af_chain_forget_frames(s);
reset_formats(s);
s->first->fmt_in = s->first->fmt_out = s->input;
if (mp_audio_config_valid(&convert_early)) {
struct af_instance *new = af_prepend(s, s->first, "lavrresample", NULL);
if (!new)
return AF_ERROR;
new->auto_inserted = true;
mp_audio_copy_config(new->data, &convert_early);
int rv = filter_reinit(new);
if (rv != AF_DETACH && rv != AF_OK)
return AF_ERROR;
MP_VERBOSE(s, "Moving up output conversion.\n");
}
// Start with the second filter, as the first filter is the special input
// filter which needs no initialization.
struct af_instance *af = s->first->next;
// Up to 7 retries per filter (channel, rate, 5x format conversions)
int max_retry = af_count_filters(s) * 7;
int retry = 0;
while (af) {
int rv = filter_reinit_with_conversion(s, af);
if (retry >= max_retry)
goto negotiate_error;
// Check if this is the first filter
struct mp_audio in = *af->prev->data;
// Reset just in case...
mp_audio_set_null_data(&in);
if (!mp_audio_config_valid(&in))
goto error;
af->fmt_in = in;
int rv = af->control(af, AF_CONTROL_REINIT, &in);
if (rv == AF_OK && !mp_audio_config_equals(&in, af->prev->data))
rv = AF_FALSE; // conversion filter needed
switch (rv) {
case AF_OK:
if (!mp_audio_config_valid(af->data))
goto error;
af->fmt_out = *af->data;
af = af->next;
break;
case AF_FALSE: {
case AF_FALSE: { // Configuration filter is needed
if (af_fix_channels(s, &af, in) == AF_OK) {
retry++;
continue;
}
if (af_fix_rate(s, &af, in) == AF_OK) {
retry++;
continue;
}
// Do this last, to prevent "format->lavrresample" being added to
// the filter chain when output formats not supported by
// af_lavrresample are in use.
if (af_fix_format_conversion(s, &af, in) == AF_OK) {
retry++;
continue;
}
// If the format conversion is (probably) caused by spdif, then
// (as a feature) drop the filter, instead of failing hard.
int fmt_in1 = af->prev->data->format;
int fmt_in2 = af->fmt_in.format;
int fmt_in2 = in.format;
if (af_fmt_is_valid(fmt_in1) && af_fmt_is_valid(fmt_in2)) {
bool spd1 = af_fmt_is_spdif(fmt_in1);
bool spd2 = af_fmt_is_spdif(fmt_in2);
if (spd1 != spd2 && af->next) {
bool spd1 = AF_FORMAT_IS_IEC61937(fmt_in1);
bool spd2 = AF_FORMAT_IS_IEC61937(fmt_in2);
if (spd1 != spd2) {
MP_WARN(af, "Filter %s apparently cannot be used due to "
"spdif passthrough - removing it.\n",
af->info->name);
struct af_instance *aft = af->prev;
af_remove(s, af);
af = aft->next;
continue;
break;
}
}
goto negotiate_error;
@@ -466,19 +624,6 @@ error:
return AF_ERROR;
}
static int af_reinit(struct af_stream *s)
{
int r = af_do_reinit(s, false);
if (r == AF_OK && mp_audio_config_valid(&s->output)) {
r = af_do_reinit(s, true);
if (r != AF_OK) {
MP_ERR(s, "Failed second pass filter negotiation.\n");
r = af_do_reinit(s, false);
}
}
return r;
}
// Uninit and remove all filters
void af_uninit(struct af_stream *s)
{
@@ -533,7 +678,7 @@ void af_destroy(struct af_stream *s)
format of the preferred output respectively. The function is
reentrant i.e. if called with an already initialized stream the
stream will be reinitialized.
If one of the preferred output parameters is 0 the one that needs
If one of the prefered output parameters is 0 the one that needs
no conversion is used (i.e. the output format in the last filter).
The return value is 0 if success and -1 if failure */
int af_init(struct af_stream *s)
@@ -578,12 +723,17 @@ struct af_instance *af_add(struct af_stream *s, char *name, char *label,
if (af_find_by_label(s, label))
return NULL;
struct af_instance *new = af_prepend(s, s->last, name, args);
struct af_instance *new;
// Insert the filter somewhere nice
if (af_is_conversion_filter(s->first->next))
new = af_append(s, s->first->next, name, args);
else
new = af_prepend(s, s->first->next, name, args);
if (!new)
return NULL;
new->label = talloc_strdup(new, label);
// Reinitialize the filter list
// Reinitalize the filter list
if (af_reinit(s) != AF_OK) {
af_remove_by_label(s, label);
return NULL;
@@ -653,29 +803,6 @@ void af_control_all(struct af_stream *s, int cmd, void *arg)
af->control(af, cmd, arg);
}
int af_control_by_label(struct af_stream *s, int cmd, void *arg, bstr label)
{
char *label_str = bstrdup0(NULL, label);
struct af_instance *cur = af_find_by_label(s, label_str);
talloc_free(label_str);
if (cur) {
return cur->control ? cur->control(cur, cmd, arg) : CONTROL_NA;
} else {
return CONTROL_UNKNOWN;
}
}
int af_send_command(struct af_stream *s, char *label, char *cmd, char *arg)
{
char *args[2] = {cmd, arg};
if (strcmp(label, "all") == 0) {
af_control_all(s, AF_CONTROL_COMMAND, args);
return 0;
} else {
return af_control_by_label(s, AF_CONTROL_COMMAND, args, bstr0(label));
}
}
// Used by filters to add a filtered frame to the output queue.
// Ownership of frame is transferred from caller to the filter chain.
void af_add_output_frame(struct af_instance *af, struct mp_audio *frame)
@@ -705,16 +832,6 @@ static struct mp_audio *af_dequeue_output_frame(struct af_instance *af)
return res;
}
static void read_remaining(struct af_instance *af)
{
int num_frames;
do {
num_frames = af->num_out_queued;
if (!af->filter_out || af->filter_out(af) < 0)
break;
} while (num_frames != af->num_out_queued);
}
static int af_do_filter(struct af_instance *af, struct mp_audio *frame)
{
if (frame)
@@ -754,7 +871,6 @@ int af_output_frame(struct af_stream *s, bool eof)
// Flush remaining frames on EOF, but do that only if the previous
// filters have been flushed (i.e. they have no more output).
if (eof && !last) {
read_remaining(cur);
int r = af_do_filter(cur, NULL);
if (r < 0)
return r;
@@ -779,12 +895,6 @@ struct mp_audio *af_read_output_frame(struct af_stream *s)
return af_dequeue_output_frame(s->last);
}
void af_unread_output_frame(struct af_stream *s, struct mp_audio *frame)
{
struct af_instance *af = s->last;
MP_TARRAY_INSERT_AT(af, af->out_queued, af->num_out_queued, 0, frame);
}
// Make sure the caller can change data referenced by the frame.
// Return negative error code on failure (i.e. you can't write).
int af_make_writeable(struct af_instance *af, struct mp_audio *frame)
+17 -13
View File
@@ -27,7 +27,6 @@
#include "audio/chmap.h"
#include "audio/audio.h"
#include "common/msg.h"
#include "common/common.h"
struct af_instance;
struct mpv_global;
@@ -35,6 +34,10 @@ struct mpv_global;
// Number of channels
#define AF_NCH MP_NUM_CHANNELS
// Flags used for defining the behavior of an audio filter
#define AF_FLAGS_REENTRANT 0x00000000
#define AF_FLAGS_NOT_REENTRANT 0x00000001
// Flags for af->filter()
#define AF_FILTER_FLAG_EOF 1
@@ -43,7 +46,9 @@ struct mpv_global;
struct af_info {
const char *info;
const char *name;
const int flags;
int (*open)(struct af_instance *vf);
bool (*test_conversion)(int src_format, int dst_format);
int priv_size;
const void *priv_defaults;
const struct m_option *options;
@@ -53,7 +58,6 @@ struct af_info {
struct af_instance {
const struct af_info *info;
struct mp_log *log;
struct MPOpts *opts;
struct replaygain_data *replaygain_data;
int (*control)(struct af_instance *af, int cmd, void *arg);
void (*uninit)(struct af_instance *af);
@@ -101,17 +105,21 @@ struct af_stream {
};
// Return values
#define AF_DETACH (CONTROL_OK + 1)
#define AF_OK CONTROL_OK
#define AF_TRUE CONTROL_TRUE
#define AF_FALSE CONTROL_FALSE
#define AF_UNKNOWN CONTROL_UNKNOWN
#define AF_ERROR CONTROL_ERROR
#define AF_DETACH 2
#define AF_OK 1
#define AF_TRUE 1
#define AF_FALSE 0
#define AF_UNKNOWN -1
#define AF_ERROR -2
#define AF_FATAL -3
// Parameters for af_control_*
enum af_control {
AF_CONTROL_REINIT = 1,
AF_CONTROL_RESET,
AF_CONTROL_SET_RESAMPLE_RATE,
AF_CONTROL_SET_FORMAT,
AF_CONTROL_SET_CHANNELS,
AF_CONTROL_SET_VOLUME,
AF_CONTROL_GET_VOLUME,
AF_CONTROL_SET_PAN_LEVEL,
@@ -120,8 +128,6 @@ enum af_control {
AF_CONTROL_GET_PAN_BALANCE,
AF_CONTROL_SET_PLAYBACK_SPEED,
AF_CONTROL_SET_PLAYBACK_SPEED_RESAMPLE,
AF_CONTROL_GET_METADATA,
AF_CONTROL_COMMAND,
};
// Argument for AF_CONTROL_SET_PAN_LEVEL
@@ -140,21 +146,19 @@ int af_remove_by_label(struct af_stream *s, char *label);
struct af_instance *af_find_by_label(struct af_stream *s, char *label);
struct af_instance *af_control_any_rev(struct af_stream *s, int cmd, void *arg);
void af_control_all(struct af_stream *s, int cmd, void *arg);
int af_control_by_label(struct af_stream *s, int cmd, void *arg, bstr label);
void af_seek_reset(struct af_stream *s);
int af_send_command(struct af_stream *s, char *label, char *cmd, char *arg);
void af_add_output_frame(struct af_instance *af, struct mp_audio *frame);
int af_filter_frame(struct af_stream *s, struct mp_audio *frame);
int af_output_frame(struct af_stream *s, bool eof);
struct mp_audio *af_read_output_frame(struct af_stream *s);
void af_unread_output_frame(struct af_stream *s, struct mp_audio *frame);
int af_make_writeable(struct af_instance *af, struct mp_audio *frame);
double af_calc_delay(struct af_stream *s);
int af_test_output(struct af_instance *af, struct mp_audio *out);
int af_from_dB(int n, float *in, float *out, float k, float mi, float ma);
int af_from_ms(int n, float *in, int *out, int rate, float mi, float ma);
float af_softclip(float a);
+172
View File
@@ -0,0 +1,172 @@
/*
* The Bauer stereophonic-to-binaural DSP using bs2b library:
* http://bs2b.sourceforge.net/
*
* Copyright (c) 2009 Andrew Savchenko
*
* 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 <bs2b.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include "af.h"
#include "options/m_option.h"
/// Internal specific data of the filter
struct af_bs2b {
int fcut; ///< cut frequency in Hz
int feed; ///< feed level for low frequencies in 0.1*dB
int profile ; ///< profile (available crossfeed presets)
t_bs2bdp filter; ///< instance of a library filter
};
#define DEF_FILTER(fmt, name) \
static int filter_##name(struct af_instance *af, struct mp_audio *data) \
{ \
if (!data) \
return 0; \
if (af_make_writeable(af, data) < 0) { \
talloc_free(data); \
return -1; \
} \
bs2b_cross_feed_##name(((struct af_bs2b*)(af->priv))->filter, \
(data->planes[0]), data->samples); \
af_add_output_frame(af, data); \
return 0; \
}
#define GET_FILTER(fmt, name) \
case AF_FORMAT_##fmt: return filter_##name;
#define FILTERS \
FILTER(FLOAT, f) \
FILTER(S32, s32) \
FILTER(U32, u32) \
FILTER(S24, s24) \
FILTER(U24, u24) \
FILTER(S16, s16) \
FILTER(U16, u16) \
FILTER(S8, s8) \
FILTER(U8, u8)
#define FILTER DEF_FILTER
FILTERS
#undef FILTER
typedef int (*filter)(struct af_instance *af, struct mp_audio *d);
static filter get_filter(int fmt)
{
switch (fmt) {
#define FILTER GET_FILTER
FILTERS
#undef FILTER
default: return NULL;
}
}
/// Initialization and runtime control
static int control(struct af_instance *af, int cmd, void *arg)
{
struct af_bs2b *s = af->priv;
switch (cmd) {
case AF_CONTROL_REINIT: {
int format;
// Sanity check
if (!arg) return AF_ERROR;
format = ((struct mp_audio*)arg)->format;
af->data->rate = ((struct mp_audio*)arg)->rate;
mp_audio_set_num_channels(af->data, 2); // bs2b is useful only for 2ch audio
mp_audio_set_format(af->data, format);
/* check for formats supported by libbs2b
and assign corresponding handlers */
af->filter_frame = get_filter(format);
if (!af->filter_frame) {
af->filter_frame = filter_f;
mp_audio_set_format(af->data, AF_FORMAT_FLOAT);
}
// bs2b have srate limits, try to resample if needed
if (af->data->rate > BS2B_MAXSRATE || af->data->rate < BS2B_MINSRATE) {
af->data->rate = BS2B_DEFAULT_SRATE;
MP_WARN(af, "Requested sample rate %d Hz is out of bounds [%d..%d] Hz.\n"
"Trying to resample to %d Hz.\n",
af->data->rate, BS2B_MINSRATE, BS2B_MAXSRATE, BS2B_DEFAULT_SRATE);
}
bs2b_set_srate(s->filter, (long)af->data->rate);
MP_VERBOSE(af, "using format %s\n",
af_fmt_to_str(af->data->format));
return af_test_output(af,(struct mp_audio*)arg);
}
}
return AF_UNKNOWN;
}
/// Deallocate memory and close library
static void uninit(struct af_instance *af)
{
struct af_bs2b *s = af->priv;
if (s->filter)
bs2b_close(s->filter);
}
/// Allocate memory, set function pointers and init library
static int af_open(struct af_instance *af)
{
struct af_bs2b *s = af->priv;
af->control = control;
af->uninit = uninit;
// NULL means failed initialization
if (!(s->filter = bs2b_open())) {
return AF_ERROR;
}
if (s->profile)
bs2b_set_level(s->filter, s->profile);
// set fcut and feed only if specified, otherwise defaults will be used
if (s->fcut)
bs2b_set_level_fcut(s->filter, s->fcut);
if (s->feed)
bs2b_set_level_feed(s->filter, s->feed);
return AF_OK;
}
#define OPT_BASE_STRUCT struct af_bs2b
/// Description of this filter
const struct af_info af_info_bs2b = {
.info = "Bauer stereophonic-to-binaural audio filter",
.name = "bs2b",
.open = af_open,
.priv_size = sizeof(struct af_bs2b),
.options = (const struct m_option[]) {
OPT_INTRANGE("fcut", fcut, 0, BS2B_MINFCUT, BS2B_MAXFCUT),
OPT_INTRANGE("feed", feed, 0, BS2B_MINFEED, BS2B_MAXFEED),
OPT_CHOICE("profile", profile, 0,
({"unset", 0},
{"default", BS2B_DEFAULT_CLEVEL},
{"cmoy", BS2B_CMOY_CLEVEL},
{"jmeier", BS2B_JMEIER_CLEVEL})),
{0}
},
};
+104
View File
@@ -0,0 +1,104 @@
/*
* This filter adds a center channel to the audio stream by
* averaging the left and right channel.
* There are two runtime controls one for setting which channel
* to insert the center-audio into called AF_CONTROL_SUB_CH.
*
* FIXME: implement a high-pass filter for better results.
*
* copyright (c) 2005 Alex Beregszaszi
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "common/common.h"
#include "af.h"
// Data for specific instances of this filter
typedef struct af_center_s
{
int ch; // Channel number which to insert the filtered data
}af_center_t;
// Initialization and runtime control
static int control(struct af_instance* af, int cmd, void* arg)
{
af_center_t* s = af->priv;
switch(cmd){
case AF_CONTROL_REINIT:{
// Sanity check
if(!arg) return AF_ERROR;
af->data->rate = ((struct mp_audio*)arg)->rate;
mp_audio_set_channels_old(af->data, MPMAX(s->ch+1,((struct mp_audio*)arg)->nch));
mp_audio_set_format(af->data, AF_FORMAT_FLOAT);
return af_test_output(af,(struct mp_audio*)arg);
}
}
return AF_UNKNOWN;
}
static int filter_frame(struct af_instance* af, struct mp_audio* data)
{
if (!data)
return 0;
if (af_make_writeable(af, data) < 0) {
talloc_free(data);
return -1;
}
struct mp_audio* c = data; // Current working data
af_center_t* s = af->priv; // Setup for this instance
float* a = c->planes[0]; // Audio data
int nch = c->nch; // Number of channels
int len = c->samples*c->nch; // Number of samples in current audio block
int ch = s->ch; // Channel in which to insert the center audio
register int i;
// Run filter
for(i=0;i<len;i+=nch){
// Average left and right
a[i+ch] = (a[i]/2) + (a[i+1]/2);
}
af_add_output_frame(af, data);
return 0;
}
// Allocate memory and set function pointers
static int af_open(struct af_instance* af){
af->control=control;
af->filter_frame = filter_frame;
return AF_OK;
}
#define OPT_BASE_STRUCT af_center_t
const struct af_info af_info_center = {
.info = "Audio filter for adding a center channel",
.name = "center",
.flags = AF_FLAGS_NOT_REENTRANT,
.open = af_open,
.priv_size = sizeof(af_center_t),
.options = (const struct m_option[]) {
OPT_INTRANGE("channel", ch, 0, 0, AF_NCH - 1, OPTDEF_INT(1)),
{0}
},
};
+122
View File
@@ -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 <assert.h>
#include "audio/format.h"
#include "af.h"
#include "osdep/endian.h"
static bool test_conversion(int src_format, int dst_format)
{
return (src_format == AF_FORMAT_U24 && dst_format == AF_FORMAT_U32) ||
(src_format == AF_FORMAT_S24 && dst_format == AF_FORMAT_S32) ||
(src_format == AF_FORMAT_U32 && dst_format == AF_FORMAT_U24) ||
(src_format == AF_FORMAT_S32 && dst_format == AF_FORMAT_S24);
}
static int control(struct af_instance *af, int cmd, void *arg)
{
switch (cmd) {
case AF_CONTROL_REINIT: {
struct mp_audio *in = arg;
struct mp_audio orig_in = *in;
struct mp_audio *out = af->data;
if (!test_conversion(in->format, out->format))
return AF_DETACH;
if ((in->format & AF_FORMAT_BITS_MASK) == AF_FORMAT_24BIT) {
mp_audio_set_format(out, af_fmt_change_bits(in->format, 32));
} else if ((in->format & AF_FORMAT_BITS_MASK) == AF_FORMAT_32BIT) {
mp_audio_set_format(out, af_fmt_change_bits(in->format, 24));
} else {
abort();
}
out->rate = in->rate;
mp_audio_set_channels(out, &in->channels);
assert(test_conversion(in->format, out->format));
return mp_audio_config_equals(in, &orig_in) ? AF_OK : AF_FALSE;
}
case AF_CONTROL_SET_FORMAT: {
mp_audio_set_format(af->data, *(int*)arg);
return AF_OK;
}
}
return AF_UNKNOWN;
}
// The LSB is always ignored.
#if BYTE_ORDER == BIG_ENDIAN
#define SHIFT(x) ((3-(x))*8)
#else
#define SHIFT(x) (((x)+1)*8)
#endif
static int filter(struct af_instance *af, struct mp_audio *data)
{
if (!data)
return 0;
struct mp_audio *out =
mp_audio_pool_get(af->out_pool, af->data, data->samples);
if (!out) {
talloc_free(data);
return -1;
}
mp_audio_copy_attributes(out, data);
size_t len = mp_audio_psize(data) / data->bps;
if (data->bps == 4) {
for (int s = 0; s < len; s++) {
uint32_t val = *((uint32_t *)data->planes[0] + s);
uint8_t *ptr = (uint8_t *)out->planes[0] + s * 3;
ptr[0] = val >> SHIFT(0);
ptr[1] = val >> SHIFT(1);
ptr[2] = val >> SHIFT(2);
}
} else {
for (int s = 0; s < len; s++) {
uint8_t *ptr = (uint8_t *)data->planes[0] + s * 3;
uint32_t val = ptr[0] << SHIFT(0)
| ptr[1] << SHIFT(1)
| ptr[2] << SHIFT(2);
*((uint32_t *)out->planes[0] + s) = val;
}
}
talloc_free(data);
af_add_output_frame(af, out);
return 0;
}
static int af_open(struct af_instance *af)
{
af->control = control;
af->filter_frame = filter;
return AF_OK;
}
const struct af_info af_info_convert24 = {
.info = "Convert between 24 and 32 bit sample format",
.name = "convert24",
.open = af_open,
.test_conversion = test_conversion,
};
+107
View File
@@ -0,0 +1,107 @@
/*
* 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 <assert.h>
#include "af.h"
#include "audio/format.h"
#include "osdep/endian.h"
static bool test_conversion(int src_format, int dst_format)
{
if ((src_format & AF_FORMAT_PLANAR) ||
(dst_format & AF_FORMAT_PLANAR))
return false;
if (((src_format & ~AF_FORMAT_SIGN_MASK) ==
(dst_format & ~AF_FORMAT_SIGN_MASK)) &&
((src_format & AF_FORMAT_TYPE_MASK) == AF_FORMAT_I))
return true;
return false;
}
static int control(struct af_instance *af, int cmd, void *arg)
{
switch (cmd) {
case AF_CONTROL_REINIT: {
struct mp_audio *in = arg;
struct mp_audio orig_in = *in;
struct mp_audio *out = af->data;
if (!test_conversion(in->format, out->format))
return AF_DETACH;
out->rate = in->rate;
mp_audio_set_channels(out, &in->channels);
return mp_audio_config_equals(in, &orig_in) ? AF_OK : AF_FALSE;
}
case AF_CONTROL_SET_FORMAT: {
mp_audio_set_format(af->data, *(int*)arg);
return AF_OK;
}
}
return AF_UNKNOWN;
}
static void si2us(void *data, int len, int bps)
{
ptrdiff_t i = -(len * bps);
uint8_t *p = &((uint8_t *)data)[len * bps];
if (BYTE_ORDER == LITTLE_ENDIAN && bps > 1)
p += bps - 1;
if (len <= 0)
return;
do {
p[i] ^= 0x80;
} while (i += bps);
}
static int filter(struct af_instance *af, struct mp_audio *data)
{
if (!data)
return 0;
if (af_make_writeable(af, data) < 0) {
talloc_free(data);
return -1;
}
int infmt = data->format;
int outfmt = af->data->format;
size_t len = data->samples * data->nch;
if ((infmt & AF_FORMAT_SIGN_MASK) != (outfmt & AF_FORMAT_SIGN_MASK))
si2us(data->planes[0], len, data->bps);
mp_audio_set_format(data, outfmt);
af_add_output_frame(af, data);
return 0;
}
static int af_open(struct af_instance *af)
{
af->control = control;
af->filter_frame = filter;
return AF_OK;
}
const struct af_info af_info_convertsignendian = {
.info = "Convert between sample format sign",
.name = "convertsign",
.open = af_open,
.test_conversion = test_conversion,
};
+194
View File
@@ -0,0 +1,194 @@
/*
* This audio filter delays the output signal for the different
* channels and can be used for simple position panning.
* An extension for this filter would be a reverb.
*
* Original author: Anders
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "common/common.h"
#include "af.h"
#define L 65536
#define UPDATEQI(qi) qi=(qi+1)&(L-1)
// Data for specific instances of this filter
typedef struct af_delay_s
{
void* q[AF_NCH]; // Circular queues used for delaying audio signal
int wi[AF_NCH]; // Write index
int ri; // Read index
float d[AF_NCH]; // Delay [ms]
char *delaystr;
}af_delay_t;
// Initialization and runtime control
static int control(struct af_instance* af, int cmd, void* arg)
{
af_delay_t* s = af->priv;
switch(cmd){
case AF_CONTROL_REINIT:{
int i;
struct mp_audio *in = arg;
if (in->bps != 1 && in->bps != 2 && in->bps != 4) {
MP_FATAL(af, "Sample format not supported\n");
return AF_ERROR;
}
// Free prevous delay queues
for(i=0;i<af->data->nch;i++)
free(s->q[i]);
mp_audio_force_interleaved_format(in);
mp_audio_copy_config(af->data, in);
// Allocate new delay queues
for(i=0;i<af->data->nch;i++){
s->q[i] = calloc(L,af->data->bps);
if(NULL == s->q[i])
MP_FATAL(af, "Out of memory\n");
}
if(AF_OK != af_from_ms(AF_NCH, s->d, s->wi, af->data->rate, 0.0, 1000.0))
return AF_ERROR;
s->ri = 0;
for(i=0;i<AF_NCH;i++){
MP_DBG(af, "Channel %i delayed by %0.3fms\n",
i,MPCLAMP(s->d[i],0.0,1000.0));
MP_TRACE(af, "Channel %i delayed by %i samples\n",
i,s->wi[i]);
}
return AF_OK;
}
}
return AF_UNKNOWN;
}
// Deallocate memory
static void uninit(struct af_instance* af)
{
int i;
for(i=0;i<AF_NCH;i++)
free(((af_delay_t*)(af->priv))->q[i]);
}
static int filter_frame(struct af_instance *af, struct mp_audio *c)
{
if (!c)
return 0;
af_delay_t* s = af->priv; // Setup for this instance
int nch = c->nch; // Number of channels
int len = mp_audio_psize(c)/c->bps; // Number of sample in data chunk
int ri = 0;
int ch,i;
if (af_make_writeable(af, c) < 0) {
talloc_free(c);
return -1;
}
for(ch=0;ch<nch;ch++){
switch(c->bps){
case 1:{
int8_t* a = c->planes[0];
int8_t* q = s->q[ch];
int wi = s->wi[ch];
ri = s->ri;
for(i=ch;i<len;i+=nch){
q[wi] = a[i];
a[i] = q[ri];
UPDATEQI(wi);
UPDATEQI(ri);
}
s->wi[ch] = wi;
break;
}
case 2:{
int16_t* a = c->planes[0];
int16_t* q = s->q[ch];
int wi = s->wi[ch];
ri = s->ri;
for(i=ch;i<len;i+=nch){
q[wi] = a[i];
a[i] = q[ri];
UPDATEQI(wi);
UPDATEQI(ri);
}
s->wi[ch] = wi;
break;
}
case 4:{
int32_t* a = c->planes[0];
int32_t* q = s->q[ch];
int wi = s->wi[ch];
ri = s->ri;
for(i=ch;i<len;i+=nch){
q[wi] = a[i];
a[i] = q[ri];
UPDATEQI(wi);
UPDATEQI(ri);
}
s->wi[ch] = wi;
break;
}
}
}
s->ri = ri;
af_add_output_frame(af, c);
return 0;
}
// Allocate memory and set function pointers
static int af_open(struct af_instance* af){
af->control=control;
af->uninit=uninit;
af->filter_frame = filter_frame;
af_delay_t *s = af->priv;
int n = 1;
int i = 0;
char* cl = s->delaystr;
while(cl && n && i < AF_NCH ){
sscanf(cl,"%f%n",&s->d[i],&n);
if(n==0 || cl[n-1] == '\0')
break;
cl=&cl[n];
if (*cl != ',')
break;
cl++;
i++;
}
return AF_OK;
}
#define OPT_BASE_STRUCT af_delay_t
const struct af_info af_info_delay = {
.info = "Delay audio filter",
.name = "delay",
.open = af_open,
.priv_size = sizeof(af_delay_t),
.options = (const struct m_option[]) {
OPT_STRING("delays", delaystr, 0),
{0}
},
};
+5 -4
View File
@@ -131,7 +131,7 @@ static void method1_int16(af_drc_t *s, struct mp_audio *c)
data[i] = tmp;
}
// Evaluation of newavg (not 100% accurate because of values clamping)
// Evaulation of newavg (not 100% accurate because of values clamping)
newavg = s->mul * curavg;
// Stores computed values for future smoothing
@@ -168,7 +168,7 @@ static void method1_float(af_drc_t *s, struct mp_audio *c)
for (i = 0; i < len; i++)
data[i] *= s->mul;
// Evaluation of newavg (not 100% accurate because of values clamping)
// Evaulation of newavg (not 100% accurate because of values clamping)
newavg = s->mul * curavg;
// Stores computed values for future smoothing
@@ -216,7 +216,7 @@ static void method2_int16(af_drc_t *s, struct mp_audio *c)
data[i] = tmp;
}
// Evaluation of newavg (not 100% accurate because of values clamping)
// Evaulation of newavg (not 100% accurate because of values clamping)
newavg = s->mul * curavg;
// Stores computed values for future smoothing
@@ -262,7 +262,7 @@ static void method2_float(af_drc_t *s, struct mp_audio *c)
for (i = 0; i < len; i++)
data[i] *= s->mul;
// Evaluation of newavg (not 100% accurate because of values clamping)
// Evaulation of newavg (not 100% accurate because of values clamping)
newavg = s->mul * curavg;
// Stores computed values for future smoothing
@@ -324,6 +324,7 @@ static int af_open(struct af_instance* af){
const struct af_info af_info_drc = {
.info = "Dynamic range compression filter",
.name = "drc",
.flags = AF_FLAGS_NOT_REENTRANT,
.open = af_open,
.priv_size = sizeof(af_drc_t),
.options = (const struct m_option[]) {
+61
View File
@@ -0,0 +1,61 @@
/*
* The name speaks for itself. This filter is a dummy and will
* not blow up regardless of what you do with it.
*
* Original author: Anders
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "af.h"
// Initialization and runtime control
static int control(struct af_instance* af, int cmd, void* arg)
{
switch(cmd){
case AF_CONTROL_REINIT: ;
*af->data = *(struct mp_audio*)arg;
MP_VERBOSE(af, "Was reinitialized: %iHz/%ich/%s\n",
af->data->rate,af->data->nch,af_fmt_to_str(af->data->format));
return AF_OK;
}
return AF_UNKNOWN;
}
// Filter data through filter
static int filter(struct af_instance* af, struct mp_audio* data)
{
af_add_output_frame(af, data);
return 0;
}
// Allocate memory and set function pointers
static int af_open(struct af_instance* af){
af->control=control;
af->filter_frame=filter;
return AF_OK;
}
// Description of this filter
const struct af_info af_info_dummy = {
.info = "dummy",
.name = "dummy",
.open = af_open,
};
+1
View File
@@ -203,6 +203,7 @@ static int af_open(struct af_instance* af){
const struct af_info af_info_equalizer = {
.info = "Equalizer audio filter",
.name = "equalizer",
.flags = AF_FLAGS_NOT_REENTRANT,
.open = af_open,
.priv_size = sizeof(af_equalizer_t),
.options = (const struct m_option[]) {
+237
View File
@@ -0,0 +1,237 @@
/*
* This audio filter exports the incoming signal to other processes
* using memory mapping. The memory mapped area contains a header:
* int nch,
* int size,
* unsigned long long counter (updated every time the contents of
* the area changes),
* the rest is payload (non-interleaved).
*
* Authors: Anders; Gustavo Sverzut Barbieri <gustavo.barbieri@ic.unicamp.br>
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <unistd.h>
#include "config.h"
#include <sys/types.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "osdep/io.h"
#include "talloc.h"
#include "af.h"
#include "options/path.h"
#define DEF_SZ 512 // default buffer size (in samples)
#define SHARED_FILE "mpv-af_export" /* default file name
(relative to ~/.mpv/ */
#define SIZE_HEADER (2 * sizeof(int) + sizeof(unsigned long long))
// Data for specific instances of this filter
typedef struct af_export_s
{
unsigned long long count; // Used for sync
void* buf[AF_NCH]; // Buffers for storing the data before it is exported
int sz; // Size of buffer in samples
int wi; // Write index
int fd; // File descriptor to shared memory area
char* filename; // File to export data
uint8_t *mmap_area; // MMap shared area
} af_export_t;
/* Initialization and runtime control
af audio filter instance
cmd control command
arg argument
*/
static int control(struct af_instance* af, int cmd, void* arg)
{
af_export_t* s = af->priv;
switch (cmd){
case AF_CONTROL_REINIT:{
int i=0;
int mapsize;
// Free previous buffers
free(s->buf[0]);
// unmap previous area
if(s->mmap_area)
munmap(s->mmap_area, SIZE_HEADER + (af->data->bps*s->sz*af->data->nch));
// close previous file descriptor
if(s->fd)
close(s->fd);
// Accept only int16_t as input format (which sucks)
mp_audio_copy_config(af->data, (struct mp_audio*)arg);
mp_audio_set_format(af->data, AF_FORMAT_S16);
// Allocate new buffers (as one continuous block)
s->buf[0] = calloc(s->sz*af->data->nch, af->data->bps);
if(NULL == s->buf[0]) {
MP_FATAL(af, "Out of memory\n");
return AF_ERROR;
}
for(i = 1; i < af->data->nch; i++)
s->buf[i] = (uint8_t *)s->buf[0] + i*s->sz*af->data->bps;
if (!s->filename) {
MP_FATAL(af, "No filename set.\n");
return AF_ERROR;
}
// Init memory mapping
s->fd = open(s->filename, O_RDWR | O_CREAT | O_TRUNC | O_CLOEXEC, 0640);
MP_INFO(af, "Exporting to file: %s\n", s->filename);
if(s->fd < 0) {
MP_FATAL(af, "Could not open/create file: %s\n",
s->filename);
return AF_ERROR;
}
// header + buffer
mapsize = (SIZE_HEADER + (af->data->bps * s->sz * af->data->nch));
// grow file to needed size
for(i = 0; i < mapsize; i++){
char null = 0;
write(s->fd, (void*) &null, 1);
}
// mmap size
s->mmap_area = mmap(0, mapsize, PROT_READ|PROT_WRITE,MAP_SHARED, s->fd, 0);
if(s->mmap_area == NULL)
MP_FATAL(af, "Could not mmap file %s\n", s->filename);
MP_INFO(af, "Memory mapped to file: %s (%p)\n",
s->filename, s->mmap_area);
// Initialize header
*((int*)s->mmap_area) = af->data->nch;
*((int*)s->mmap_area + 1) = s->sz * af->data->bps * af->data->nch;
msync(s->mmap_area, mapsize, MS_ASYNC);
// Use test_output to return FALSE if necessary
return af_test_output(af, (struct mp_audio*)arg);
}
}
return AF_UNKNOWN;
}
/* Free allocated memory and clean up other stuff too.
af audio filter instance
*/
static void uninit( struct af_instance* af )
{
af_export_t* s = af->priv;
free(s->buf[0]);
// Free mmaped area
if(s->mmap_area)
munmap(s->mmap_area, sizeof(af_export_t));
if(s->fd > -1)
close(s->fd);
}
/* Filter data through filter
af audio filter instance
data audio data
*/
static int filter(struct af_instance *af, struct mp_audio *data)
{
if (!data)
return 0;
struct mp_audio* c = data; // Current working data
af_export_t* s = af->priv; // Setup for this instance
int16_t* a = c->planes[0]; // Incomming sound
int nch = c->nch; // Number of channels
int len = c->samples*c->nch; // Number of sample in data chunk
int sz = s->sz; // buffer size (in samples)
int flag = 0; // Set to 1 if buffer is filled
int ch, i;
// Fill all buffers
for(ch = 0; ch < nch; ch++){
int wi = s->wi; // Reset write index
int16_t* b = s->buf[ch]; // Current buffer
// Copy data to export buffers
for(i = ch; i < len; i += nch){
b[wi++] = a[i];
if(wi >= sz){ // Don't write outside the end of the buffer
flag = 1;
break;
}
}
s->wi = wi % s->sz;
}
// Export buffer to mmaped area
if(flag){
// update buffer in mapped area
memcpy(s->mmap_area + SIZE_HEADER, s->buf[0], sz * c->bps * nch);
s->count++; // increment counter (to sync)
memcpy(s->mmap_area + SIZE_HEADER - sizeof(s->count),
&(s->count), sizeof(s->count));
}
af_add_output_frame(af, data);
return 0;
}
/* Allocate memory and set function pointers
af audio filter instance
returns AF_OK or AF_ERROR
*/
static int af_open( struct af_instance* af )
{
af->control = control;
af->uninit = uninit;
af->filter_frame = filter;
af_export_t *priv = af->priv;
if (!priv->filename || !priv->filename[0]) {
MP_FATAL(af, "no export filename given");
return AF_ERROR;
}
return AF_OK;
}
#define OPT_BASE_STRUCT af_export_t
const struct af_info af_info_export = {
.info = "Sound export filter",
.name = "export",
.open = af_open,
.priv_size = sizeof(af_export_t),
.options = (const struct m_option[]) {
OPT_STRING("filename", filename, 0),
OPT_INTRANGE("buffersamples", sz, 0, 1, 2048, OPTDEF_INT(DEF_SZ)),
{0}
},
};
+132
View File
@@ -0,0 +1,132 @@
/*
* Copyright (C) 2004 Alex Beregszaszi & Pierre Lombard
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <math.h>
#include <limits.h>
#include "common/common.h"
#include "af.h"
// Data for specific instances of this filter
typedef struct af_extrastereo_s
{
float mul;
}af_extrastereo_t;
// Initialization and runtime control
static int control(struct af_instance* af, int cmd, void* arg)
{
switch(cmd){
case AF_CONTROL_REINIT:{
// Sanity check
if(!arg) return AF_ERROR;
mp_audio_copy_config(af->data, (struct mp_audio*)arg);
mp_audio_force_interleaved_format(af->data);
mp_audio_set_num_channels(af->data, 2);
if (af->data->format != AF_FORMAT_FLOAT)
mp_audio_set_format(af->data, AF_FORMAT_S16);
return af_test_output(af,(struct mp_audio*)arg);
}
}
return AF_UNKNOWN;
}
// Filter data through filter
static void play_s16(af_extrastereo_t *s, struct mp_audio* data)
{
register int i = 0;
int16_t *a = (int16_t*)data->planes[0]; // Audio data
int len = data->samples*data->nch; // Number of samples
int avg, l, r;
for (i = 0; i < len; i+=2)
{
avg = (a[i] + a[i + 1]) / 2;
l = avg + (int)(s->mul * (a[i] - avg));
r = avg + (int)(s->mul * (a[i + 1] - avg));
a[i] = MPCLAMP(l, SHRT_MIN, SHRT_MAX);
a[i + 1] = MPCLAMP(r, SHRT_MIN, SHRT_MAX);
}
}
static void play_float(af_extrastereo_t *s, struct mp_audio* data)
{
register int i = 0;
float *a = (float*)data->planes[0]; // Audio data
int len = data->samples * data->nch; // Number of samples
float avg, l, r;
for (i = 0; i < len; i+=2)
{
avg = (a[i] + a[i + 1]) / 2;
l = avg + (s->mul * (a[i] - avg));
r = avg + (s->mul * (a[i + 1] - avg));
a[i] = af_softclip(l);
a[i + 1] = af_softclip(r);
}
}
static int filter_frame(struct af_instance *af, struct mp_audio *data)
{
if (!data)
return 0;
if (af_make_writeable(af, data) < 0) {
talloc_free(data);
return -1;
}
if (data->format == AF_FORMAT_FLOAT) {
play_float(af->priv, data);
} else {
play_s16(af->priv, data);
}
af_add_output_frame(af, data);
return 0;
}
// Allocate memory and set function pointers
static int af_open(struct af_instance* af){
af->control=control;
af->filter_frame = filter_frame;
return AF_OK;
}
#define OPT_BASE_STRUCT af_extrastereo_t
const struct af_info af_info_extrastereo = {
.info = "Increase difference between audio channels",
.name = "extrastereo",
.flags = AF_FLAGS_NOT_REENTRANT,
.open = af_open,
.priv_size = sizeof(af_extrastereo_t),
.options = (const struct m_option[]) {
OPT_FLOAT("mul", mul, 0, OPTDEF_FLOAT(2.5)),
{0}
},
};
+8 -8
View File
@@ -29,10 +29,10 @@ struct priv {
int in_format;
int in_srate;
struct m_channels in_channels;
struct mp_chmap in_channels;
int out_format;
int out_srate;
struct m_channels out_channels;
struct mp_chmap out_channels;
int fail;
};
@@ -44,8 +44,8 @@ static void force_in_params(struct af_instance *af, struct mp_audio *in)
if (priv->in_format != AF_FORMAT_UNKNOWN)
mp_audio_set_format(in, priv->in_format);
if (priv->in_channels.num_chmaps > 0)
mp_audio_set_channels(in, &priv->in_channels.chmaps[0]);
if (priv->in_channels.num)
mp_audio_set_channels(in, &priv->in_channels);
if (priv->in_srate)
in->rate = priv->in_srate;
@@ -58,8 +58,8 @@ static void force_out_params(struct af_instance *af, struct mp_audio *out)
if (priv->out_format != AF_FORMAT_UNKNOWN)
mp_audio_set_format(out, priv->out_format);
if (priv->out_channels.num_chmaps > 0)
mp_audio_set_channels(out, &priv->out_channels.chmaps[0]);
if (priv->out_channels.num)
mp_audio_set_channels(out, &priv->out_channels);
if (priv->out_srate)
out->rate = priv->out_srate;
@@ -124,10 +124,10 @@ const struct af_info af_info_format = {
.options = (const struct m_option[]) {
OPT_AUDIOFORMAT("format", in_format, 0),
OPT_INTRANGE("srate", in_srate, 0, 1000, 8*48000),
OPT_CHANNELS("channels", in_channels, 0, .min = 1),
OPT_CHMAP("channels", in_channels, CONF_MIN, .min = 0),
OPT_AUDIOFORMAT("out-format", out_format, 0),
OPT_INTRANGE("out-srate", out_srate, 0, 1000, 8*48000),
OPT_CHANNELS("out-channels", out_channels, 0, .min = 1),
OPT_CHMAP("out-channels", out_channels, CONF_MIN, .min = 0),
OPT_FLAG("fail", fail, 0),
{0}
},
+670
View File
@@ -0,0 +1,670 @@
/*
* Experimental audio filter that mixes 5.1 and 5.1 with matrix
* encoded rear channels into headphone signal using FIR filtering
* with HRTF.
*
* Author: ylai
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <math.h>
#include <libavutil/common.h>
#include "af.h"
#include "dsp.h"
/* HRTF filter coefficients and adjustable parameters */
#include "af_hrtf.h"
typedef struct af_hrtf_s {
/* Lengths */
int dlbuflen, hrflen, basslen;
/* L, C, R, Ls, Rs channels */
float *lf, *rf, *lr, *rr, *cf, *cr;
const float *cf_ir, *af_ir, *of_ir, *ar_ir, *or_ir, *cr_ir;
int cf_o, af_o, of_o, ar_o, or_o, cr_o;
/* Bass */
float *ba_l, *ba_r;
float *ba_ir;
/* Whether to matrix decode the rear center channel */
int matrix_mode;
/* How to decode the input:
0 = 5/5+1 channels
1 = 2 channels
2 = matrix encoded 2 channels */
int decode_mode;
/* Full wave rectified (FWR) amplitudes and gain used to steer the
active matrix decoding of front channels (variable names
lpr/lmr means Lt + Rt, Lt - Rt) */
float l_fwr, r_fwr, lpr_fwr, lmr_fwr;
float adapt_l_gain, adapt_r_gain, adapt_lpr_gain, adapt_lmr_gain;
/* Matrix input decoding require special FWR buffer, since the
decoding is done in place. */
float *fwrbuf_l, *fwrbuf_r, *fwrbuf_lr, *fwrbuf_rr;
/* Rear channel delay buffer for matrix decoding */
float *rear_dlbuf;
/* Full wave rectified amplitude and gain used to steer the active
matrix decoding of center rear channel */
float lr_fwr, rr_fwr, lrprr_fwr, lrmrr_fwr;
float adapt_lr_gain, adapt_rr_gain;
float adapt_lrprr_gain, adapt_lrmrr_gain;
/* Cyclic position on the ring buffer */
int cyc_pos;
int print_flag;
int mode;
} af_hrtf_t;
/* Convolution on a ring buffer
* nx: length of the ring buffer
* nk: length of the convolution kernel
* sx: ring buffer
* sk: convolution kernel
* offset: offset on the ring buffer, can be
*/
static float conv(const int nx, const int nk, const float *sx, const float *sk,
const int offset)
{
/* k = reminder of offset / nx */
int k = offset >= 0 ? offset % nx : nx + (offset % nx);
if(nk + k <= nx)
return af_filter_fir(nk, sx + k, sk);
else
return af_filter_fir(nk + k - nx, sx, sk + nx - k) +
af_filter_fir(nx - k, sx + k, sk);
}
/* Detect when the impulse response starts (significantly) */
static int pulse_detect(const float *sx)
{
/* nmax must be the reference impulse response length (128) minus
s->hrflen */
const int nmax = 128 - HRTFFILTLEN;
const float thresh = IRTHRESH;
int i;
for(i = 0; i < nmax; i++)
if(fabs(sx[i]) > thresh)
return i;
return 0;
}
/* Fuzzy matrix coefficient transfer function to "lock" the matrix on
a effectively passive mode if the gain is approximately 1 */
static inline float passive_lock(float x)
{
const float x1 = x - 1;
const float ax1s = fabs(x - 1) * (1.0 / MATAGCLOCK);
return x1 - x1 / (1 + ax1s * ax1s) + 1;
}
/* Unified active matrix decoder for 2 channel matrix encoded surround
sources */
static inline void matrix_decode(short *in, const int k, const int il,
const int ir, const int decode_rear,
const int dlbuflen,
float l_fwr, float r_fwr,
float lpr_fwr, float lmr_fwr,
float *adapt_l_gain, float *adapt_r_gain,
float *adapt_lpr_gain, float *adapt_lmr_gain,
float *lf, float *rf, float *lr,
float *rr, float *cf)
{
const int kr = (k + MATREARDELAY) % dlbuflen;
float l_gain = (l_fwr + r_fwr) /
(1 + l_fwr + l_fwr);
float r_gain = (l_fwr + r_fwr) /
(1 + r_fwr + r_fwr);
/* The 2nd axis has strong gain fluctuations, and therefore require
limits. The factor corresponds to the 1 / amplification of (Lt
- Rt) when (Lt, Rt) is strongly correlated. (e.g. during
dialogues). It should be bigger than -12 dB to prevent
distortion. */
float lmr_lim_fwr = lmr_fwr > M9_03DB * lpr_fwr ?
lmr_fwr : M9_03DB * lpr_fwr;
float lpr_gain = (lpr_fwr + lmr_lim_fwr) /
(1 + lpr_fwr + lpr_fwr);
float lmr_gain = (lpr_fwr + lmr_lim_fwr) /
(1 + lmr_lim_fwr + lmr_lim_fwr);
float lmr_unlim_gain = (lpr_fwr + lmr_fwr) /
(1 + lmr_fwr + lmr_fwr);
float lpr, lmr;
float l_agc, r_agc, lpr_agc, lmr_agc;
float f, d_gain, c_gain, c_agc_cfk;
#if 0
static int counter = 0;
static FILE *fp_out;
if(counter == 0)
fp_out = fopen("af_hrtf.log", "w");
if(counter % 240 == 0)
fprintf(fp_out, "%g %g %g %g %g ", counter * (1.0 / 48000),
l_gain, r_gain, lpr_gain, lmr_gain);
#endif
/*** AXIS NO. 1: (Lt, Rt) -> (C, Ls, Rs) ***/
/* AGC adaption */
d_gain = (fabs(l_gain - *adapt_l_gain) +
fabs(r_gain - *adapt_r_gain)) * 0.5;
f = d_gain * (1.0 / MATAGCTRIG);
f = MATAGCDECAY - MATAGCDECAY / (1 + f * f);
*adapt_l_gain = (1 - f) * *adapt_l_gain + f * l_gain;
*adapt_r_gain = (1 - f) * *adapt_r_gain + f * r_gain;
/* Matrix */
l_agc = in[il] * passive_lock(*adapt_l_gain);
r_agc = in[ir] * passive_lock(*adapt_r_gain);
cf[k] = (l_agc + r_agc) * M_SQRT1_2;
if(decode_rear) {
lr[kr] = rr[kr] = (l_agc - r_agc) * M_SQRT1_2;
/* Stereo rear channel is steered with the same AGC steering as
the decoding matrix. Note this requires a fast updating AGC
at the order of 20 ms (which is the case here). */
lr[kr] *= (l_fwr + l_fwr) /
(1 + l_fwr + r_fwr);
rr[kr] *= (r_fwr + r_fwr) /
(1 + l_fwr + r_fwr);
}
/*** AXIS NO. 2: (Lt + Rt, Lt - Rt) -> (L, R) ***/
lpr = (in[il] + in[ir]) * M_SQRT1_2;
lmr = (in[il] - in[ir]) * M_SQRT1_2;
/* AGC adaption */
d_gain = fabs(lmr_unlim_gain - *adapt_lmr_gain);
f = d_gain * (1.0 / MATAGCTRIG);
f = MATAGCDECAY - MATAGCDECAY / (1 + f * f);
*adapt_lpr_gain = (1 - f) * *adapt_lpr_gain + f * lpr_gain;
*adapt_lmr_gain = (1 - f) * *adapt_lmr_gain + f * lmr_gain;
/* Matrix */
lpr_agc = lpr * passive_lock(*adapt_lpr_gain);
lmr_agc = lmr * passive_lock(*adapt_lmr_gain);
lf[k] = (lpr_agc + lmr_agc) * M_SQRT1_2;
rf[k] = (lpr_agc - lmr_agc) * M_SQRT1_2;
/*** CENTER FRONT CANCELLATION ***/
/* A heuristic approach exploits that Lt + Rt gain contains the
information about Lt, Rt correlation. This effectively reshapes
the front and rear "cones" to concentrate Lt + Rt to C and
introduce Lt - Rt in L, R. */
/* 0.67677 is the emprical lower bound for lpr_gain. */
c_gain = 8 * (*adapt_lpr_gain - 0.67677);
c_gain = c_gain > 0 ? c_gain : 0;
/* c_gain should not be too high, not even reaching full
cancellation (~ 0.50 - 0.55 at current AGC implementation), or
the center will s0und too narrow. */
c_gain = MATCOMPGAIN / (1 + c_gain * c_gain);
c_agc_cfk = c_gain * cf[k];
lf[k] -= c_agc_cfk;
rf[k] -= c_agc_cfk;
cf[k] += c_agc_cfk + c_agc_cfk;
#if 0
if(counter % 240 == 0)
fprintf(fp_out, "%g %g %g %g %g\n",
*adapt_l_gain, *adapt_r_gain,
*adapt_lpr_gain, *adapt_lmr_gain,
c_gain);
counter++;
#endif
}
static inline void update_ch(af_hrtf_t *s, short *in, const int k)
{
const int fwr_pos = (k + FWRDURATION) % s->dlbuflen;
/* Update the full wave rectified total amplitude */
/* Input matrix decoder */
if(s->decode_mode == HRTF_MIX_MATRIX2CH) {
s->l_fwr += abs(in[0]) - fabs(s->fwrbuf_l[fwr_pos]);
s->r_fwr += abs(in[1]) - fabs(s->fwrbuf_r[fwr_pos]);
s->lpr_fwr += abs(in[0] + in[1]) -
fabs(s->fwrbuf_l[fwr_pos] + s->fwrbuf_r[fwr_pos]);
s->lmr_fwr += abs(in[0] - in[1]) -
fabs(s->fwrbuf_l[fwr_pos] - s->fwrbuf_r[fwr_pos]);
}
/* Rear matrix decoder */
if(s->matrix_mode) {
s->lr_fwr += abs(in[2]) - fabs(s->fwrbuf_lr[fwr_pos]);
s->rr_fwr += abs(in[3]) - fabs(s->fwrbuf_rr[fwr_pos]);
s->lrprr_fwr += abs(in[2] + in[3]) -
fabs(s->fwrbuf_lr[fwr_pos] + s->fwrbuf_rr[fwr_pos]);
s->lrmrr_fwr += abs(in[2] - in[3]) -
fabs(s->fwrbuf_lr[fwr_pos] - s->fwrbuf_rr[fwr_pos]);
}
switch (s->decode_mode) {
case HRTF_MIX_51:
/* 5/5+1 channel sources */
s->lf[k] = in[0];
s->cf[k] = in[4];
s->rf[k] = in[1];
s->fwrbuf_lr[k] = s->lr[k] = in[2];
s->fwrbuf_rr[k] = s->rr[k] = in[3];
break;
case HRTF_MIX_MATRIX2CH:
/* Matrix encoded 2 channel sources */
s->fwrbuf_l[k] = in[0];
s->fwrbuf_r[k] = in[1];
matrix_decode(in, k, 0, 1, 1, s->dlbuflen,
s->l_fwr, s->r_fwr,
s->lpr_fwr, s->lmr_fwr,
&(s->adapt_l_gain), &(s->adapt_r_gain),
&(s->adapt_lpr_gain), &(s->adapt_lmr_gain),
s->lf, s->rf, s->lr, s->rr, s->cf);
break;
case HRTF_MIX_STEREO:
/* Stereo sources */
s->lf[k] = in[0];
s->rf[k] = in[1];
s->cf[k] = s->lr[k] = s->rr[k] = 0;
break;
}
/* We need to update the bass compensation delay line, too. */
// TODO: should this use lf/cf/rf etc. instead?
s->ba_l[k] = in[0];
s->ba_r[k] = in[1];
if (s->decode_mode == HRTF_MIX_51) {
s->ba_l[k] += in[4] + in[2];
s->ba_r[k] += in[4] + in[3];
}
}
static void clear_coeff(af_hrtf_t *s, float *c)
{
memset(c, 0, s->dlbuflen * sizeof(float));
}
static void reset(af_hrtf_t *s)
{
clear_coeff(s, s->lf);
clear_coeff(s, s->rf);
clear_coeff(s, s->lr);
clear_coeff(s, s->rr);
clear_coeff(s, s->cf);
clear_coeff(s, s->cr);
clear_coeff(s, s->ba_l);
clear_coeff(s, s->ba_r);
clear_coeff(s, s->fwrbuf_l);
clear_coeff(s, s->fwrbuf_r);
clear_coeff(s, s->fwrbuf_lr);
clear_coeff(s, s->fwrbuf_rr);
}
/* Initialization and runtime control */
static int control(struct af_instance *af, int cmd, void* arg)
{
af_hrtf_t *s = af->priv;
int test_output_res;
switch(cmd) {
case AF_CONTROL_REINIT:
reset(s);
af->data->rate = 48000;
mp_audio_set_channels_old(af->data, ((struct mp_audio*)arg)->nch);
if(af->data->nch == 2) {
/* 2 channel input */
if(s->decode_mode != HRTF_MIX_MATRIX2CH) {
/* Default behavior is stereo mixing. */
s->decode_mode = HRTF_MIX_STEREO;
}
} else if (af->data->nch < 5) {
mp_audio_set_channels_old(af->data, 5);
}
mp_audio_set_format(af->data, AF_FORMAT_S16);
test_output_res = af_test_output(af, (struct mp_audio*)arg);
// after testing input set the real output format
mp_audio_set_num_channels(af->data, 2);
s->print_flag = 1;
return test_output_res;
case AF_CONTROL_RESET:
reset(s);
return AF_OK;
}
return AF_UNKNOWN;
}
/* Deallocate memory */
static void uninit(struct af_instance *af)
{
af_hrtf_t *s = af->priv;
free(s->lf);
free(s->rf);
free(s->lr);
free(s->rr);
free(s->cf);
free(s->cr);
free(s->ba_l);
free(s->ba_r);
free(s->ba_ir);
free(s->fwrbuf_l);
free(s->fwrbuf_r);
free(s->fwrbuf_lr);
free(s->fwrbuf_rr);
}
/* Filter data through filter
Two "tricks" are used to compensate the "color" of the KEMAR data:
1. The KEMAR data is refiltered to ensure that the front L, R channels
on the same side of the ear are equalized (especially in the high
frequencies).
2. A bass compensation is introduced to ensure that 0-200 Hz are not
damped (without any real 3D acoustical image, however).
*/
static int filter(struct af_instance *af, struct mp_audio *data)
{
af_hrtf_t *s = af->priv;
if (!data)
return 0;
struct mp_audio *outframe =
mp_audio_pool_get(af->out_pool, &af->fmt_out, data->samples);
if (!outframe) {
talloc_free(data);
return -1;
}
mp_audio_copy_attributes(outframe, data);
short *in = data->planes[0]; // Input audio data
short *out = outframe->planes[0]; // Output audio data
short *end = in + data->samples * data->nch; // Loop end
float common, left, right, diff, left_b, right_b;
const int dblen = s->dlbuflen, hlen = s->hrflen, blen = s->basslen;
if(s->print_flag) {
s->print_flag = 0;
switch (s->decode_mode) {
case HRTF_MIX_51:
MP_INFO(af, "Using HRTF to mix %s discrete surround into "
"L, R channels\n", s->matrix_mode ? "5+1" : "5");
break;
case HRTF_MIX_STEREO:
MP_INFO(af, "Using HRTF to mix stereo into "
"L, R channels\n");
break;
case HRTF_MIX_MATRIX2CH:
MP_INFO(af, "Using active matrix to decode 2 channel "
"input, HRTF to mix %s matrix surround into "
"L, R channels\n", "3/2");
break;
default:
MP_WARN(af, "bogus decode_mode: %d\n", s->decode_mode);
break;
}
if(s->matrix_mode)
MP_INFO(af, "Using active matrix to decode rear center "
"channel\n");
}
/* MPlayer's 5 channel layout (notation for the variable):
*
* 0: L (LF), 1: R (RF), 2: Ls (LR), 3: Rs (RR), 4: C (CF), matrix
* encoded: Cs (CR)
*
* or: L = left, C = center, R = right, F = front, R = rear
*
* Filter notation:
*
* CF
* OF AF
* Ear->
* OR AR
* CR
*
* or: C = center, A = same side, O = opposite, F = front, R = rear
*/
while(in < end) {
const int k = s->cyc_pos;
update_ch(s, in, k);
/* Simulate a 7.5 ms -20 dB echo of the center channel in the
front channels (like reflection from a room wall) - a kind of
psycho-acoustically "cheating" to focus the center front
channel, which is normally hard to be perceived as front */
s->lf[k] += CFECHOAMPL * s->cf[(k + CFECHODELAY) % s->dlbuflen];
s->rf[k] += CFECHOAMPL * s->cf[(k + CFECHODELAY) % s->dlbuflen];
switch (s->decode_mode) {
case HRTF_MIX_51:
case HRTF_MIX_MATRIX2CH:
/* Mixer filter matrix */
common = conv(dblen, hlen, s->cf, s->cf_ir, k + s->cf_o);
if(s->matrix_mode) {
/* In matrix decoding mode, the rear channel gain must be
renormalized, as there is an additional channel. */
matrix_decode(in, k, 2, 3, 0, s->dlbuflen,
s->lr_fwr, s->rr_fwr,
s->lrprr_fwr, s->lrmrr_fwr,
&(s->adapt_lr_gain), &(s->adapt_rr_gain),
&(s->adapt_lrprr_gain), &(s->adapt_lrmrr_gain),
s->lr, s->rr, NULL, NULL, s->cr);
common +=
conv(dblen, hlen, s->cr, s->cr_ir, k + s->cr_o) *
M1_76DB;
left =
( conv(dblen, hlen, s->lf, s->af_ir, k + s->af_o) +
conv(dblen, hlen, s->rf, s->of_ir, k + s->of_o) +
(conv(dblen, hlen, s->lr, s->ar_ir, k + s->ar_o) +
conv(dblen, hlen, s->rr, s->or_ir, k + s->or_o)) *
M1_76DB + common);
right =
( conv(dblen, hlen, s->rf, s->af_ir, k + s->af_o) +
conv(dblen, hlen, s->lf, s->of_ir, k + s->of_o) +
(conv(dblen, hlen, s->rr, s->ar_ir, k + s->ar_o) +
conv(dblen, hlen, s->lr, s->or_ir, k + s->or_o)) *
M1_76DB + common);
} else {
left =
( conv(dblen, hlen, s->lf, s->af_ir, k + s->af_o) +
conv(dblen, hlen, s->rf, s->of_ir, k + s->of_o) +
conv(dblen, hlen, s->lr, s->ar_ir, k + s->ar_o) +
conv(dblen, hlen, s->rr, s->or_ir, k + s->or_o) +
common);
right =
( conv(dblen, hlen, s->rf, s->af_ir, k + s->af_o) +
conv(dblen, hlen, s->lf, s->of_ir, k + s->of_o) +
conv(dblen, hlen, s->rr, s->ar_ir, k + s->ar_o) +
conv(dblen, hlen, s->lr, s->or_ir, k + s->or_o) +
common);
}
break;
case HRTF_MIX_STEREO:
left =
( conv(dblen, hlen, s->lf, s->af_ir, k + s->af_o) +
conv(dblen, hlen, s->rf, s->of_ir, k + s->of_o));
right =
( conv(dblen, hlen, s->rf, s->af_ir, k + s->af_o) +
conv(dblen, hlen, s->lf, s->of_ir, k + s->of_o));
break;
default:
/* make gcc happy */
left = 0.0;
right = 0.0;
break;
}
/* Bass compensation for the lower frequency cut of the HRTF. A
cross talk of the left and right channel is introduced to
match the directional characteristics of higher frequencies.
The bass will not have any real 3D perception, but that is
OK (note at 180 Hz, the wavelength is about 2 m, and any
spatial perception is impossible). */
left_b = conv(dblen, blen, s->ba_l, s->ba_ir, k);
right_b = conv(dblen, blen, s->ba_r, s->ba_ir, k);
left += (1 - BASSCROSS) * left_b + BASSCROSS * right_b;
right += (1 - BASSCROSS) * right_b + BASSCROSS * left_b;
/* Also mix the LFE channel (if available) */
if(data->nch >= 6) {
left += in[5] * M3_01DB;
right += in[5] * M3_01DB;
}
/* Amplitude renormalization. */
left *= AMPLNORM;
right *= AMPLNORM;
switch (s->decode_mode) {
case HRTF_MIX_51:
case HRTF_MIX_STEREO:
/* "Cheating": linear stereo expansion to amplify the 3D
perception. Note: Too much will destroy the acoustic space
and may even result in headaches. */
diff = STEXPAND2 * (left - right);
out[0] = av_clip_int16(left + diff);
out[1] = av_clip_int16(right - diff);
break;
case HRTF_MIX_MATRIX2CH:
/* Do attempt any stereo expansion with matrix encoded
sources. The L, R channels are already stereo expanded
by the steering, any further stereo expansion will sound
very unnatural. */
out[0] = av_clip_int16(left);
out[1] = av_clip_int16(right);
break;
}
/* Next sample... */
in = &in[data->nch];
out = &out[af->data->nch];
(s->cyc_pos)--;
if(s->cyc_pos < 0)
s->cyc_pos += dblen;
}
talloc_free(data);
af_add_output_frame(af, outframe);
return 0;
}
static int allocate(af_hrtf_t *s)
{
if ((s->lf = malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->rf = malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->lr = malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->rr = malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->cf = malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->cr = malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->ba_l = malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->ba_r = malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->fwrbuf_l =
malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->fwrbuf_r =
malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->fwrbuf_lr =
malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
if ((s->fwrbuf_rr =
malloc(s->dlbuflen * sizeof(float))) == NULL) return -1;
return 0;
}
/* Allocate memory and set function pointers */
static int af_open(struct af_instance* af)
{
int i;
af_hrtf_t *s;
float fc;
af->control = control;
af->uninit = uninit;
af->filter_frame = filter;
s = af->priv;
s->dlbuflen = DELAYBUFLEN;
s->hrflen = HRTFFILTLEN;
s->basslen = BASSFILTLEN;
s->cyc_pos = s->dlbuflen - 1;
/* With a full (two axis) steering matrix decoder, s->matrix_mode
should not be enabled lightly (it will also steer the Ls, Rs
channels). */
s->matrix_mode = 0;
s->decode_mode = HRTF_MIX_51;
switch (s->mode) {
case 0: /* Use matrix rear decoding. */
s->matrix_mode = 1;
break;
case 1: /* Input needs matrix decoding. */
s->decode_mode = HRTF_MIX_MATRIX2CH;
break;
case 2:
s->matrix_mode = 0;
break;
}
s->print_flag = 1;
if (allocate(s) != 0) {
MP_ERR(af, "Memory allocation error.\n");
return AF_ERROR;
}
for(i = 0; i < s->dlbuflen; i++)
s->lf[i] = s->rf[i] = s->lr[i] = s->rr[i] = s->cf[i] =
s->cr[i] = 0;
s->lr_fwr =
s->rr_fwr = 0;
s->cf_ir = cf_filt + (s->cf_o = pulse_detect(cf_filt));
s->af_ir = af_filt + (s->af_o = pulse_detect(af_filt));
s->of_ir = of_filt + (s->of_o = pulse_detect(of_filt));
s->ar_ir = ar_filt + (s->ar_o = pulse_detect(ar_filt));
s->or_ir = or_filt + (s->or_o = pulse_detect(or_filt));
s->cr_ir = cr_filt + (s->cr_o = pulse_detect(cr_filt));
if((s->ba_ir = malloc(s->basslen * sizeof(float))) == NULL) {
MP_ERR(af, "Memory allocation error.\n");
return AF_ERROR;
}
fc = 2.0 * BASSFILTFREQ / (float)af->data->rate;
if(af_filter_design_fir(s->basslen, s->ba_ir, &fc, LP | KAISER, 4 * M_PI) ==
-1) {
MP_ERR(af, "Unable to design low-pass "
"filter.\n");
return AF_ERROR;
}
for(i = 0; i < s->basslen; i++)
s->ba_ir[i] *= BASSGAIN;
return AF_OK;
}
#define OPT_BASE_STRUCT af_hrtf_t
const struct af_info af_info_hrtf = {
.info = "HRTF Headphone",
.name = "hrtf",
.open = af_open,
.priv_size = sizeof(af_hrtf_t),
.options = (const struct m_option[]) {
OPT_CHOICE("mode", mode, 0, ({"m", 0}, {"s", 1}, {"0", 2})),
{0}
},
};
+510
View File
@@ -0,0 +1,510 @@
/*
* 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 MPLAYER_AF_HRTF_H
#define MPLAYER_AF_HRTF_H
#define HRTF_MIX_51 0
#define HRTF_MIX_STEREO 1
#define HRTF_MIX_MATRIX2CH 2
/* Amplitude scaling factors */
#define M17_0DB 0.1414213562
#define M9_03DB 0.3535533906
#define M6_99DB 0.4472135955
#define M4_77DB 0.5773502692
#define M3_01DB 0.7071067812
#define M1_76DB 0.8164965809
#define DELAYBUFLEN 1024 /* Length of the delay buffer */
#define HRTFFILTLEN 64 /* HRTF filter length */
#define IRTHRESH 0.001 /* Impulse response pruning thresh. */
#define AMPLNORM M6_99DB /* Overall amplitude renormalization */
#define BASSFILTFREQ 180 /* Bass compensation filter cut (Hz) */
#define BASSFILTLEN 193 /* Bass compensation filter length */
#define BASSGAIN M_SQRT2 /* Bass compensation gain */
#define BASSCROSS 0.35 /* Bass cross talk */
#define FWRDURATION 240 /* FWR average duration (samples) */
#define MATREARDELAY 720 /* Matrix mode rear delay (samples) */
#define MATAGCTRIG 8.0 /* (Fuzzy) AGC trigger */
#define MATAGCDECAY 1.0 /* AGC baseline decay rate (1/samp.) */
#define MATAGCLOCK 0.2 /* AGC range (around 1) where the
matrix behaves passively */
#define MATCOMPGAIN 0.37 /* Cross talk compensation gain,
0.50 - 0.55 is full cancellation. */
#define CFECHODELAY 360 /* Center front echo delay (samples) */
#define CFECHOAMPL M17_0DB /* Center front echo amplitude */
#define STEXPAND2 0.07 /* Stereo expansion / 2 */
/* Head related impulse response (HRIR) derived from KEMAR measurement
data by Bill Gardner <billg@media.mit.edu> and Keith Martin
<kdm@media.mit.edu>
URL: http://sound.media.mit.edu/KEMAR.html
Distributed under GPL with authors' permission
*/
/* EQUALIZED KEMAR HRIR
How to generate these data:
1. You need the MIT Media Lab's KEMAR data, read it into an software
capable of signal/time series analysis (like Mathematica, Matlab,
...)
2. Construct an equalizing FIR inverse filter by calculating the
transfer function of the front, same side impulse response, then
take 1 over the absolute magnitude.
3. Cut the poles in the inverse filter's transfer function
specification by limiting the amplification to 2.5 (note, this
number assumes that you have correct signal processing
normalization of the Fourier transform).
4. Design the FIR inverse filter by calculating the inverse Fourier
transform, then chopping the coefficients down to a reasonable
number (N = 15 is used here), apply the Kaiser-Bessel window (alpha
= 2 is used here). Note the objective is remove the color bias
only (as if you are using an equalizer), _not_ to do a full inverse
filtering. (Note: beta = pi*alpha in other notation.)
For N = 15, alpha = 2, you should get the following impulse
response:
0.001001558668605168, 0.00698457265741865, 0.040453643039829436,
0.012230541722147855, -0.11939760844854072, 0.16468099899755967,
-0.30297563073747436, 1.3140211791355982, -0.30297563073747436,
0.16468099899755967, -0.11939760844854072, 0.012230541722147855,
0.040453643039829436, 0.00698457265741865, 0.001001558668605168
5. Linearly convolve all KEMAR HRIR with this inverse filter.
6. Resample from 44.1 kHz sampling frequency to 48 kHz.
*/
/* Center front (-5 degree) - not 0 degree in order to create a clear
front image from a finite distance */
static const float cf_filt[128] = {
-0.00008638082319075036, 0.0003198059946385229,
-0.0005010631339162132, 0.0011424741331126876,
-0.001584220794688753, 0.001742715363246275,
-0.0011080796626780694, 0.0001651829990860167,
0.005235028337314985, 0.0035223828473357776,
0.010057681388431303, -0.033469432129545514,
0.013391253316233523, 0.004858462839827063,
0.08172161220103627, 0.26158596134500023,
-0.12420314583323326, -0.14298458356097565,
0.14421897280453896, -0.1635792507629016,
-0.02187136722480014, 0.2426863044711817,
0.07229814207917194, 0.0942742651913879,
0.29856830878076834, 0.2944146162057754,
-0.12122157003421209, -0.19640092165631157,
0.11623836502034968, -0.05794027397995521,
-0.34313138341973776, -0.19487516249168105,
0.010118993953802401, -0.09460218797710966,
-0.16761521117359582, 0.004154461610153861,
0.052768641758969316, -0.00041823982226147407,
0.021634960445143514, 0.07562793486871108,
0.08895407129506479, 0.039857755093416214,
0.044257936180422945, 0.061557584906101664,
0.015547268541895703, -0.023908191934932484,
0.009498030443468223, 0.03816269003221337,
-0.009820500607303615, -0.042003975527908084,
-0.03335447117311547, -0.029294510859746596,
-0.05212623136198511, -0.073427547153205,
-0.061190797824958836, -0.04620925059966413,
-0.04204619420702159, -0.02331915902615157,
0.00211481411477094, 0.00852563995740107,
0.008766809731743399, 0.008666632180812078,
0.018279202191625352, 0.02924332751289675,
0.022293148257836494, 0.012362146008584188,
0.008572582458807008, 0.006491370763597344,
-0.0019366944997535774, -0.006318669309634434,
-0.006457921690218669, -0.015050265524669974,
-0.02110660282616213, -0.017027809096377904,
-0.01651052305334348, -0.022770064150046673,
-0.01999875754219472, -0.012294792027337775,
-0.011506057031057188, -0.011448970577312903,
-0.004823572302580925, 0.0022451134042777883,
0.004145473526859826, 0.005629030064546135,
0.008588029213398785, 0.010092048834844231,
0.007182013245552008, 0.0014600979508720656,
-0.0038314646272511756, -0.003443901997881347,
-0.0029483418254804047, -0.007609357112679647,
-0.006518368948030822, -0.004495803701497202,
-0.007109113004849672, -0.008346237278084265,
-0.005560847336252453, -0.002993453167553188,
-0.005122897816824269, -0.004389782626604215,
-0.0010912633695218108, -0.0019712029474458835,
-0.005870162265802235, -0.005626159534954128,
-0.00027254977910844407, 0.0013794425431633785,
-0.0005919083190430062, -0.0007861203545416682,
-0.0007049560240893946, -0.0032720188494468868,
-0.004460645567968504, -0.0032018528193571696,
-0.0030579229375062105, -0.003593998902656612,
-0.0038032977997776445, -0.004613776010454773,
-0.0059796549143736845, -0.00420126194319768,
-0.0012374419948287222, 0.0008572699213050608,
0.0021490971020081094, 0.00047295283198381995,
-0.0009670277915884887, -0.001354440866080231,
-0.002962902746547851, -0.00533935813338141,
-0.005469203016468759, -0.004355784273189485
};
/* Front, same side (30 degree) */
static const float af_filt[128] = {
-0.004140580614755493, 0.005790934614385445,
0.003318916682081112, 0.014257145544366063,
0.007328442487127339, -0.06550381777876194,
0.03502225818161845, -0.013090579770708259,
0.2517776798694195, 0.420770489950659,
-0.3418854608834852, -0.24371032493696737,
0.04901356150030018, -0.1778083521632833,
0.26448004245714163, 0.23245199964546834,
0.033053145803936305, 0.46811222821062415,
0.5359265986255611, -0.011912195468533787,
-0.39763432601411647, -0.034482864386898314,
0.029445398240649626, -0.3850940407863262,
-0.3272328478175581, -0.14701421403616477,
-0.08522137400169517, -0.14936851633336035,
-0.09432605283433723, 0.0991200405937827,
0.011075012089917331, -0.0051036489980274685,
0.0933903289749412, 0.1344189369609565,
0.10507466913017807, 0.04240159324684365,
0.06559270110638656, 0.026984119875617524,
-0.03359846103238096, -0.018000197099174275,
0.042031818548178244, 0.03849039666888434,
-0.02450829674011345, -0.03407882403088576,
-0.029230189282961977, -0.046964865291761734,
-0.09458258700116245, -0.1527349330901158,
-0.15411577687826097, -0.08761679790956928,
-0.033623549089171874, -0.007204768531481949,
0.008273425020444852, 0.021368717994908505,
0.04366608267875025, 0.05660907333076205,
0.06775726495503939, 0.05621881735271431,
0.03576231950669927, 0.02500825834889175,
0.015423811076054601, 0.007903258334503761,
-0.0053873014137761945, -0.006987955469434698,
-0.012027972007598602, -0.025228281243816594,
-0.026225091797257318, -0.023809293997344882,
-0.03250172017712295, -0.03195696301067249,
-0.01784813952189948, -0.01663267233760342,
-0.016184530450468065, -0.011659883749357463,
-0.0035378511240219163, -0.0005485800790443406,
0.0018432660108168625, 0.011634844139907534,
0.018333603402051105, 0.020447379185133056,
0.00850783664147828, 0.0004694148911037838,
-0.0017047130409786676, -0.0022409152834483997,
-0.000860472174892845, -0.004111075059198666,
-0.003527843382056666, -0.009640160874903018,
-0.01750044574231376, -0.015613389403672443,
-0.010790028120953001, -0.0095313499955768,
-0.007469721416726809, -0.0019186578145117315,
-0.00014977322572890802, -0.0029803838028179728,
-0.006520567233727221, 0.000035015132033882596,
0.009245098100543752, 0.009896930052308656,
0.008316744929565786, 0.004575207140193997,
-0.0000647420103997081, -0.004502916832871627,
-0.004225962213251224, -0.002886014126381486,
-0.006416834142585976, -0.007156609995423569,
-0.008840274447579472, -0.01441763751386817,
-0.015435817484659574, -0.00924487254924743,
-0.0021571721940235205, 0.0028540722992305453,
0.00273577475088536, -0.000788412365513805,
-0.0032650029728365907, -0.003880217646231338,
-0.0035302087299613778, -0.0038531436176586246,
-0.0011921632190514074, -0.0020722967099011938,
-0.004985351145629344, -0.0042375588844648735,
-0.003030360463006021, -0.0014161075428041471,
-0.0005083025643192044, 0.00035096963769606926
};
/* Front, opposite (-30 degree) */
static const float of_filt[128] = {
-0.000013472538374193126, -0.00008048061877079751,
0.000043927265781258155, -0.000017931700794858892,
-0.000034774602476112886, -0.00009576223008735474,
0.0001557797638630691, -0.00018742885883751094,
0.00026512448626705716, -0.0001451040203319678,
-0.00008263233117758043, 0.0006486245853639179,
-0.0010631408451846698, 0.0026571994100746143,
0.0014179177997092787, 0.0062326502956616256,
-0.008194149324545333, -0.006568029415878379,
0.009538759710818582, 0.012309193558632693,
0.12336638055838955, 0.046164307101829005,
-0.10228706407884815, 0.04047687260345798,
-0.00296595313977046, -0.07057949208414134,
0.08172114840714612, 0.08736490764127891,
0.05105250431333021, 0.11627179512747428,
0.20717888490340705, 0.09375052213570291,
-0.09784374168330194, -0.010493571845901443,
0.053131894303891716, -0.10157443971694806,
-0.16264032634244974, -0.05402369511361273,
-0.0274403608654217, -0.09860277022495063,
-0.06841875821090282, -0.004434574400066223,
-0.0005222661652743502, -0.006231881259827263,
0.014410397820340159, 0.04885649512730243,
0.04361962569042684, 0.03399214029009391,
0.04961073933475931, 0.04067325604132289,
0.007850647519227257, 0.004564440466905299,
0.02257107958021618, 0.008183791928884486,
-0.014913479343180557, -0.018685938460856224,
-0.01745737397226911, -0.02327177054233603,
-0.03723048632685227, -0.044739390162299685,
-0.042651220125613766, -0.03730017561004743,
-0.029039465434276192, -0.01885087458914294,
-0.01207127752277769, -0.006779800724164512,
-0.001930416967444157, 0.000029454577995528385,
0.0013822760965755472, 0.0014799128583230202,
0.0002068200609199832, 0.0022254295286201083,
0.005143858159434566, 0.0018580542060917013,
-0.0019426046325146259, -0.0014464042108543495,
-0.0034430083560735582, -0.009692758426099499,
-0.011840035292593485, -0.010716508855893968,
-0.012939889036853034, -0.0121846427935653,
-0.006198503315630782, -0.0023186723099380305,
-0.002679872498314837, -0.003086020446226295,
-0.0015709623347698936, -0.0008147490468332398,
-0.0012384575726770983, -0.0005212877089109362,
0.0017707578744906142, 0.001324932723905786,
-0.0017023653780617696, -0.0045108927752919425,
-0.005422155613096912, -0.0039489323837623835,
-0.005295995750506547, -0.00629706566356189,
-0.004685732198036754, -0.0048076735568143,
-0.005978864279217503, -0.005928999306332966,
-0.004187703549017582, -0.003213999896976475,
-0.0028068699816073414, -0.0010889703907593833,
0.0003276714243495386, -0.0013015007040186994,
-0.003208050402434782, -0.0025115319088208545,
-0.0013787553006401076, -0.0018279087370218635,
-0.0025904836507747754, -0.002071221947222004,
-0.0026424212922485594, -0.0039837031817577,
-0.0041635566057380965, -0.004355223489150822,
-0.004350395332709937, -0.0036693292471930263,
-0.003386384394185026, -0.003972568655001128,
-0.004332336840023821, -0.002648767912111827,
-0.001384410080218114, -0.0011353792711849466,
-0.0013726264946164232, -0.0020075119315034313
};
/* Rear, same side (135 degree) */
static const float ar_filt[128] = {
0.004573315040810066, 0.0013592578059426913,
0.01553271930902704, -0.0002356117224941317,
-0.05746098219774702, 0.03430688963370445,
0.00808371687447385, 0.21893535841158596,
0.2984357591724814, -0.3302799746504719,
-0.3194029149806245, 0.21633225051331056,
0.24371260938097083, -0.08843705549751085,
0.03939684701343366, 0.45386926431114494,
0.07599118140753386, -0.18114706160474578,
0.285640624686038, 0.4049515236666218,
-0.05347890222071792, -0.31464359045319074,
-0.1033502246468194, -0.04553593949283157,
-0.1880747731157464, -0.13629090230626037,
-0.10435789106123239, -0.19818232801888755,
-0.16701805476330397, -0.022793111199284,
0.058049696762683685, 0.007048321372693906,
-0.002966419183225961, 0.10140569697797763,
0.11648999956673124, 0.05218347182779882,
0.028427001212735392, 0.04151900310166159,
-0.0006960604221423734, -0.05898623212226975,
-0.03801934531173312, -0.029306970535287986,
-0.04549125782835908, -0.0599222718506552,
-0.058299618975430116, -0.03765579129720727,
-0.03559302657499581, -0.020647901025903054,
-0.005720957338744348, -0.0041915732688915545,
-0.0011470880098346143, 0.008737404798553,
0.023444168098121512, 0.024204226042172663,
0.01894897166475026, 0.020807655257479588,
0.021570431128040954, 0.006800556178576289,
-0.009000089216921362, -0.010969824547067934,
-0.0033653428332822374, -0.012676936164668659,
-0.026739938673413587, -0.023427869194287573,
-0.023302007105117244, -0.023647155590533712,
-0.021289317515613106, -0.009120487305069884,
0.0009251551667728967, 0.00004285344125653763,
-0.00009042365479456271, 0.00022573242339446494,
0.00720168491586098, 0.007111875505402431,
0.003186514817683482, 0.00810087718334745,
0.012619557025922575, 0.007854726400013397,
-0.0024013592881066267, -0.001452457473161119,
-0.0025535188366093945, -0.012428911627809337,
-0.013729251536694145, -0.0070099675146427344,
-0.007165284278706593, -0.01639289295622301,
-0.015831795079778305, -0.007305768485523729,
-0.003608863157004021, -0.0032640528878698084,
0.0030901263998481944, 0.00749497566124848,
0.002515185532327241, 0.00004840875738621367,
0.0017596043486043966, 0.0046229941553338144,
0.0034259167322926096, 0.003707347634186093,
0.0035584806528586328, -0.0019078936035275198,
-0.006057343815214898, -0.0069262470468817,
-0.004345020728618624, -0.004177623355574794,
-0.005373506556122508, -0.006624933928893836,
-0.008679541408588839, -0.010718719681595322,
-0.011392246979594496, -0.007893917064389902,
-0.0027572935365832536, -0.00006064707149834412,
-0.0012512537319656323, -0.0024501501002409786,
-0.0022106788572895998, -0.00234124933370301,
-0.0008953445167066823, 0.0005393670625637734,
-0.00033175600142209297, -0.004023994309351289,
-0.008655472335784443, -0.009899957354849682,
-0.008664952919996412, -0.00553483124503576,
-0.003735336089277662, -0.002754824348643885,
-0.0026884314856593368, -0.004084181815125924
};
/* Rear, opposite (-135 degree) */
static const float or_filt[128] = {
0.0001220944028243897, -0.000021785381808441314,
5.823057988603169e-6, -0.00001217768176447613,
-0.00006123604397345513, 5.574117262531134e-6,
-0.00004935331914366778, 1.1771577934768211e-6,
-0.000059236211621095756, 9.503536190497286e-6,
-0.0001494445696103564, 0.00012248858284145305,
-0.0000963975321456313, 6.017905197665205e-6,
0.00003353395360402643, -0.0001931511015359506,
0.0005113536523931485, -0.0005676652619386114,
0.0012057159755477467, 0.0009370492250339692,
0.004596472288877981, -0.0018831773384237068,
-0.008208535225621212, 0.0038178646400751056,
0.008726517739105965, 0.06664363898418262,
0.06788684221502142, -0.04492315162807267,
-0.04019906311255255, 0.026203059677375153,
0.013678129114847544, -0.014334962223993527,
0.010141709596167392, 0.11559131576945537,
0.1586402064538425, 0.059975334707967023,
0.004671725963777715, 0.031498678282775874,
0.014338626006524587, -0.014749719448472231,
-0.02055508237941379, -0.05407690143992048,
-0.07767559836886143, -0.05029091786216801,
-0.030808335706574427, -0.03401958135442541,
-0.030520368430288967, -0.014168302104259355,
0.011907621259989802, 0.014286081013069,
0.006377467879613449, 0.018546823568277478,
0.028297012771618273, 0.025222339408338186,
0.021931611353415138, 0.019708894333646355,
0.01729258494072014, 0.017468204169564034,
0.009729094845051928, -0.002976992018531901,
-0.00956986166277019, -0.016125733548332074,
-0.02934094241442545, -0.04133767871051455,
-0.043536981145416466, -0.0385966307108608,
-0.02784453599342459, -0.018995135307247116,
-0.012849534096536747, -0.004437491064613308,
0.00028385411598204655, 0.003776874988516643,
0.008069432041547833, 0.008764754183751848,
0.008020908861878062, 0.006830351461360802,
0.002218330884267235, -0.0020478725582339444,
-0.003997428121462543, -0.007066287373515421,
-0.00940847412544698, -0.010938998446237963,
-0.011775483016151306, -0.011391103919484287,
-0.010586061195163017, -0.009842793078929053,
-0.007753202010139829, -0.00569213732353025,
-0.006506783349722073, -0.005346134281903736,
-0.003913089814898934, -0.0036091443854759727,
-0.0020328564301266287, 0.00017932870773467683,
0.0032779786679056357, 0.003969695813293966,
0.0020339334412434987, -0.00011345940675415259,
-0.0018344103399567666, -0.003556764701666365,
-0.004263523639408391, -0.002940568582022133,
-0.0034341188272627556, -0.006023399920020824,
-0.0077456903203677865, -0.007912219312377842,
-0.00625202770436523, -0.00530785086116117,
-0.005569722659634311, -0.004664448462594344,
-0.0037747773914077747, -0.004175649656985592,
-0.004659601521384289, -0.005008602967819641,
-0.004730625079902729, -0.0034039554356604146,
-0.0017110333873406587, -0.0006091938771510242,
-0.0016051679050678297, -0.003312864664007262,
-0.004505512715977288, -0.004152222189861692,
-0.003218596419678823, -0.0027277806209877343,
-0.001715005444317267, -0.0012589960071233749,
-0.001852908777923165, -0.002540339553144362
};
/* Center rear (180 degree) */
static const float cr_filt[128] = {
-0.00005989110716536726, -0.00022790291829128702,
0.0002659166098971966, -0.0003774772716776257,
0.0004540309551867803, -0.000420238187386368,
0.00025518536450885686, 0.00028285526288953955,
-0.001016391007574093, 0.0028634984299063795,
0.0021574799687976045, 0.01035121276682072,
-0.010481720917298163, -0.013197198495899292,
0.0031928225328717195, 0.02903137843618603,
0.1632429772511569, 0.1047487989875262,
-0.10464685060623742, -0.09260196288035998,
-0.007514241993554443, 0.013596249226741712,
-0.019876166508450258, 0.1255626123599804,
0.3648170359521724, 0.19458249753223478,
-0.04434070930031298, 0.046582528121935265,
0.09484427347230277, -0.03137795311969644,
-0.10297437925363695, -0.09351091015917065,
-0.1129521092162064, -0.14925322995658827,
-0.1231466295584665, -0.06356719756705227,
-0.05442277895126282, -0.07568433015661316,
-0.023314932828602003, 0.04260950721318558,
0.02249026315598923, 0.02048195669571197,
0.05651342117268278, 0.05885038917623213,
0.03797102097397795, 0.011767394419953451,
0.00560502503429481, 0.005051125343961189,
-0.012925933188033823, -0.023918884651306566,
-0.013251659441678816, -0.010694772488866284,
-0.03080486448617846, -0.03661278237783158,
-0.0379227303416262, -0.042189005718490775,
-0.026595666344596286, -0.009759025956801257,
-0.002064986663513004, -0.002420117028098389,
-0.006629991977552491, 0.004619970897631026,
0.019450642967537877, 0.0173521119057514,
0.017641425439988062, 0.02270029598048491,
0.018976431925275348, 0.009299852902290885,
-0.001695039371619912, -0.00675162574265618,
-0.009380968871003034, -0.011208396125485165,
-0.01308640049201482, -0.0165636375633249,
-0.022004099870933345, -0.025173458684139286,
-0.016918759559175375, -0.00865150653575917,
-0.006999929082792643, -0.005454830010518988,
-0.0021129521131095317, 0.00018717090054046307,
-0.0002864344788569993, 0.0017615225381095569,
0.006985907557802283, 0.010577308310476465,
0.006466104789306027, -0.0014988738575948326,
-0.0039669755229277195, -0.0065156971200080235,
-0.009343206924192169, -0.0076430644693577495,
-0.004395214976600924, -0.003052735340422483,
-0.007019103043066595, -0.00974109267696527,
-0.007968015032797376, -0.007801513845528344,
-0.007535748903681969, -0.003543341967287925,
0.0015083125553729722, 0.0023345972556147025,
-0.0010043623069557037, -0.0025295765105203746,
-0.0023701840891643634, -0.0005908186035024362,
0.0029826252289082847, 0.004829048542117764,
0.004488360022902081, 0.00002643748103005408,
-0.0042100779212597295, -0.006170600558114495,
-0.007267149164680168, -0.006825522903494639,
-0.006899834372739123, -0.0073493916110062675,
-0.009554351265163382, -0.011790297433830197,
-0.010645796603734424, -0.0064661575394022106,
-0.002026743466524137, -0.0004337034584909932,
-0.0011172647031654614, -0.0017947816283674731,
-0.00255615052036616, -0.0017721562881944813,
-0.0002379619297227554, 0.0007130120121089036
};
#endif /* MPLAYER_AF_HRTF_H */
+86
View File
@@ -0,0 +1,86 @@
/*
* simple voice removal filter
*
* copyright (c) 2006 Reynaldo H. Verdejo Pinochet
* Based on code by Alex Beregszaszi for his 'center' filter.
*
* 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 <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "af.h"
// Data for specific instances of this filter
// Initialization and runtime control
static int control(struct af_instance* af, int cmd, void* arg)
{
switch(cmd){
case AF_CONTROL_REINIT:
mp_audio_copy_config(af->data, (struct mp_audio*)arg);
mp_audio_set_format(af->data, AF_FORMAT_FLOAT);
return af_test_output(af,(struct mp_audio*)arg);
}
return AF_UNKNOWN;
}
static int filter_frame(struct af_instance *af, struct mp_audio *c)
{
if (!c)
return 0;
if (af_make_writeable(af, c) < 0) {
talloc_free(c);
return 0;
}
float* a = c->planes[0]; // Audio data
int nch = c->nch; // Number of channels
int len = c->samples*nch; // Number of samples in current audio block
register int i;
/*
FIXME1 add a low band pass filter to avoid suppressing
centered bass/drums
FIXME2 better calculated* attenuation factor
*/
for(i=0;i<len;i+=nch)
{
a[i] = (a[i] - a[i+1]) * 0.7;
a[i+1]=a[i];
}
af_add_output_frame(af, c);
return 0;
}
// Allocate memory and set function pointers
static int af_open(struct af_instance* af){
af->control = control;
af->filter_frame = filter_frame;
return AF_OK;
}
// Description of this filter
const struct af_info af_info_karaoke = {
.info = "Simple karaoke/voice-removal audio filter",
.name = "karaoke",
.flags = AF_FLAGS_NOT_REENTRANT,
.open = af_open,
};
+851
View File
@@ -0,0 +1,851 @@
/*
* LADSPA plugin loader
*
* Written by Ivo van Poorten <ivop@euronet.nl>
* Copyright (C) 2004, 2005
*
* 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/>.
*/
/* ------------------------------------------------------------------------- */
/* Global Includes */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include <math.h>
#include <limits.h>
#include <dlfcn.h>
#include <ladspa.h>
/* ------------------------------------------------------------------------- */
/* Local Includes */
#include "af.h"
#define _(x) (x)
/* ------------------------------------------------------------------------- */
/* Filter specific data */
typedef struct af_ladspa_s
{
int status; /**< Status of the filter.
* Either AF_OK or AF_ERROR
* Because MPlayer re-inits audio filters that
* _clearly_ returned AF_ERROR anyway, I use this
* in play() to skip the processing and return
* the data unchanged.
*/
int activated; /**< 0 or 1. Activate LADSPA filters only once, even
* if the buffers get resized, to avoid a stuttering
* filter.
*/
char *file;
char *label;
char *controls;
char *myname; /**< It's easy to have a concatenation of file and label */
void *libhandle;
const LADSPA_Descriptor *plugin_descriptor;
int nports;
int ninputs;
int *inputs;
int noutputs;
int *outputs;
int ninputcontrols;
int *inputcontrolsmap; /**< Map input port number [0-] to actual port */
float *inputcontrols;
int noutputcontrols;
int *outputcontrolsmap;
float *outputcontrols;
int nch; /**< number of channels */
int bufsize;
float **inbufs;
float **outbufs;
LADSPA_Handle *chhandles;
} af_ladspa_t;
/* ------------------------------------------------------------------------- */
static int af_open(struct af_instance *af);
static int af_ladspa_malloc_failed(char*);
/* ------------------------------------------------------------------------- */
#define OPT_BASE_STRUCT af_ladspa_t
const struct af_info af_info_ladspa = {
.info = "LADSPA plugin loader",
.name = "ladspa",
.open = af_open,
.priv_size = sizeof(af_ladspa_t),
.options = (const struct m_option[]) {
OPT_STRING("file", file, 0),
OPT_STRING("label", label, 0),
OPT_STRING("controls", controls, 0),
{0}
},
};
/* ------------------------------------------------------------------------- */
/* By lack of a better word (in my vocabulary) this is called 'parse'.
* Feel free to suggest an alternative.
*/
/** \brief Check for inputs, outputs and controls of a given filter.
*
* This function counts and checks all input, output and control ports
* of the filter that was loaded. If it turns out to be a valid
* filter for MPlayer use, it prints out a list of all controls and
* the corresponding range of its value at message level MSGL_V.
*
* \param setup Current setup of the filter. Must have its
* plugin_descriptor set!
*
* \return Returns AF_OK if it has a valid input/output/controls
* configuration. Else, it returns AF_ERROR.
*/
static int af_ladspa_parse_plugin(struct af_instance *af) {
af_ladspa_t *setup = af->priv;
int p, i;
const LADSPA_Descriptor *pdes = setup->plugin_descriptor;
LADSPA_PortDescriptor d;
LADSPA_PortRangeHint hint;
if (!setup->libhandle)
return AF_ERROR; /* only call parse after a succesful load */
if (!setup->plugin_descriptor)
return AF_ERROR; /* same as above */
/* let's do it */
setup->nports = pdes->PortCount;
/* allocate memory for all inputs/outputs/controls */
setup->inputs = calloc(setup->nports, sizeof(int));
if (!setup->inputs) return af_ladspa_malloc_failed(setup->myname);
setup->outputs = calloc(setup->nports, sizeof(int));
if (!setup->outputs) return af_ladspa_malloc_failed(setup->myname);
setup->inputcontrolsmap = calloc(setup->nports, sizeof(int));
if (!setup->inputcontrolsmap) return af_ladspa_malloc_failed(setup->myname);
setup->inputcontrols = calloc(setup->nports, sizeof(float));
if (!setup->inputcontrols) return af_ladspa_malloc_failed(setup->myname);
setup->outputcontrolsmap = calloc(setup->nports, sizeof(int));
if (!setup->outputcontrolsmap) return af_ladspa_malloc_failed(setup->myname);
setup->outputcontrols = calloc(setup->nports, sizeof(float));
if (!setup->outputcontrols) return af_ladspa_malloc_failed(setup->myname);
/* set counts to zero */
setup->ninputs = 0;
setup->noutputs = 0;
setup->ninputcontrols = 0;
setup->noutputcontrols = 0;
/* check all ports, see what type it is and set variables according to
* what we have found
*/
for (p=0; p<setup->nports; p++) {
d = pdes->PortDescriptors[p];
if (LADSPA_IS_PORT_AUDIO(d)) {
if (LADSPA_IS_PORT_INPUT(d)) {
setup->inputs[setup->ninputs] = p;
setup->ninputs++;
} else if (LADSPA_IS_PORT_OUTPUT(d)) {
setup->outputs[setup->noutputs] = p;
setup->noutputs++;
}
}
if (LADSPA_IS_PORT_CONTROL(d)) {
if (LADSPA_IS_PORT_INPUT(d)) {
setup->inputcontrolsmap[setup->ninputcontrols] = p;
setup->ninputcontrols++;
/* set control to zero. set values after reading the rest
* of the suboptions and check LADSPA_?_HINT's later.
*/
setup->inputcontrols[p] = 0.0f;
} else if (LADSPA_IS_PORT_OUTPUT(d)) {
/* read and handle these too, otherwise filters that have them
* will sig11
*/
setup->outputcontrolsmap[setup->noutputcontrols]=p;
setup->noutputcontrols++;
setup->outputcontrols[p] = 0.0f;
}
}
}
if (setup->ninputs == 0) {
MP_WARN(af, "%s: %s\n", setup->myname,
_("WARNING! This LADSPA plugin has no audio inputs.\n The incoming audio signal will be lost."));
} else if (setup->ninputs == 1) {
MP_VERBOSE(af, "%s: this is a mono effect\n", setup->myname);
} else if (setup->ninputs == 2) {
MP_VERBOSE(af, "%s: this is a stereo effect\n", setup->myname);
} else {
MP_VERBOSE(af, "%s: this is a %i-channel effect, "
"support is experimental\n", setup->myname, setup->ninputs);
}
if (setup->noutputs == 0) {
MP_ERR(af, "%s: %s\n", setup->myname,
_("This LADSPA plugin has no audio outputs."));
return AF_ERROR;
}
if (setup->noutputs != setup->ninputs ) {
MP_ERR(af, "%s: %s\n", setup->myname,
_("The number of audio inputs and audio outputs of the LADSPA plugin differ."));
return AF_ERROR;
}
MP_VERBOSE(af, "%s: this plugin has %d input control(s)\n",
setup->myname, setup->ninputcontrols);
/* Print list of controls and its range of values it accepts */
for (i=0; i<setup->ninputcontrols; i++) {
p = setup->inputcontrolsmap[i];
hint = pdes->PortRangeHints[p];
MP_VERBOSE(af, " --- %d %s [", i, pdes->PortNames[p]);
if (LADSPA_IS_HINT_BOUNDED_BELOW(hint.HintDescriptor)) {
MP_VERBOSE(af, "%0.2f , ", hint.LowerBound);
} else {
MP_VERBOSE(af, "... , ");
}
if (LADSPA_IS_HINT_BOUNDED_ABOVE(hint.HintDescriptor)) {
MP_VERBOSE(af, "%0.2f]\n", hint.UpperBound);
} else {
MP_VERBOSE(af, "...]\n");
}
}
return AF_OK;
}
/* ------------------------------------------------------------------------- */
/* This function might "slightly" look like dlopenLADSPA in the LADSPA SDK :-)
* But, I changed a few things, because imho it was broken. It did not support
* relative paths, only absolute paths that start with a /
* I think ../../some/dir/foobar.so is just as valid. And if one wants to call
* his library '...somename...so' he's crazy, but it should be allowed.
* So, search the path first, try plain *filename later.
* Also, try adding .so first! I like the recursion the SDK did, but it's
* better the other way around. -af ladspa=cmt:amp_stereo:0.5 is easier to type
* than -af ladspa=cmt.so:amp_stereo:0.5 :-))
*/
/** \brief dlopen() wrapper
*
* This is a wrapper around dlopen(). It tries various variations of the
* filename (with or without the addition of the .so extension) in various
* directories specified by the LADSPA_PATH environment variable. If all fails
* it tries the filename directly as an absolute path to the library.
*
* \param filename filename of the library to load.
* \param flag see dlopen(3) for a description of the flags.
*
* \return returns a pointer to the loaded library on success, or
* NULL if it fails to load.
*/
static void* mydlopen(const char *filename, int flag) {
char *buf;
const char *end, *start, *ladspapath;
int endsinso;
size_t filenamelen;
void *result = NULL;
#if defined(__MINGW32__) || defined(__CYGWIN__)
/* For Windows there's only absolute path support.
* If you have a Windows machine, feel free to fix this.
* (path separator, shared objects extension, et cetera). */
MP_VERBOSE(af, "\ton windows, only absolute pathnames "
"are supported\n");
MP_VERBOSE(af, "\ttrying %s\n", filename);
return dlopen(filename, flag);
#endif
filenamelen = strlen(filename);
endsinso = 0;
if (filenamelen > 3)
endsinso = (strcmp(filename+filenamelen-3, ".so") == 0);
if (!endsinso) {
buf=malloc(filenamelen+4);
strcpy(buf, filename);
strcat(buf, ".so");
result=mydlopen(buf, flag);
free(buf);
}
if (result)
return result;
ladspapath=getenv("LADSPA_PATH");
if (ladspapath) {
start=ladspapath;
while (*start != '\0') {
int needslash;
end=start;
while ( (*end != ':') && (*end != '\0') )
end++;
buf=malloc(filenamelen + 2 + (end-start) );
if (end > start)
strncpy(buf, start, end-start);
needslash=0;
if (end > start)
if (*(end-1) != '/') {
needslash = 1;
buf[end-start] = '/';
}
strcpy(buf+needslash+(end-start), filename);
result=dlopen(buf, flag);
free(buf);
if (result)
return result;
start = end;
if (*start == ':')
start++;
} /* end while there's still more in the path */
} /* end if there's a ladspapath */
/* last resort, just open it again, so the dlerror() message is correct */
return dlopen(filename,flag);
}
/* ------------------------------------------------------------------------- */
/** \brief Load a LADSPA Plugin
*
* This function loads the LADSPA plugin specified by the file and label
* that are present in the setup variable. First, it loads the library.
* If it fails, it returns AF_ERROR. If not, it continues to look for the
* specified label. If it finds it, it sets the plugin_descriptor inside
* setup and returns AF_OK. If it doesn't, it returns AF_ERROR. Special case
* is a label called 'help'. In that case, it prints a list of all available
* labels (filters) in the library specified by file.
*
* \param setup Current setup of the filter. Contains filename and label.
*
* \return Either AF_ERROR or AF_OK, depending on the success of the operation.
*/
static int af_ladspa_load_plugin(struct af_instance *af) {
af_ladspa_t *setup = af->priv;
const LADSPA_Descriptor *ladspa_descriptor;
LADSPA_Descriptor_Function descriptor_function;
int i;
/* load library */
MP_VERBOSE(af, "%s: loading ladspa plugin library %s\n",
setup->myname, setup->file);
setup->libhandle = mydlopen(setup->file, RTLD_NOW);
if (!setup->libhandle) {
MP_ERR(af, "%s: %s %s\n\t%s\n", setup->myname,
_("failed to load"), setup->file, dlerror() );
return AF_ERROR;
}
MP_VERBOSE(af, "%s: library found.\n", setup->myname);
/* find descriptor function */
dlerror();
descriptor_function = (LADSPA_Descriptor_Function) dlsym (setup->libhandle,
"ladspa_descriptor");
if (!descriptor_function) {
MP_ERR(af, "%s: %s\n\t%s\n", setup->myname,
_("Couldn't find ladspa_descriptor() function in the specified library file."), dlerror());
return AF_ERROR;
}
/* if label == help, list all labels in library and exit */
if (strcmp(setup->label, "help") == 0) {
MP_INFO(af, "%s: %s %s:\n", setup->myname,
_("available labels in"), setup->file);
for (i=0; ; i++) {
ladspa_descriptor = descriptor_function(i);
if (ladspa_descriptor == NULL) {
return AF_ERROR;
}
MP_INFO(af, " %-16s - %s (%lu)\n",
ladspa_descriptor->Label,
ladspa_descriptor->Name,
ladspa_descriptor->UniqueID);
}
}
MP_VERBOSE(af, "%s: looking for label\n", setup->myname);
/* find label in library */
for (i=0; ; i++) {
ladspa_descriptor = descriptor_function(i);
if (ladspa_descriptor == NULL) {
MP_ERR(af, "%s: %s\n", setup->myname,
_("Couldn't find label in plugin library."));
return AF_ERROR;
}
if (strcmp(ladspa_descriptor->Label, setup->label) == 0) {
setup->plugin_descriptor = ladspa_descriptor;
MP_VERBOSE(af, "%s: %s found\n", setup->myname,
setup->label);
return AF_OK;
}
}
return AF_OK;
}
/* ------------------------------------------------------------------------- */
/** \brief Print a malloc() failed error message.
*
* Generic function which can be called if a call to malloc(), calloc(),
* strdup(), et cetera, failed. It prints a message to the console and
* returns AF_ERROR.
*
* \return AF_ERROR
*/
static int af_ladspa_malloc_failed(char *myname) {
return AF_ERROR;
}
/* ------------------------------------------------------------------------- */
/** \brief Controls the filter.
*
* Control the behaviour of the filter.
*
* Commands:
* CONTROL_REINIT Sets the af structure with proper values for number
* of channels, rate, format, et cetera.
* \param af Audio filter instance
* \param cmd The command to execute
* \param arg Arguments to the command
*
* \return Either AF_ERROR or AF_OK, depending on the succes of the
* operation.
*/
static int control(struct af_instance *af, int cmd, void *arg) {
af_ladspa_t *setup = (af_ladspa_t*) af->priv;
switch(cmd) {
case AF_CONTROL_REINIT:
MP_VERBOSE(af, "%s: (re)init\n", setup->myname);
if (!arg) return AF_ERROR;
/* accept FLOAT, let af_format do conversion */
mp_audio_copy_config(af->data, (struct mp_audio*)arg);
mp_audio_set_format(af->data, AF_FORMAT_FLOAT);
return af_test_output(af, (struct mp_audio*)arg);
}
return AF_UNKNOWN;
}
/* ------------------------------------------------------------------------- */
/** \brief Uninitialise the LADSPA Plugin Loader filter.
*
* This function deactivates the plugin(s), cleans up, frees all allocated
* memory and exits.
*
* \return No return value.
*/
static void uninit(struct af_instance *af) {
if (af->priv) {
af_ladspa_t *setup = (af_ladspa_t*) af->priv;
const LADSPA_Descriptor *pdes = setup->plugin_descriptor;
if (setup->myname) {
MP_VERBOSE(af, "%s: cleaning up\n", setup->myname);
free(setup->myname);
}
if (setup->chhandles) {
for (int i = 0; i < setup->nch; i+=setup->ninputs) {
if (pdes->deactivate) pdes->deactivate(setup->chhandles[i]);
if (pdes->cleanup) pdes->cleanup(setup->chhandles[i]);
}
free(setup->chhandles);
}
free(setup->inputcontrolsmap);
free(setup->inputcontrols);
free(setup->outputcontrolsmap);
free(setup->outputcontrols);
free(setup->inputs);
free(setup->outputs);
if (setup->inbufs) {
for(int i = 0; i < setup->nch; i++)
free(setup->inbufs[i]);
free(setup->inbufs);
}
if (setup->outbufs) {
for (int i = 0; i < setup->nch; i++)
free(setup->outbufs[i]);
free(setup->outbufs);
}
if (setup->libhandle)
dlclose(setup->libhandle);
}
}
/* ------------------------------------------------------------------------- */
/** \brief Process chunk of audio data through the selected LADSPA Plugin.
*
* \param af Pointer to audio filter instance
* \param data Pointer to chunk of audio data
*
* \return Either AF_ERROR or AF_OK
*/
static int filter_frame(struct af_instance *af, struct mp_audio *data)
{
if (!data)
return 0;
af_ladspa_t *setup = af->priv;
const LADSPA_Descriptor *pdes = setup->plugin_descriptor;
float *audio = (float*)data->planes[0];
int nsamples = data->samples*data->nch;
int nch = data->nch;
int rate = data->rate;
int i, p;
if (setup->status !=AF_OK) {
talloc_free(data);
return -1;
}
if (af_make_writeable(af, data) < 0) {
talloc_free(data);
return -1;
}
/* See if it's the first call. If so, setup inbufs/outbufs, instantiate
* plugin, connect ports and activate plugin
*/
if ( (setup->bufsize != nsamples/nch) || (setup->nch != nch) ) {
/* if setup->nch==0, it's the first call, if not, something has
* changed and all previous mallocs have to be freed
*/
if (setup->nch != 0) {
MP_TRACE(af, "%s: bufsize change; free old buffer\n",
setup->myname);
if(setup->inbufs) {
for(i=0; i<setup->nch; i++)
free(setup->inbufs[i]);
free(setup->inbufs);
}
if(setup->outbufs) {
for(i=0; i<setup->nch; i++)
free(setup->outbufs[i]);
free(setup->outbufs);
}
} /* everything is freed */
setup->bufsize = nsamples/nch;
setup->nch = nch;
setup->inbufs = calloc(nch, sizeof(float*));
setup->outbufs = calloc(nch, sizeof(float*));
MP_TRACE(af, "%s: bufsize = %d\n",
setup->myname, setup->bufsize);
for(i=0; i<nch; i++) {
setup->inbufs[i] = calloc(setup->bufsize, sizeof(float));
setup->outbufs[i] = calloc(setup->bufsize, sizeof(float));
}
/* only on the first call, there are no handles. */
if (!setup->chhandles) {
setup->chhandles = calloc(nch, sizeof(LADSPA_Handle));
/* create handles
* for stereo effects, create one handle for two channels
*/
for(i=0; i<nch; i++) {
if (i % setup->ninputs) { /* stereo effect */
/* copy the handle from previous channel */
setup->chhandles[i] = setup->chhandles[i-1];
continue;
}
setup->chhandles[i] = pdes->instantiate(pdes, rate);
}
}
/* connect input/output ports for each channel/filter instance
*
* always (re)connect ports
*/
for(i=0; i<nch; i++) {
pdes->connect_port(setup->chhandles[i],
setup->inputs[i % setup->ninputs],
setup->inbufs[i]);
pdes->connect_port(setup->chhandles[i],
setup->outputs[i % setup->ninputs],
setup->outbufs[i]);
/* connect (input) controls */
for (p=0; p<setup->nports; p++) {
LADSPA_PortDescriptor d = pdes->PortDescriptors[p];
if (LADSPA_IS_PORT_CONTROL(d)) {
if (LADSPA_IS_PORT_INPUT(d)) {
pdes->connect_port(setup->chhandles[i], p,
&(setup->inputcontrols[p]) );
} else {
pdes->connect_port(setup->chhandles[i], p,
&(setup->outputcontrols[p]) );
}
}
}
/* Activate filter (if it isn't already :) ) */
if (pdes->activate && !setup->activated && i % setup->ninputs == 0)
pdes->activate(setup->chhandles[i]);
} /* All channels/filters done! except for... */
setup->activated = 1;
/* Stereo effect with one channel left. Use same buffer for left
* and right. connect it to the second port.
*/
for (p = i; p % setup->ninputs; p++) {
pdes->connect_port(setup->chhandles[i-1],
setup->inputs[p % setup->ninputs],
setup->inbufs[i-1]);
pdes->connect_port(setup->chhandles[i-1],
setup->outputs[p % setup->ninputs],
setup->outbufs[i-1]);
} /* done! */
} /* setup for first call/change of bufsize is done.
* normal playing routine follows...
*/
/* Right now, I use a separate input and output buffer.
* I could change this to in-place processing (inbuf==outbuf), but some
* ladspa filters are broken and are not able to handle that. This seems
* fast enough, so unless somebody complains, it stays this way :)
*/
/* Fill inbufs */
for (p=0; p<setup->bufsize; p++) {
for (i=0; i<nch; i++) {
setup->inbufs[i][p] = audio[p*nch + i];
}
}
/* Run filter(s) */
for (i=0; i<nch; i+=setup->ninputs) {
pdes->run(setup->chhandles[i], setup->bufsize);
}
/* Extract outbufs */
for (p=0; p<setup->bufsize; p++) {
for (i=0; i<nch; i++) {
audio[p*nch + i] = setup->outbufs[i][p];
}
}
/* done */
af_add_output_frame(af, data);
return 0;
}
/* ------------------------------------------------------------------------- */
/** \brief Open LADSPA Plugin Loader Filter
*
* \param af Audio Filter instance
*
* \return Either AF_ERROR or AF_OK
*/
static int af_open(struct af_instance *af) {
af->control=control;
af->uninit=uninit;
af->filter_frame = filter_frame;
af_ladspa_t *setup = af->priv;
setup->status = AF_ERROR; /* will be set to AF_OK if
* all went OK and filter()
* should proceed.
*/
setup->myname = strdup(af_info_ladspa.name);
if (!setup->myname)
return af_ladspa_malloc_failed((char*)af_info_ladspa.name);
if (!setup->file || !setup->file[0]) {
MP_ERR(af, "%s: %s\n", setup->myname,
_("No library file specified."));
uninit(af);
return AF_ERROR;
}
if (!setup->label || !setup->label[0]) {
MP_ERR(af, "%s: %s\n", setup->myname,
_("No filter label specified."));
uninit(af);
return AF_ERROR;
}
free(setup->myname);
setup->myname = calloc(strlen(af_info_ladspa.name)+strlen(setup->file)+
strlen(setup->label)+6, 1);
snprintf(setup->myname, strlen(af_info_ladspa.name)+
strlen(setup->file)+strlen(setup->label)+6, "%s: (%s:%s)",
af_info_ladspa.name, setup->file, setup->label);
/* load plugin :) */
if ( af_ladspa_load_plugin(af) != AF_OK )
return AF_ERROR;
/* see what inputs, outputs and controls this plugin has */
if ( af_ladspa_parse_plugin(af) != AF_OK )
return AF_ERROR;
/* ninputcontrols is set by now, read control values from arg */
float val;
char *line = setup->controls;
for (int i = 0; i < setup->ninputcontrols; i++) {
if (!line || (i != 0 && *line != ',')) {
MP_ERR(af, "%s: %s\n", setup->myname,
_("Not enough controls specified on the command line."));
return AF_ERROR;
}
if (i != 0)
line++;
if (sscanf(line, "%f", &val) != 1) {
MP_ERR(af, "%s: %s\n", setup->myname,
_("Not enough controls specified on the command line."));
return AF_ERROR;
}
setup->inputcontrols[setup->inputcontrolsmap[i]] = val;
line = strchr(line, ',');
}
MP_VERBOSE(af, "%s: input controls: ", setup->myname);
for (int i = 0; i < setup->ninputcontrols; i++) {
MP_VERBOSE(af, "%0.4f ",
setup->inputcontrols[setup->inputcontrolsmap[i]]);
}
MP_VERBOSE(af, "\n");
/* check boundaries of inputcontrols */
MP_VERBOSE(af, "%s: checking boundaries of input controls\n",
setup->myname);
for (int i = 0; i < setup->ninputcontrols; i++) {
int p = setup->inputcontrolsmap[i];
LADSPA_PortRangeHint hint =
setup->plugin_descriptor->PortRangeHints[p];
val = setup->inputcontrols[p];
if (LADSPA_IS_HINT_BOUNDED_BELOW(hint.HintDescriptor) &&
val < hint.LowerBound) {
MP_ERR(af, "%s: Input control #%d is below lower boundary of %0.4f.\n",
setup->myname, i, hint.LowerBound);
return AF_ERROR;
}
if (LADSPA_IS_HINT_BOUNDED_ABOVE(hint.HintDescriptor) &&
val > hint.UpperBound) {
MP_ERR(af, "%s: Input control #%d is above upper boundary of %0.4f.\n",
setup->myname, i, hint.UpperBound);
return AF_ERROR;
}
}
MP_VERBOSE(af, "%s: all controls have sane values\n",
setup->myname);
/* All is well! */
setup->status = AF_OK;
return AF_OK;
}
/* ------------------------------------------------------------------------- */
+70 -186
View File
@@ -26,18 +26,15 @@
#include <assert.h>
#include <libavcodec/avcodec.h>
#include <libavutil/audioconvert.h>
#include <libavutil/intreadwrite.h>
#include <libavutil/common.h>
#include <libavutil/bswap.h>
#include <libavutil/mem.h>
#include "config.h"
#include "common/av_common.h"
#include "common/common.h"
#include "af.h"
#include "audio/audio_buffer.h"
#include "audio/chmap_sel.h"
#include "audio/fmt-conversion.h"
@@ -53,57 +50,19 @@ const uint16_t ac3_bitrate_tab[19] = {
typedef struct af_ac3enc_s {
struct AVCodec *lavc_acodec;
struct AVCodecContext *lavc_actx;
AVPacket pkt;
int bit_rate;
struct mp_audio *input; // frame passed to libavcodec
struct mp_audio *pending; // unconsumed input data
int in_samples; // samples of input per AC3 frame
int out_samples; // upper bound on encoded output per AC3 frame
int64_t encoder_buffered;
int in_sampleformat;
int cfg_add_iec61937_header;
int cfg_bit_rate;
int cfg_min_channel_num;
char *cfg_encoder;
char **cfg_avopts;
} af_ac3enc_t;
// fmt carries the input format. Change it to the best next-possible format
// the encoder likely accepts.
static void select_encode_format(AVCodecContext *c, struct mp_audio *fmt)
{
int formats[AF_FORMAT_COUNT];
af_get_best_sample_formats(fmt->format, formats);
for (int n = 0; formats[n]; n++) {
const enum AVSampleFormat *lf = c->codec->sample_fmts;
for (int i = 0; lf && lf[i] != AV_SAMPLE_FMT_NONE; i++) {
int mpfmt = af_from_avformat(lf[i]);
if (mpfmt && mpfmt == formats[n]) {
mp_audio_set_format(fmt, mpfmt);
goto done_fmt;
}
}
}
done_fmt: ;
int rate =
af_select_best_samplerate(fmt->rate, c->codec->supported_samplerates);
if (rate > 0)
fmt->rate = rate;
struct mp_chmap_sel sel = {0};
const uint64_t *lch = c->codec->channel_layouts;
for (int n = 0; lch && lch[n]; n++) {
struct mp_chmap chmap = {0};
mp_chmap_from_lavc(&chmap, lch[n]);
mp_chmap_sel_add_map(&sel, &chmap);
}
struct mp_chmap res = fmt->channels;
mp_chmap_sel_adjust(&sel, &res);
if (!mp_chmap_is_empty(&res))
mp_audio_set_channels(fmt, &res);
}
// Initialization and runtime control
static int control(struct af_instance *af, int cmd, void *arg)
{
@@ -116,20 +75,26 @@ static int control(struct af_instance *af, int cmd, void *arg)
struct mp_audio *in = arg;
struct mp_audio orig_in = *in;
if (!af_fmt_is_pcm(in->format) || in->nch < s->cfg_min_channel_num)
if (AF_FORMAT_IS_SPECIAL(in->format) || in->nch < s->cfg_min_channel_num)
return AF_DETACH;
// At least currently, the AC3 encoder doesn't export sample rates.
in->rate = 48000;
select_encode_format(s->lavc_actx, in);
mp_audio_set_format(in, s->in_sampleformat);
if (in->rate != 48000 && in->rate != 44100 && in->rate != 32000)
in->rate = 48000;
af->data->rate = in->rate;
mp_chmap_reorder_to_lavc(&in->channels);
if (in->nch > AC3_MAX_CHANNELS)
mp_audio_set_num_channels(in, AC3_MAX_CHANNELS);
mp_audio_set_format(af->data, AF_FORMAT_S_AC3);
mp_audio_set_num_channels(af->data, 2);
if (!mp_audio_config_equals(in, &orig_in))
return AF_FALSE;
s->in_samples = AC3_FRAME_SIZE;
if (s->cfg_add_iec61937_header) {
s->out_samples = AC3_FRAME_SIZE;
} else {
@@ -137,11 +102,14 @@ static int control(struct af_instance *af, int cmd, void *arg)
}
mp_audio_copy_config(s->input, in);
mp_audio_realloc(s->input, s->in_samples);
s->input->samples = 0;
talloc_free(s->pending);
s->pending = NULL;
MP_DBG(af, "reinit: %d, %d, %d.\n", in->nch, in->rate, s->in_samples);
MP_DBG(af, "af_lavcac3enc reinit: %d, %d, %d.\n",
in->nch, in->rate, s->in_samples);
int bit_rate = s->bit_rate ? s->bit_rate : default_bit_rate[in->nch];
@@ -152,7 +120,6 @@ static int control(struct af_instance *af, int cmd, void *arg)
avcodec_close(s->lavc_actx);
// Put sample parameters
s->lavc_actx->sample_fmt = af_to_avformat(in->format);
s->lavc_actx->channels = in->nch;
s->lavc_actx->channel_layout = mp_chmap_to_lavc(&in->channels);
s->lavc_actx->sample_rate = in->rate;
@@ -162,26 +129,14 @@ static int control(struct af_instance *af, int cmd, void *arg)
MP_ERR(af, "Couldn't open codec %s, br=%d.\n", "ac3", bit_rate);
return AF_ERROR;
}
if (s->lavc_actx->frame_size < 1) {
MP_ERR(af, "encoder didn't specify input frame size\n");
return AF_ERROR;
}
}
s->in_samples = s->lavc_actx->frame_size;
mp_audio_realloc(s->input, s->in_samples);
s->input->samples = 0;
s->encoder_buffered = 0;
if (s->lavc_actx->frame_size != AC3_FRAME_SIZE) {
MP_ERR(af, "lavcac3enc: unexpected ac3 "
"encoder frame size %d\n", s->lavc_actx->frame_size);
return AF_ERROR;
}
return AF_OK;
}
case AF_CONTROL_RESET:
if (avcodec_is_open(s->lavc_actx))
avcodec_flush_buffers(s->lavc_actx);
talloc_free(s->pending);
s->pending = NULL;
s->input->samples = 0;
s->encoder_buffered = 0;
return AF_OK;
}
return AF_UNKNOWN;
}
@@ -192,6 +147,7 @@ static void uninit(struct af_instance* af)
af_ac3enc_t *s = af->priv;
if (s) {
av_free_packet(&s->pkt);
if(s->lavc_actx) {
avcodec_close(s->lavc_actx);
av_free(s->lavc_actx);
@@ -200,13 +156,6 @@ static void uninit(struct af_instance* af)
}
}
static void update_delay(struct af_instance *af)
{
af_ac3enc_t *s = af->priv;
af->delay = ((s->pending ? s->pending->samples : 0) + s->input->samples +
s->encoder_buffered) / (double)s->input->rate;
}
static int filter_frame(struct af_instance *af, struct mp_audio *audio)
{
af_ac3enc_t *s = af->priv;
@@ -217,7 +166,6 @@ static int filter_frame(struct af_instance *af, struct mp_audio *audio)
talloc_free(s->pending);
s->pending = audio;
update_delay(af);
return 0;
}
@@ -229,120 +177,62 @@ static void swap_16(uint16_t *ptr, size_t size)
// Copy data from input frame to encode frame (because libavcodec wants a full
// AC3 frame for encoding, while filter input frames can be smaller or larger).
// Return true if the frame is complete.
static bool fill_buffer(struct af_instance *af)
// Return true if the
static bool fill_buffer(af_ac3enc_t *s)
{
af_ac3enc_t *s = af->priv;
af->delay = 0;
if (s->pending) {
if (!mp_audio_is_writeable(s->input))
assert(s->input->samples == 0); // we can't have sent a partial frame
mp_audio_realloc_min(s->input, s->in_samples);
int copy = MPMIN(s->in_samples - s->input->samples, s->pending->samples);
s->input->samples += copy;
mp_audio_copy(s->input, s->input->samples - copy, s->pending, 0, copy);
mp_audio_skip_samples(s->pending, copy);
}
update_delay(af);
return s->input->samples >= s->in_samples;
}
// Return <0 on error, 0 on need more input, 1 on success (and *frame set).
// To actually advance the read pointer, set s->input->samples=0 afterwards.
static int read_input_frame(struct af_instance *af, AVFrame *frame)
{
af_ac3enc_t *s = af->priv;
if (!fill_buffer(af))
return 0; // need more input
if (mp_audio_to_avframe(s->input, frame) < 0)
return -1;
return 1;
}
static int filter_out(struct af_instance *af)
{
af_ac3enc_t *s = af->priv;
if (!s->pending)
return 0;
if (!fill_buffer(s))
return 0; // need more input
AVFrame *frame = av_frame_alloc();
if (!frame) {
MP_FATAL(af, "Could not allocate memory \n");
return -1;
}
int err = -1;
frame->nb_samples = s->in_samples;
frame->format = s->lavc_actx->sample_fmt;
frame->channel_layout = s->lavc_actx->channel_layout;
assert(s->input->num_planes <= AV_NUM_DATA_POINTERS);
frame->extended_data = frame->data;
for (int n = 0; n < s->input->num_planes; n++)
frame->data[n] = s->input->planes[n];
frame->linesize[0] = s->input->samples * s->input->sstride;
AVPacket pkt = {0};
av_init_packet(&pkt);
#if HAVE_AVCODEC_NEW_CODEC_API
// Send input as long as it wants.
while (1) {
err = read_input_frame(af, frame);
if (err < 0)
goto done;
if (err == 0)
break;
err = -1;
int lavc_ret = avcodec_send_frame(s->lavc_actx, frame);
// On EAGAIN, we're supposed to read remaining output.
if (lavc_ret == AVERROR(EAGAIN))
break;
if (lavc_ret < 0) {
MP_FATAL(af, "Encode failed.\n");
goto done;
}
s->encoder_buffered += s->input->samples;
s->input->samples = 0;
}
int lavc_ret = avcodec_receive_packet(s->lavc_actx, &pkt);
if (lavc_ret == AVERROR(EAGAIN)) {
// Need to buffer more input.
err = 0;
goto done;
}
if (lavc_ret < 0) {
MP_FATAL(af, "Encode failed.\n");
goto done;
}
#else
err = read_input_frame(af, frame);
if (err < 0)
goto done;
if (err == 0)
goto done;
err = -1;
int ok;
int lavc_ret = avcodec_encode_audio2(s->lavc_actx, &pkt, frame, &ok);
int lavc_ret = avcodec_encode_audio2(s->lavc_actx, &s->pkt, frame, &ok);
av_frame_free(&frame);
s->input->samples = 0;
if (lavc_ret < 0 || !ok) {
MP_FATAL(af, "Encode failed.\n");
goto done;
return -1;
}
#endif
MP_DBG(af, "avcodec_encode_audio got %d, pending %d.\n",
pkt.size, s->pending->samples + s->input->samples);
s->encoder_buffered -= AC3_FRAME_SIZE;
s->pkt.size, s->pending->samples);
struct mp_audio *out =
mp_audio_pool_get(af->out_pool, af->data, s->out_samples);
if (!out)
goto done;
return -1;
mp_audio_copy_attributes(out, s->pending);
int frame_size = pkt.size;
int frame_size = s->pkt.size;
int header_len = 0;
char hdr[8];
if (s->cfg_add_iec61937_header && pkt.size > 5) {
int bsmod = pkt.data[5] & 0x7;
if (s->cfg_add_iec61937_header && s->pkt.size > 5) {
int bsmod = s->pkt.data[5] & 0x7;
int len = frame_size;
frame_size = AC3_FRAME_SIZE * 2 * 2;
@@ -360,19 +250,13 @@ static int filter_out(struct af_instance *af)
char *buf = (char *)out->planes[0];
memcpy(buf, hdr, header_len);
memcpy(buf + header_len, pkt.data, pkt.size);
memset(buf + header_len + pkt.size, 0,
frame_size - (header_len + pkt.size));
swap_16((uint16_t *)(buf + header_len), pkt.size / 2);
memcpy(buf + header_len, s->pkt.data, s->pkt.size);
memset(buf + header_len + s->pkt.size, 0,
frame_size - (header_len + s->pkt.size));
swap_16((uint16_t *)(buf + header_len), s->pkt.size / 2);
out->samples = frame_size / out->sstride;
af_add_output_frame(af, out);
err = 0;
done:
av_packet_unref(&pkt);
av_frame_free(&frame);
update_delay(af);
return err;
return 0;
}
static int af_open(struct af_instance* af){
@@ -383,9 +267,9 @@ static int af_open(struct af_instance* af){
af->filter_frame = filter_frame;
af->filter_out = filter_out;
s->lavc_acodec = avcodec_find_encoder_by_name(s->cfg_encoder);
s->lavc_acodec = avcodec_find_encoder_by_name("ac3");
if (!s->lavc_acodec) {
MP_ERR(af, "Couldn't find encoder %s.\n", s->cfg_encoder);
MP_ERR(af, "Audio LAVC, couldn't find encoder for codec %s.\n", "ac3");
return AF_ERROR;
}
@@ -394,34 +278,37 @@ static int af_open(struct af_instance* af){
MP_ERR(af, "Audio LAVC, couldn't allocate context!\n");
return AF_ERROR;
}
if (mp_set_avopts(af->log, s->lavc_actx, s->cfg_avopts) < 0)
return AF_ERROR;
// For this one, we require the decoder to expert lists of all supported
// parameters. (Not all decoders do that, but the ones we're interested
// in do.)
if (!s->lavc_acodec->sample_fmts ||
!s->lavc_acodec->channel_layouts)
{
MP_ERR(af, "Audio encoder doesn't list supported parameters.\n");
const enum AVSampleFormat *fmts = s->lavc_acodec->sample_fmts;
for (int i = 0; fmts[i] != AV_SAMPLE_FMT_NONE; i++) {
s->in_sampleformat = af_from_avformat(fmts[i]);
if (s->in_sampleformat) {
s->lavc_actx->sample_fmt = fmts[i];
break;
}
}
if (!s->in_sampleformat) {
MP_ERR(af, "Audio LAVC, encoder doesn't "
"support expected sample formats!\n");
return AF_ERROR;
}
MP_VERBOSE(af, "[af_lavcac3enc]: in sample format: %s\n",
af_fmt_to_str(s->in_sampleformat));
av_init_packet(&s->pkt);
s->input = talloc_zero(s, struct mp_audio);
if (s->cfg_bit_rate) {
int i;
for (i = 0; i < 19; i++) {
if (ac3_bitrate_tab[i] == s->cfg_bit_rate) {
s->bit_rate = ac3_bitrate_tab[i] * 1000;
if (ac3_bitrate_tab[i] == s->cfg_bit_rate)
break;
}
}
if (i >= 19) {
MP_WARN(af, "unable set unsupported bitrate %d, use default "
"bitrate (check manpage to see supported bitrates).\n",
s->cfg_bit_rate);
MP_WARN(af, "af_lavcac3enc unable set unsupported "
"bitrate %d, use default bitrate (check manpage to see "
"supported bitrates).\n", s->cfg_bit_rate);
s->cfg_bit_rate = 0;
}
}
@@ -439,15 +326,12 @@ const struct af_info af_info_lavcac3enc = {
.cfg_add_iec61937_header = 1,
.cfg_bit_rate = 640,
.cfg_min_channel_num = 3,
.cfg_encoder = "ac3",
},
.options = (const struct m_option[]) {
OPT_FLAG("tospdif", cfg_add_iec61937_header, 0),
OPT_CHOICE_OR_INT("bitrate", cfg_bit_rate, 0, 32, 640,
({"auto", 0}, {"default", 0})),
OPT_INTRANGE("minch", cfg_min_channel_num, 0, 2, 6),
OPT_STRING("encoder", cfg_encoder, 0),
OPT_KEYVALUELIST("o", cfg_avopts, 0),
{0}
},
};
+30 -47
View File
@@ -3,18 +3,18 @@
*
* Filter graph creation code taken from FFmpeg ffplay.c (LGPL 2.1 or later)
*
* mpv is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* mpv is 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 Lesser General Public License for more details.
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with mpv. If not, see <http://www.gnu.org/licenses/>.
* 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>
@@ -34,14 +34,11 @@
#include <libavfilter/buffersink.h>
#include <libavfilter/buffersrc.h>
#include "config.h"
#include "audio/format.h"
#include "audio/fmt-conversion.h"
#include "af.h"
#include "common/av_common.h"
#include "common/tags.h"
#include "options/m_option.h"
@@ -50,7 +47,6 @@
#if LIBAVFILTER_VERSION_MICRO < 100
#define graph_parse(graph, filters, inputs, outputs, log_ctx) \
avfilter_graph_parse(graph, filters, inputs, outputs, log_ctx)
#define avfilter_graph_send_command(a, b, c, d, e, f, g) -1
#else
#define graph_parse(graph, filters, inputs, outputs, log_ctx) \
avfilter_graph_parse_ptr(graph, filters, &(inputs), &(outputs), log_ctx)
@@ -67,8 +63,6 @@ struct priv {
bool eof;
struct mp_tags *metadata;
// options
char *cfg_graph;
char **cfg_avopts;
@@ -196,10 +190,6 @@ static int control(struct af_instance *af, int cmd, void *arg)
if (af_to_avformat(in->format) == AV_SAMPLE_FMT_NONE)
mp_audio_set_format(in, AF_FORMAT_FLOAT);
// Removing this requires fixing AVFrame.data vs. AVFrame.extended_data
if (in->channels.num > AV_NUM_DATA_POINTERS)
return AF_ERROR;
if (!mp_chmap_is_lavc(&in->channels))
mp_chmap_reorder_to_lavc(&in->channels); // will always work
@@ -216,27 +206,13 @@ static int control(struct af_instance *af, int cmd, void *arg)
mp_chmap_from_lavc(&out_cm, l_out->channel_layout);
mp_audio_set_channels(out, &out_cm);
if (!mp_audio_config_valid(out) || out->channels.num > AV_NUM_DATA_POINTERS)
if (!mp_audio_config_valid(out))
return AF_ERROR;
p->timebase_out = l_out->time_base;
return mp_audio_config_equals(in, &orig_in) ? AF_OK : AF_FALSE;
}
case AF_CONTROL_COMMAND: {
if (!p->graph)
break;
char **args = arg;
return avfilter_graph_send_command(p->graph, "all",
args[0], args[1], &(char){0}, 0, 0)
>= 0 ? CONTROL_OK : CONTROL_ERROR;
}
case AF_CONTROL_GET_METADATA:
if (p->metadata) {
*(struct mp_tags *)arg = *p->metadata;
return CONTROL_OK;
}
return CONTROL_NA;
case AF_CONTROL_RESET:
reset(af);
return AF_OK;
@@ -244,17 +220,6 @@ static int control(struct af_instance *af, int cmd, void *arg)
return AF_UNKNOWN;
}
static void get_metadata_from_av_frame(struct af_instance *af, AVFrame *frame)
{
#if HAVE_AVFRAME_METADATA
struct priv *p = af->priv;
if (!p->metadata)
p->metadata = talloc_zero(p, struct mp_tags);
mp_tags_copy_from_av_dictionary(p->metadata, av_frame_get_metadata(frame));
#endif
}
static int filter_frame(struct af_instance *af, struct mp_audio *data)
{
struct priv *p = af->priv;
@@ -266,15 +231,32 @@ static int filter_frame(struct af_instance *af, struct mp_audio *data)
if (!p->graph)
goto error;
AVFilterLink *l_in = p->in->outputs[0];
if (data) {
frame = mp_audio_to_avframe_and_unref(data);
data = NULL;
frame = av_frame_alloc();
if (!frame)
goto error;
frame->nb_samples = data->samples;
frame->format = l_in->format;
// Timebase is 1/sample_rate
frame->pts = p->samples_in;
p->samples_in += frame->nb_samples;
frame->channel_layout = l_in->channel_layout;
frame->sample_rate = l_in->sample_rate;
#if LIBAVFILTER_VERSION_MICRO >= 100
// FFmpeg being a stupid POS
frame->channels = l_in->channels;
#endif
frame->extended_data = frame->data;
for (int n = 0; n < data->num_planes; n++)
frame->data[n] = data->planes[n];
frame->linesize[0] = frame->nb_samples * data->sstride;
p->samples_in += data->samples;
}
if (av_buffersrc_add_frame(p->in, frame) < 0)
@@ -325,7 +307,6 @@ static int filter_out(struct af_instance *af)
af->delay = in_time - out_time;
}
get_metadata_from_av_frame(af, frame);
af_add_output_frame(af, out);
av_frame_free(&frame);
return 0;
@@ -345,6 +326,8 @@ static int af_open(struct af_instance *af)
af->uninit = uninit;
af->filter_frame = filter_frame;
af->filter_out = filter_out;
// Removing this requires fixing AVFrame.data vs. AVFrame.extended_data
assert(MP_NUM_CHANNELS <= AV_NUM_DATA_POINTERS);
return AF_OK;
}
+188 -320
View File
@@ -28,9 +28,9 @@
#include <assert.h>
#include <libavutil/opt.h>
#include <libavutil/audioconvert.h>
#include <libavutil/common.h>
#include <libavutil/samplefmt.h>
#include <libavutil/channel_layout.h>
#include <libavutil/mathematics.h>
#include "common/common.h"
@@ -49,7 +49,6 @@
#define avresample_convert(ctx, out, out_planesize, out_samples, in, in_planesize, in_samples) \
swr_convert(ctx, out, out_samples, (const uint8_t**)(in), in_samples)
#define avresample_set_channel_mapping swr_set_channel_mapping
#define avresample_set_compensation swr_set_compensation
#else
#error "config.h broken or no resampler found"
#endif
@@ -59,30 +58,12 @@
#include "options/m_option.h"
#include "audio/filter/af.h"
#include "audio/fmt-conversion.h"
#include "osdep/endian.h"
struct af_resample_opts {
int filter_size;
int phase_shift;
int linear;
double cutoff;
int normalize;
};
struct af_resample {
int allow_detach;
char **avopts;
double playback_speed;
struct AVAudioResampleContext *avrctx;
struct mp_audio avrctx_fmt; // output format of avrctx
struct mp_audio pool_fmt; // format used to allocate frames for avrctx output
struct mp_audio pre_out_fmt; // format before final conversion (S24)
struct AVAudioResampleContext *avrctx_out; // for output channel reordering
struct af_resample_opts opts; // opts requested by the user
// At least libswresample keeps a pointer around for this:
int reorder_in[MP_NUM_CHANNELS];
int reorder_out[MP_NUM_CHANNELS];
struct mp_audio_pool *reorder_buffer;
int in_rate_af; // filter input sample rate
int in_rate; // actual rate (used by lavr), adjusted for playback speed
@@ -93,45 +74,50 @@ struct af_resample {
struct mp_chmap out_channels;
};
struct af_resample {
int allow_detach;
char **avopts;
double playback_speed;
struct mp_audio *pending;
bool avrctx_ok;
struct AVAudioResampleContext *avrctx;
struct AVAudioResampleContext *avrctx_out; // for output channel reordering
struct af_resample_opts ctx; // opts in the context
struct af_resample_opts opts; // opts requested by the user
// At least libswresample keeps a pointer around for this:
int reorder_in[MP_NUM_CHANNELS];
int reorder_out[MP_NUM_CHANNELS];
struct mp_audio_pool *reorder_buffer;
};
#if HAVE_LIBAVRESAMPLE
static double get_delay(struct af_resample *s)
static int get_delay(struct af_resample *s)
{
return avresample_get_delay(s->avrctx) / (double)s->in_rate +
avresample_available(s->avrctx) / (double)s->out_rate;
return avresample_get_delay(s->avrctx);
}
static int get_out_samples(struct af_resample *s, int in_samples)
static void drop_all_output(struct af_resample *s)
{
return avresample_get_out_samples(s->avrctx, in_samples);
while (avresample_read(s->avrctx, NULL, 1000) > 0) {}
}
static int get_drain_samples(struct af_resample *s)
{
return avresample_get_out_samples(s->avrctx, 0);
}
#else
static double get_delay(struct af_resample *s)
static int get_delay(struct af_resample *s)
{
int64_t base = s->in_rate * (int64_t)s->out_rate;
return swr_get_delay(s->avrctx, base) / (double)base;
return swr_get_delay(s->avrctx, s->ctx.in_rate);
}
static int get_out_samples(struct af_resample *s, int in_samples)
static void drop_all_output(struct af_resample *s)
{
#if LIBSWRESAMPLE_VERSION_MAJOR > 1 || LIBSWRESAMPLE_VERSION_MINOR >= 2
return swr_get_out_samples(s->avrctx, in_samples);
#else
return av_rescale_rnd(in_samples, s->out_rate, s->in_rate, AV_ROUND_UP)
+ swr_get_delay(s->avrctx, s->out_rate);
#endif
while (swr_drop_output(s->avrctx, 1000) > 0) {}
}
static int get_drain_samples(struct af_resample *s)
{
return 4096; // libswscale does not have this
}
#endif
static void close_lavrr(struct af_instance *af)
{
struct af_resample *s = af->priv;
if (s->avrctx)
avresample_close(s->avrctx);
avresample_free(&s->avrctx);
if (s->avrctx_out)
avresample_close(s->avrctx_out);
avresample_free(&s->avrctx_out);
}
static int resample_frame(struct AVAudioResampleContext *r,
struct mp_audio *out, struct mp_audio *in)
{
@@ -154,110 +140,72 @@ static int rate_from_speed(int rate, double speed)
return lrint(rate * speed);
}
// Return the format libavresample should convert to, given the final output
// format mp_format. In some cases (S24) we perform an extra conversion step,
// and signal here what exactly libavresample should output. It will be the
// input to the final conversion to mp_format.
static int check_output_conversion(int mp_format)
static bool needs_lavrctx_reconfigure(struct af_resample *s,
struct mp_audio *in,
struct mp_audio *out)
{
if (mp_format == AF_FORMAT_S24)
return AV_SAMPLE_FMT_S32;
return af_to_avformat(mp_format);
return s->ctx.in_rate_af != in->rate ||
s->ctx.in_format != in->format ||
!mp_chmap_equals(&s->ctx.in_channels, &in->channels) ||
s->ctx.out_rate != out->rate ||
s->ctx.out_format != out->format ||
!mp_chmap_equals(&s->ctx.out_channels, &out->channels) ||
s->ctx.filter_size != s->opts.filter_size ||
s->ctx.phase_shift != s->opts.phase_shift ||
s->ctx.linear != s->opts.linear ||
s->ctx.cutoff != s->opts.cutoff;
}
static struct mp_chmap fudge_pairs[][2] = {
{MP_CHMAP2(BL, BR), MP_CHMAP2(SL, SR)},
{MP_CHMAP2(SL, SR), MP_CHMAP2(BL, BR)},
{MP_CHMAP2(SDL, SDR), MP_CHMAP2(SL, SR)},
{MP_CHMAP2(SL, SR), MP_CHMAP2(SDL, SDR)},
};
// Modify out_layout and return the new value. The intention is reducing the
// loss libswresample's rematrixing will cause by exchanging similar, but
// strictly speaking incompatible channel pairs. For example, 7.1 should be
// changed to 7.1(wide) without dropping the SL/SR channels. (We still leave
// it to libswresample to create the remix matrix.)
static uint64_t fudge_layout_conversion(struct af_instance *af,
uint64_t in, uint64_t out)
static bool test_conversion(int src_format, int dst_format)
{
for (int n = 0; n < MP_ARRAY_SIZE(fudge_pairs); n++) {
uint64_t a = mp_chmap_to_lavc(&fudge_pairs[n][0]);
uint64_t b = mp_chmap_to_lavc(&fudge_pairs[n][1]);
if ((in & a) == a && (in & b) == 0 &&
(out & a) == 0 && (out & b) == b)
{
out = (out & ~b) | a;
MP_VERBOSE(af, "Fudge: %s -> %s\n",
mp_chmap_to_str(&fudge_pairs[n][0]),
mp_chmap_to_str(&fudge_pairs[n][1]));
}
}
return out;
}
// mp_chmap_get_reorder() performs:
// to->speaker[n] = from->speaker[src[n]]
// but libavresample does:
// to->speaker[dst[n]] = from->speaker[n]
static void transpose_order(int *map, int num)
{
int nmap[MP_NUM_CHANNELS] = {0};
for (int n = 0; n < num; n++) {
for (int i = 0; i < num; i++) {
if (map[n] == i)
nmap[i] = n;
}
}
memcpy(map, nmap, sizeof(nmap));
return af_to_avformat(src_format) != AV_SAMPLE_FMT_NONE &&
af_to_avformat(dst_format) != AV_SAMPLE_FMT_NONE;
}
static int configure_lavrr(struct af_instance *af, struct mp_audio *in,
struct mp_audio *out, bool verbose)
struct mp_audio *out)
{
struct af_resample *s = af->priv;
close_lavrr(af);
s->avrctx = avresample_alloc_context();
s->avrctx_out = avresample_alloc_context();
if (!s->avrctx || !s->avrctx_out)
goto error;
s->avrctx_ok = false;
enum AVSampleFormat in_samplefmt = af_to_avformat(in->format);
enum AVSampleFormat out_samplefmt = check_output_conversion(out->format);
enum AVSampleFormat out_samplefmtp = av_get_planar_sample_fmt(out_samplefmt);
enum AVSampleFormat out_samplefmt = af_to_avformat(out->format);
if (in_samplefmt == AV_SAMPLE_FMT_NONE ||
out_samplefmt == AV_SAMPLE_FMT_NONE ||
out_samplefmtp == AV_SAMPLE_FMT_NONE)
goto error;
if (in_samplefmt == AV_SAMPLE_FMT_NONE || out_samplefmt == AV_SAMPLE_FMT_NONE)
return AF_ERROR;
s->out_rate = out->rate;
s->in_rate_af = in->rate;
s->in_rate = rate_from_speed(in->rate, s->playback_speed);
s->out_format = out->format;
s->in_format = in->format;
s->out_channels= out->channels;
s->in_channels = in->channels;
avresample_close(s->avrctx);
avresample_close(s->avrctx_out);
av_opt_set_int(s->avrctx, "filter_size", s->opts.filter_size, 0);
av_opt_set_int(s->avrctx, "phase_shift", s->opts.phase_shift, 0);
av_opt_set_int(s->avrctx, "linear_interp", s->opts.linear, 0);
talloc_free(s->pending);
s->pending = NULL;
av_opt_set_double(s->avrctx, "cutoff", s->opts.cutoff, 0);
s->ctx.out_rate = out->rate;
s->ctx.in_rate_af = in->rate;
s->ctx.in_rate = rate_from_speed(in->rate, s->playback_speed);
s->ctx.out_format = out->format;
s->ctx.in_format = in->format;
s->ctx.out_channels= out->channels;
s->ctx.in_channels = in->channels;
s->ctx.filter_size = s->opts.filter_size;
s->ctx.phase_shift = s->opts.phase_shift;
s->ctx.linear = s->opts.linear;
s->ctx.cutoff = s->opts.cutoff;
av_opt_set_int(s->avrctx, "filter_size", s->ctx.filter_size, 0);
av_opt_set_int(s->avrctx, "phase_shift", s->ctx.phase_shift, 0);
av_opt_set_int(s->avrctx, "linear_interp", s->ctx.linear, 0);
av_opt_set_double(s->avrctx, "cutoff", s->ctx.cutoff, 0);
int normalize = s->opts.normalize;
if (normalize < 0)
normalize = af->opts->audio_normalize;
#if HAVE_LIBSWRESAMPLE
av_opt_set_double(s->avrctx, "rematrix_maxval", normalize ? 1 : 1000, 0);
#else
av_opt_set_int(s->avrctx, "normalize_mix_level", !!normalize, 0);
av_opt_set_double(s->avrctx, "rematrix_maxval", 1.0, 0);
#endif
if (mp_set_avopts(af->log, s->avrctx, s->avopts) < 0)
goto error;
return AF_ERROR;
struct mp_chmap map_in = in->channels;
struct mp_chmap map_out = out->channels;
@@ -272,89 +220,45 @@ static int configure_lavrr(struct af_instance *af, struct mp_audio *in,
uint64_t in_ch_layout = mp_chmap_to_lavc_unchecked(&map_in);
uint64_t out_ch_layout = mp_chmap_to_lavc_unchecked(&map_out);
struct mp_chmap in_lavc, out_lavc;
mp_chmap_from_lavc(&in_lavc, in_ch_layout);
mp_chmap_from_lavc(&out_lavc, out_ch_layout);
if (verbose && !mp_chmap_equals(&in_lavc, &out_lavc)) {
MP_VERBOSE(af, "Remix: %s -> %s\n", mp_chmap_to_str(&in_lavc),
mp_chmap_to_str(&out_lavc));
}
if (in_lavc.num != map_in.num) {
// For handling NA channels, we would have to add a planarization step.
MP_FATAL(af, "Unsupported channel remapping.\n");
goto error;
}
mp_chmap_get_reorder(s->reorder_in, &map_in, &in_lavc);
transpose_order(s->reorder_in, map_in.num);
if (mp_chmap_equals(&out_lavc, &map_out)) {
// No intermediate step required - output new format directly.
out_samplefmtp = out_samplefmt;
} else {
// Verify that we really just reorder and/or insert NA channels.
struct mp_chmap withna = out_lavc;
mp_chmap_fill_na(&withna, map_out.num);
if (withna.num != map_out.num)
goto error;
}
mp_chmap_get_reorder(s->reorder_out, &out_lavc, &map_out);
s->avrctx_fmt = *out;
mp_audio_set_channels(&s->avrctx_fmt, &out_lavc);
mp_audio_set_format(&s->avrctx_fmt, af_from_avformat(out_samplefmtp));
s->pre_out_fmt = *out;
mp_audio_set_format(&s->pre_out_fmt, af_from_avformat(out_samplefmt));
// If there are NA channels, the final output will have more channels than
// the avrctx output. Also, avrctx will output planar (out_samplefmtp was
// not overwritten). Allocate the output frame with more channels, so the
// NA channels can be trivially added.
s->pool_fmt = s->avrctx_fmt;
if (map_out.num > out_lavc.num)
mp_audio_set_channels(&s->pool_fmt, &map_out);
out_ch_layout = fudge_layout_conversion(af, in_ch_layout, out_ch_layout);
// Real conversion; output is input to avrctx_out.
av_opt_set_int(s->avrctx, "in_channel_layout", in_ch_layout, 0);
av_opt_set_int(s->avrctx, "out_channel_layout", out_ch_layout, 0);
av_opt_set_int(s->avrctx, "in_sample_rate", s->in_rate, 0);
av_opt_set_int(s->avrctx, "out_sample_rate", s->out_rate, 0);
av_opt_set_int(s->avrctx, "in_sample_rate", s->ctx.in_rate, 0);
av_opt_set_int(s->avrctx, "out_sample_rate", s->ctx.out_rate, 0);
av_opt_set_int(s->avrctx, "in_sample_fmt", in_samplefmt, 0);
av_opt_set_int(s->avrctx, "out_sample_fmt", out_samplefmtp, 0);
av_opt_set_int(s->avrctx, "out_sample_fmt", out_samplefmt, 0);
// Just needs the correct number of channels for deplanarization.
struct mp_chmap fake_chmap;
mp_chmap_set_unknown(&fake_chmap, map_out.num);
uint64_t fake_out_ch_layout = mp_chmap_to_lavc_unchecked(&fake_chmap);
if (!fake_out_ch_layout)
goto error;
av_opt_set_int(s->avrctx_out, "in_channel_layout", fake_out_ch_layout, 0);
av_opt_set_int(s->avrctx_out, "out_channel_layout", fake_out_ch_layout, 0);
struct mp_chmap in_lavc;
mp_chmap_from_lavc(&in_lavc, in_ch_layout);
mp_chmap_get_reorder(s->reorder_in, &map_in, &in_lavc);
av_opt_set_int(s->avrctx_out, "in_sample_fmt", out_samplefmtp, 0);
struct mp_chmap out_lavc;
mp_chmap_from_lavc(&out_lavc, out_ch_layout);
mp_chmap_get_reorder(s->reorder_out, &out_lavc, &map_out);
// Same configuration; we just reorder.
av_opt_set_int(s->avrctx_out, "in_channel_layout", out_ch_layout, 0);
av_opt_set_int(s->avrctx_out, "out_channel_layout", out_ch_layout, 0);
av_opt_set_int(s->avrctx_out, "in_sample_fmt", out_samplefmt, 0);
av_opt_set_int(s->avrctx_out, "out_sample_fmt", out_samplefmt, 0);
av_opt_set_int(s->avrctx_out, "in_sample_rate", s->out_rate, 0);
av_opt_set_int(s->avrctx_out, "out_sample_rate", s->out_rate, 0);
av_opt_set_int(s->avrctx_out, "in_sample_rate", s->ctx.out_rate, 0);
av_opt_set_int(s->avrctx_out, "out_sample_rate", s->ctx.out_rate, 0);
// API has weird requirements, quoting avresample.h:
// * This function can only be called when the allocated context is not open.
// * Also, the input channel layout must have already been set.
avresample_set_channel_mapping(s->avrctx, s->reorder_in);
avresample_set_channel_mapping(s->avrctx_out, s->reorder_out);
if (avresample_open(s->avrctx) < 0 || avresample_open(s->avrctx_out) < 0) {
if (avresample_open(s->avrctx) < 0 ||
avresample_open(s->avrctx_out) < 0)
{
MP_ERR(af, "Cannot open Libavresample Context. \n");
goto error;
return AF_ERROR;
}
s->avrctx_ok = true;
return AF_OK;
error:
close_lavrr(af);
return AF_ERROR;
}
@@ -382,133 +286,129 @@ static int control(struct af_instance *af, int cmd, void *arg)
if (af_to_avformat(in->format) == AV_SAMPLE_FMT_NONE)
mp_audio_set_format(in, AF_FORMAT_FLOAT);
if (check_output_conversion(out->format) == AV_SAMPLE_FMT_NONE)
if (af_to_avformat(out->format) == AV_SAMPLE_FMT_NONE)
mp_audio_set_format(out, in->format);
int r = ((in->format == orig_in.format) &&
mp_chmap_equals(&in->channels, &orig_in.channels))
? AF_OK : AF_FALSE;
if (r == AF_OK)
r = configure_lavrr(af, in, out, true);
if (r == AF_OK && needs_lavrctx_reconfigure(s, in, out))
r = configure_lavrr(af, in, out);
return r;
}
case AF_CONTROL_SET_FORMAT: {
int format = *(int *)arg;
if (format && af_to_avformat(format) == AV_SAMPLE_FMT_NONE)
return AF_FALSE;
mp_audio_set_format(af->data, format);
return AF_OK;
}
case AF_CONTROL_SET_CHANNELS: {
mp_audio_set_channels(af->data, (struct mp_chmap *)arg);
return AF_OK;
}
case AF_CONTROL_SET_RESAMPLE_RATE:
af->data->rate = *(int *)arg;
return AF_OK;
case AF_CONTROL_SET_PLAYBACK_SPEED_RESAMPLE: {
s->playback_speed = *(double *)arg;
int new_rate = rate_from_speed(s->ctx.in_rate_af, s->playback_speed);
if (new_rate != s->ctx.in_rate && s->avrctx_ok && af->fmt_out.format) {
// Before reconfiguring, drain the audio that is still buffered
// in the resampler.
struct mp_audio *pending = talloc_zero(NULL, struct mp_audio);
mp_audio_copy_config(pending, &af->fmt_out);
pending->samples = get_drain_samples(s);
if (pending->samples > 0) {
mp_audio_realloc_min(pending, pending->samples);
int r = resample_frame(s->avrctx, pending, NULL);
pending->samples = MPMAX(r, 0);
}
// Reinitialize resampler.
configure_lavrr(af, &af->fmt_in, &af->fmt_out);
s->pending = pending;
}
return AF_OK;
}
case AF_CONTROL_RESET:
if (s->avrctx) {
#if HAVE_LIBSWRESAMPLE
swr_close(s->avrctx);
if (swr_init(s->avrctx) < 0) {
close_lavrr(af);
return AF_ERROR;
}
#else
while (avresample_read(s->avrctx, NULL, 1000) > 0) {}
#endif
}
drop_all_output(s);
return AF_OK;
}
return AF_UNKNOWN;
}
#undef ctx_opt_set_int
#undef ctx_opt_set_dbl
static void uninit(struct af_instance *af)
{
close_lavrr(af);
struct af_resample *s = af->priv;
if (s->avrctx)
avresample_close(s->avrctx);
avresample_free(&s->avrctx);
if (s->avrctx_out)
avresample_close(s->avrctx_out);
avresample_free(&s->avrctx_out);
talloc_free(s->pending);
}
// The LSB is always ignored.
#if BYTE_ORDER == BIG_ENDIAN
#define SHIFT24(x) ((3-(x))*8)
#else
#define SHIFT24(x) (((x)+1)*8)
#endif
static void extra_output_conversion(struct af_instance *af, struct mp_audio *mpa)
static bool needs_reorder(int *reorder, int num_ch)
{
if (mpa->format == AF_FORMAT_S32 && af->data->format == AF_FORMAT_S24) {
size_t len = mp_audio_psize(mpa) / mpa->bps;
for (int s = 0; s < len; s++) {
uint32_t val = *((uint32_t *)mpa->planes[0] + s);
uint8_t *ptr = (uint8_t *)mpa->planes[0] + s * 3;
ptr[0] = val >> SHIFT24(0);
ptr[1] = val >> SHIFT24(1);
ptr[2] = val >> SHIFT24(2);
}
mp_audio_set_format(mpa, AF_FORMAT_S24);
}
for (int p = 0; p < mpa->num_planes; p++) {
void *ptr = mpa->planes[p];
int total = mpa->samples * mpa->spf;
if (af_fmt_from_planar(mpa->format) == AF_FORMAT_FLOAT) {
for (int s = 0; s < total; s++)
((float *)ptr)[s] = av_clipf(((float *)ptr)[s], -1.0f, 1.0f);
} else if (af_fmt_from_planar(mpa->format) == AF_FORMAT_DOUBLE) {
for (int s = 0; s < total; s++)
((double *)ptr)[s] = MPCLAMP(((double *)ptr)[s], -1.0, 1.0);
}
for (int n = 0; n < num_ch; n++) {
if (reorder[n] != n)
return true;
}
return false;
}
// This relies on the tricky way mpa was allocated.
static void reorder_planes(struct mp_audio *mpa, int *reorder,
struct mp_chmap *newmap)
static void reorder_planes(struct mp_audio *mpa, int *reorder)
{
struct mp_audio prev = *mpa;
mp_audio_set_channels(mpa, newmap);
// The trailing planes were never written by avrctx, they're the NA channels.
int next_na = prev.num_planes;
for (int n = 0; n < mpa->num_planes; n++) {
int src = reorder[n];
assert(src >= -1 && src < prev.num_planes);
if (src >= 0) {
mpa->planes[n] = prev.planes[src];
} else {
assert(next_na < mpa->num_planes);
mpa->planes[n] = prev.planes[next_na++];
af_fill_silence(mpa->planes[n], mpa->sstride * mpa->samples,
mpa->format);
}
assert(reorder[n] >= 0 && reorder[n] < mpa->num_planes);
mpa->planes[n] = prev.planes[reorder[n]];
}
}
static int filter_resample(struct af_instance *af, struct mp_audio *in)
static int filter(struct af_instance *af, struct mp_audio *in)
{
struct af_resample *s = af->priv;
struct mp_audio *out = NULL;
if (!s->avrctx)
goto error;
if (s->pending) {
if (s->pending->samples) {
af_add_output_frame(af, s->pending);
} else {
talloc_free(s->pending);
}
s->pending = NULL;
}
int samples = get_out_samples(s, in ? in->samples : 0);
struct mp_audio out_format = s->pool_fmt;
out = mp_audio_pool_get(af->out_pool, &out_format, samples);
int samples = avresample_available(s->avrctx) +
av_rescale_rnd(get_delay(s) + (in ? in->samples : 0),
s->ctx.out_rate, s->ctx.in_rate, AV_ROUND_UP);
struct mp_audio *out = mp_audio_pool_get(af->out_pool, af->data, samples);
if (!out)
goto error;
if (in)
mp_audio_copy_attributes(out, in);
mp_audio_realloc_min(out, out->samples);
af->delay = get_delay(s) / (double)s->ctx.in_rate;
if (out->samples) {
out->samples = resample_frame(s->avrctx, out, in);
if (out->samples < 0)
goto error;
}
struct mp_audio real_out = *out;
mp_audio_copy_config(out, &s->avrctx_fmt);
if (out->samples && !mp_audio_config_equals(out, &s->pre_out_fmt)) {
assert(af_fmt_is_planar(out->format) && out->format == real_out.format);
reorder_planes(out, s->reorder_out, &s->pool_fmt.channels);
if (!mp_audio_config_equals(out, &s->pre_out_fmt)) {
struct mp_audio *new = mp_audio_pool_get(s->reorder_buffer,
&s->pre_out_fmt,
if (needs_reorder(s->reorder_out, out->nch)) {
if (AF_FORMAT_IS_PLANAR(out->format)) {
reorder_planes(out, s->reorder_out);
} else if (out->samples) {
struct mp_audio *new = mp_audio_pool_get(s->reorder_buffer, out,
out->samples);
if (!new)
goto error;
@@ -521,17 +421,12 @@ static int filter_resample(struct af_instance *af, struct mp_audio *in)
}
}
extra_output_conversion(af, out);
talloc_free(in);
if (out->samples) {
af_add_output_frame(af, out);
} else {
talloc_free(out);
}
af->delay = get_delay(s);
return 0;
error:
talloc_free(in);
@@ -539,39 +434,6 @@ error:
return -1;
}
static int filter(struct af_instance *af, struct mp_audio *in)
{
struct af_resample *s = af->priv;
int new_rate = rate_from_speed(s->in_rate_af, s->playback_speed);
bool need_reinit = fabs(new_rate / (double)s->in_rate - 1) > 0.01;
if (s->avrctx) {
AVRational r = av_d2q(s->playback_speed * s->in_rate_af / s->in_rate,
INT_MAX / 2);
// Essentially, swr/avresample_set_compensation() does 2 things:
// - adjust output sample rate by sample_delta/compensation_distance
// - reset the adjustment after compensation_distance output samples
// Increase the compensation_distance to avoid undesired reset
// semantics - we want to keep the ratio for the whole frame we're
// feeding it, until the next filter() call.
int mult = INT_MAX / 2 / MPMAX(MPMAX(abs(r.num), abs(r.den)), 1);
r = (AVRational){ r.num * mult, r.den * mult };
if (avresample_set_compensation(s->avrctx, r.den - r.num, r.den) < 0)
need_reinit = true;
}
if (need_reinit && new_rate != s->in_rate) {
// Before reconfiguring, drain the audio that is still buffered
// in the resampler.
filter_resample(af, NULL);
// Reinitialize resampler.
configure_lavrr(af, &af->fmt_in, &af->fmt_out, false);
}
return filter_resample(af, in);
}
static int af_open(struct af_instance *af)
{
struct af_resample *s = af->priv;
@@ -583,9 +445,17 @@ static int af_open(struct af_instance *af)
if (s->opts.cutoff <= 0.0)
s->opts.cutoff = af_resample_default_cutoff(s->opts.filter_size);
s->avrctx = avresample_alloc_context();
s->avrctx_out = avresample_alloc_context();
s->reorder_buffer = mp_audio_pool_create(s);
return AF_OK;
if (s->avrctx && s->avrctx_out) {
return AF_OK;
} else {
MP_ERR(af, "Cannot initialize Libavresample Context. \n");
uninit(af);
return AF_ERROR;
}
}
#define OPT_BASE_STRUCT struct af_resample
@@ -594,13 +464,13 @@ const struct af_info af_info_lavrresample = {
.info = "Sample frequency conversion using libavresample",
.name = "lavrresample",
.open = af_open,
.test_conversion = test_conversion,
.priv_size = sizeof(struct af_resample),
.priv_defaults = &(const struct af_resample) {
.opts = {
.filter_size = 16,
.cutoff = 0.0,
.phase_shift = 10,
.normalize = -1,
},
.playback_speed = 1.0,
.allow_detach = 1,
@@ -611,8 +481,6 @@ 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_CHOICE("normalize", opts.normalize, 0,
({"no", 0}, {"yes", 1}, {"auto", -1})),
OPT_KEYVALUELIST("o", avopts, 0),
{0}
},
Loaded 100 of 551 files, more files were not shown because too many files have changed in this diff. Show more