It would make somewhat sense for libcs which don't implement locales at
all, such as Bionic.
Beyond that, setlocale() is specified that it can return NULL, and we
shouldn't crash if that happens.
Makes the next commit simpler. It's probably a bad idea to add more
fields to the global state, but on the other hand the client API state
is pretty much per-instance anyway. It also will help with things like
the proposed libmpv custom stream API.
This makes no sense, because the client is obligated to react to this
event.
This also happens to fix a deadlock with JSON IPC clients sending
"disable_event all", because MPV_EVENT_SHUTDOWN was used to stop the
thread driving the socket connection (fixes#2558).
Client API users can enable log output with mpv_request_log_messages().
But you can enable only a single log level. This is normally enough, but
the --msg-level option (which controls the terminal log level) provides
more flexibility. Due to internal complexity, it would be hard to
provide the same flexibility for each client API handle. But there's a
simple way to achieve basically the same thing: add an option that sends
log messages to the API handle, which would also be printed to the
terminal as by --msg-level.
The only change is that we don't disable this logic if the terminal is
disabled. Instead we check for this before the message is output, which
in theory can lower performance if messages are being spammed. It could
be handled with some more effort, but the gain would be negligible.
Adding an external audio track before loading the main file didn't work
right. For one, mp_switch_track() assumes it is called after the main
file is loaded. (The difference is that decoders are only initialized
once the main file is loaded, and we avoid doing this before that for
whatever reason.)
To avoid further messiness, just allow mp_switch_track() to be called at
any time. Also make it do what mp_mark_user_track_selection() did, since
the latter requires current_track to be set. (One could probably simply
allow current_track to be set at this point, but it'd interfere with
default track selection anyway and thus would be pointless.)
Fixes#1984.
There is not much of a reason to have these wrappers around. Use POSIX
standard functions directly, and use a separate utility function to take
care of the timespec calculations. (Course POSIX for using this weird
format for time values.)
The client API (libmpv) and encoding (--o) have slightly different
defaults from the command line player. Instead of doing a bunch of calls
to set the options explicitly, use profiles. This is simpler and has the
advantage that they can be listed on command line (instead of possibly
forcing the user to find and read the code to know all the details).
Unlike other VOs, this rendered OSD even while no VO was created
(because the renderer lives as long as the API user wants). Change this,
and refactor the code so that the OSD object is accessible only while
the VO is created.
(There is a short time where the OSD can still be accessed even after VO
destruction - this is not a race condition, though it's inelegant and
unfortunately unavoidable.)
Move the command line parsing and some other things to the common init
routine shared between command line player and client API. This means
they're using almost exactly the same code now.
The main intended side effect is that the client API will load mpv.conf;
though still only if config loading is enabled.
(The cplayer still avoids creating an extra thread, passes a command
line, and prints an exit status to the terminal. It also has some
different defaults.)
This does what it's documented to do.
The implementation reuses the code in mpv_detach_destroy(). Due to the
way async requests currently work, just sending a synchronous dummy
request (like a "ignore" command) would be enough to ensure
synchronization, but this code will continue to work even if this
changes.
The line "ctx->event_mask = 0;" is removed, but it shouldn't be needed.
(If a client is somehow very slow to terminate, this could silence an
annoying queue overflow message, but all in all it does nothing.)
Calling mpv_wait_async_requests() and mpv_wait_event() concurrently is
in theory allowed, so change pthread_cond_signal() to
pthread_cond_broadcast() to avoid missed wakeups.
As requested in issue #1542.
Sigh...
The C locale system is incredibly shitty, and if used, breaks basic
string functions. The locale can change the decimal mark from "." to
",", which affects conversion between floats and strings: snprintf() and
strtod() respect the locale decimal mark, and change behavior. (What's
even better, the behavior of these functions can change asynchronously,
if setlocale() is called after threads were started.)
So just check the locale in the client API, and refuse to work if it's
wrong. This also makes the lib print to stderr, which I consider the
lesser evil in this specific situation.
Before this, we merely printed a message to the terminal. Now the API
user can determine this properly. This might be important for API users
which somehow maintain complex state, which all has to be invalidated if
(state-changing) events are missing due to an overflow.
This also forces the client API user to empty the event queue, which is
good, because otherwise the event queue would reach the "filled up"
state immediately again due to further asynchronous events being added
to the queue.
Also add some minor improvements to mpv_wait_event() documentation, and
some other minor cosmetic changes.
mpv_opengl_cb_uninit_gl() can be called at any time; but then the
decoder must be destroyed due to complications with hardware decoding.
This is why kill_video() exists. To make things easier, there is the
invariant that while vo_opengl_cb is active, the OpenGL state must
exist. But kill_video() didn't actually destroy the VO; only the video
decoder. This could trigger an assertion (vo_opengl_cb.c:187).
Actually, the video output is always destroyed lazily at a later point
if the decoder is destroyed, but not early enough for out purposes.
This may or may not be useful for client API users.
Fold this API extension into the previous API bump. The previous bump
was only yesterday, so it's ok.
Until now, calling mpv_opengl_cb_uninit_gl() at a "bad moment" could
make the whole thing to explode. The API user was asked to avoid such
situations by calling it only in "good moments". But this was probably a
bit too subtle and could easily be overlooked.
Integrate the approach the qml example uses directly into the
implementation. If the OpenGL context is to be unitialized, forcefully
disable video, and block until this is done.
Before this commit, this was defined to trigger undefined behavior. This
was nice because it required less code; but on the other hand, Lua as
well as IPC support had to check these things manually. Do it directly
in the API to avoid code duplication, and to make the API more robust.
(The total code size still grows, though...)
Since all of the failure cases were originally meant to ruin things
forever, there is no way to return error codes. So just print the
errors.
This adds API to libmpv that lets host applications use the mpv opengl
renderer. This is a more flexible (and possibly more portable) option to
foreign window embedding (via --wid).
This assumes that methods like context sharing and multithreaded OpenGL
rendering are infeasible, and that a way is needed to integrate it with
an application that uses a single thread to render everything.
Add an example that does this with QtQuick/qml. The example is
relatively lazy, but still shows how relatively simple the integration
is. The FBO indirection could probably be avoided, but would require
more work (and would probably lead to worse QtQuick integration, because
it would have to ignore transformations like rotation).
Because this makes mpv directly use the host application's OpenGL
context, there is no platform specific code involved in mpv, except
for hw decoding interop.
main.qml is derived from some Qt example.
The following things are still missing:
- a way to do better video timing
- expose GL renderer options, allow changing them at runtime
- support for color equalizer controls
- support for screenshots
This is simply not allowed, and doing it triggered an assertion. It's
still not allowed, because the terminal and related functionality is a
global resource, and there doesn't seem to be a sane way to manage the
signal handlers.
But be a bit nicer, and just the terminal if it's already in use.
Note that terminal _output_ happens anyway. This becomes usable with
this commit. To facilitate logging-only usage further, also explicitly
disable terminal input, so that "terminal=yes" can be used for logging
without much interference with other things. (It'll still overwrite some
signal handlers, though.)
Currently, --ytdl is off by default, but even if this is changed, never
enable it by default for the client API. It would be inappropriate to
start an intrusive external subprocess behind the host application's
back.
Use a fixed size array for the client name, which also limits the client
name in size. Sanitize the client name string, and replace characters
that are not in [A-Za-z0-9] with '_'.
The values compared here happen to be of unsigned enum types - but the
test is not supposed to break if we somehow force the enum to signed, or
if the compiler happens to use a signed type (as far as I remember, the
exact integer type the compiler can use is implementation-defined).
Add a generic mechanism to the VO to relay "extra" events from VO to
player. Use it to notify the core of window resizes, which in turn will
be used to mark all affected properties ("window-scale" in this case) as
changed.
(I refrained from hacking this as internal command into input_ctx, or to
poll the state change, etc. - but in the end, maybe it would be best to
actually pass the client API context directly to the places where events
can happen.)
This is probably what libmpv users want; and it also improves error
reporting (or we'd have to add a way to communicate such mid-playback
failures as events).
Especially with other components (libavcodec, OSX stuff), the thread
list can get quite populated. Setting the thread name helps when
debugging.
Since this is not portable, we check the OS variants in waf configure.
old-configure just gets a special-case for glibc, since doing a full
check here would probably be a waste of effort.
A vague idea to get something similar what libquvi did.
Undocumented because it might change a lot, or even be removed. To give
an idea what it does, a Lua script could do the following:
-- type ID priority
mp.commandv("hook_add", "on_load", 0, 0)
mp.register_script_message("hook_run", function(param, param2)
-- param is "0", the user-chosen ID from the hook_add command
-- param2 is the magic value that has to be passed to finish
-- the hook
mp.resume_all()
-- do something, maybe set options that are reset on end:
mp.set_property("file-local-options/name", "value")
-- or change the URL that's being opened:
local url = mp.get_property("stream-open-filename")
mp.set_property("stream-open-filename", url .. ".png")
-- let the player (or the next script) continue
mp.commandv("hook_ack", param2)
end)
Allows passing native types as arguments.
Also some minor doc improvements, including giving some (natural)
improvements to mpv_free_node_contents().
Note: mpv_command_node_async() is completely untested.
The event monitor is used to get keyboard events when there is no window, but
since it is a global monitor to the current process, we don't want it in a
library setting.
After @frau's split of macosx_events from macosx_application, `is_cplayer' is
not needed anymore. At the moment only global events such as Media Keys and
Apple Remote work, because the VO-level ones were hardcoded to be disabled.
(that will be fix in a later commit ).
Maybe using strings for log levels was a mistake (too broad and too
impractical), so I'm adding numeric log level at least for the receiver
side. This makes it easier to map mpv log levels to other logging
systems.
I'm still too stingy to add a function to set the log level by a numeric
value, though.
The numeric values are not directly mapped to the internal mpv values,
because then almost every file in mpv would have to include the client
API header.
Coalesce this into API version 1.6, since 1.6 was bumped just yesterday.
Commit 64b7811c tried to do the "right thing" with respect to whether
keyboard input should be enabled or not. It turns out that X11 does
something stupid by design. All modern toolkits work around this native
X11 behavior, but embedding breaks these workarounds.
The only way to handle this correctly is the XEmbed protocol. It needs
to be supported by the toolkit, and probably also some mpv support. But
Qt has inconsistent support for it. In Qt 4, a X11 specific embedding
widget was needed. Qt 5.0 doesn't support it at all. Qt 5.1 apparently
supports it via QWindow, but if it really does, I couldn't get it to
work.
So add a hack instead. The new --input-x11-keyboard option controls
whether mpv should enable keyboard input on the X11 window or not. In
the command line player, it's enabled by default, but in libmpv it's
disabled.
This hack has the same problem as all previous embedding had: move the
mouse outside of the window, and you don't get keyboard input anymore.
Likewise, mpv will steal all keyboard input from the parent application
as long as the mouse is inside of the mpv window.
Also see issue #1090.
If you send the "quit" or "stop" command with the client API, it will
now attempt to kill network I/O immediately (same as normal input in the
previous commits).
This makes the player wait until each script is loaded. Do this to give
the script a chance to setup all its event handlers. It might also be
useful to allow a script to change options that matter for playback.
While waiting for a script to be loaded, the player actually accepts
input. This is needed because the scripts can execute player commands
anyway while they are being "loaded". The player won't react to most
commands though: it can't quit or navigate the playlist in this state.
For deciding whether a script is finally loaded, we use a cheap hack: if
mpv_wait_event() is called, it's considered loaded. Let's hope this is
good enough. I think it's better than introducing explicit API for this.
Although I'm sure this will turn out as too simplistic some time in the
future, the same would probably happen with a more explicit API.
The event was copied early, and wasn't released if it was rejected
instead of being added to the event queue. Fix by copying the event at a
point when it's certainly added to the event queue.
The dup_event_data() function is merely moved.
Add a mechanism to the client API code, which allows the player core to
query whether a client API event is needed at all. Use it for the cache
update.
In this case, this is probably a pure microoptimization; but the
mechanism will be useful for other things too.
Until recently, vo_opengl could be accessed from a single thread only,
due to the OpenGL API context being thread-specific. This issue doesn't
exist anymore, because VOs run on their own thread. This means we can
simply lock/unlock the playloop instead of doing something complicated
to get the playloop thread to execute our code.
Internally, there are two mechanisms which can trigger property
notification as used with "observed" properties in the client API.
The first mechanism associates events with a group of properties that
are potentially changed by a certain event. mp_event_property_change[]
declares these associations, and maps each event to a set of strings.
When an event happens, the set of strings is matched against the list of
observed properties of each client. Make this more efficient by
comparing bitsets of events instead. This way, only a bit-wise "and" is
needed for each observed property. Even better, we can completely skip
clients which have no observed properties that match.
The second mechanism just updates individual properties explicitly by
name. Optimize this by using the property index instead. It would be
nice if we could reuse the first mechanism for the second one, but
there are too many properties to fit into a 64 bit mask.
(Though the limit on 64 events might get us into trouble later...)
This is perfectly allowed, but was ignored, because it's a corner case.
It doesn't actually wait for other clients to be destroyed, but on the
other hand I think there's no way to have other clients before
initialization.
CC: @mpv-player/stable
While I'm not very fond of "const", it's important for declarations
(it decides whether a symbol is emitted in a read-only or read/write
section). Fix all these cases, so we have writeable global data only
when we really need.
Since redundant wakeups are avoided now, it's easy to miss a wakeup when
creating/setting the pipe/callback after the client API was signalled.
If the client API is signalled, need_wakeup is set to true, and
wakeup_client skips writing to the pipe or calling the client API. That
this can happen is not very obvious to the client API, so trigger a
wakeup right on start in order to remove this special case.
Until now, availability of new log messages (through the mechanism
associated with mpv_request_log_messages()) did not wakeup the client
API properly. Commit 3b7402b5 was basically a hack to improve that
somewhat, but it wasn't a solution.
The main problem is that the client API itself is producing messages, so
the message callback would attempt to lock the client API lock,
resulting in a deadlock. Even if the lock was recursive, we'd run into
lock-order issues.
Solve this by using a separate lock for waiting and wakeup. Also, since
it's a natural addition, avoid redundant wakeups. This means the wakeup
callback as well as the wakeup pipe will be triggered only once until
the next mpv_wait_event() call happens.
This might make the wakeup callback be invoked in a reentrant way for
the first time, for example if a mpv_* function prints to a log. Adjust
the docs accordingly. (Note that non-reentrant beheavior was never
guaranteed - basically the wakeup callback is somewhat dangerous and
inconvenient.)
Also remove some traces of unneeded code. ctx->shutdown for one was
never set, and probably a leftover of an abandoned idea.
A bit verbose, but less misleading. In most cases, the API user probably
actually wants mpv_terminate_destroy() instead, so the less-useful
function shouldn't have a simnpler name anyway.
mpv_destroy() should perhaps better be called mpv_detach(), because it
destroys only the handle, not necessarily the player. The player is only
terminated if a quit command is sent.
This function quits automatically, and additionally waits until the
player is completely destroyed. It removes the possibility that the
player core is still uninitializing, while all client handles are
already destroyed. (Although in practice, the difference is usually not
important.)
Now a negative timeout mean an infinite timeout. This is similar to the
poll() system call. Apparently this is more intuitive and less confusing
than specifying a "very high" value as timeout if you want to wait
forever.
For callers that never pass negative timeouts, nothing changes.
Listening on messages currently uses polling (every time
mpv_wait_event() has no new events, the message buffer is polled and a
message event is possibly created). Improve this situation a bit, and
call the user-supplied wakeup callback.
This will increase the frequency with which the wakeup callback is
called, but the client is already supposed to be able to deal with this
situation. Also, as before, calling mpv_wait_event() from the wakeup
callback is forbidden, so the client can't read new messages from the
callback directly.
The wakeup pipe is written either. Since the wakeup pipe is created
lazily, we can't access the pipe handle without creating a race
condition or a deadlock. (This is actually very silly, since in practice
the race condition won't matter, but for now let's keep it clean.)
If an API user calls mpv_wait_event() and mpv_observe_property() before
mpv_initialize(), it could happen that a property was accessed before
initialization, which is not ok.
This was always intended this way, and even documented in client.h. Due
to an oversight it was never actually implemented.
The intention is that mpv embedded in applications and "real mpv" don't
conflict. An API user can undo this by setting the "config" option to
"yes", if using the user's mpv config is desired.
Until now, an error was reported only if the command couldn't be parsed.
Attempt to do more fine-grained reporting. This is not necessarily
perfect, but it's an improvement.
This is probably a good idea, because it would make it easier for
software embedding mpv to configure the mpv parts, without requiring the
host program to provide explicit mechanisms for this (other than calling
mpv_load_config_file()).
The code paths for setting options by string and by direct "raw" value
were too different, which resulted in some weird code. Make the code
paths closer to each other.
Also, use this to remove the weirdness in the mpv_set_option()
implementation.
Use the time as returned by mp_time_us() for mpthread_cond_timedwait(),
instead of calculating the struct timespec value based on a timeout.
This (probably) makes it easier to wait for a specific deadline.
If a property is notified as changed, and then again (before the change
notification is returned to the client), and the second change is a
sporadic change (i.e. nothing actually changed) and the change
notification was associated with with a data type, it could happen that
a change was "overlooked", because it would detect no change on the
second notification.
This is actually a pretty annoying corner case, due to the annoying way
we do things, so just store both the previously returned _and_ the newly
obtained property value. then we always compare with the user value to
check for a change, excluding any possibility of a missed change.
Note that we don't (can't/shouldn't) care if a value changes, and then
changes back; it's fine if that doesn't generate a notification. This is
due to how property notifications are supposed to be coalesced.
This was part of osdep/threads.c out of laziness. But it doesn't contain
anything OS dependent. Note that the rest of threads.c actually isn't
all that OS dependent either (just some minor ifdeffery to work around
the lack of clock_gettime() on OSX).
This should fix some issues, such as not being able to set the
"no-video" option with MPV_FORMAT_FLAG.
Note that this changes semantics a bit. Now setting an option strictly
overwrite it, even if the corresponding command line option does not.
For example, if we change --sub to append by default, then setting the
"sub" option via the client API would still never append. (Oddly, this
also applies to --vf-add, which will overwrite the old value when using
the client API.)
I'm doing this because there's no proper separation between the command
line parser and setting an option using the MPV_FORMAT_STRING format.
Maybe the solution to this mess would be adding format aware code (i.e.
m_option_set_node) to every option type, and falling back to strings
only if needed - but this would mean that you couldn't set e.g. an
integer option using MPV_FORMAT_STRING, which doesn't seem to be ideal
either.
In conclusion, the current approach seems to be most robust, but I'm
open to suggestions should someone find that these semantics are a
problem.
And slightly adjust the semantics of MPV_EVENT_PAUSE/MPV_EVENT_UNPAUSE.
The real pause state can now be queried with the "core-idle" property,
the user pause state with the "pause" property, whether the player is
paused due to cache with "paused-for-cache", and the keep open event can
be guessed with the "eof-reached" property.
Otherwise, the client API user could not know why playback was stopped.
Regarding the fact that 0 is used both for normal EOF and EOF on error:
this is because mplayer traditionally did not distinguish these, and in
general it's hard to tell the real reason. (There are various weird
corner cases which make it hard.)
This turned out ridiculously complex. I think it will have to be
simplified some day. Main reason for the complexity are:
- filtering properties by forcing clients to observe individual
properties explicitly
(to avoid spamming clients with changes they don't want)
- optional retrieval of property value with the notification
(the basic idea was that this is more user friendly)
- allowing to the client to specify a format in which the value
should be retrieved
(because if a property changes its type, the client API couldn't
convert it properly, and compatibility would break)
I don't know yet which of these are important, and everything could
change. In particular, the interface and semantics should be adjusted
to reduce the implementation complexity.
While I consider the API complete, there could (and probably will) be
bugs left. Also while the implementation is complete, it's inefficient.
The complexity of the property matching is O(a*b*c) with a clients,
b observed properties, and c properties changing at once. I threw away
an earlier implementation using bitmasks, because it was too unwieldy.
Remove the use of mp_ring and use a simple array and a bunch of
variables instead. This is way less awkwad.
The change in reserve_reply fixes incorrect tracking of free events.
Change script_message to broadcast the message to all clients. Add a new
script_message_to command, which does what the old script_message
command did.
This is intended as simplification, although it might lead to chaos too.
Sending an asynchronous request and then calling mpv_destroy() would
crash the player when trying to send the reply to the removed client.
Fix this by waiting until all remaining replies have been sent.
Always map MPV_FORMAT_STRING to setting property value directly through
M_PROPERTY_SET_STRING, instead of trying to go through
M_PROPERTY_SET_NODE.
This treats a direct MPV_FORMAT_STRING query differently from a
MPV_FORMAT_STRING wrapped in a mpv_node. This was already the case in
mpv_get_property(). The reason for all this is that mpv_node is supposed
to be the exact type, while a direct MPV_FORMAT_STRING goes through all
possible conversions.
Not sure if these semantics are good.
1. Cannot set option after initialized: it seems that this bug has
existed since libmpv was introduced first. Maybe just a typo.
2. Crash when setting property with native format: mpv_set_property
just causes a crash when using a native format. I found an invalid
casting and fixed it.
3. Wrong error value for mpv_get_property: when an error occurred,
mpv_get_property always returns wrong format error because every
error for property except M_PROPERTY_NOT_IMPLEMENTED is just ignored.
Signed-off-by: wm4 <wm4@nowhere>
Closes pull request #593. Does not incldue the first fix, which was not
correct. The underlying bug will be fixed by a later commit.
Commit message extracted from pull request and slightly edited.
Not sure about this... might redo.
At least this provides a case of a broadcasted event, which requires
per-event data allocation.
See github issue #576.
May or may not be useful in some ways.
We require a context parameter for this just to be sure, even if the
internal implementation currently doesn't.
That's one less mpv internal function for the Lua wrapper.
This is only half-implemented: actually the option will first be
converted from mpv_node to its native type, then it's converted to a
string, and then back to its native type. This is because the option
API was made for strings and not anything else.
Other than being grossly inelegant, the only downside is probably with
string lists and key/value lists, which don't escape strings containing
syntax elements correctly.
This actually makes use of the client.h declarations and the mpv_node
mechanisms added some commits ago.
For now, using MPV_FORMAT_STRING will usually fallback to explicit
string conversion, but not in the other cases. E.g. reading a numeric
property as string will work, but not reading a string property as
number. Other than that, only MPV_FORMAT_INT64->MPV_FORMAT_DOUBLE does
an automatic conversion.
I'm not sure whether these semantics and API are good, so comments and
suggestions are welcome.
With mpv_set_property(h, "property", MPV_FORMAT_STRING, ptr), ptr now
has to be of type char** instead of char*. This makes it more consistent
with mpv_get_property() and also non-pointer formats, which will be
introduced in the following commits. mpv_set_property() of course does
not change its interface (only its implementation is adjusted to keep
its interface).
This also affects mpv_set_option(), but again not
mpv_set_option_string().
Add a client API, which is intended to be a stable API to get some rough
control over the player. Basically, it reflects what can be done with
input.conf commands or the old slavemode. It will replace the old
slavemode (and enable the implementation of a new slave protocol).