Compare commits

...
810 Commits
Author SHA1 Message Date
Alessandro Ghedini 973b555672 Release 0.6.2 2014-10-24 20:38:45 +02:00
wm4 0a40fb00b4 player: fix exiting if both audio and video fail initializing
The player was supposed to exit playback if both video and audio failed
to initialize (or if one of the streams was not selected when the other
stream failed). This didn't work; for one this check was missing from
one of the failure paths. And more importantly, both checked the
current_track array incorrectly.

Fix these issues, and move the failure handling code into a common
function.

CC: @mpv-player/stable

Conflicts:
	player/audio.c
	player/video.c
2014-10-23 20:27:32 +02:00
wm4 3c8aecb711 sub: adjustments to --ass-style-override option
Now requires newest libass git. Since this feature wasn't part of a
libass release yet, I'm not bothering making the mpv code compatible
with as how it was previously implemented (it will just be disabled
with any older libass).

CC: @mpv-player/stable (because mpv-build uses libass git, and this
                        breaks the feature)
2014-10-18 15:05:51 +02:00
wm4 b3707f4e21 audio: don't go to sleep after audio reinit
It possibly goes to sleep without actually starting to decode audio.
Possibly fixes a problem with --no-osc --no-video reported on IRC.

CC: @mpv-player/stable
2014-10-18 15:05:46 +02:00
wm4 af58a8c324 terminal: recognize ^h
Fixes #1185.

CC: @mpv-player/stable
2014-10-18 15:05:35 +02:00
shdown 3fae6aaae8 player: quote %-starting strings
Leading percent sign is a quote indicator so it needs to be quoted
itself.
2014-10-18 15:04:54 +02:00
shdown 919540ce8e common: fix \x-style escaping
This was rejecting correct escapes and accepting incorrect ones.
2014-10-18 15:04:46 +02:00
shdown ad9d1a3fb7 manpage: fix reference to a defunct option
The change was made with faad40aad9.
2014-10-18 15:04:27 +02:00
wm4 f16b1cdc17 player: fix crash on early audio uninit
Could crash when exiting playback in very early stages of
initialization.

CC: @mpv-player/stable
2014-10-16 13:13:26 +02:00
wm4 f2e289dc80 player: fix --frames
This could produce an extra frame, because reaching the maximum merely
signals the playloop to exit, without strictly enforcing the limit.

Fixes #1181.

CC: @mpv-player/stable
2014-10-15 15:15:58 +02:00
wm4 4a0e50d2a6 player: signal EOF when using --frames 2014-10-15 15:15:53 +02:00
wm4 a6eb0714fa demux_mkv: fix undefined behavior
With some files, the extradata variable can remain uninitialized, but
will be used for memory access.

CC: @mpv-player/stable (with high priority)
2014-10-15 15:13:47 +02:00
Alessandro Ghedini 7d9f8f75ea Release 0.6.1 2014-10-12 14:25:35 +02:00
wm4 2ffdc0da13 af_lavcac3enc: fix byte order
Oops.

Fixes #1172.

CC: @mpv-player/stable
2014-10-12 12:43:12 +02:00
wm4 7ae6484cd4 gl_x11: distinguish missing GLX and too old GLX versions
This probably led to confusing output.

CC: @mpv-player/stable
2014-10-12 12:43:08 +02:00
wm4 08d144138b command: don't display non-sense if volume is unavailable
Showed "Volume: (unavailable)%". That was dumb.

The message string is now a bit convoluted; mostly because the property
expand syntax can't do "if-else", just "if".

CC: @mpv-player/stable
2014-10-12 12:43:05 +02:00
wm4 58b511d947 build: install input config files into doc dir
Users using binary packages don't have obvious access to them, so this
seems like a good idea.
2014-10-12 12:42:59 +02:00
wm4 9b8b2933f3 etc/mplayer-input.conf: fix off by one error
playlist-pos is 0-based, but everyone thinks it's 1-based. Stupid crap.

(The "not the same as MPlayer" refers to a playlist manipulation command
that doesn't exist anymore in mpv.)

CC: @mpv-player/stable
2014-10-11 14:08:59 +02:00
wm4 24c05b2a82 player: don't mess up cursor visibility state
Manually setting can break things forever, because it puts the VO cursor
state out of sync with the remembered state by handle_cursor_autohide().
Use the normal autohide code during idle mode too instead. (Originally
the idea was to make the cursor always visible in idle mode, but not so
important.)

Regression since e1e8b07c. Fixes #1166.

CC: @mpv-player/stable

Conflicts:
	player/playloop.c
2014-10-11 14:08:29 +02:00
wm4 1412b0171d audio/out/push: make draining slightly more robust
Don't wait after the audio thread has pushed the remaining audio to the
AO. Avoids hard hangs if the heuristic fails completely (could still
happen if get_delay returns absurd values).

CC: @mpv-player/stable
2014-10-11 14:03:13 +02:00
wm4 5c1c99b858 audio/out/push: fix EOF heuristic
Since the internal AO driver API has no proper way to determine EOF, we
need to guess by querying get_delay. But some AOs (e.g. ao_pulse with
no-latency-hacks set) may never reach 0, maybe because they naively add
the latency to the buffer level. In this case our heuristic can break.

Fix by always using the delay to estimate the EOF time. It's not even
that important - it's mostly used to avoid blocking draining. So this
should be ok.

CC: @mpv-player/stable (maybe)
2014-10-11 14:03:08 +02:00
wm4 f66e320d7b video: try harder to decode cover art picture only once
For cover art, we pretend that the video stream is infinite, but also
stop decoding once we have an image on the VO (this seems advantageous
for the case when strange filters are inserted or the VO image gets
lost). Since a while ago, the video chain started decoding 2 images
though ("Non-monotonic video pts: 0.000000 <= 0.000000"), which is
annoying and wasteful.

Improve this by handling a certain corner case at initialization, which
will decode a second image while the first one is still stuck in the
filter chain. Also, just in case there are filters which buffer a lot,
also force EOF filtering (which means we tell the filters to flush
buffered frames).

CC: @mpv-player/stable
2014-10-11 14:01:21 +02:00
wm4 fa2381765e vf_lavfi: fix compilation failure
Apparently this fails to compile with clang6. Patch by someone else.

CC: @mpv-player/stable
2014-10-11 14:00:52 +02:00
wm4 f220617267 demux_lavf: blacklist jpeg files
We handle them under demux_mf.c for stupid reasons; mostly so that
an image is shown for a second instead of just flashing it.

CC: @mpv-player/stable
2014-10-11 13:59:54 +02:00
wm4 381843eb88 ao_pulse: don't use pa_format_info_to_sample_spec()
This function is available starting with PulseAudio 2.0, while we only
require 1.0. This broke compilation on Ubuntu 12.04.5 LTS.

Use our own function to calculate the buffer size, which is actually
simpler and needs slightly less code.

Hopefully fixes #1154.
CC: @mpv-player/stable
2014-10-11 13:59:43 +02:00
wm4 9258d0461e audio/out/push: fix some AOs freezing on exit
Caused by a dumb deadlock.
2014-10-11 13:59:22 +02:00
wm4 e2f59fcabd etc: add an input config file that reverts recent key binding changes
This is for users who don't like changes. I'm hoping it will make the
process of cleaning up key bindings less bumpy.

It should be mentioned in the release notes of the next release.
2014-10-11 13:58:53 +02:00
wm4 5b76ce3865 audio/out/push: make draining more robust
It was more complicated than it had to be: the audio thread already
determines whether audio has ended, so we can use that. Remove the
separate logic for draining.
2014-10-11 13:57:40 +02:00
wm4 1b29964a3e audio/out/push: limit fallback sleep time to reasonable limits 2014-10-11 13:57:34 +02:00
wm4 180fed4bc4 ao_pulse: change suspend circumvention logic
Commit 957097 attempted to use PA_STREAM_FAIL_ON_SUSPEND to make
ao_pulse exit if the stream was started suspended.

Unfortunately, PA_STREAM_FAIL_ON_SUSPEND is active even during playback.
If you pause mpv, pulseaudio will close the actual audio device after a
while (or something like this), and unpausing won't work. Instead, it
will spam "Entity killed" error messages.

Undo this change and check for suspended audio manually during init.

CC: @mpv-player/stable
2014-10-11 13:57:03 +02:00
Alessandro Ghedini fb3bf1ae81 vf_stereo3d: fix "auto" input format with libav 2014-10-11 13:56:43 +02:00
Kevin Mitchell f842b3f2b2 manpage: improve consistency with new ~/.config/mpv default
Signed-off-by: wm4 <wm4@nowhere>
2014-10-11 13:56:06 +02:00
wm4 e4f6235a47 player: properly wakeup when delaying OSD
Not sure in which situations this could make a difference; probably
none in practice, but it's more correct.

CC: @mpv-player/stable
2014-10-11 13:55:27 +02:00
wm4 89df07aa6d video: return responsibility of video redraw back to playloop
When the VO was moved it its own thread, responsibility for redrawing
was given to the VO thread itself. So if there was a condition that
indicated that redrawing was required, like expose events or certain
VOCTRLs, the VO thread was redrawing itself.

This worked fine, but there are some corner cases where this works
rather badly. E.g. if I fullscreen the player and hit panscan controls
with mpv's default autorepeat rate, playback stops. This happens because
the VO redraws itself after every panscan change command. Running each
(repeated) command takes so long due to redrawing and (involuntary)
waiting on vsync, that it never leaves the input processing loop while
the key is held down. I suspect that in my case, redrawing in fullscreen
mode just gets slow enough that it takes 2 vsyncs instead of 1 on
average, and the processing time gets larger than the autorepeat delay.

Fix this by taking redraw control from the VO, and instead let the
playloop issue a "real" redraw command to the VO if needed. This
basically reverts redraw handling to what it was before moving the VO to
a thread.

CC: @mpv-player/stable
2014-10-11 13:55:22 +02:00
Stephen Caraher 04a8dd38d5 man: replaced : with , in broken --lua-opts osc example
--lua-opts is a key-value list, so the option parser accepts only commas.

Signed-off-by: wm4 <wm4@nowhere>
CC: @mpv-player/stable
2014-10-11 13:54:10 +02:00
wm4 72e881b60d command: don't show message on "osd" command by default
Apparently this was not very popular.

CC: @mpv-player/stable
2014-10-11 13:54:00 +02:00
wm4 45b99d9799 manpage: remove non-existing ratio-pos property
Use percent-pos instead, which is exactly the same, except with the
range 0.0-100.0.

I'm not sure how this got there; it was probably introduced and then
removed again as percent-pos got more precise.

CC: @mpv-player/stable
2014-10-11 13:53:47 +02:00
wm4 b784083fb5 x11: fix --wid=0
Another fallout resulting from the changes whether or not to wait for
mapping the window. In this case, it obviously makes no sense to wait
for mapping, because the root window is always mapped. Mapping will
never happen, and it would wait forever.

Fixes #1139.
CC: @mpv-player/stable
2014-10-11 13:53:41 +02:00
wm4 d7cf596e2a manpage: redocument audio delay key bindings
Fixes #1131.
CC: @mpv-player/stable
2014-10-11 13:53:34 +02:00
wm4 a2e38ca657 player: don't print audio/video init failure message twice
The messages "Audio: no audio" and "Video: no video" could be printed
twice each if initializing them failed. Prevent his silliness.

CC: @mpv-player/stable
2014-10-11 13:53:27 +02:00
wm4 3e410f423d vo_vdpau: don't try to create surfaces of size 0
At least on kwin, we decide to proceed without waiting for the window
being mapped (due to the frame exts hack, see commit 8c002b79). But that
leaves us with a window size of 0x0, which causes VdpOutputSurfaceCreate
to fail. This prints some warnings, although vo_vdpau recovers later and
this has no other bad consequences.

Do the following things to deal with this:
- set the "known" window size to the suggested window size before the
  window is even created
- allow calling XGetGeometry on the window even if the window is not
  mapped yet (this should work just fine)
- make the output surface minimum size 1x1

Strictly speaking, only one of these would be required to make the
warning disappear, but they're all valid changes and increase robustness
and correctness. At no point we use a window size of 0x0 as magic value
for "unset" or unknown size, so keeping it unset has no purpose anyway.

CC: @mpv-player/stable
2014-10-11 13:51:53 +02:00
wm4 061f509757 demux_disc: bluray: fix stream language (2)
Commit 50e131b43e happened to make it work for DVD (because the higher
bits of the ID are masked in the DVD case), but failed for Bluray. This
probably fixes it, although I don't have a sample to multiple streams to
confirm it really does it right.

CC: @mpv-player/stable
2014-10-11 13:51:41 +02:00
Alessandro Ghedini 03bfc2b3fd Release 0.6.0 2014-09-30 20:52:47 +02:00
Kevin Mitchell 61ebe6137e man: fix to->too typo 2014-09-30 11:24:38 -07:00
wm4 4ea05577bd audio: remove --audiodrop
This would play some silence in case video was slower than audio. If
framedropping is already enabled, there's no other way to keep A/V
sync, short of changing audio playback speed (which would give worse
results). The --audiodrop option inserted silence if there was more
than 500ms desync.

This worked somewhat, but I think it was a silly idea after all. Whether
the playback experience is really bad or slightly worse doesn't really
matter. There also was a subtle bug with PTS handling, that apparently
caused A/V desync anyway at ridiculous playback speeds.

Just remove this feature; nobody is going to use it anyway.
2014-09-30 18:05:55 +02:00
James Ross-Gowan f23827d557 w32_common: quit event loop on destroy
When embedding, if the parent window is destroyed, it will cause mpv's
window to be destroyed as well. Since WM_USER wakeups are sent to the
window, destroying the window will prevent wakeups and cause uninit to
hang.

Fix this by quitting the event loop on WM_DESTROY. Events should only be
processed for the lifetime of the window, from CreateWindowEx to
WM_DESTROY. After the event loop is finished, mp_dispatch_queue_process
can handle any remaining requests.
2014-09-30 23:01:06 +10:00
wm4 c2592be4f0 vd_lavc: fix a small memory leak on init error
The private context wasn't free'd when codec init failed. Restructure
the code so that it can't happen.
2014-09-29 20:37:12 +02:00
wm4 053196de84 x11: always wait for mapped when using --wid
Might help with embedding with mozplugger. I can't confirm whether it
fixes the issue.

See #1090.
2014-09-29 18:06:45 +02:00
wm4 50e131b43e demux_disc: export BD/DVD audio language
This was "forgotten".
2014-09-29 18:06:45 +02:00
wm4 b9e4eefdb1 stream: don't drop buffers on failed seeks
Might matter when libavformat tries to do tiny seekbacks in an
unseekable stream, and the seekback buffer isn't large enough. In this
case, seeking would fail, and would drop the current buffer. The
seekback would end up dropping future data.

This change probably doesn't have any observable effects. libavformat
normally has its own stream buffer, and demux_mkv.c tries carefully
never to seek back.
2014-09-29 18:06:44 +02:00
wm4 6b9aee20bd cache_file: refuse to cache unseekable streams
This makes no sense to use with DVD/BD/DVB and some others, and these
streams happen to be unseekable.

Also, other kinds of unseekable streams (like reading from pipe) should
work, but will exhibit sketchy behavior if they need to seek. So just
disable it, and leave these problems to the memory cache (cache.c).
2014-09-29 18:06:44 +02:00
wm4 b0cb2977ed demux_lavf: bluray: don't skip stream data when flushing
This code meant to flush demuxer internal buffers by doing a byte seek
to the current position. In theory this shouldn't drop any stream data.
However, if the stream positions mismatch, then avio_seek() (called by
av_seek_frame()) stops being a no-op, and might for example read some
data to skip to the seek target. (This can happen if the distance is
less than SHORT_SEEK_THRESHOLD.)

The positions get out of sync because we drop data at one point (which
is what we _want_ to do). Strictly speaking, the AVIOContext flushing is
done incorrectly, becuase pb->pos points to the start of the buffer, not
the current position. So we have to increment pb->pos by the buffered
amount.

Since there are other weird reasons why the positions might go out of
sync (such as stream_dvd.c dropping buffers itself), and they don't
necessarily need to be in sync in the first place unless AVIOContext has
nothing buffered internally, just use the sledgehammer approach and
correct the position manually.

Also run av_seek_frame() after this. Currently, it shouldn't read
anything, but who knows how that might change with future libavformat
development.

This whole change didn't have any observable effect for me, but I'm
hoping it fixes a reported problem.
2014-09-29 18:06:44 +02:00
wm4 39451732e9 demux_disc: bluray: potentially fix some aspects of seeking
When flushing the AVIOContext, make sure it can't seek back to discarded
data. buf_ptr is just the current read position, while buf_end - buffer
is the actual buffer size. Since mpegts.c is littered with seek calls,
it might be that the ability to seek could read

Mark the stream (which the demuxer uses) as not seekable. The cache can
enable seeking again (this behavior is sometimes useful for other
things). I think this should have had no bad influence in theory, since
seeking BD/DVD first does the "real" seek, then flushes libavformat and
reads new packets.
2014-09-29 18:06:44 +02:00
Alessandro Ghedini 0fee6537bb mpv.desktop: add more ogg-related mime types
Also adds audio/ogg and video/ogg.
2014-09-29 18:06:44 +02:00
Otto Modinos cbfb6de667 lua: add mpv/lua directories to the lua path
Signed-off-by: wm4 <wm4@nowhere>
2014-09-28 20:23:38 +02:00
wm4 34fc0720f7 DOCS/client_api_examples: qtexample: remove broken resizing
The intention was to adjust the window size to video size. It never
worked well; it prevented the user to make the window smaller. For
unknown reason it stopped resizing properly as well.

This is just a cheap example, and I don't intend to fight with Qt, so
replace the "demonstration" behavior by something slightly lamer.
2014-09-28 20:18:18 +02:00
wm4 3273db1ef7 client API, X11: change default keyboard input handling again
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.
2014-09-28 20:11:00 +02:00
wm4 aeaa1767e9 Fix build with libavfilter disabled
Although I'm not sure why we even support this.
2014-09-28 19:10:50 +02:00
wm4 295b6dc169 stream_bluray: autodetect AVCHD directories
Fixes #1127.
2014-09-27 18:33:36 +02:00
wm4 cdb25d5a21 video: change automatic rotation and 3D filter insertion
We inserted these filters with fixed parameters, which was ok. But this
also didn't change image parameters for the filters down the filter
chain and the VO. For example, if rotation by 90° was requested by the
file, we would insert a filter and rotate the video, but the VO would
still receive image parameters that direct rotation by 90°.

This wasn't a problem, but it could become one.

Fix this by letting the filters automatically pick up the image params.
The image params are reset on application. (We could probably also
always try to apply and reset image params in a filter, instead of
having special "auto" parameters. This would probably work, and video.c
would insert a "rotate=0" filter. But I'm afraid this would be confusing
and the current solution is cosmetically slightly nicer.)

Unfortunately, the vf_stereo3d.c change turned out a big mess, but once
the "internal" filter is fully replaced with libavfilter, most of this
can be radically simplified.
2014-09-27 18:31:59 +02:00
wm4 0ec6df2ddf vf_lavfi: make chaining from other filters more flexible
Some filters exists only to create a specific lavfi graph. Allow these
filters to reset the graph exactly on reconfig, and allow them to modify
some image parameters too. Also make vf_lw_update_graph() behave like
vf_lw_set_graph() - they had a subtitle difference with filter==NULL.

Useful for the following commit.
2014-09-27 17:21:29 +02:00
wm4 cbf7180c90 input: copy options automatically
Originally, all options were copied to ensure that input_ctx remins
thread-safe, even if options are changed asynchronously. But this got
a bit inconsistent. Copy them automatically and reduce some weirdness.
2014-09-27 16:25:29 +02:00
wm4 b4d1494336 input: separate creation and loading of config
Until now, creating the input_ctx was delayed until the command line
and config files were parsed. Separate creation and loading so that
input_ctx is available from start.

This should make it possible to simplify some things. For example,
some complications with Cocoa were apparently only because input_ctx
was available only "later". (Although I'm not sure if this is still
relevant, or if the Cocoa code should even be organized this way.)
2014-09-27 16:01:55 +02:00
Bruno George Moraes acf6aef882 stream: change malloc+memset to calloc
Also removed some memset that were left on some calloc that was already in
the code.

Signed-off-by: wm4 <wm4@nowhere>
2014-09-27 16:01:49 +02:00
wm4 650af29471 audio/out/push: clean up properly on init error
Close the wakeup pipes, free the mutex and condition var.
2014-09-27 04:54:17 +02:00
wm4 e79de41b97 audio/out: check device buffer size for push.c only
Should fix #1125.
2014-09-27 04:52:46 +02:00
wm4 d778130dc4 audio/out: disable ao_sndio by default
Don't build it, move it down the autoprobe list even if it's enabled. It
doesn't work well enough.
2014-09-26 15:52:29 +02:00
wm4 4784ca32c9 audio/out: fail init on unknown audio buffer
A 0 audio buffer makes push.c go haywire. Shouldn't normally happen.
2014-09-26 15:50:04 +02:00
wm4 387d5f55e6 ao_sndio: print a warning when draining audio
libsndio has absolutely no mechanism to discard already written audio
(other than SIGKILLing the sound server). sio_stop() will always block
until all audio is played. This is a legitimate design bug.

In theory, we could just not stop it at all, so if the player is e.g.
paused, the remaining audio would be played. When resuming, we would
have to do something to ensure get_delay() returns the right value. But
I couldn't get it to work in all cases.
2014-09-26 15:46:39 +02:00
wm4 da1918b894 ao_sndio: update buffer status on get_delay
get_delay needs to report the current audio buffer status. It's
important for A/V sync that this information is current, but functions
which update it were called on play() or get_space() calls only.
2014-09-26 15:46:36 +02:00
wm4 3208f8c445 ao_sndio: change p->delay to samples
This was in bytes, but it's more convenient to use samples (or frames;
in any case the smallest unit of audio that includes all channels).

Remove the ao->bps line too; it will be set after init() returns.
2014-09-26 15:46:33 +02:00
wm4 12d93fdfef ao_sndio: set non-blocking flag
Otherwise the feed thread and the playloop will get randomly blocked.

This seems to fix most A/V sync issues.
2014-09-26 15:46:30 +02:00
wm4 1b1421866d ao_sndio: fix some incorrect comments
The AO API always uses sample counts.
2014-09-26 15:46:23 +02:00
wm4 17d031f88c old-configure: minor improvements
Use a trap to remove the temp dir on exit. Write config.log to old_build
instead of the top-level dir.
2014-09-26 13:53:20 +02:00
wm4 8fd954ac8e build: add -Wno-format-zero-length
This warning makes absolutely no sense. Passing an empty string to
printf-like functions is perfectly fine. In the OSD case, it just sets
an empty message, practically clearing the OSD.
2014-09-26 13:52:55 +02:00
wm4 fdf40743bc demux_mkv: don't use default_duration for parsed packets
Makes it behave slightly better for VP9. This is also the behavior
libavformat has.

Also while we're at it, don't set duration except for the first packet.
Normally we don't use the duration except for subtitles (which are never
parsed or "laced"), so this should make no observable difference.
2014-09-26 01:25:48 +02:00
wm4 d6c27855d7 stream_bluray: allow opening BDMV directories directly
Similar as the previous commits.

Most of the code is actually copied from the stream_dvdnav.c code, but
I'd rather prefer to duplicate it, than to entangle them. The latter
would probably result in terrible things in a few years.
2014-09-26 00:30:21 +02:00
wm4 c3f7773138 stream_dvdnav: allow opening DVD directories directly
Same hack as with stream_dvd.c.

VIDEO_TS.IFO files are now opened via stream_dvdnav.c. Directories
containing a VIDEO_TS.IFO or VIDEO_TS/VIDEO_TS.IFO file are also
opened with it.
2014-09-26 00:30:21 +02:00
wm4 d191de8564 stream_dvd: better .ifo probing
stream_dvd.c includes a pseudo-protocol that recognizes .IFO files, and
plays them using libdvdread. This was relatively lazy, and could perhaps
easily trigger with files that just had the .ifo extension.

Make the checks stricter, and even probe the file header. Apparently the
first bytes in an .ifo file are always "DVDVIDEO-VTS", so check for
this.

Refuse to load the main "video_ts.ifo". The plan is to use stream_dvdnav
for it.

This also removes at least 1 memory leak.
2014-09-25 23:54:18 +02:00
wm4 d8f993705c player: do not wrongly clear OSD bar stops, reindent
set_osd_bar_chapters() always cleared the OSD bar stops, even if the
current bar was not the seek bar. Obviously it should leave the state of
the bar alone in this case.

Also change the function control flow so that we can drop one
indentation level, and do the equivalent change for the other OSD bar
functions.
2014-09-25 21:32:56 +02:00
wm4 ed116e8b06 player: simplify OSD message handling code
Eliminate the remains of the OSD message stack. Another simplification
comes from the fact that we do not need to care about time going
backwards (we always use a monotonic time source, and wrapping time
values are practically impossible). What this code was pretty trivial,
and by now unnecessarily roundabout.

Merge get_osd_msg() into update_osd_msg(), and add_osd_msg() into
set_osd_msg_va().
2014-09-25 21:32:56 +02:00
wm4 07668e50de player: move code to make playloop smaller
This is basically a cosmetic change, although it weirdly also affects
the percent position in encoding mode.
2014-09-25 21:32:56 +02:00
wm4 d23ffd243f player: rate-limit OSD text update
There's no need to update OSD messages and the terminal status if nobody
is going to see it. Since the player doesn't block on video display
anymore, this update happens to often and probably burns slightly more
CPU than necessary. (OSD redrawing is handled separately, so it's just
mostly useless text processing and such.)

Change it so that it's updated only on every video frame or all 50ms
(whatever comes first).

For VO OSD, we could in theory try to lock to the OSD redraw heuristic
or the display refresh rate, but that's more complicated and doesn't
work for the terminal status.
2014-09-25 21:32:56 +02:00
wm4 9537e33057 player: fix OSD redraw heuristic with audio-only mode
When using --force-window (and no video or cover art), this heuristic
prevents any redrawing during seeking. It should be applied only if
there is any form of video.
2014-09-25 21:32:56 +02:00
wm4 5116c6c242 sub: approximate subtitle display in no-video mode
This makes subtitle display somewhat work if no video is displayed, but
a VO window exists (--force-window or cover art display).

The main problem with normal subtitle display is that it's locked to
video: it uses the video PTS as reference, and the subtitles advance
only if a new video frame is displayed. In audio-only mode on the other
hand, no video frame is ever displayed (or only 1 in the cover art
case). You would need a workaround to adjust the subtitle PTS, and you
would have to decide with what frequency to update the display. In
general, there is no "right" display FPS for subtitles. Some formats
(ASS) have animations parameterized by time, and any refresh rate could
be used.

Sidestep these problems by enabling the text OSD-based subtitle
mechanism. This is similar to --no-sub-ass, and updates and renders
subtitles with plain OSD. It has some caveats: no bitmap subs, somewhat
incorrect timing, no formatting. Timing in particular is a bit strange
and depends how often the audio output asks for new data, or other
events that happen to wakeup the playloop.
2014-09-25 21:32:56 +02:00
wm4 debbff76f9 Remove mpbswap.h
This was once central, but now it's almost unused. Only vf_divtc still
uses it for extremely weird and incomprehensible reasons. The use in
stream.c is trivial. Replace these, and remove mpbswap.h.
2014-09-25 21:32:55 +02:00
wm4 09b7956ca5 stream_cdda, demux_raw: always use s16le
stream_cdda's output format is linked to demux_raw's default audio
format, and at least we don't care enough to provide a separate
mechanism to let stream_cdda explicitly set the format, so they must
match.

Judging from the existing code, it looks like CDDA always outputs little
endian. stream_cdda.c changed this back to native endian (what demux_raw
expects). Just make them both little endian. This requires less code,
and also having a raw demuxer's behavior depend on the endianness of the
machine isn't very sane anyway.
2014-09-25 21:32:06 +02:00
ChrisK2 1c9f30cca7 osc: update cache display
now similar to what the status line displays
2014-09-25 11:57:49 +02:00
wm4 7aa933cc9e demux_mkv: get rid of MS structs
See previous commits. This finally replaces directly reading the file
data into a struct with reading them manually. In theory this is more
portable (no alignment issues and other things). For the most part,
it's nice seeing this gone.
2014-09-25 02:22:50 +02:00
wm4 9c3c199558 audio: remove WAVEFORMATEX from internal demuxer API
Same as with the previous commit. A bit more involved due to how the
code is written.
2014-09-25 01:56:51 +02:00
wm4 fd7dde404d video: remove BITMAPINFOHEADER from internal demuxer API
MPlayer traditionally did this because it made sense: the most important
formats (avi, asf/wmv) used Microsoft formats, and many important
decoders (win32 binary codecs) also did. But the world has changed, and
I've always wanted to get rid of this thing from the codebase.

demux_mkv.c internally still uses it, because, guess what, Matroska has
a VfW muxing mode, which uses these data structures natively.
2014-09-25 00:59:15 +02:00
wm4 e977624d87 audio: confine demux_mkv audio PCM hack
Let codec_tags.c do the messy mapping.

In theory we could simplify further by makign demux_mkv.c directly use
codec names instead of the MPlayer-inherited "internal FourCC" business,
but I'd rather not touch this - it would just break things.
2014-09-24 23:33:21 +02:00
wm4 9ac86d9e99 audio: decouple demux and audio decoder/filter sample formats
For a while, we used this to transfer PCM from demuxer to the filter
chain. We had a special "codec" that mapped what MPlayer used to do
(MPlayer passes the AF sample format over an extra field to ad_pcm,
which specially interprets it).

Do this by providing a mp_set_pcm_codec() function, which describes a
sample format in a generic way, and sets the appropriate demuxer header
fields so that libavcodec interprets it correctly. We use the fact that
libavcodec has separate PCM decoders for each format. These are
systematically named, so we can easily map them.

This has the advantage that we can change the audio filter chain as we
like, without losing features from the "rawaudio" demuxer. In fact, this
commit also gets rid of the audio filter chain formats completely.
Instead have an explicit list of PCM formats. (We could even just have
the user pass libavcodec PCM decoder names directly, but that would be
annoying in other ways.)
2014-09-24 22:55:50 +02:00
wm4 8a8f65d73d ao_sndio: fix U24 bit width
This was wrong since the initial commit.
2014-09-24 21:32:15 +02:00
wm4 1d45a3a163 TOOLS/umpv: drop unnecessary check
This was supposed to make sure that argv[1:] does not fail, but Python
actually allows mismatching bounds for slicing.
2014-09-24 21:29:30 +02:00
shdown 546c0f0b25 TOOLS/umpv: use python octal notation 2014-09-24 02:12:30 +02:00
shdown c6d0e41335 TOOLS/mpv_identify.sh: remove pointless escape 2014-09-24 02:08:49 +02:00
shdown 7e5f707baf TOOLS/idet.sh: add description
Just a copy of c0cd58e3f5 commit message
(with a small fix: ildetect.sh+ildetect.so, not
ildetect.sh+ildetect.sh).
2014-09-24 02:08:47 +02:00
shdown 3eae8b7170 TOOLS/idet.sh: remove unused and duplicated assignments 2014-09-24 02:08:45 +02:00
wm4 735a9c39d7 player: change --keep-open semantics
By popular request.
2014-09-24 01:56:53 +02:00
wm4 53c288d364 player: show correct playback time with --keep-open --no-video
Whatever.
2014-09-24 01:37:07 +02:00
wm4 e12fae8ef5 player: --loop-file takes precedence before --keep-open 2014-09-24 01:31:45 +02:00
wm4 7954017b56 ao_oss: improve format negotiation, and hopefully fix pass-through
Digital pass-through was probably broken. Possibly fix it (no way to
test). This also should make the logic slightly saner.

Fortunately, it's unlikely that anyone who uses OSS has a spdif setup.
2014-09-24 01:12:14 +02:00
wm4 bf927531aa ao_coreaudio: fix build failure
Commit 5b5a3d0c broke this. The really funny thing is that this code was
actually always under "#if BYTE_ORDER == BIG_ENDIAN". The breaking
commit just edited this code slightly, but it must have failed to
compile on big endian long before (since over 1 year ago, commit d3fb58).
2014-09-24 00:05:18 +02:00
wm4 429260a35c ao_oss: unbreak
Oops.
2014-09-23 23:34:30 +02:00
wm4 c2fa9f6629 ao_pulse: digital pass-through
Should be able to pass-through AC3, DTS, and others.

It seems PulseAudio wants players to fallback to PCM on certain events
signaled by the server, but we don't implement that. There's not much
documentation available anyway.
2014-09-23 23:11:55 +02:00
wm4 7230d88c7e ao_pulse: correctly wait for stream state
This works similar to condition variables; for some reason this
apparently worked fine until now, but it breaks with passthrough mode.
2014-09-23 23:11:55 +02:00
wm4 601fb2f93a ao_pulse: use pa_stream_new_extended()
Needed for compressed audio pass-through later.
2014-09-23 23:11:55 +02:00
wm4 81bf9a1963 audio: cleanup spdif format definitions
Before this commit, there was AF_FORMAT_AC3 (the original spdif format,
used for AC3 and DTS core), and AF_FORMAT_IEC61937 (used for AC3, DTS
and DTS-HD), which was handled as some sort of superset for
AF_FORMAT_AC3. There also was AF_FORMAT_MPEG2, which used
IEC61937-framing, but still was handled as something "separate".

Technically, all of them are pretty similar, but may use different
bitrates. Since digital passthrough pretends to be PCM (just with
special headers that wrap digital packets), this is easily detectable by
the higher samplerate or higher number of channels, so I don't know why
you'd need a separate "class" of sample formats (AF_FORMAT_AC3 vs.
AF_FORMAT_IEC61937) to distinguish them. Actually, this whole thing is
just a mess.

Simplify this by handling all these formats the same way.
AF_FORMAT_IS_IEC61937() now returns 1 for all spdif formats (even MP3).
All AOs just accept all spdif formats now - whether that works or not is
not really clear (seems inconsistent due to earlier attempts to make
DTS-HD work). But on the other hand, enabling spdif requires manual user
interaction, so it doesn't matter much if initialization fails in
slightly less graceful ways if it can't work at all.

At a later point, we will support passthrough with ao_pulse. It seems
the PulseAudio API wants to know the codec type (or maybe not - feeding
it DTS while telling it it's AC3 works), add separate formats for each
codecs. While this reminds of the earlier chaos, it's stricter, and most
code just uses AF_FORMAT_IS_IEC61937().

Also, modify AF_FORMAT_TYPE_MASK (renamed from AF_FORMAT_POINT_MASK) to
include special formats, so that it always describes the fundamental
sample format type. This also ensures valid AF formats are never 0 (this
was probably broken in one of the earlier commits from today).
2014-09-23 23:11:54 +02:00
wm4 308d72a02e ao_wasapi: fix fragile format-mapping code
This code tried to play with the format bits, and potentially could
create invalid formats, or reinterpret obscure formats in unexpected
ways.

Also there was an abort() call if the winapi or mpv used a format with
unexpected bit-width. This could probably easily happen; for example,
mpv supports at least one 64 bit format. And what would happen on 8 bit
formats anyway?

Untested.
2014-09-23 23:09:29 +02:00
wm4 b745c2d005 audio: drop swapped-endian audio formats
Until now, the audio chain could handle both little endian and big
endian formats. This actually doesn't make much sense, since the audio
API and the HW will most likely prefer native formats. Or at the very
least, it should be trivial for audio drivers to do the byte swapping
themselves.

From now on, the audio chain contains native-endian formats only. All
AOs and some filters are adjusted. af_convertsignendian.c is now wrongly
named, but the filter name is adjusted. In some cases, the audio
infrastructure was reused on the demuxer side, but that is relatively
easy to rectify.

This is a quite intrusive and radical change. It's possible that it will
break some things (especially if they're obscure or not Linux), so watch
out for regressions. It's probably still better to do it the bulldozer
way, since slow transition and researching foreign platforms would take
a lot of time and effort.
2014-09-23 23:09:25 +02:00
wm4 5b5a3d0c46 audio: remove swapped-endian spdif formats
IEC 61937 frames should always be little endian (little endian 16 bit
words). I don't see any apparent need why the audio chain should handle
swapped-endian formats.

It could be that some audio outputs might want them (especially on big
endian architectures). On the other hand, it's not clear how that works
on these architectures, and it's not even known whether the current code
works on big endian at all. If something should break, and it should
turn out that swapped-endian spdif is needed on any platform/AO,
swapping still could be done in-place within the affected AO, and
there's no need for the additional complexity in the rest of the player.

Note that af_lavcac3enc outputs big endian spdif frames for unknown
reasons. Normally, the resulting data is just pulled through an auto-
inserted conversion filter and turned into little endian. Maybe this was
done as a trick so that the code didn't have to byte-swap the actual
audio frame. In any case, just make it output little endian frames.

All of this is untested, because I have no receiver hardware.
2014-09-23 19:34:14 +02:00
wm4 1f4a74cbed vf_vapoursynth: make it possible to get filter output incrementally
Until now, we always required the playback core to decode a new frame to
get more output from the filter. That seems to be completely
unnecessary, because filtered results may arrive before that.

Add a filter_out callback, and restructure the code such that it can
return any filtered frames, or block if it hasn't read at least one
frame.

In the worst case, it still can happen that bursts of input requests and
output requests happen. (This commit tries to reduce burst-like
behavior, but it's not entirely possible due to the indeterministic
nature of VS threading.)

This is a similar change as with 95bb0bb6.
2014-09-23 00:35:57 +02:00
wm4 9fe076f02a player: allow passing number of loops to --loop-file
E.g. --loop-file=2 will play the file 3 times (one time normally, and 2
repeats).

Minor syntax issue: "--loop-file 5" won't work, you have to use
"--loop-file=5". This is because "--loop-file" still has to work for
compatibility, so the "old" syntax with a space between option name and
value can't work.
2014-09-22 22:56:00 +02:00
wm4 9ce4526139 audio: prefer libavcodec over libmpg123
libavcodec/libavformat now handles gapless audio better. In theory, this
could be implemented with ad_mpg123 too, but since libavformat strips
metadata from mp3 files and passes pure mp3 packets to the decoders
only, this can't work by itself. Instead, the player must pass this
metadata separately. libav* do this relatively transparently over packet
"side data" (attached to AVPacket).

It might also be possible to let libmpg123 handles all this by
implementing it as demuxer that outputs PCM, but that would have other
problems, and I think it's better to make libavformat work correctly.

libmpg123 can still be used with '--ad=mpg123:mp3'.

Also see issue #1101.
2014-09-22 22:38:06 +02:00
wm4 2cfc35892c command: no space before "%" in volume default OSD message
More consistent with other output, such as the terminal status line.

Also see issue #1103.
2014-09-22 18:07:34 +02:00
wm4 f605b03f63 video: filter new frames at a better time (2)
We generally want 2 things:
1. minimal wakeups for decoding each frame
2. minimal number of frames decoded on continuous seeking

Commit 35810cb8 changed this a bit, and fixed 1. But it broke 2., and
now it decodes 2 frames instead of 1 when you keep seeking (arrow key
held down or such). This made seeking appear slower.

Fix this by making the logic more explicit. In particular, call the
filters only if we actually try to get a new frame.

When playing with --no-audio and all other distractions disabled (like
OSC), it still wakes up 2 times per frame - but the second time is
merely because the VO didn't accept the new frame yet.
2014-09-22 18:06:59 +02:00
wm4 63a2024a8b osd: fix --term-osd=no
It didn't actually disable it.

I'm actually not sure what this option is useful for, but fixing it
can't harm.
2014-09-22 00:29:45 +02:00
wm4 14ff4cf318 command: improve "osd" command
Be less annoying, print the actual OSD level instead of something
meaningless, but still clear the OSD if OSD level 0 (no OSD) is set.

Remove the special handling for terminal OSD, that was just dumb.
2014-09-22 00:25:59 +02:00
wm4 709002a3b2 command: use show_property_osd() sub_step
Simpler and more consistent.
2014-09-22 00:08:19 +02:00
wm4 c99a966251 command: when changing a property, always show it on OSD
This means that if a property not listed in property_osd_display[] is
changed, it will be shown on the OSD as "name: ${name}".

Properties that are listed in property_osd_display[] and have osd_name
not set stay invisible by default. This is used for "pause" and
"fullscreen", which (like before this commit) are not shown by default,
because it would be annoying.

The defaults still can be changed with command prefixes (osd-msg,
no-osd, others).
2014-09-21 23:54:33 +02:00
wm4 903bd1d893 command: simplify OSD property display code
Probably not many user-visible changes. One notable change is that the
terminal OSD code for OSD bar fallback handling is removed with no
replacement. Instead, terminal OSD gets the same text message as normal
OSD. For volume, this is ok, because the text message is reasonable.
Other properties will look worse, but could be adjusted, and there are
in fact no other such properties that would be useful in audio-only
mode.

The fallback message for seeking falls away as well, but that message
was useless anyway - the terminal status line provides all information
anyway.

I believe the show_property_osd() code is now much easier to follow.
2014-09-21 23:48:24 +02:00
wm4 4a0bbe256e command: allow changing some OSD-related options even with no VO
If no VO was open, these options couldn't be changed or even queried.
Although these properties are nearly useless if no VO exists, there's
actually no good reason to forbid querying or setting them. Also, even
if the VO is created, it doesn't mean the VO window was created.
2014-09-21 16:01:53 +02:00
wm4 60ca2d8f4d command: remove unneeded ifdefs
Why bother?

Also, since now some properties could be mapped to non-existing options,
but mp_property_generic_option() is used, deal with this case and return
a not-found error code.
2014-09-21 16:00:03 +02:00
wm4 a0cee03394 command: always show OSD message when changing volume etc.
If there's a command that uses the OSD by default, then always print the
associated message (or a fallback made of name + value), even if the
command has an associated OSD bar.

This means volume, gamma, panscan, etc. all show both a message and a
OSD bar.

Also, add a '%' to the volume message. The extra_msg thing is not needed
anymore.

See issue #1103.
2014-09-21 15:55:22 +02:00
wm4 58db0a55f3 options: remove --volstep
It's just confusing; users are encouraged to edit input.conf instead
(changing the argument to the "add" command).

Update input.conf to keep the old behavior.
2014-09-21 15:41:33 +02:00
Ben Boeckel 54d1dae687 TOOLS: idet: remove extra '$' in $(()) expansion 2014-09-21 15:06:47 +02:00
wm4 b12a287227 manpage: clarify vf_pp docs
Make the note about quoting more prominent.
Add a warning that this filter is useless for new files.
2014-09-21 11:10:52 +02:00
wm4 a4241f9de6 video: fix redrawing when pausing after framedrop
When pausing after a frame was just dropped, we're logically at the
dropped frame, and thus should redraw the dropped frame. This was
implemented, but didn't work after unpausing for the second time,
because of a minor logic bug.
2014-09-21 10:06:06 +02:00
wm4 1cf229f462 video: fix some vo_direct3d crashes due to FFmpeg nonsense
For incomprehensible reasons, AV_PIX_FMT_GRAY8 (and some others) have a
palette. This literally makes no sense and this issue has bitten us
before, but it is how it is.

This also caused a crash with vo_direct3d: this mapped a texture as
IMGFMT_Y8 (i.e. AV_PIX_FMT_GRAY8), and when copying this, it tried to
copy the non-existent palette.

Fixes #1113.
2014-09-21 09:33:51 +02:00
shdown bb005a385a TOOLS/umpv: make URL detection consistent with mpv method
See mp_is_url in options/path.c.
2014-09-20 15:18:53 +02:00
shdown dfbb4d03ee TOOLS/umpv: print error message to stderr 2014-09-20 15:18:51 +02:00
shdown 5332ecf651 TOOLS/umpv: use MPV environment variable, not UMPV_OPTIONS
Just like the rest of TOOLS/*.sh scripts.
2014-09-20 15:18:49 +02:00
wm4 68b7217d41 vo_vdpau: better integration with the generic framedrop code
vo_vdpau uses its own framedrop code, mostly for historic reasons. It
has some tricky heuristics, of which I'm not sure how they work, or if
they have any effect at all, but in any case, I want to keep this code
for now. One day it might get fully ported to the vo.c framedrop code,
or just removed.

But improve its interaction with the user-visible framedrop controls.
Make --framedrop actually enable and disable the vo_vdpau framedrop
code, and increment the number of dropped frames correctly.

The code path for other VOs should be equivalent. The vo_vdpau behavior
should, except for the improvements mentioned above, be mostly
equivalent as well. One minor change is that frames "shown" during
preemption are always count as dropped.

Remove the statement from the manpage that vo_vdpau is the default; this
hasn't been the case for a while.
2014-09-20 15:17:12 +02:00
wm4 461c78e4d9 vo_vdpau: fix confusion around vsync_interval
vc->vsync_interval and vsync_interval should be the same value, but
actually vc->vsync_interval was updated after vsync_interval was
initialized. This was probably not intended. Fix this by removing the
duplicate local variable. There were probably no bad effects.
2014-09-20 14:54:19 +02:00
wm4 5e6c9963d8 input: explain why we use semaphores
Also switch function names for better self-documentation.
2014-09-20 04:22:37 +02:00
wm4 34fac3bf68 osdep: hack to fix build with low quality pthreads-w32 headers
When compiling semaphore_osx.c on win32, the following error happened:

/usr/i686-w64-mingw32/include/semaphore.h:160:6: error: unknown type name 'mode_t'

This is because this system header references symbols that are not
not defined anywhere. This is clearly a bug in pthreads-w32, but has
been known and unfixed since 2012, so add a hack to fix it.

We build semaphore_osx.c this way because it saves us an extra configure
check. On win32, Linux, etc. it's empty and contains
"#include <semaphore.h>" only.

Should fix #1108.
2014-09-20 04:18:40 +02:00
wm4 7329101478 mixer: always restore volume (even with pulse), don't unmute
Be less clever, and restore the volume state even with AOs like pulse,
which have per-application audio.

Before this commit we didn't do this, because the volume is global (even
if per-application), so the volume will persist between invocations. But
to me it looks like always restoring is less tricky and makes for easier
to understand semantics.

Also, don't always unmute on exit. Unmuting was done even with ao_pulse,
and interfered with user expectations (see #1107).

This might annoy some users, because mpv will change the volume all the
time. We will see.

Fixes #1107.
2014-09-20 02:02:29 +02:00
wm4 f64199fcdc manpage: document terminal status line components
(The classic MPlayer documentation had this in separate files, but we
deleted them ages ago.)
2014-09-20 00:50:04 +02:00
wm4 f5fb1e915e player: rename "Late:" field to "SD:"
Follow up to previous commit.

This is probably confusing from a user point of view, since this field
shouldn't show up normally anymore. (Before this commit, it could show
up sporadically when a slow operation was performed during playback,
such as switching fullscreen.)
2014-09-20 00:48:30 +02:00
wm4 771583c285 video: actually count decoder-dropped frames
Normally, feeding a packet to the decoder should always return a frame
_if_ we received a frame before. So while we can't know exactly whether
a frame was dropped, at least the normal case is easily detectable.

This means we display something closer to the actual framedrop count,
instead of a bad guess.
2014-09-20 00:45:39 +02:00
wm4 4047e7e6cb video: improve decoder-based framedropping mode
This is the "old" framedropping mode (derived from MPlayer). At least in
the mplayer2/mpv source base, it stopped working properly years ago (or
maybe it never worked properly). For one, it depends on the video
framerate, which assume constant framerate. Another problem was that it
could lead to freezing video display: video could get so much behind
that it couldn't recover from framedrop.

Make some small changes to improve this.

Don't use the current audio position to check how much we are behind.
Instead, use the last known A/V difference. last_av_difference is
updated only when a video frame is scheduled for display. This means we
can keep stop dropping once we're done catching up, even if video is
technically still behind. What helps us here that this forces a video
frame to be displayed after a while. Likewise, we reset the
dropped_frames count only when scheduling a new frame for display as
well.

Some inspiration was taken from earlier work by xnor (see issue #620),
although the implementation turned out quite different.

This still uses the demuxer-reported (possibly broken) FPS value. It
also doesn't account for filters changing FPS. We can't do much about
this, because without decoding _and_ filtering, we just can't know how
long a frame is. In theory, you could derive that from the raw packet
timestamps and the filter chain contents, but actually doing this is
too involved. Fortunately, the main thing the FPS affects is actually
the displayed framedrop count.
2014-09-20 00:45:11 +02:00
wm4 65e816b3fe player: make code more obvious
Or at least I think so.
2014-09-20 00:45:11 +02:00
wm4 116d1d0dfa player: use backwards flag for seeking external tracks
Otherwise, the external track could end up at a position that's too
late.
2014-09-20 00:45:10 +02:00
wm4 70f4721574 player: reset last_av_difference if not applicable
Don't let stale values linger around.

Also fix a slightly related case in audio.c.
2014-09-20 00:44:37 +02:00
wm4 c86b4790a8 af_hrtf: initialize coefficient arrays
Sometimes, --af=hrtf produces heavy artifacts or silence. It's possible
that this commit fixes these issues. My theory is that usually, the
uninitialized coefficients quickly converge to sane values as more audio
is filtered, which would explain why there are often artifacts on init,
with normal playback after that. It's also possible that sometimes, the
uninitialized values were NaN or inf, so that the artifacts (or silence)
would never go away.

Fix this by initializing the coefficients to 0. I'm not sure if this is
correct, but certainly better than before.

See issue #1104.
2014-09-19 21:16:42 +02:00
Alexander Preisinger 30175538fe input: add locking for repeat info 2014-09-19 17:48:06 +02:00
Alexander Preisinger b99c67f9bb build: update minimum wayland version
Uh oh.
2014-09-19 17:40:26 +02:00
Alexander Preisinger 29467736cf wayland: use reported rete and delay
If native-keyrepeat is true then we set the rate and delay reported by the
compositor.
2014-09-19 17:38:24 +02:00
Alexander Preisinger be516022b6 input: add function for setting repeat info
Let us set a different rate and delay.

Needed for the following commit where we set rate and delay reported by weston.
But only if the option native-keyrepeat is set.
2014-09-19 17:36:37 +02:00
wm4 95bb0bb671 vf_lavfi: fetch output frames incrementally
Uses the new mechanism introduced in the previous commit.

Depending on the actual filter, this distributes CPU load more evenly
over time, although it probably doesn't matter.
2014-09-18 19:36:55 +02:00
wm4 580cf433bd video/filter: allow better dataflow
Consider a filter which turns 1 frame into 2 frames (such as an
deinterlacer). Until now, we forced filters to produce all output frames
at once. This was done for simplicity.

Change the filter API such that a filter can produce frames
incrementally.
2014-09-18 19:36:27 +02:00
wm4 5c8549ac68 video: separate calling decoder/filter
Rename video_decode_and_filter to video_filter, and add a new
video_decode_and_filter function. This function now calls the decoder.
This is done so that we can check filters a second time after decoding,
which avoids a useless playloop iteration.

(This and the previous commits are really just microoptimizations, which
simply reduce the number of times the playloop has to recheck
everything.)
2014-09-18 19:35:23 +02:00
wm4 e37ad620aa video: check whether there are enough frames after filtering
Move the check to a function. Run the check a second time after
decoding/filtering. This second check is strictly speaking redundant
(which is why it wasn't done until now), but it avoids a useless
playloop iteration.
2014-09-18 19:34:56 +02:00
wm4 35810cb8b4 video: filter new frames at a better time
Move this code below the code that "shifts" the newly filtered frame.
This allows us to skip a useless playloop iteration later, because
obviously we need to filter a new frame after the previous frame has
been "shifted", and not before that.
2014-09-18 19:32:25 +02:00
wm4 ea2b19f646 player: allow overriding OSD message for all OSD levels
Until now, you could override only level 3 with --osd-status-msg. Extend
this, add add --osd-msg1 to --osd-msg3 (one for each OSD level). OSD
level 0 always means disable OSD, so that isn't included.

--osd-msg3 corresponds to --osd-status-msg, but they're not exactly the
same. To allow more customization, --osd-msgN do not include the OSD
symbol. The symbol can be manually added with "${osd-sym-cc}". We keep
the "old" option for some short-term compatibility.

--osd-msg1 should be particularly useful; for example you could do:

    --osd-msg1='${?pause==yes:${osd-sym-cc}}'

to display a "paused" symbol when paused, and nothing during normal
playback. (Although admittedly, the syntax is quite a bit of work.)
2014-09-18 01:23:33 +02:00
wm4 6c3d25e6f5 command: allow using ASS tags on OSD messages
We don't allow this by default, because it would be silly if random
external data (like filenames or file tags) could accidentally trigger
them.

Add a property that magically disables this ASS tag escaping.

Note that malicious input could still disable ASS tag escaping by
itself. This would be annoying but harmless.
2014-09-18 00:49:55 +02:00
wm4 a522441bbe command: add osd-sym-cc property
This allows you to reproduce the OSD symbol.
2014-09-18 00:12:59 +02:00
Rudolf Polzer a173d3a2fb TOOLS/idet.sh: Handle the case of multiple Parsed_idet_0: output lines.
This seems to happen frequently now. It is handled by adding their values.
2014-09-17 14:11:56 +02:00
wm4 396756e58a ao_oss: prevent hang when unpausing after device was lost
Pausing/unpausing while the audio device can't be reopened, and then
unpausing again when the device is finally reopened, can hang the
player for a while.

This happens because p->prepause_samples grows without bounds each
time the player is unpaused while the device is lost. On unpause,
ao_oss plays prepause_samples of silence to compensate for A/V timing
issues due to the partially lost buffer (we can't pause the device at
an arbitrary sample position, and the current period will be lost).
This in turn will make the player appear to be frozen if too much
audio is queued. (Normally, play() must never block, but here it
happens because more data is written than get_space() reports. A
better implementation would never let prepause_samples grow larger
than the period size.)

The unbounded growth happens because get_space() always returns that
the device can be written while the device is lost. So limit it to
200ms. (A better implementation would limit it to the period size.)

Also see #1080.
2014-09-17 00:33:40 +02:00
wm4 c158e4641a ao_oss: move code around
More logical, and preparation for the next commit. No functional
changes.
2014-09-17 00:14:21 +02:00
shdown f2c46bc1d1 TOOLS: eliminate echoes with variable substitutions
echo behaviour with backslash escapes seems to be non-portable: dash does
expand such an escapes and bash does not, so use cat/printf instead.
2014-09-17 00:00:05 +02:00
shdown 02d0b2f31c TOOLS/mpv_identify.sh: simplify line-by-line reading
Use here-document idiom to read mpv output line-by-line.
2014-09-16 23:59:56 +02:00
wm4 6ef40cb910 video: wake up core as soon as possible
There's no reason to let the core wait until the frame is done
displaying. In practice, the core normally didn't need this additional
wakeup, and the VO was quick enough to fetch the new frame, before the
core even attempted to queue a new frame. But it wasn't entirely clean,
and the correct wakeup handling might matter in some cases.
2014-09-16 23:59:13 +02:00
wm4 60f5e53f60 options: change --volstep to 2
With default settings, this allows you to hit the 100% mark (with
default --softvol-max in the middle) even if you've reached min or max
volume before. This is because 50 is not divisible by 3 (old default)
but by 2 (new default).

Not really sure why there still can be issues with higher --softvol-max
and --volstep=1, but this is where I stop caring.
2014-09-16 19:12:02 +02:00
wm4 d83a9f7f03 player: don't let multiline filenames set options on resume
If --write-filename-in-watch-later-config is used, and the filename
contains newline characters (as generally allowed on Unix), then the
newline will be written to the resume file literally, and the parts
after the newline character are interpreted as options.

This is possibly security relevant.

Change newline characters (and in fact any other special characters)
to '_'.

Reported as #1099 (this commit is a reimplementation of the proposed
pull request).

CC: @mpv-player/stable
2014-09-16 18:23:01 +02:00
wm4 caaeb15318 demux: gracefully handle packet allocation failures
Now the packet allocation functions can fail.
2014-09-16 18:11:00 +02:00
wm4 26e0cce969 TOOLS/mpv_identify.sh: mark as executable 2014-09-16 17:34:19 +02:00
Otto Modinos 33a63d8e6e options.lua: call msg.debug after resolving 'identifier' 2014-09-16 17:34:08 +02:00
Ben Boeckel b41ece5ad4 command: avoid a double -> int cast
Just check against zero directly.

Changes behavior, but that should be ok.

Signed-off-by: wm4 <wm4@nowhere>
2014-09-16 17:33:47 +02:00
Ben Boeckel 5fd8660f5f TOOLS: idet: use quotes for the verdict value
ShellCheck warns about "vara-varb" about not being in $(()), but we
actually want the literal string, so quote it. Also fix a typo.
2014-09-16 17:32:39 +02:00
Ben Boeckel 11c044aa48 TOOLS: shellcheck: quote variable expansions 2014-09-16 17:32:33 +02:00
Ben Boeckel 45e2345a7f TOOLS: shellcheck: remove '$' on variables in $(()) expansion 2014-09-16 17:29:46 +02:00
Ben Boeckel ec2c6a17dc TOOLS, version.sh: shellcheck: replace cmd with $(cmd)
Signed-off-by: wm4 <wm4@nowhere>
2014-09-16 17:29:39 +02:00
Ben Boeckel ba2a3f40ac TOOLS: idet: remove unused code 2014-09-16 17:29:11 +02:00
Alexander Preisinger 95053ba78b vo_wayland: remove unnecessary check
buffer_pool_get_front now returns always a valid buffer.
No need for corner cases.
2014-09-16 15:54:10 +02:00
Alexander Preisinger 20643b6c91 wayland/buffer: use buffer macros consistently 2014-09-16 15:48:07 +02:00
Aleksey Andreev 9e1ea9b3cd manpage: fix typo in input.rst
Signed-off-by: wm4 <wm4@nowhere>
2014-09-15 23:23:26 +02:00
wm4 cfdeb9d8ce input.conf: map ESC to exiting fullscreen
Apparently making ESC exit fullscreen mode is the more popular
convention compared to ESC quitting the program.

It was also concluded that ESC should do nothing when the windows is
already in normal state.

See discussion in #973.
2014-09-15 23:22:21 +02:00
wm4 b2b1b848da af_lavrresample: fix crash with size 0
The filter output size can be 0. Due to how filtering works, this is
nothing unusual, but avresample_convert() will return 0. The same case
is already handling with "normal" resampling (this commit fixes the
reordering code).

Additionally, don't use an assert(). avresample_convert() failing is
unusual, but might also happen due to e.g. internal out of memory
conditions, so we shouldn't just crash on it.

Curiously observed with --ao=oss --audio-channels=5.1 when changing
speed.
2014-09-15 23:14:19 +02:00
wm4 7c2fb859ab ao_oss: don't break playback when device can't be reopened
Apparently NetBSD users want/need this (see issue #1080).

In order not to break playback, we need at least to emulate get_delay().
We do this approximately by using the system clock.

Also, always close the audio device on reset. Reopen it on play only. If
we can't reopen it, don't retry until after the next time reset or
resume is called, to avoid spam and unexpectedly "stealing" back the
audio device.

Also do something about framestepping causing audio desync.
2014-09-15 23:08:19 +02:00
wm4 d5b8b5b901 ao_oss: audio_buf_info isn't state
The context struct had an audio_buf_info field, but there's no reason
why this would be needed. It's a tiny struct, and it isn't permanent
state. It's always returned by SNDCTL_DSP_GETOSPACE. Keeping this as
field is just confusing, so get rid of it.
2014-09-15 22:02:04 +02:00
wm4 b951326a38 ao_oss: remove duplicate audio device open code
The code for reopening the audio device was separate, and duplicated
some of the "real" open code. This was very badly done, and major
required parts of initialization were skipped. Fix this by removing
the code duplication. This consists mainly of moving the code for
opening the device to a separate function, and adding some changes
to handle format changes gracefully. (We can't change the audio
format on the fly, but we can at least not explode and play noise
when that happens.)

As a minor change, actually always use SNDCTL_DSP_RESET when closing
the audio device. We don't want to wait until the rest of the buffer
is played.

Also, don't use strerror() when printing the error message that
reopening failed, simply because reopen_device() takes care of this,
and also errno might be clobbered at this point.
2014-09-15 22:02:04 +02:00
wm4 9ca1582953 ao_oss: assume audio format reinit is not needed with SNDCTL_DSP_RESET
I have no idea whether this is true, because there literally doesn't
seem to exist documentation for SNDCTL_DSP_RESET. But at least on
Linux' OSS emulation, it is true. Also, it would be quite insane if
it would be needed.
2014-09-15 21:56:46 +02:00
wm4 2308eda2b8 ao_oss: don't use SNDCTL_DSP_RESET when pausing on NetBSD
It seems on NetBSD SNDCTL_DSP_RESET exists, but using it for pausing
is not feasible. We still use it to discard the audio buffer when
closing the audio device.
2014-09-15 21:54:28 +02:00
wm4 8efc4b7e24 ao_oss: fix incorrect comments using bytes instead of samples
MPlayer uses bytes, mpv uses sample counts in the AO API.
2014-09-15 20:22:12 +02:00
wm4 8c002b79d3 x11: if the WM supports _NET_FRAME_EXTENTS, don't wait for map
Some window managers can prevent mapping of a window as a feature. i3
can put new windows on a certain workspace (with "assign"), so if mpv is
started on a different workspace, the window will never be mapped.

mpv currently waits until the window is mapped (blocking almost all of
the player), in order to avoid race conditions regarding the window
size. We don't want to remove this, but on the other hand we also don't
want to block the player forever in these situations.

So what we need is a way to know when the window manager is "done" with
processing the map request. Unfortunately, there doesn't seem to be a
standard way for this. So, instead we could do some arbitrary
communication with the WM, that may act as "barrier" after map request
and the "immediate" mapping of the window. If the window is not mapped
after this barrier, it means the window manager decided to delay the
mapping indefinitely. Use the _NET_REQUEST_FRAME_EXTENTS message as such
a barrier. WMs supporting this message must set the _NET_FRAME_EXTENTS
property on the mpv window, and we receive a PropertyNotify event. If
that happens, we always continue and cancel waiting for the MapNotify
event.

I don't know if this is sane or if there's a better mechanism. Also,
this works only for WMs which support this message, which are not many.
But at least it appears to work on i3. It may reintroduce flickering on
fullscreen with other WMs, though.
2014-09-15 19:19:01 +02:00
wm4 930c61b64c DOCS/client_api_examples: qtexample: resize to video size
This is pretty imperfect, but it's just a demo.

The main purpose is clarifying how and when to get the video size.

In theory, retrieving the properties this way has a race condition:
after reading dwidth, the video could resize again. But the worst that
can happen are mismatching dwidth/dheight values, and the
MPV_EVENT_VIDEO_RECONFIG event would be immediately received again,
which would fix the mismatch. You could read the full video-out-params
property to absolutely avoid it, but it's not worth the trouble.
2014-09-15 18:38:42 +02:00
wm4 ac2047e02e manpage: clarify description of dwidth/dheight 2014-09-15 18:29:53 +02:00
Ben Boeckel 9bfa38add6 img_convert: sanitizer: avoid invalid left-shifts
(a << 24) is not in the valid int range when a is 255, so use an
unsigned instead.

Signed-off-by: wm4 <wm4@nowhere>
2014-09-14 21:10:09 +02:00
Ben Boeckel 3f6212cd8d sanitizer: avoid divide-by-zero instances
Merges pull request #1094, with some minor changes. mpv expects IEEE,
and IEEE allows divisions by 0 for floats, so these shouldn't actually
be a problem, but do it anyway for the sake of clang.

Signed-off-by: wm4 <wm4@nowhere>
2014-09-14 21:07:30 +02:00
wm4 e0b4daf3ad input: use libwaio for pipe input on Windows
Use libwaio to read from pipes (stdin or named pipes) on Windows. This
liberates us from nasty issues, such as pipes (as created by most
programs) not being possible to read in a non-blocking or event-driven
way. Although it would be possible to do that in a somewhat sane way
on Vista+, it's still not easy, and on XP it's especially hard. libwaio
handles these things for us.

Move pipe.c to pipe-unix.c, and remove Windows specific things. Also
adjust the input.c code to make this work cleanly.
2014-09-14 16:24:01 +02:00
wm4 b44571abab x11: remove unused function 2014-09-14 15:59:10 +02:00
wm4 955671f64a player: shorten skip heuristic for playlist_prev to 1 second
See issue #1084.
2014-09-14 10:32:24 +02:00
wm4 08116feec7 input: fix nested commands
Regression from today.
2014-09-13 18:41:34 +02:00
wm4 b6d8d5e05c stream: fix build with emulated atomics
This code was legal with C11 atomics, but it fails with our
compatibility wrapper.
2014-09-13 17:08:47 +02:00
wm4 b799bf0dbf client API: use playback abort mechanism
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).
2014-09-13 16:52:42 +02:00
wm4 893f4a0fee input: distinguish playlist navigation and quit commands for abort
Refine the ugly hack from the previous commit, and let the "quit"
command and some others abort playback immediately. For
playlist_next/playlist_prev, still use the old hack, because we can't
know if they would stop playback or not.
2014-09-13 16:47:30 +02:00
wm4 2e91d44e20 stream: redo playback abort handling
This mechanism originates from MPlayer's way of dealing with blocking
network, but it's still useful. On opening and closing, mpv waits for
network synchronously, and also some obscure commands and use-cases can
lead to such blocking. In these situations, the stream is asynchronously
forced to stop by "interrupting" it.

The old design interrupting I/O was a bit broken: polling with a
callback, instead of actively interrupting it. Change the direction of
this. There is no callback anymore, and the player calls
mp_cancel_trigger() to force the stream to return.

libavformat (via stream_lavf.c) has the old broken design, and fixing it
would require fixing libavformat, which won't happen so quickly. So we
have to keep that part. But everything above the stream layer is
prepared for a better design, and more sophisticated methods than
mp_cancel_test() could be easily introduced.

There's still one problem: commands are still run in the central
playback loop, which we assume can block on I/O in the worst case.
That's not a problem yet, because we simply mark some commands as being
able to stop playback of the current file ("quit" etc.), so input.c
could abort playback as soon as such a command is queued. But there are
also commands abort playback only conditionally, and the logic for that
is in the playback core and thus "unreachable". For example,
"playlist_next" aborts playback only if there's a next file. We don't
want it to always abort playback.

As a quite ugly hack, abort playback only if at least 2 abort commands
are queued - this pretty much happens only if the core is frozen and
doesn't react to input.
2014-09-13 16:09:51 +02:00
wm4 2dd819705d input: "quit_watch_later" and "stop" are abort commands
This means they get special handling for asynchronously aborting
playback, even if the player is "stuck".

Also document "stop". It seems somewhat useful for client API users
(although that will be implemented properly only in the following
commits.)
2014-09-13 14:10:10 +02:00
Philip Sequeira 7c77f0b803 TOOLS/zsh.pl: complete options that take file names 2014-09-13 02:03:09 +02:00
Alessandro Ghedini 1273febc44 options: add M_OPT_FILE flag to mark options that want a file(list) 2014-09-13 02:03:09 +02:00
wm4 b5d253a5cb m_config: fix theoretic undefined behavior
The memcpy() is actually not enough: the types are incompatible, and no
memcpy, union, etc. will change that. (Although no real compiler will
ever break this.) Attempt to make this theoretically correct by actually
using a struct pointer. It's not the same struct type, but supposedly
it's ok, because all struct pointers always have the same size and
representation in standard C.
2014-09-13 01:27:54 +02:00
wm4 8bf57b8192 player: fix idle mode event handling
Idle mode went to sleep too early, e.g. just pressing "ESC" did nothing,
until the next event happened. This was because it directly went to
sleep after processing commands. What we should do instead is rechecking
all state after processing commands, redraw OSD, and then go to sleep.
This also fixes some strange OSD-related behavior.

Also move some other code around to separate idle mode initialization
from the normal run loop.
2014-09-13 01:14:07 +02:00
wm4 b0a3d38b4c input: don't autorepeat cycle_values command
Not sure why this was originally added as autorepeated. It makes no
sense, because switching between choices should never autorepeat. (For
the normal "add"/"cycle" commands, autorepeat is usually enabled, but
command.c tries to disable it specifically for choice properties.)
2014-09-13 01:14:07 +02:00
wm4 a3b393d68c input: simplify
Just some minor things. In particular, don't call mp_input_wakeup()
manually, but make it part of queuing commands (as far as possible).
2014-09-13 01:14:07 +02:00
wm4 fc5df2b970 input: fix autorepeat
Mismatching units in timeout calculation.

Also, as a near-cosmetic change, explicitly wake up the core on the
right time. Currently this does nothing, because the core is woken up
anyway - but it will matter with the next commit.
2014-09-13 01:14:07 +02:00
wm4 f93dd45ac1 manpage: document shift+pgup/pgdwn bindings 2014-09-13 01:14:07 +02:00
wm4 d26a0ae111 ao_oss: fix audio device leak on error
Close the audio device if it was already opened, but the rest of
initialization failed.
2014-09-11 02:05:12 +02:00
wm4 5f80e3f91a ao_oss: use poll(), drop --disable-audio-select support
Replace select() usage with poll() (and reduce code duplication).

Also, while we're at it, drop --disable-audio-select, since it has the
wrong name anyway. And I have doubts that this is needed anywhere. If
it is, it should probably fallback to doing the right thing by default,
instead of requiring the user to do it manually. Since nobody has done
that yet, and since this configure option has been part of MPlayer ever
since ao_oss was added, it's probably safe to say it's not needed.

The '#ifdef SNDCTL_DSP_GETOSPACE' was pointless, since it's already used
unconditionally in another place.
2014-09-11 02:03:15 +02:00
wm4 f744aadb77 ao_pulse: dump library version etc.
Might help with debugging.

Unfortunately, there doesn't seem to be a way to get the actual
pulseaudio server version.
2014-09-10 23:14:06 +02:00
wm4 f790d6aafd old-build: fix build with wayland 2014-09-10 23:10:43 +02:00
Alexander Preisinger 369868e404 wayland_common: fix changing videos when fullscreen
I broke it again.
2014-09-10 19:21:52 +02:00
Alexander Preisinger 94fe57856d vo_wayland: pixel perfect buffers
1.  Separate buffer and temporary file handling from the vo to make maintenance
    and reading code easier

2.  Skip resizing as much as possible if back buffer is still busy.

3.  Detach and mark osd buffers for deletion if we want to redraw them and they
    are still busy. This could be a possible case for the video buffers as
    well. Maybe better than double buffering.

All the above steps made it possible to have resizing without any artifacts
even for subtitles. Also fixes dozen of bugs only I knew, like broken subtitles
for rgb565 buffers. I can now sleep at night again.
2014-09-10 19:10:19 +02:00
Diogo Franco (Kovensky) 5bbf5ee103 osdep/semaphore_osx.c: Include osdep/semaphore.h before #ifdef
osdep/semaphore.h is the file that defines the very #define that is
tested in the #ifdef that wraps its inclusion, so it was never compiled.
2014-09-10 17:22:20 +09:00
wm4 302a04091b build: fix everything
A missing dependency entry made ./waf configure always fail.
2014-09-10 04:09:06 +02:00
wm4 524db3384b osdep: fix windows build
Oops.
2014-09-10 03:29:24 +02:00
wm4 e9b756c7ad input: remove central select() call
This is now unused. Get rid of it and all surrounding infrastructure,
and replace the remaining "wakeup pipe" with a semaphore.
2014-09-10 03:24:45 +02:00
wm4 564b957cc3 osdep: add POSIX semaphore emulation for OSX
OSX is POSIX conformant, but it's a sad joke: it provides the
<semaphore.h> prototype as the standard demands, but they're empty
wrappers, and all functions just return ENOSYS.

Emulate them similar to how osdep/io.h emulate filesystem functions on
Windows. By including the header, working sem_* functions become
available.

To make it async-signal safe, use a pipe for wakeup (write() is AS-safe,
but mutexes can't be). Actually I'm not sure anymore if we really need
AS-safety, but for now the emulation can do it.

On Linux, the system provides a far more efficient and robust
implementation. We definitely want to avoid using the emulation if
possible, so this code is active on OSX only. For convenience we always
build the source file though, even if the implementation is disabled and
no actual code is generated.

(Linux provides working semaphores, but is formally not POSIX
conformant. On OSX it's the opposite. Is POSIX a complete joke?)
2014-09-10 03:24:19 +02:00
wm4 ae63702a2c input: remove useless joystick.h/lirc.h include files
These really just waste space.
2014-09-10 00:51:36 +02:00
wm4 e2a093df02 input: use an input thread for joystick 2014-09-10 00:48:59 +02:00
wm4 fe0ca7559c input: use an input thread for lirc 2014-09-10 00:48:45 +02:00
wm4 5be678386b input: add convenience function for running input sources in threads 2014-09-10 00:48:12 +02:00
wm4 256fea7655 input: make some fields internal 2014-09-10 00:48:12 +02:00
wm4 49a0b61880 terminal-unix: don't read from stdin if it's not a terminal
I'm not quite sure what we should actually do (maybe read input
commands?), but interpreting input as terminal key sequences is
definitely weird. So just do nothing.
2014-09-10 00:48:12 +02:00
wm4 28fc13977e terminal-unix: move to thread
Do terminal input with a thread, instead of using the central select()
loop. This also changes some details how SIGTERM is handled.

Part of my crusade against mp_input_add_fd().
2014-09-10 00:48:12 +02:00
wm4 d0b525121a terminal-win: minor simplification
Code should be equivalent.
2014-09-10 00:48:12 +02:00
wm4 670f965f1a win32: don't request window size larger than the screen
An attempt at fixing #1070. Apparently something goes wrong if the
video size is equal to the screen size. Since the window decorations
add to the window size, it must actually be larger than the screen.
Actually I don't know what exactly is going wrong, but since this
commit also slightly improves the behavior otherwise, it's a win
anyway.

Try to keep the window size strictly below screen size, even accounting
for window decorations. Size it down and center the window so that it
fits (by either touching the left/right or top/bottom screen borders).
I haven't found any information on what is the maximum allowed size and
position of a window so that it doesn't collide with the task bar, so
assume that we can use the entire screen, minus 1 pixel to avoid
triggering fullscreen semantics (if that is even possible).
2014-09-10 00:48:07 +02:00
wm4 e1e8b07cfa player: reset some VO state when video is terminated
Useful for idle mode or if video is switched off during playback, and
--force-window is used.
2014-09-09 01:23:10 +02:00
wm4 c0fbab7a7c player: deal with some corner cases with playlist navigation
The purpose is making accessing the current playlist entry saner when
commands are executed during initialization, termination, or after
playlist navigation commands.

For example, the "playlist_remove current" command will invalidate
playlist->current - but some things still access the playlist entry even
on uninit. Until now, checking stop_play implicitly took care of it, so
it worked, but it was still messy.

Introduce the mpctx->playing field, which points to the current playlist
entry, even if the entry was removed and/or the playlist's current entry
was moved (e.g. due to playlist navigation).
2014-09-09 01:23:10 +02:00
wm4 9cb1e2c58c player: normalize playlist entries on add
This is not necessarily more correct, but it's less trouble.
2014-09-09 01:23:10 +02:00
wm4 76f9eede34 input: fix missed wakeups, simplify
mp_input_read_cmd() reset the wakeup flag, but only mp_input_wait()
should be able to do that.
2014-09-09 01:23:09 +02:00
wm4 b578abe81b ao_pulse: fix typo in error message
Closes #1076.
2014-09-08 17:19:53 +02:00
wm4 4ef531f815 input: fix use after free with legacy commands
To handle legacy commands, string replacement is used; the modified
string is returned by parse_cmd_str(), but it also frees all temporary
memory, which includes the replaced string.

Closes #1075.
2014-09-08 15:13:11 +02:00
wm4 3b5f28bd0f input: fix exiting with signals
Quitting through SIGTERM etc. was accidentally ignored since commit
f5af5962 from today.
2014-09-08 01:11:32 +02:00
wm4 8c7a9b0cd0 stream: change cache return values
Basically a cosmetic change, because currently the player just continues
even if the cache fails initializing.
2014-09-07 20:45:39 +02:00
wm4 f5af596237 player: some more input refactoring
Continues commit 348dfd93. Replace other places where input was manually
fetched with common code.

demux_was_interrupted() was a weird function; I'm not entirely sure
about its original purpose, but now we can just replace it with simpler
code as well. One difference is that we always look at the command
queue, rather than just when cache initialization failed. Also, instead
of discarding all but quit/playlist commands (aka abort command), run
all commands. This could possibly lead to unwanted side-effects, like
just ignoring commands that have no effect (consider pressing 'f' for
fullscreen right on start: since the window is not created yet, it would
get discarded). But playlist navigation still works as intended, and
some if not all these problems already existed before that in some
forms, so it should be ok.
2014-09-07 20:44:54 +02:00
wm4 5546af421f win32: copy event flags after running VOCTRLs
reinit_window_state() will set VO_EVENT_RESIZE when it runs, so we
don't need to set it manually depending on the VOCTRL.

Probably avoids duplicated resize events. I don't expect this actually
fixes anything, but might help spotting other bugs easier (if there
are any).
2014-09-07 13:22:50 +02:00
wm4 017b3fa9db lua: synchronously wait until scripts are loaded
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.
2014-09-06 17:02:47 +02:00
wm4 348dfd93c4 player: minor refactoring
Expose the central event handling functions explicitly, so that other
parts of the player can use them.

No functional changes. Preparation for the next commit.
2014-09-06 16:57:46 +02:00
wm4 94113e632f audio/out: fix active waiting during pause again
This was fixed in commit 8432eaefa, and commit 39609fc1 of course broke
it again. This was pretty stupid.
2014-09-06 16:25:27 +02:00
Stefano Pigozzi a1d3afb395 vo_corevideo: remove this VO
This was kept in the codebase because it is slightly faster than --vo=opengl
on really old Intel cards (from the GMA era). Time to kill it, and let it rest.

Fixes #1061
2014-09-06 14:10:22 +02:00
wm4 a6774d3a83 stream_lavf: assume icy title data is terminated with ';'
Should fix #1071.
2014-09-06 13:46:17 +02:00
wm4 7791e25fa0 audio: fix initial sync with huge AO buffer
With e.g --start=-3 --audio-buffer=10 the decoder entered EOF state
before the initial sync was finished, entered STATUS_EOF, and just
started playing audio from a random position.

This doesn't handle seeking outside of the file, which is a different
case. E.g. --start=30:00 with audio and video enabled in a file shorter
than 30:00 will play a random last part of audio. This could perhaps be
fixed by using the hr-seek target for cutting audio, instead of the
video PTS, but that would be kind of intrusive, so don't do it for now.
The simpler solution, assuming audio EOF on video EOF, wouldn't work,
because we allow audio to start before video, or to last after video.
2014-09-06 13:33:29 +02:00
wm4 39609fc19a audio/out/push: redo audio waiting
Improve the logic how the audio thread decides how to wait until the AO
is ready for new data. The previous commit makes some of this easier,
although it turned out that it wasn't required, and we still can handle
AOs with bad get_space implementation (although the new code prints an
error message, and it might fail in obscure situations).

The new code is pretty similar to the old one, and the main thing that
changes is that complicated conditions are tweaked. AO waiting is now
used better (mainly instead of max>0, r>0 is used). Whether to wakeup
is reevaluated every time, instead of somehow doing the wrong thing
and compensating for it with a flag.

This fixes the specific situation when the device buffer is full, and
we don't want to buffer more data. In the old code, this wasn't handled
correctly: the AO went to sleep forever, because it prevented proper
wakeup by the AO driver, and as consequence never asked the core for new
data. Commit 4fa3ffeb was a hack-fix against this, and now that we have
a proper solution, this hack is removed as well.

Also make the refill threshold consistent and always use 1/4 of the
buffer. (The threshold is used for situations when an AO doesn't
support proper waiting or chunked processing.)

This commit will probably cause a bunch of regressions again.
2014-09-06 12:59:04 +02:00
wm4 769ac6fb7b audio/out: always round get_space on period size
Round get_space() results in the same way play() rounds the input size.
Some audio APIs do this for various reasons.

This affects only "push" based AOs. Some of these need no change,
because they either do it already right (like ao_openal), or they seem
not to have any such requirements (like ao_pulse).

Needed for the following commit.
2014-09-06 12:59:00 +02:00
wm4 d9941e01cc ao_sndio: fix a comment
Whether this code was written with the correct assumptions in mind, I
don't know.
2014-09-06 12:58:57 +02:00
wm4 6c9ce5bee2 ao_pcm: minor simplification 2014-09-06 12:58:54 +02:00
wm4 4962a1ece3 ao_oss: minor simplification
Equivalent code.
2014-09-06 12:58:48 +02:00
wm4 cf04ddca38 mplayer-input.conf: fix broken binding
"#" starts a comment, so the # key needs to be handled specially.
MPlayer has the same issue, but its input.conf is wrong. Or at least I
think it's wrong; looking at the MPlayer code it's doubtful they somehow
special-case and handle this.
2014-09-06 02:49:28 +02:00
wm4 439a05d8c3 audio/out: remove old things
Remove the unnecessary indirection through ao fields.

Also fix the inverted result of AOCONTROL_HAS_TEMP_VOLUME. Hopefully the
change is equivalent. But actually, it looks like the old code did it
wrong.
2014-09-06 02:30:57 +02:00
wm4 197f18402e sub: fix possible deadlock with --no-sub-ass and similar
This is a deadlock caused by a lock order issue: sub/osd.c locks the OSD
first, then the subtitle decoder lock. player/sub.c does the reverse.

Fix this by discussing away the requirement for locking (see below),
which allows us to drop the broken sub lock. sub_get_text() still
acquires and releases the sub decoder lock, but it's not held at the
same time as the OSD lock anymore, so it should be fine.

Originally, the sub lock was acquired because sub_get_text() returns a
pointer to a mutable string. We simply declare that it's ok to call it
unlocked, as long as only 1 thread accesses it, which works out fine in
this case.
2014-09-06 00:16:15 +02:00
wm4 bdf49d137e audio/out: make EOF handling properly event-based
With --gapless-audio=no, changing from one file to the next apparently
made it hang, until the player was woken up by unrelated events like
input. The reason was that the AO doesn't notify the player of EOF
properly. the played was querying ao_eof_reached(), and then just went
to sleep, without anything waking it up.

Make it event-based: the AO wakes up the playloop if the EOF state
changes.

We could have fixed this in a simpler way by synchronously draining the
AO in these cases. But I think proper event handling is preferable.

Fixes: #1069
CC: @mpv-player/stable (perhaps)
2014-09-05 23:45:54 +02:00
wm4 6b59d6a47b vo_sdl: fix typo 2014-09-05 22:10:20 +02:00
wm4 ce246296b3 af_hrtf: request required samplerate, instead of erroring out
It seems hrtf works in 48khz only - and if that wasn't the input, the
filter just exited with an error. Make it request the 48khz instead. The
player will insert a resampling filter.

Not sure why it wasn't done like this in the first place.
2014-09-05 20:49:35 +02:00
wm4 5f29073abf af_hrtf: cosmetics: reindent misaligned code block 2014-09-05 20:47:54 +02:00
wm4 eaa1f16564 audio: correctly initialize output buffer
Just like the previous commit, this takes care of fallout from commit
7ab228, which fixed a bug, but introduced some new ones.

CC: @mpv-player/stable
2014-09-05 17:51:45 +02:00
James Ross-Gowan eba8eeda78 player: check for null in resume config search
Signed-off-by: wm4 <wm4@nowhere>

CC: @mpv-player/stable
2014-09-05 17:51:45 +02:00
James Ross-Gowan 5c3f3fd3da win32: add tmpfile() replacement
The Windows version of tmpfile is actually pretty broken. It tries to
create the file in the root directory of the current drive, which means
on Vista and up, it normally fails due to insufficient permissions.
Replace it with a version that uses GetTempPath.

Also remove the Windows-specific note about automatic deletion of the
cache file. FILE_FLAG_DELETE_ON_CLOSE is available in NT, and it should
be pretty reliable.
2014-09-05 17:51:44 +02:00
wm4 15a882d2ed audio: fix random crashes on uninit
I added this non-sense earlier this day. Oops.
2014-09-05 04:33:24 +02:00
wm4 545c2d7206 manpage: fix sub_add description
It is in fact selected. The manpage wasn't updated when this was
changed.
2014-09-05 02:42:25 +02:00
Bruno George de Moraes bca4219dd0 malloc+memset(0) to calloc
Signed-off-by: wm4 <wm4@nowhere>
2014-09-05 01:59:11 +02:00
wm4 a7d737a698 audio: make buffer size configurable
Really only for testing.
2014-09-05 01:53:10 +02:00
wm4 7ab228629e audio: fix obscure audio resync failure with timelines
Somehow, there was a larger misunderstanding in the code: ao_buffer
does not need to be preserved over audio reinit for proper support of
gapless audio. The actual AO internal buffer takes care of this.

In fact, preserving ao_buffer just breaks audio resync. In the ordered
chapter case, end_pts is used, which means not all audio data in the
buffer is played, thus some data is left over when audio decoding
resumes on the next segment. This triggers some code that aborts resync
if there's "audio decoded" (ao_buffer contains something), but no PTS
is known (nothing was actually decoded yet).

Simplify, and always bind the output buffer to the decoder.

CC: @mpv-player/stable (maybe)
2014-09-05 01:53:10 +02:00
wm4 787839e8ec cosmetics: remove a stray ';' 2014-09-05 01:53:10 +02:00
wm4 b518142236 build: handle insane libavcodec API bullshit
The oldest supported FFmpeg release doesn't provide
av_vdpau_alloc_context(). With these versions, the application has no
other choice than to hard code the size of AVVDPAUContext. (On the other
hand, there's av_alloc_vdpaucontext(), which does the same thing, but is
FFmpeg specific - not sure if it was available early enough, so I'm not
touching it.)

Newer FFmpeg and Libav releases require you to call this function, for
ABI compatibility reasons. It's the typcal lakc of foresight that make
FFmpeg APIs terrible. mpv successfully pretended that this crap didn't
exist (ABI compat. is near impossible to reach anyway) - but it appears
newer developments in Libav change the function from initializing the
struct with all-zeros to something else, and mpv vdpau decoding would
stop working as soon as this new work is relewased.

So, add a configure test (sigh).

CC: @mpv-player/stable
2014-09-05 01:52:29 +02:00
wm4 e267ff93f3 video: rename VOCTRL_GET_WINDOW_SIZE
Make it clear that this accesses the un-fullscreened window size.
2014-09-05 01:52:16 +02:00
wm4 c15957b43a ebml: warn if there are too many subelements
Seems like a good idea.
2014-09-04 19:21:19 +02:00
wm4 d9aaf78530 demux_mkv: allow up to 256 MB of extradata to make broken files work
What the flying fuck?

Unfortunately, these are already in the wild.

CC: @mpv-player/stable
2014-09-04 19:20:47 +02:00
Stefano Pigozzi 7b0de4aa0e build: add a check_program check
This wraps waf's find_program in our own check boilerplate code so that it
can be used in the declarative dependencies section of the wscript.

Can be used like this:

    }, {
        'name': 'sed',
        'desc': 'sed program',
        'func': check_program('sed', 'SED'),
    }, {

First argument is the program name, and the second is the waf variable name
where the program path will be stored. In this example we will be able to
refer to sed with ${{SED}} when creating waf Tasks in wscript_build.

/cc @giselher: I think you need this for wayland-scanner.
2014-09-03 23:52:56 +02:00
Alexander Preisinger fc68c9269d wayland: print some useful outptu info
Prints output informations, useful for finding out if we detect the right mode
and for debugging.
2014-09-03 21:35:26 +02:00
Alexander Preisinger 8bd5df3ac1 wayland: only save current mode of outputs
Other ones are not needed.
2014-09-03 21:35:26 +02:00
Kenneth Zhou 98b9d47482 x11: add rewind and forward keys
Signed-off-by: wm4 <wm4@nowhere>
2014-09-03 21:08:54 +02:00
wm4 0835e093e2 path: remove XDG bullshit
Don't worry, your ~/.config/... paths are safe. This merely removes
handling of $XDG_CONFIG_DIRS for global paths.

Maybe there is a better solution for this, like still including the
"traditional" config dir. But I will leave the fine reading of this
(crappy) spec and fixing the code accordingly to someone else. So, if
anyone has interest in getting this behavior back, you will have to
write a patch. This patch should _also_ not break expected behavior.

Fixes #1060.
2014-09-03 02:07:36 +02:00
wm4 9e512c5a98 demux: allow increasing filepos only
The last demuxed file position (demuxer->filepos) is used to estimate
the total playback percentage in files with possible timestamp resets
(like MPEG-PS). Until know, reading from any stream set this position
freely. This makes the position jump around.

Fix this by allowing icnreasing file position only. Reset it on seeking.
With crazy formats, this still could go wrong, but there's only so much
you can do.
2014-09-03 02:00:18 +02:00
wm4 bf74a4cc46 player: add --media-title option
Requested by ChrisK2.
2014-09-02 22:28:11 +02:00
wm4 6c1e528518 player: properly resume playlists loaded at runtime
If a playlist is loaded from the internal playlist (like
"mpv playlist.m3u"), then attempt to resume from it.

CC: @mpv-player/stable
2014-09-02 22:16:20 +02:00
wm4 2da246b9f7 player: add --osd-playing-msg option 2014-09-02 00:12:52 +02:00
wm4 291d986810 player: show HLS bitrate as fallback for track titles
HLS streams as demuxed by libavformat have no track title metadata. So
show the HLS bitrate if no title is set. Could be useless or annoying,
so it's a bit controversial, I guess.
2014-09-01 23:50:25 +02:00
wm4 5f14543668 player: simplistic HLS bitrate selection
--hls-bitrate=min/max lets you select the min or max bitrate. That's it.
Something more sophisticated might be possible, but is probably not even
worth the effort.
2014-09-01 23:47:27 +02:00
wm4 8d92128f6b command: remove broken quvi-format property
Never really worked, and libquvi is probably a lost cause anyway.
2014-09-01 23:27:33 +02:00
wm4 2f537bafa5 demux: get rid of old wrapper
demux_info_get() used to be central, but was turned into a wrapper, and
now there was only one caller left. Get rid of it.
2014-09-01 22:12:39 +02:00
wm4 0aaf688c2d command: make m_property_strdup_ro with NULL mean unavailable
This catches a few cases which basically call:

    m_property_strdup_ro(..., ..., NULL)

which would return NULL strings. This should generally be avoided
(although it's allowed due to reasons), and it seems most callers
actually intend this to mean M_PROPERTY_UNAVAILABLE.
2014-09-01 21:50:54 +02:00
wm4 4124a175e1 command: disable some commands/properties properly in idle mode
In particular, don't allow to add any external subtitle tracks in idle
mode. This make no sense and would just lead to leaks or worse.
2014-09-01 21:44:54 +02:00
wm4 e87617593f player: reset playback-related fields right on start 2014-09-01 21:02:43 +02:00
Martin Herkt 27a065182c man: fix a whole bunch of typos 2014-09-01 04:27:13 +02:00
wm4 5ea84e17c0 player: don't allow remote playlists to load local files
Because that might be a bad idea.

Note that remote playlists still can use any protocol marked with
is_safe and is_network, because the case of http-hosted playlists
containing URLs using other streaming protocols is not unusual.
2014-09-01 00:13:22 +02:00
wm4 129a7c056a playlist: don't add the base path twice
Loading a playlist with --playlist from a sub-directory added the
playlist's base path twice: one time in the playlist demuxer, and then
again in playlist_parse_file(). The latter function is used only for
--playlist, so it worked when loading the playlist directly.

(This is probably a mess-up when the MPlayer playlist parsers were
replaced with newer code.)

CC: @mpv-player/stable
2014-09-01 00:13:10 +02:00
wm4 f59f1e532e client API: fix memory leak with rejected events
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.
2014-08-31 19:51:41 +02:00
wm4 866e0e1670 player: always load playlists
Until now, you had to use --load-unsafe-playlists or --playlist to get
playlists loaded. Change this and always load playlists by default.

This still attempts to reject unsafe URLs. For example, trying to invoke
libavdevice pseudo-demuxer is explicitly prevented. Local paths and any
http links (and some more) are always allowed.
2014-08-31 19:49:39 +02:00
wm4 fc0fa9a221 audio: go to draining state instead of EOF if audio starts later
Probably no observable effect, but it's more correct. Setting audio to
EOF could have bad effects otherwise (anywhere the player logic for
example decides whether EOF was reached, and such).
2014-08-31 14:48:58 +02:00
wm4 fd4045965e video: adjust some Matroska 3D formats
There is no proper and exact spec (Matroska tradition), so we probably
have to rely on guessing for this.

Also see issue #1045.
2014-08-31 14:48:58 +02:00
wm4 8432eaefa0 audio/out: prevent burning CPU when seeking while paused
The audio/video sync code in player/audio.c calls ao_reset() each time
audio decoding is entered, but the player is paused, and there would be
more than 1 sample to skip to make audio start match with video start.
This caused a wakeup feedback loop with push.c.

CC: @mpv-player/stable
2014-08-31 14:48:58 +02:00
wm4 64b7811c28 x11: when using --wid, inherit event flags from parent window
When embedding a X window, it's hard to control whether it receives
mouse/keyboard input or not. It seems the X protocol itself makes this
hard (basically due to the outdated design mismatching with modern
toolkits), and we have to take care of these things explicitly.

Simply do this by manually querying and using the parent window event
flags.

This restores some MPlayer behavior (it doesn't add back exactly the
same code, but it's very similar).

This probably has some potential to interfere with libmpv embedding, so
bump the client API minor.

CC: @mpv-player/stable (if applied, client-api-changes.rst has to be
    adjusted to include the 0.5.2 release)
2014-08-31 14:48:26 +02:00
Otto Modinos a910b5c6df lua: expose mp_getcwd through mp.utils 2014-08-31 00:58:27 +02:00
wm4 8956878448 manpage: be more explicit about "estimated-..." properties
In particular, use the note markup. The issue about rounded timestamps
is mostly with respect to Matroska (which usually rounds them to
milliseconds), which somewhat adds to the reliability issue.
2014-08-31 00:22:01 +02:00
wm4 94140e0897 csputils: adjust comment
Make it clear that the value is linked to the StereoMode element. You
can't change this without adjusting demux_mkv.c.
2014-08-30 23:54:19 +02:00
wm4 8599c959fe video: initial Matroska 3D support
This inserts an automatic conversion filter if a Matroska file is marked
as 3D (StereoMode element). The basic idea is similar to video rotation
and colorspace handling: the 3D mode is added as a property to the video
params. Depending on this property, a video filter can be inserted.

As of this commit, extending mp_image_params is actually completely
unnecessary - but the idea is that it will make it easier to integrate
with VOs supporting stereo 3D mogrification. Although vo_opengl does
support some stereo rendering, it didn't support the mode my sample file
used, so I'll leave that part for later.

Not that most mappings from Matroska mode to vf_stereo3d mode are
probably wrong, and some are missing.

Assuming that Matroska modes, and vf_stereo3d in modes, and out modes
are all the same might be an oversimplification - we'll see.

See issue #1045.
2014-08-30 23:24:46 +02:00
wm4 c80adac077 cache_file: add a mode that creates a temporary file
Since we have to be portable, our options for creating temporary files
are somewhat limited. tmpfile() happens to be available everywhere, so
use that. This function doesn't allow having a "visible" filename or
location, so we use the magic string "TMP" for this.
2014-08-30 20:03:31 +02:00
wm4 829fdef219 player: reduce default demuxer cache
A (hopefully) temporary hack to make stream switching delays tolerable.
It's not clear how this should be handled (either executing a precise
seek on track switching, or always enabling all streams), so get this
issue out of the way for now by picking a rather low value.
2014-08-30 19:37:21 +02:00
shdown b8f2f0d69e TOOLS/mpv_identify.sh: simplify $MPV handling 2014-08-30 19:23:42 +02:00
shdown 4a976c469c TOOLS/mpv_identify.sh: various style improvements
Double-quote everything, eliminate unneeded evals and deprecated
`backtits` substitution syntax.
2014-08-30 19:23:42 +02:00
shdown 880d5c8a4a TOOLS/mpv_identify.sh: move script body to a function
Don't prepend each variable with __midentify__, just make them local
to the function.
2014-08-30 19:23:42 +02:00
shdown cbe03b6255 TOOLS/youtube-dl_mpv.sh: simplify $MPV handling 2014-08-30 19:23:42 +02:00
shdown 43d4667028 TOOLS/youtube-dl_mpv.sh: disable globbing before expanding $video_url
$video_url can contain a question mark, which can be expanded to a
character in an existing file name if globbing is enabled.
2014-08-30 19:23:41 +02:00
wm4 948dfe651d manpage: document that --cache-file doesn't work with ordered chapters 2014-08-30 19:17:44 +02:00
wm4 b7fa981899 stream: correctly propagate uncached stream type
This makes the ordered chapter code not think that a stream from the
local filesystem is not a local file (it checks uncached_type).
2014-08-30 19:05:57 +02:00
wm4 98ef68bdfd demux_lavf: print a warning if av_read_frame() returns an error
Because why not.
2014-08-30 15:15:38 +02:00
shdown 730d94741c vf_softpulldown: handle null mpi_image correctly
Check if mpi is NULL before accessing mpi->fields.
2014-08-30 15:15:38 +02:00
shdown 3307af43c5 input: make ar_rate and ar_delay fields of input_ctx signed
ar_rate is set to -1 when autorepeat is disabled; there is no reason
for ar_delay to stay unsigned.
2014-08-30 15:15:37 +02:00
shdown 8ee1bcf1fa input: handle reaching MP_MAX_FDS correctly
Don't dereference fd and increment ictx->num_fds on fail.
2014-08-30 15:15:37 +02:00
shdown e2ecf3d03d demux_mkv: eliminate redundant branch
In the else branch pict_type is always 3, so pict_type != 3 is always
false. (Note that I have no idea of what it was supposed to do and it is
just an equivalent of the old behaviour.)
2014-08-30 15:15:37 +02:00
shdown f49099b94d demux: eliminate redundant check
pkt can't be NULL since it's initialized from ds->head, which is checked
at the beginning.
2014-08-30 15:15:37 +02:00
shdown 5bc3b7c368 demux_disc: handle new_sh_stream() fail correctly
Break the cycle on fail. Old code was checking if sh is NULL after
accessing it's fields.
2014-08-30 15:15:37 +02:00
Alexander Preisinger 593e5e4a25 gl_wayland: fix crash after eglInitialze failed
Only execute most of the opengl termination procedure if we actually have an
egl context.
2014-08-30 10:17:51 +02:00
wm4 ce93ee8bd0 manpage: fix minor grammar issue 2014-08-29 20:56:08 +02:00
Bin Jin 225f2e67b7 vo_opengl: remove macro operator from shader
Removes '##' operator from OpenGL shader code.
2014-08-29 20:56:03 +02:00
wm4 a8299cec29 TOOLS/youtube-dl_mpv: allow playing multiple URLs
Unfortunately this also means you can't pass extra mpv options after the
URL anymore. You can prefix the script with MPV='mpv --options' though.
2014-08-29 20:20:29 +02:00
wm4 7d79cd57ff player: fix quit handling when seeking past EOF while paused
The player didn't quit when seeking past EOF in audio-only mode while
paused. The only case when we don't want to quit is when the last video
frame is displayed while paused.

This logic was probably broken a while ago, but I'm not exactly sure.

CC: @mpv-player/stable
2014-08-29 19:13:34 +02:00
wm4 68ff8a0484 Move compat/ and bstr/ directory contents somewhere else
bstr.c doesn't really deserve its own directory, and compat had just
a few files, most of which may as well be in osdep. There isn't really
any justification for these extra directories, so get rid of them.

The compat/libav.h was empty - just delete it. We changed our approach
to API compatibility, and will likely not need it anymore.
2014-08-29 12:31:52 +02:00
wm4 4bc9c52a12 bstr: preparation for next commit
Just so I can move this file without modifying its contents in the next
commit.

compat/compiler.h is to be moved to osdep/ with the next commit, so add
a dummy header.
2014-08-29 12:16:55 +02:00
wm4 ac2502141d stream: tweaks to network reconnection code
Don't reconnect to the cache (since the cached stream already handles
reconnection). This is necessary, because since commit 0b428e44 the
"streaming" field (which also controls whether attempting to reconnect
makes sense at all) is inherited to the cache stream wrapper.

Also, let the stream reset its own position on reconnect. This removes
some assumptions and messy handling from the reconnect function.

Make sure the cache is dropped on reconnect. This takes care of
readjusting the stream position if necessary. (Also drop the cache on
DVB channel switching commands.)
2014-08-29 11:58:49 +02:00
Ryan Jacobs 66f158b89b command: remove extra space
Signed-off-by: wm4 <wm4@nowhere>
2014-08-29 11:58:25 +02:00
wm4 ff7a1c21ce options: more detailed output for --vf-... error message 2014-08-28 17:51:33 +02:00
wm4 e47a9bd721 command: export demuxer cache info properties 2014-08-28 17:49:10 +02:00
wm4 fb1266c98b player: update cache state only if requested
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.
2014-08-28 17:49:09 +02:00
wm4 f9f436a490 audio: restore old speed change behavior
Don't attempt to resync after speed changes. Note that most other cases
of audio reinit (like switching tracks etc.) still resync, but other
code paths take care of setting the audio_status accordingly.

This restores the old behavior of not trying to fix audio desync, which
was probably changed with commit 261506e3.

Note that the code as of now wasn't even entirely correct, since the A/V
sync values are slightly shifted. The dsync depends on the audio buffer
size, so a larger buffer size will show more extreme desync. Also see
mplayer2 commit 213a224e, which should fixed this - it was not merged
into mpv, because it disabled audio for too long, resulting in a worse
user experience. This is similar to the issue this commit attempts to
fix.

Fixes: #1042 (probably)
CC: @mpv-player-stable
2014-08-28 14:26:38 +02:00
Ben Boeckel 7c0a5698eb posix: use STD*_FILENO constants
Rather than "magic" numbers, use meaningful constant names provided by
unistd.h.
2014-08-28 12:03:17 +02:00
Ben Boeckel 2a44e2d1b2 tv: initialize frequencies to 0 2014-08-28 12:02:50 +02:00
Ben Boeckel 9780ff9642 player: simplify chapter display name code
The display name is always recomputed, so we can always toss the input
name.
2014-08-28 12:02:41 +02:00
Ben Boeckel e023524481 player: don't sort a NULL list
This can occur if the directory does not have any files in it which
causes files to never be non-NULL for qsort.
2014-08-28 12:02:09 +02:00
wm4 a95cfac078 vo_opengl: don't pass (char*)NULL as %s printf argument
glGetString(GL_SHADING_LANGUAGE_VERSION) can return NULL; I suppose this
happens on legacy OpenGL, while all the other fields are guaranteed to
exist.
2014-08-28 01:52:15 +02:00
wm4 2c99464b47 vo_opengl: fix shader
Regression since commit f14722a4. For some reason, this worked on
nvidia, but rightfully failed on mesa.

At least in C, the ## operator indeed needs two macro arguments, and
you can't just concatenate with non-arguments.

This change will most likely fix it.

CC: @bjin
2014-08-28 00:40:37 +02:00
wm4 f8a1bd1253 player: dynamically change cache wait times
Remove the hardcoded wait time of 2 seconds. Instead, adjust the wait
time each time we unpause: if downloading the data took longer than its
estimated playback time, increase the amount of data we wait for. If
it's shorter, decrease it.

The +/- is supposed to avoid oscillating between two values if the
elapsed time and the wait time are similar. It's not sure if this
actually helps with anything, but it can't harm.
2014-08-27 23:24:55 +02:00
wm4 cb642e7c84 player: slightly better cache underrun detection
Use the "native" underrun detection, instead of guessing by a low cache
duration. The new underrun detection (which was added with the original
commit) might have the problem that it's easy for the playloop to miss
the underrun event. The underrun is actually not stored as state, so if
the demuxer thread adds a new packet before the playloop happens to see
the state, it's as if it never happened. On the other hand, this means
that network was fast enough, so it should be just fine.

Also, should it happen that we don't know the cached range (the
ts_duration < 0 case), just wait until the demuxer goes idle (i.e.
read_packet() decides to stop). This pretty much should affect broken or
unusual files only, and there might be various things that could go
wrong. But it's more robust in the normal case: this situation also
happens when no packets have been read yet, and we don't want to
consider this as reason to resume playback.
2014-08-27 23:12:49 +02:00
wm4 7bb1afb8ea demux_lavf: don't reject av:// if cache is enabled
Enabling the cache doesn't make much in this situation, but there's also
no reason not to reject it.
2014-08-27 23:12:49 +02:00
wm4 1c44db2992 demux: reset idle state on seeks 2014-08-27 23:12:49 +02:00
wm4 c7208319d3 player: better cache status on status line
The cache percentage was useless. It showed how much of the total stream
cache was in use, but since the cache size is something huge and
unrelated to the bitrate or network speed, the information content of
the percentage was rather low.

Replace this with printing the duration of the demuxer-cached data, and
the size of the stream cache in KB.

I'm not completely sure about the formatting; suggestions are welcome.
Note that it's not easy to know how much playback time the stream cache
covers, so it's always in bytes.
2014-08-27 23:12:47 +02:00
wm4 dad90f616d player: fix basic playback
The "buffering" logic was active even if the stream cache was disabled.
This is contrary to what the manpage says. It also breaks playback
because of another bug: the demuxer cache is smaller than 2 seconds,
and thus the resume condition never becomes true.

Explicitly run this code only if the stream cache is enabled. Also, fix
the underlying problem of the breakage, and resume when the demuxer
thread stops reading in any case, not just on EOF.

Broken by previous commit. Unbreaks playback of local files.
2014-08-27 10:59:22 +02:00
wm4 0b428e4482 player: redo how stream caching and pausing on low cache works
Add the --cache-secs option, which literally overrides the value of
--demuxer-readahead-secs if the stream cache is active. The default
value is very high (10 seconds), which means it can act as network
cache.

Remove the old behavior of trying to pause once the byte cache runs
low. Instead, do something similar wit the demuxer cache. The nice
thing is that we can guess how many seconds of video it has cached,
and we can make better decisions. But for now, apply a relatively
naive heuristic: if the cache is below 0.5 secs, pause, and wait
until at least 2 secs are available.

Note that due to timestamp reordering, the estimated cached duration
of video might be inaccurate, depending on the file format. If the
file format has DTS, it's easy, otherwise the duration will seemingly
jump back and forth.
2014-08-27 03:39:04 +02:00
wm4 a8513f8b37 demux: reduce wakeups if no cache is active
The purpose of the unconditional pthread_cond_signal() when reading
cached DEMUXER_CTRLs and STREAM_CTRLs was apparently to update the
stream cache state. Otherwise, the cached fields would never be updated
when the stream is e.g. paused.

The same could be said about other CTRLs, but these aren't as important,
since they are normally updated while reading packet data.

In order to reduce wakeups, make this logic explicit.
2014-08-27 00:20:38 +02:00
Bin Jin 08b5dccd12 vo_opengl: add parameter to gaussian filter
Add a new parameter 'p' to gaussian filter. The new formula used
 a different base taken from fmtconv plugin, so that the
 new parameter is exactly same as the one used in Avisynth and
 Vapoursynth.

 The new default value is 2 / log(2) * 10, with the default value it
 conforms to the original kernel taken from vector-agg.
2014-08-26 22:19:32 +02:00
Bin Jin b3e788d3f4 vo_opengl: add radius options for filters
Add two new options, make it possible for user to set the radius
for some of the filters with no fixed radius.

Also add three new filters with the new radius parameter supported.
2014-08-26 22:19:30 +02:00
Bin Jin f14722a40f vo_opengl: add cparam1 and cparam2 options
Although cscale is rarely used, it's possible that params of cscale
are accidentally set to lparam1 and lparam2, which might cause
unexpected results.
2014-08-26 22:19:27 +02:00
Bin Jin a8b67c66f2 vo_opengl: add spline64 filter kernel
The coefficients are taken from fmtconv plugin for vapoursynth:
https://github.com/vapoursynth/fmtconv/blob/master/src/fmtc/ContFirSpline64.cpp

The package is licensed under WTFPL, and it's from the same author
of Dither plugin for avisynth.
2014-08-26 22:18:55 +02:00
wm4 3ec6705e34 TOOLS: youtube wrapper: allow overriding mpv binary 2014-08-26 20:47:30 +02:00
wm4 3cc3dea915 player: fix weird behavior when framestepping over format changes
When video format changes, the frame before the frame with the new
format sets video_status briefly to STATUS_DRAINING. This caused the
code to handle the EOF case to kick in, which just pauses the player
when trying to step past the last frame. As a result, trying to
framestep over format changes resulted in pausing the player.

Fix by testing against the correct status.
2014-08-26 20:45:41 +02:00
wm4 b7f72aa2f4 input: make key bindings like "Shift+X" work (for ASCII)
"Shift+X" didn't actually map any key, as opposed to "Shift+x". This is
because shift usually changes the case of a character, so a plain
printable character like "X" simply can never be combined with shift.

But this is not very intuitive. Always remove the shift code from
printable characters. Also, for ASCII, actually apply the case mapping
to uppercase characters if combined with shift. Doing this for unicode
in general would be nice, but that would require lookup tables. In
general, we don't know anyway what character a key produces when
combined with shift - it could be anything, and depends on the keyboard
layout.
2014-08-26 20:39:28 +02:00
wm4 480febf043 input: make all modifier flags unsigned 2014-08-26 20:39:23 +02:00
Otto Modinos cc971c06f4 manpage: mention that mp.commandv doesn't expand properties
The little lua snippet at #488 as well as the actual implementation
seems to indicate that not expanding properties is indeed the correct
behavior.  Document that.

Signed-off-by: wm4 <wm4@nowhere>
2014-08-25 22:18:25 +02:00
wm4 6410c4c8ef input: stdin is 0, not 1
Oops. I can never remember this right.
2014-08-25 21:39:24 +02:00
wm4 f104ef1282 player: minor changes
This shouldn't change anything functionally.

Change the A/V desync message. --framedrop is enabled by default now, so
the text must be changed a little. I've never heard of audio outputs
messing up A/V sync recently, so remove that part.

Remove the unused ao_pts field.

Reorder 2 A/V sync related expressions so that they look the same.
2014-08-25 21:39:24 +02:00
Stefano Pigozzi f4ccf22e16 coreaudio_device: fix overwriting of user input
Fixes #1030
2014-08-25 10:08:54 +02:00
wm4 740f0f61d8 input: redo how --input-file is handled
Abandon the "old" infrastructure for --input-file (mp_input_add_fd(),
select() loop, non-blocking reads). Replace it with something that
starts a reader thread, using blocking input.

This is for the sake of Windows. Windows is a truly insane operating
system, and there's not even a way to read a pipe in a non-blocking
way, or to wait for new input in an interruptible way (like with
poll()). And unfortunately, some want to use pipe to send input to
mpv. There are probably (slightly) better IPC mechanisms available
on Windows, but for the sake of platform uniformity, make this work
again for now.

On Vista+, CancelIoEx() could probably be used. But there's no way on
XP. Also, that function doesn't work on wine, making development
harder. We could forcibly terminate the thread, which might work, but
is unsafe. So what we do is starting a thread, and if we don't want
the pipe input anymore, we just abandon the thread. The thread might
remain blocked forever, but if we exit the process, the kernel will
forcibly kill it. On Unix, just use poll() to handle this.

Unfortunately the code is pretty crappy, but it's ok, because it's late
and I wanted to stop working on this an hour ago.

Tested on wine; might not work on a real Windows.
2014-08-25 01:00:21 +02:00
wm4 cae22ae3b6 msg: allow duplicating a mp_log
Trivial; this is mostly just reindenting the normal codepath.
2014-08-25 00:48:56 +02:00
wm4 95286cd8b8 command: change OSD formatting of "speed" property
The "x   " prefix annoyed some users.
2014-08-25 00:48:55 +02:00
wm4 12509fabc7 options: compatibility hack for --slave-broken
Seems some programs were still relying on it. Whatever, it's not hard to
support.

CC: @mpv-player/stable
2014-08-25 00:48:55 +02:00
wm4 20d88a6dea input: change verbosity of some message levels
For --input-test, print messages on terminal by default.

Raise message level for enabling input sections, because the OSC makes
this very extremely annoying.
2014-08-25 00:48:55 +02:00
wm4 f7eea070f0 vo_opengl: don't cut off feature list output 2014-08-25 00:48:55 +02:00
wm4 758f8f7bd4 demux: always use AVPacket
This is a simplification, because it lets us use the AVPacket
functions, instead of handling the details manually.

It also allows the libavcodec rawvideo decoder to use reference
counting, so it doesn't have to memcpy() the full image data. The change
in av_common.c enables this.

This change is somewhat risky, because we rely on the following AVPacket
implementation details and assumptions:
- av_packet_ref() doesn't access the input padding, and just copies the
  data. By the API, AVPacket is always padded, and we violate this. The
  lavc implementation would have to go out of its way to make this a
  real problem, though.
- We hope that the way we make the AVPacket refcountable in av_common.c
  is actually supported API-usage. It's hard to tell whether it is.

Of course we still use our own "old" demux_packet struct, just so that
libav* API usage is somewhat isolated.
2014-08-25 00:46:26 +02:00
James Ross-Gowan ef1c6e9295 win32: correct SGR sequence handling
This should get colour working again on the Windows console.

Fixes #1032.
2014-08-24 13:23:11 +02:00
James Ross-Gowan 67c6335efc win32: correct HANDLE type
The correct type is HANDLE, not HANDLE*, though this change shouldn't
affect functionality.
2014-08-24 13:23:09 +02:00
wm4 c31a91230d demux: avoid unnecessary wakeups
If a packet is appended to a stream, and there were already packets
queued, nothing about the state changed, as far as the user (i.e. the
player) is concerned. Thus no wakeup is needed.

The pthread_cond_signal() call following this is not interesting - it
will simply be a NOP if there are actually no waiters.
2014-08-24 13:21:32 +02:00
wm4 2c114db2f1 sd_lavc: remove ineffective code
It makes no sense to set the packet duration, because libavcodec doesn't
know the timebase. And in fact, no subtitle decoder accesses the packet
duration, except text subtitle converters, which are not relevant here.
So this code did nothing - drop it.

Also fix a blatantly incorrect comment.
2014-08-24 12:26:34 +02:00
wm4 1cedb323ad video: avoid unnecessary frame dropping
If duration<0, it means the duration is unknown. Disable framedropping,
because end_time makes no sense in this case.

Also, strictly never drop the first frame.

This fixes weird behavior with the cover-art case (for the 100th time).
2014-08-23 12:48:45 +02:00
wm4 39b42814e0 player: restore silent seeking
Commit 846257da introduced an accidental feature: if you kept seeking
(so playback never really resumes), the audio would never be played.
This was nice, but commit 4c25b000 accidentally removed it again (due
to the video_next_pts being earlier available than it used to be, so
audio could be played before the player executed the next queued seek).

Implicitly reintroduce the old behavior again by not decoding a second
video frame immediately. Usually, the second frame is used to compute
the frame duration needed to for accurate framedropping, but since the
first frame after a seek is never dropped, we don't need this.

Now the video code will queue the new frame to the VO immediately, and
since fill_audio_out_buffers() is called in the playloop before
write_video() and execute_queued_seek(), it never gets the chance to
enter STATUS_READY, and seeks will be silent.

This also has a nice side-effect: since the second frame is not decoded
and filtered, seeking becomes slightly faster (back to the same level
as with framedrop disabled).

It seems this still sometimes plays a period of audio when keeping a
seek key down. In my tests, this appeared to happen because the seek
finished before the next key repeat was sent.
2014-08-23 12:02:40 +02:00
wm4 21f52aeeba audio: minor improvements to timeline switching
In theory, timestamps can be negative, so we shouldn't just return -1
as special value.

Remove the separate code for clearing decode buffers; use the same code
that is used for normal seek reset.
2014-08-23 11:39:07 +02:00
wm4 b55e093075 demux_lavf: fix crash with unknown streams
Could happen with DVD .vob files.
2014-08-23 04:49:54 +02:00
ChrisK2 4386b80f2e osc: Use osd-font for playlist buttons
Now that we use the symbols from the font, we should also
actually use the font.
2014-08-22 23:50:50 +02:00
wm4 005f592d54 player: some more debugging output 2014-08-22 16:25:55 +02:00
wm4 d5fa5a96a8 video: some debugging output 2014-08-22 16:21:58 +02:00
wm4 d0b64a6fc4 input.conf: bind ctrl+c
Just like I can terminate it on the terminal with this key combination,
I want to be able to do the same on the X window.
2014-08-22 16:18:09 +02:00
wm4 26500425f6 ao_dsound: raise default buffer size to 200ms, make it configurable 2014-08-22 16:12:47 +02:00
wm4 4c25b000b5 player: fix recent speed change regression
Commit 5afc025c broke this. The reason is that mpctx->delay is updated
when a new video frame is added. This value is also needed to resync
audio, but it will be for the wrong PTS. They must be consistent with
each other, and if they aren't, initial sync will be off by N video
frames, which results at least in worse user experience.

This can be reproduced by for example heavily switching between normal
and 2x speed, or similar.

Fix by readding the video_next_pts field (keeping its use minimal,
instead of reverting the commit that removed it).
2014-08-22 15:36:48 +02:00
wm4 75005ec06d player: don't clobber playback position on video end
If video reaches EOF, and audio is also EOF (or is otherwise not
meaningful, like audio disabled), then the playback position was briefly
set to 0. Fix this by not trying to use a bogus audio PTS.

CC: @mpv-player/stable (maybe)
2014-08-22 14:22:06 +02:00
wm4 e9e73f8d03 video: refactor queue handling
This simplifies the code, and fixes an odd bug: the second-last frame
was displayed for a very short duration if framedrop was enabled. The
reason was that basically the time difference between second-last and
last frame were skipped, because at this point EOF was already
signaled. Also see commit b0959488 for a similar issue in the
same code.

This removes the messiness of the next_frame 2-frame queue, and
strictly runs the "new frame" code when a frame is moved to the first
position of the queue, instead of somehow messing with return codes.

This also merges update_video() into video_output_image().
2014-08-22 14:22:06 +02:00
wm4 5afc025cc9 video: get rid of video_next_pts field
Not really needed anymore. Code should be mostly equivalent.

Also get rid of some other now-unused or outdated things.
2014-08-22 14:22:06 +02:00
wm4 7b3a889c92 video: move some code around
No functional changes. init_vo() is now needed a bit further down, and
moving it keeps definition and use close. adjust_sync() will be used by
a function further up in one of the following commits.
2014-08-22 14:22:06 +02:00
wm4 bc90f71d35 video: minor simplification
This is mostly equivalent, but simpler, and reduces some duplication.
2014-08-22 14:22:06 +02:00
Bin Jin aeb3f08280 manpage: remove duplicated content
Probably be accidentally added in b6b8bffd.

CC: @mpv-player/stable
Signed-off-by: wm4 <wm4@nowhere>
2014-08-22 14:22:06 +02:00
Bin Jin 1e12afa80a vf_vapoursynth: add more VS frame properties
Add the missing frame properties in 48587e88.
2014-08-22 14:22:06 +02:00
Bin Jin 96c2021cb1 vf_vapoursynth: add display resolution support
Add two new script environment variables 'video_in_dw' and
'video_in_dh', representing the display resolution of video. Along
with video resolution, sample ratio aspect can be calculated in
scripts.

Currently it's impossible to change sample ratio aspect with single
vapoursynth filter since '_SARNum' and '_SARDen' frame properties
from output clip will be ignored. A following 'dsize' filter is
necessary for this purpose.
2014-08-22 14:22:04 +02:00
wm4 e2d27cded7 osc: revert disabling use_suspend
It was an unintended/accidental change.
2014-08-21 22:46:33 +02:00
wm4 c41fdfb4ef build: disable terminfo and termcap code by default
If nobody complains soon enough, I will remove the code completely.
2014-08-21 22:45:58 +02:00
wm4 4b5c3ea7a7 terminal-unix: new input handling code
This is independent of terminfo/termcap, and supports more keys.
Originally, the goal was just extending the set of supported key
sequences, but since the terminfo stuff actually makes this much harder,
and since it's a big blob of bloated legacy crap, just drop it. Instead,
use hardcoded tables.

It's pretty easy to get on the same level as the old code (with fewer
LOC), and we avoid additional error situations, such as mallocs which
could fail (the old code just ignores malloc failures). We also try to
support some xterm escape sequences, which are in relatively widespread
use. (I'm not sure about the urxvt ones.)

Trying to deal with xterm shift/ctrl/alt modifiers is probably a bit
overcomplicated, and only deals with prefixes - xterm randomly uses
prefix sequences for some keys, and suffixes for others (what the heck).

Additionally, try to drop unknown escape codes. This basically relies
on a trick: in almost 100% of all situations, a read() call will
actually return complete sequences (possibly because of pipe semantics
and atomic writes from the terminal emulator?), so it's easy to drop
unknown sequences. This prevents that they trigger random key bindings
as the code interprets the part after ESC as normal keys.

This also drops the use of terminfo for sending smkx/rmkx. It seems
even vt100 (to which virtually everything non-legacy is reasonably
compatible with) supports the codes we hardcode, so it should be fine.

This commit actually changes only the code if terminfo/termcap are not
found. The next commit will make this code default.
2014-08-21 22:45:58 +02:00
wm4 58a9610acf terminal-win: read input from a thread
Surprisingly, WaitFor* works on console handles. We can simply run the
code for reading the console in a thread, and don't have to worry about
crazy win32 crap in the rest of the player's input code anymore.

This also fixes the issue that you couldn't unpause the player from the
terminal, because the player would stop polling for input.
2014-08-21 22:45:58 +02:00
wm4 5890e59dbc terminal: some cleanups
In particular, remove all the stupid debug printfs from the win code.
2014-08-21 22:45:58 +02:00
wm4 070c54dff4 terminal-win: remove nonsensical code
Something about a non-working MinGW thing? Really, I don't care. It
also prevents using the console API properly.
2014-08-21 22:45:58 +02:00
wm4 47b29094c3 win32: emulate some ANSI terminal escape codes
We already redirect all terminal output through our own wrappers (for
the sake of UTF-8), so we might as well use it to handle ANSI escape
codes.

This also changes behavior on UNIX: we don't retrieve some escape codes
per terminfo anymore, and just hardcode them. Every terminal should
understand them.

The advantage is that we can pretend to have a real terminal in the
normal player code, and Windows atrocities are locked away in glue
code.
2014-08-21 22:45:58 +02:00
wm4 218ace2b02 audio: limit on low (and not high) buffer size
The original intention was probably to avoid unnecessarily high numbers
of wakeups. Change it to wait at most 25% of buffer time instead of 75%
until refilling. Might help with the dsound problems in issue #1024, but
I don't know if success is guaranteed.
2014-08-21 22:45:58 +02:00
wm4 f1e78306cb vaapi: try dealing with Intel's braindamaged shit drivers
So talking to a certain Intel dev, it sounded like modern VA-API drivers
are reasonable thread-safe. But apparently that is not the case. Not at
all. So add approximate locking around all vaapi API calls.

The problem appeared once we moved decoding and display to different
threads. That means the "vaapi-copy" mode was unaffected, but decoding
with vo_vaapi or vo_opengl lead to random crashes.

Untested on real Intel hardware. With the vdpau emulation, it seems to
work fine - but actually it worked fine even before this commit, because
vdpau was written and designed not by morons, but competent people
(vdpau is guaranteed to be fully thread-safe).

There is some probability that this commit doesn't fix things entirely.
One problem is that locking might not be complete. For one, libavcodec
_also_ accesses vaapi, so we have to rely on our own guesses how and
when lavc uses vaapi (since we disable multithreading when doing hw
decoding, our guess should be relatively good, but it's still a lavc
implementation detail). One other reason that this commit might not
help is Intel's amazing potential to fuckup anything that is good and
holy.
2014-08-21 22:45:58 +02:00
ChrisK2 03f97e4cae osd+osc: Add left-arrow to osd-font
For use as playlist navigation button in OSC, now the osd-font
carries all symbols needed by the OSC.
2014-08-21 18:45:41 +02:00
wm4 c3cc9e8b88 etc/mpv.desktop: add audio/flac mimetype
Fixes #1025.

CC: @mpv-player/stable
2014-08-21 01:06:18 +02:00
wm4 7758c15e95 video: don't assume query_format is thread-safe
Although it's probably safe for most VOs, there's no guarantee.
2014-08-20 21:35:45 +02:00
wm4 09897bed7f terminal-unix: eliminate unnecessary variable 2014-08-20 21:19:20 +02:00
Alexander Preisinger 614ff883bc wayland: replace deprecated xkbcommon functions
Available and stable since forever (xkbcommon 0.2).
2014-08-20 17:16:18 +02:00
Alexander Preisinger 631be0774d options.rst: fix warning 2014-08-20 16:44:19 +02:00
Alexander Preisinger 759fdcb2f9 vo_wayland: fix formatting inconsistencies 2014-08-20 16:40:33 +02:00
Alexander Preisinger 3bf83f7642 vo_wayand: save the flip time in the frame handler
This value is more accurate than the default value.
2014-08-20 16:35:06 +02:00
Andrey Morozov 1cb15316b0 command: add estimated-frame-count & estimated-frame-number properties
Signed-off-by: wm4 <wm4@nowhere>
2014-08-19 21:47:14 +02:00
wm4 960f0ccfa1 example.conf: demuxer-thread is now enabled by default
Provide a more useful example instead.
2014-08-19 20:10:26 +02:00
wm4 3c07e86fd3 TOOLS/stats-conv.py: improvements
This is still pretty useful for debugging timing-dependent things.
2014-08-19 20:09:46 +02:00
wm4 3d968fc620 video: add VOCTRL_GET_RECENT_FLIP_TIME
This could be used by VO implementations to report a recent vsync time
to the generic VO code, which in turn will use it and the display FPS
to estimate at which point in time the next vsync will happen.
2014-08-18 23:04:31 +02:00
wm4 cd2e4db8a5 vo_opengl: add check-pattern suboption for testing
This uses glXGetVideoSyncSGI() to check how many vsyncs happened since
the last flip_page() call. It allows checking a pattern of vsync
increments of at most 2 elements. For example, to check ~24 fps playback
on a ~60 Hz monitor, this can be used:

--vo=opengl:check-pattern=[3-2]:waitvsync

Whether the reported results are accurate or just plain wrong may depend
on the driver and if the waitvsync sub-option is used. There are no
guarantees.

This option is undocumented, and may be removed again in the near or
distant future.
2014-08-18 23:04:31 +02:00
wm4 aaadcef52f video: dump vsync phase into stats file
For debugging (drawing fun plots with TOOLS/stats-conv.py).

Also move last_flip under the correct comment: it's not protected by the
lock, and can be accessed by the VO thread only.
2014-08-18 23:04:28 +02:00
wm4 7520d39e8b vaapi: we need more surfaces
Playing with high framedrop could make it run out of surfaces. In
theory, we wouldn't need an additional surface, if we could just clear
the vo_vaapi internal surface - but doing so would probably be a pain,
so I don't care.
2014-08-18 22:59:01 +02:00
Alexander Preisinger 752dce9284 wayland: dynamically report display fps
Only reports the most recently entered output if the window is displayed on
2 or more outputs. Should be changed to the lowest fps of all outputs the
window is visible. Until no one complains this will have to wait.

Look for the VO framedropping for more information on this topic.
2014-08-18 22:00:39 +02:00
wm4 39b8b0a41f manpage: fix opengl-hq defaults
The FBO format was changed some time ago.

CC: @mpv-player/stable
2014-08-18 02:05:06 +02:00
wm4 52ead45f05 command: drop " %" from "cache" property OSD-formatting 2014-08-18 01:42:43 +02:00
wm4 9f31b73cda player: never print status messages before playback begins
After a new file is loaded, playback never starts instantly. Rather, it
takes some playloop iterations until initial audio and video have been
decoded, and the outputs have been (lazily) initialized. This means you
will get status line updates between the messages that inform of the
initialized outputs. This is a bit annoying and clutters the terminal
output needlessly.

Fix this by never printing the status line before playback isn't fully
initialized. Do this by reusing the --term-playing-msg code (which
prints a message once playback is initialized). This also makes sure the
status line _is_ shown during playback restart when doing seeks.

It's possible that the change will make the output more confusing if for
some reason is stuck forever initializing playback, but that seems like
an obscure corner case that never happens, so forget about it.
2014-08-18 01:25:59 +02:00
wm4 eb2924054f player: remove unneeded call
print_status() is called at a later point anyway (and before sleeping),
so this code has little effect. This code was added in commit a4f7a3df5,
and I can't observe any problems with idle mode anymore.

Now print_status() is called from a single place only, within osd.c.
2014-08-18 01:21:21 +02:00
wm4 0cee4498f1 DOCS/tech-overview.txt: some updates 2014-08-18 01:21:13 +02:00
wm4 1e04c474ab x11: listen to xrandr events
If the Xrandr configuration changes, re-read it. So if you change
display modes or screen configuration, it will update the framedrop
refresh rate accordingly.

This passes the rootwin to XRRSelectInput(), which may or may not be
allowed. But it works, and the documentation (which is worse than used
toilet paper, great job Xorg) doesn't forbid it, or in fact say anything
about what the window parameter is even used for.
2014-08-17 15:39:18 +02:00
Philip Sequeira b36ed6d9f9 TOOLS/zsh.pl: protect global environment 2014-08-17 12:51:10 +02:00
Philip Sequeira c7e67d008a TOOLS/zsh.pl: fix a ret that hadn't been changed to rc 2014-08-17 12:51:10 +02:00
Philip Sequeira 4b8f512217 TOOLS/zsh.pl: complete profiles
Implemented in shell, because it has to be done at runtime.
2014-08-17 12:51:10 +02:00
wm4 3778e63330 x11: fix xrandr conditional compilation
Oops.

Fixes #1020.
2014-08-17 04:35:24 +02:00
wm4 61b0163d58 af_lavrresample: minor cosmetics 2014-08-17 03:29:09 +02:00
wm4 513779d3b8 video: make vo_opengl the default over vo_vdpau
Nvidia's vdpau implementation is pretty good, but other factors make it
much less attractive for use as default VO. For example, Mesa often has
low quality drivers (mess up things with the presentation queue and the
vdpau API time source). Intel ruins things completely, and we're likely
to run on emulation via OpenGL. Compositing has unknown effects (to me
anyway), but appears to reduce the vdpau advantages.

One important reason to prefer vo_vdpau was that it could do proper
framedropping. Framedropping got fixed for the other VOs, so this reason
is going away.
2014-08-17 02:54:50 +02:00
wm4 761037dcc6 video: enable framedropping by default 2014-08-17 02:51:13 +02:00
wm4 5b64f5ad35 video: take refresh rate changes into account
This works only on X11, and only if the refresh rate changes due to the
window being moved to another screen (detected by us). It doesn't
include system screen reconfiguration yet.

This calls VOCTRL_GET_DISPLAY_FPS on every frame, which makes me uneasy.
It means extra thread communication with the win32 and Cocoa backends.
On the other hand, a frame doesn't happen _that_ often, and the
communication should still be pretty cheap and fast, so it's probably
ok.

Also needs some extra fuzz for vo_vdpau.c, because that does everything
differently.
2014-08-17 02:50:59 +02:00
wm4 4822056db7 x11: fix memory leaks
Oh, we have to free this stuff. OK.
2014-08-17 02:47:44 +02:00
wm4 d811f6a9ed build: use pkg-config for xscreensaver 2014-08-16 22:00:00 +02:00
wm4 f8f3a1b4a1 build: drop check for XF86keysym.h
This is always included in the Xorg development headers. Strictly
speaking it's not necessarily available with other X implementations,
but these are hopefully all dead.
2014-08-16 21:57:51 +02:00
wm4 fe782a6e95 x11: use xrandr to retrieve display refresh rate
Drop use of the ancient XF86VM, and use the slightly less ancient Xrandr
extension to retrieve the refresh rate. Xrandr has the advantage that it
supports multiple monitors (at least the modern version of it).

For now, we don't attempt any dynamic reconfiguration. We don't request
and listen to Xrandr events, and we don't notify the VO code of changes
in the refresh rate. (The later works by assuming that X coordinates map
directly to Xrandr coordinates, which probably is wrong with compositing
window manager, at least if these use complicated transformations. But I
know of no API to handle this.)

It would be nice to drop use of the Xinerama extension too, but
unfortunately, at least one EWMH feature uses Xinerama screen numbers,
and I don't know how that maps to Xrandr outputs.
2014-08-16 21:56:22 +02:00
wm4 925c431ff7 demux: enable thread by default
And change the defaults for the other queue options to reduce latency.
2014-08-16 17:15:51 +02:00
wm4 b822faa6cf demux: add option to control the readahead buffer by a duration value
--demuxer-readahead-secs now controls how much the demuxer should
readahead by an amount of seconds. This is based on the raw packet
timestamps. It's not always very exact. For example, h264 in Matroska
does not store any linear timestamps (only PTS values which are going
to be reordered by the decoder), so this heuristic is usually off by
several hundred milliseconds.

The decision whether to readahead is basically OR-ed with the other
--demuxer-readahead-packets options. Change the manpage descriptions
to subtly convey these semantics.
2014-08-16 17:10:08 +02:00
wm4 e6e3bc7cd9 demux: remove unused function 2014-08-16 17:10:08 +02:00
wm4 14c1d864d9 player: cosmetics: make code more compact 2014-08-16 17:10:08 +02:00
wm4 a4cfab7ee0 vo_wayland: fix redrawing logic
I must have broken it some time ago. The error case dealing with an
unavailable backbuffer was broken, and didn't handle memory management
correctly.
2014-08-16 17:09:59 +02:00
wm4 4f984b987c video: add --display-fps switch to control framedrop FPS
Since the display FPS is currently detected on X11 only (and even there
it's known to be wrong on certain setups), it seems like a good idea to
make this user-configurable.
2014-08-16 00:05:02 +02:00
wm4 07aba86b37 audio: add a mode to insert silence on severe A/V desync
This is probably a stupid idea, but it can't be denied that this
actually allows playing video without larger desync, even if video is
too slow.
2014-08-15 23:52:42 +02:00
wm4 72ee9bb56c vo_opengl: optional support for using GLX_SGI_video_sync
I'm not sure about the merit, though it does print nice numbers if debug
output is enabled.

Basically, this tries to achieve similar results as the glFinish()
business, but again it entirely depends on the drivers whether this
does anything meaningful, or whether it's actively harmful.
2014-08-15 23:36:13 +02:00
wm4 db65151890 gl_common: add SGI_video_sync extension 2014-08-15 23:36:10 +02:00
wm4 4a297554bc vo_opengl: if glfinish is used, also call it after swappping
It seems that at least on nvidia systems with composting disabled, we
can get it to block deterministically on the actual vsync event, which
should improve framedropping.
2014-08-15 23:36:02 +02:00
wm4 543ba6c114 video: add VO framedropping mode
This mostly uses the same idea as with vo_vdpau.c, but much simplified.

On X11, it tries to get the display framerate with XF86VM, and limits
the frequency of new video frames against it. Note that this is an old
extension, and is confirmed not to work correctly with multi-monitor
setups. But we're using it because it was already around (it is also
used by vo_vdpau).

This attempts to predict the next vsync event by using the time of the
last frame and the display FPS. Even if that goes completely wrong,
the results are still relatively good.

On other systems, or if the X11 code doesn't return a display FPS, a
framerate of 1000 is assumed. This is infinite for all practical
purposes, and means that only frames which are definitely too late are
dropped. This probably has worse results, but is still useful.

"--framedrop=yes" is basically replaced with "--framedrop=decoder". The
old framedropping mode is kept around, and should perhaps be improved.
Dropping on the decoder level is still useful if decoding itself is too
slow.
2014-08-15 23:33:33 +02:00
wm4 22a9529012 vo: eliminate a redundant variable
Originally, I probably had plans to allow NULL images to handle things
like the last frame case, but that idea was dropped later.
2014-08-15 23:32:45 +02:00
wm4 fa7c421588 player: use virtual time for --audio-file with ordered chapters
Apparently users prefer this behavior.

It was used for subtitles too, so move the code to calculate the video
offset into a separate function. Seeking also needs to be fixed.

Fixes #1018.
2014-08-15 23:32:37 +02:00
wm4 318e8da250 lua: wake up the core when setting OSD
The OSD is marked as changed, but the core isn't notified and this
doesn't immediately wakeup. (Possibly the OSD code should wakeup the
core instead, but maybe that woudl be overkill.)

Observed when using "mp.use_suspend = false" in the OSC, and pausing,
and moving the mouse pointer out of the window. The last part of the
fade remained visible for longer than intended.
2014-08-15 23:32:31 +02:00
ChrisK2 364e06261a osc: Overhaul (wip)
Code reorganized to make layouts exchangeable
alternative test layout can be tested with
layout=slimbox
in the OSC config

timers are now used to properly animate the fade out when the
player is paused

duplicate seeks are discarded again
2014-08-15 15:24:22 +02:00
wm4 d5940fabcd sub: add option to workaround broken mkv files
See additions to options.rst.
2014-08-14 23:59:35 +02:00
wm4 498644afaf sub: call sub_reset() on seeks only
sub_reset() was called on cycling subtitle tracks and on seeking. Since
we don't want that subtitles disppear on cycling, sd_lavc.c didn't clear
its internal subtitle queue on reset, which meant that seeking with PGS
subtitles could leave the subtitle on screen (PGS subtitles usually
don't have a duration set).

Call it only on seeking, so we can also strictly clear the subtitle
queue in sd_lavc.

(This still can go very wrong if you disable a subtitle, seek, and
enable it again - for example, if used with libavformat that uses "SSA"
style demuxed ASS subtitle packets. That shouldn't happen with newer
libavformat versions, and the user can "correct" it anyway by executing
a seek while the subtitle is selected.)
2014-08-14 23:53:53 +02:00
wm4 a7107686d7 client API: directly lock playloop
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.
2014-08-14 19:40:43 +02:00
wm4 8f77d9df4a lua: allow disabling suspend
I'd like to enable this by default, but unfortunately the OSC seems to
have some problems with it.
2014-08-14 19:30:35 +02:00
wm4 a31330608b client API: adjust documentation for mpv_suspend()
It's not true anymore that the core will stop replying for 50ms
(waiting for video) without calling this function. Simplify the
documentation accordingly. Accessing properties that go through
the VO still have this problem, though.
2014-08-14 19:29:21 +02:00
wm4 51a7070e26 vo: remove unused libavutil include 2014-08-14 19:29:02 +02:00
wm4 de399278fc vo: fix mingw compilation 2014-08-14 01:30:20 +02:00
wm4 061a5af544 demux_lavf: support new metadata update API
This Libav-invented API is of course completely different from the
FFmpeg-one. (The fun part is that I approved of both.)
2014-08-14 01:18:18 +02:00
Alessandro Ghedini e7cab32fae TOOLS/zsh.pl: properly set the return value
The previous commit made the completion script always return non-zero, even when
a match is found. This explicitly sets the return value to zero whenever a match
is found but defaults to non-zero in case nothing is matched.
2014-08-13 23:42:38 +02:00
c_14 fd98863b1f TOOLS/zsh.pl: properly return non-zero when no matches are found
Returning a non-zero value signals to the zsh completion system that no matches
were added by the script so that it can try the user-defined matchers (e.g.
those defined with matcher-list).

Fixes #1008.
2014-08-13 22:57:59 +02:00
Alexander Preisinger 69a160f187 wayland: pointer interface is created after theme
Just always load the theme. It gets freed properly and dosn't bother anyone.

Fixes #1012.

CC: @mpv-player/stable
2014-08-13 22:34:18 +02:00
wm4 3eaa407c6f video: reduce non-sense messages when playing coverart
Don't print PTS warnings by skipping the normal video path.
2014-08-13 22:01:10 +02:00
wm4 b0959488d1 video: don't run new frame processing on every iteration
This ran adjust_sync() on every playloop iteration, instead of every
newly decoded frame. It seems this was idempotent in the common case,
but the code was originally designed to be run once only, so restore
that.
2014-08-13 22:01:10 +02:00
wm4 4a325a8592 video: move some more code around
No functional changes.
2014-08-13 22:01:09 +02:00
wm4 48bd1294eb video: move some code around 2014-08-13 21:53:47 +02:00
wm4 311ce60b16 video: exit early when nothing to do
These cases were probably confusing. Exit early, which makes it much
clearer what's going on. Should not change anything functionally.
2014-08-13 21:51:26 +02:00
wm4 d4e0fc76bb video: minor simplification of the old framedrop code
No changes in functionality, other than being slightly more correct at
stream EOF.
2014-08-13 21:50:23 +02:00
wm4 010b86fd34 player: don't quit with --loop-file
Fixes #1009.

CC: @mpv-player/stable
2014-08-13 21:50:01 +02:00
Alessandro Ghedini 2607d6e419 vdpau: correctly mark invalid mixer as such on vdp_video_mixer_create() failure
Otherwise vdp_video_mixer_destroy() would later fail when called on an invalid
video mixer handle. With mesa r600 vdpau driver, this would cause a segfault.
2014-08-13 17:57:19 +02:00
Jan Palus 69d5356d76 build: fix libmpv build when using system waf
Since the 'syms' tool is shipped in waf's extras, when using system waf the
default tool overrides our own. Force our syms tool by providing the tooldir.

Fixes #1006
2014-08-13 17:09:45 +02:00
wm4 9ed9c68fda vo_vdpau: fix screenshots with anamorphic video
Fixes #1007.

CC: @mpv-player/stable
2014-08-13 00:52:05 +02:00
wm4 f6f93b6336 x11: vdpau GLX interop needs X11 threads
Xlib is not thread-safe. Or actually it is, but it's an incomprehensible
hack that was added later, and which needs to be acitvated manually
(this makes no sense). And it appears that the vdpau accesses X from the
decoder thread if GLX interop is used (and not in any other situations -
this doesn't make too much sense either).

So, just call the magic function that enables Xlib thread-safety.
2014-08-13 00:26:13 +02:00
wm4 defa0a20e0 af_lavcac3enc: lower minimum channel number to 3
It seems only stereo PCM should be passed through.
2014-08-12 23:45:41 +02:00
FRAU KOUJIRO 060ba226e6 docs: cocoa example uses wakeup callback API
Also, imitate the qt example somewhat.
2014-08-12 23:40:58 +02:00
FRAU KOUJIRO dcf4ee905b docs: simple cocoa API usage example 2014-08-12 23:40:55 +02:00
wm4 be792c085a af_lavcac3enc: change default bitrate to 640
No reason to use less.

Since the name "default" is misleading now, replace it with "auto"
(still recognize the old name).
2014-08-12 23:34:28 +02:00
wm4 5ed7bc6321 video: fix and simplify video format changes and last frame display
The previous commit broke these things, and fixing them is separate in
this commit in order to reduce the volume of changes.

Move the image queue from the VO to the playback core. The image queue
is a remnant of the old way how vdpau was implemented, and increasingly
became more and more an artifact. In the end, it did only one thing:
computing the duration of the current frame. This was done by taking the
PTS difference between the current and the future frame. We keep this,
but by moving it out of the VO, we don't have to special-case format
changes anymore. This simplifies the code a lot.

Since we need the queue to compute the duration only, a queue size
larger than 2 makes no sense, and we can hardcode that.

Also change how the last frame is handled. The last frame is a bit of a
problem, because video timing works by showing one frame after another,
which makes it a special case. Make the VO provide a function to notify
us when the frame is done, instead. The frame duration is used for that.

This is not perfect. For example, changing playback speed during the
last frame doesn't update the end time. Pausing will not stop the clock
that times the last frame. But I don't think this matters for such a
corner case.
2014-08-12 23:24:08 +02:00
wm4 df58e82237 video: move display and timing to a separate thread
The VO is run inside its own thread. It also does most of video timing.
The playloop hands the image data and a realtime timestamp to the VO,
and the VO does the rest.

In particular, this allows the playloop to do other things, instead of
blocking for video redraw. But if anything accesses the VO during video
timing, it will block.

This also fixes vo_sdl.c event handling; but that is only a side-effect,
since reimplementing the broken way would require more effort.

Also drop --softsleep. In theory, this option helps if the kernel's
sleeping mechanism is too inaccurate for video timing. In practice, I
haven't ever encountered a situation where it helps, and it just burns
CPU cycles. On the other hand it's probably actively harmful, because
it prevents the libavcodec decoder threads from doing real work.

Side note:

Originally, I intended that multiple frames can be queued to the VO. But
this is not done, due to problems with OSD and other certain features.
OSD in particular is simply designed in a way that it can be neither
timed nor copied, so you do have to render it into the video frame
before you can draw the next frame. (Subtitles have no such restriction.
sd_lavc was even updated to fix this.) It seems the right solution to
queuing multiple VO frames is rendering on VO-backed framebuffers, like
vo_vdpau.c does. This requires VO driver support, and is out of scope
of this commit.

As consequence, the VO has a queue size of 1. The existing video queue
is just needed to compute frame duration, and will be moved out in the
next commit.
2014-08-12 23:24:08 +02:00
wm4 a1be3cf147 DOCS: mark the recent release in client-api-changes.rst
Also add instructions to release-policy.md, since this can be easily
forgotten.

CC: @mpv-player/stable
2014-08-12 23:01:19 +02:00
wm4 52f2f67553 input.conf: add some bindings for changing audio-delay
Requested on: https://github.com/mpv-player/mpv/commit/90ec3334174e80c16f00971886223a3afabc1aca#commitcomment-7331673

Might remove or remap them again later.
2014-08-11 23:40:35 +02:00
wm4 3f353f1219 input.conf: make explanatory text more readable
Or at leats this is the intention. It's a bit hard to tell which
information is needed, and which not.
2014-08-11 23:32:37 +02:00
wm4 b8f025a58a video: don't keep multiple pointers to hwdec info struct
This makes a certain corner case simpler at a later point.
2014-08-11 23:09:39 +02:00
wm4 056622c33e vaapi: fix uninitialized value read
Found with valgrind. This is somewhat terrifying, because the VA-API API
function is supposed to fill these values, and we access them only if
the API functions return success. So this shouldn't have happened.
2014-08-11 21:57:41 +02:00
wm4 beceb2fedc vf_vapoursynth: print more diagnostics on error 2014-08-11 21:57:15 +02:00
wm4 bead9766bc manpage: update keybindings 2014-08-11 21:56:37 +02:00
wm4 f9d2ad6c17 Move status-line.lua
Looks like TOOLS/lua/ is now established as dumping ground for random
Lua scripts, so DOCS/lua_examples/ is not needed anymore.
2014-08-11 17:08:32 +02:00
wm4 0ed48f5ec9 player: remove cache status from video OSD 2014-08-11 17:01:20 +02:00
wm4 9dd160ea97 demux: reduce log spam if threading is disabled 2014-08-11 15:55:12 +02:00
wm4 37357e2265 video: fix dangling pointer issue
The function video_decode_and_filter(), called between initializing the
local vf variable and using it, can actually destroy and recreate the
filter. Thus, the vf variable turns into a dangling pointer if that
happens.

Could be observed with: --hwdec=vda --deinterlace=yes --vf=yadif

(Also happens with vdpau/vaapi.)
2014-08-11 15:37:13 +02:00
wm4 33a8e2a9ad vdpau: allocate surfaces by age
Whether this helps is probably questionable and depends on the GPU. But
the vaapi code does it too.
2014-08-11 14:03:53 +02:00
wm4 ef9b399020 input: fix event wakeup
When a new event was added, merely a flag was set, instead of actually
waking up the core (if needed). This was ok in ancient times when all
event sources were part of the select() loop. But now there are several
cases where other threads can add input, and then you actually need to
wakeup the core in order to make it read the events at all.
2014-08-11 13:50:56 +02:00
wm4 bce48f30d2 input.conf: change LEFT/RIGHT keys to seek 5s instead of 10s 2014-08-11 13:37:18 +02:00
wm4 a87005b7fa command: for OSD, format cache property as integer
For convenience. Use ${=cache} to get the old formatting.
2014-08-11 13:30:08 +02:00
wm4 b016f92309 command: fix dangling pointer issue in script key bindings code
This code was sending a string to a different thread, and then
deallocated the string shortly after, which means most of the time
the other thread was accessing a dangling pointer.

It's possible that this is the cause for #1002.
2014-08-11 13:00:57 +02:00
wm4 ece61bfa10 player: don't delay OSD redraw when paused
We want this heuristic to trigger during normal playback only.
2014-08-10 13:24:29 +02:00
wm4 f5257e2c7d vo_sdl: fix redrawing issue
vo_sdl.c has broken event handling and just polls. The polling time was
quite low, so the playloop OSD redrawing heuristic inhibited redraws,
which made the window appear frozen when paused.
2014-08-10 13:24:29 +02:00
wm4 2a403092cd input.conf: map shift+pgup/dwn to the old seek bindings 2014-08-09 02:24:10 +02:00
wm4 8dfe0c73c9 video: remove "hard" framedrop mode
Completely useless, and could accidentally be enabled by cycling
framedrop modes. Just get rid of it.

But still allow triggering the old code with --vd-lavc-framedrop, in
case someone asks for it. If nobody does, this new option will be
removed eventually.
2014-08-09 00:35:35 +02:00
wm4 91be5e5c31 etc/example.conf: update cache options
Some of them changed semantics or got renamed.

Note that the replacements in the example.conf are not necessarily the
equivalents of the replaced options.
2014-08-09 00:13:16 +02:00
wm4 26d69758f6 command: run OSD display code even if a property is unavailable
Trying to jump chapters in a gile that has no chapters does nothing,
not even show a warning. This is confusing. The reason is that the
"add chapter" command will just bail out completely if the property
is unavailable.

This was because it exited when it couldn't get the property type.
Instead of exiting, just don't enter the code that needs the type.

(I'm not sure when this behavior changed. I consider it a regression.
It was probably caused by changes to the chapter code, which perhaps
started returning UNAVAILABLE instead of OK if there are no chapters.)
2014-08-09 00:08:04 +02:00
wm4 e0fb2a4f2d etc: add mplayer-input.conf 2014-08-09 00:08:04 +02:00
wm4 8b48b3fd3b input.conf: switch chapter seek next/previous keys
"UP" seeks forward, so "PGUP" should skip to the next chapter.

Fixes #998.
2014-08-08 23:26:03 +02:00
wm4 c4feba847c manpage: update key bindings 2014-08-08 12:06:01 +02:00
Alexander Preisinger b6b8bffd2d manpage: add sections and order by usage
Split the options into the following sections:

 * Playback Control
 * Program Behaviour
 * Video
 * Audio
 * Subtitles
 * Window
 * Disc Devices
 * Equalizer
 * Demuxer
 * Input
 * OSD
 * Screenshot
 * Software Scaler
 * Terminal
 * TV
 * Cache
 * Network
 * DVB
 * PVR
 * Miscellaneous

Most options are sorted by usefullness and how often they're used or how
important they are.
This makes finding the right options easier and adds some sort of structure.
2014-08-08 08:30:06 +02:00
wm4 b4f72b46e5 ao_dsound: reduce default buffer size
Reduce from 1000ms to 100ms. Since there is an audio thread updating AOs
quickly enough now, requesting such a large buffer size makes no sense
anymore.
2014-08-08 01:56:23 +02:00
wm4 90ec333417 input.conf: unmap some more obscure bindings
Changing audio-delay is probably not needed.

Changing balance "works", but not as expected (sets up a pan matrix to
change left/right contributions to each other, rather than changing the
relative volumes of each channel).

I expect that the rest are not in use by anyone.
2014-08-08 00:43:14 +02:00
wm4 fa682af6ee command: add a "seeking" property
The client API exports this state via events already, but maybe it's
better to explicitly provide this property in order to facilitate use on
OSD and similar cases.
2014-08-08 00:16:20 +02:00
wm4 5f042864f5 player: indicate on the status line whether a seek is active
This is delayed by 300ms - before that, the status doesn't change. I
feel like it would too annoying if the status line would "flicker" on
normal seek by quickly showing and hiding the indicator.
2014-08-08 00:05:24 +02:00
wm4 e1ff914679 input.conf: remap pgup/dwn to chapter seeks
As discussed in #973.

Keep the old bindings for now; there's no reason to unmap them yet.
2014-08-07 23:55:09 +02:00
wm4 7898169484 build: add hacks to force waf to generate valid .pc files
Don't like this? You're invited to fix this crap.
2014-08-07 23:45:40 +02:00
wm4 5906041343 input: fix off by one error in command parser
Should fix #989.
2014-08-07 18:21:36 +02:00
wm4 886ac09699 audio: fix encoding mode
If this code is not skipped, encoding (or dumping with --ao=pcm) will
attempt to adjust video timing to audio. Since another commit (0cce8fe6)
already avoids writing audio ahead, this didn't slow down encoding to
realtime, but it was still significantly slower.

This change should actually remove all extra sleeping.
2014-08-07 18:07:43 +02:00
wm4 483595e2d4 client API: qtexample: don't pass deallocated strings to mpv
The temporary QByteArray is deallocated already at the end of the
statement in C++, instead of the end of the scope (like in C).
2014-08-07 00:35:38 +02:00
wm4 1483fd443a demux: fix playback abort if --demuxer-thread is not used
Switching tracks caused cached_demux_control() to catch the command to
switch tracks, even if no thread was running. Thus, the tracks were
never really switched, and EOF happened immediately on playback start.

Fix it by not using the cache at all if the demuxer thread is disabled.
The cache code still has to be called somewhere, though, because it
handles stream metadata update.

Regression from today.
2014-08-07 00:34:14 +02:00
wm4 af57444bcb player: remove unused declaration 2014-08-07 00:30:43 +02:00
wm4 dfc5d96916 gitignore: fix manpage entries 2014-08-06 20:35:55 +02:00
wm4 41ff8a661b old-build: HAVE_COCOA_APPLICATION must be set
Also fix a typo in the Makefile manpage rule.
2014-08-06 20:33:51 +02:00
wm4 3234f5a123 stream_dvb: restore --dvbin-file option
Got lost some time ago. Although I'm not sure if it actually does
anything on MPlayer (it exists there, but might broken, not sure).

Fixes #988 (untested).
2014-08-06 20:30:48 +02:00
wm4 796db66174 stream_dvb: fix channels.conf preference order
channels.conf was never used (even though its config path was resolved).

Also remove the non-sense with the access() call.

Fixes #987 (untested).
2014-08-06 20:30:47 +02:00
wm4 19fd67096b vo_direct3d: allow resizing before video init
This can just happen in the time between VO creation, and the first call
to vo_reconfig. It seems the recent threading changes exposed this bug.

Fixes #986.
2014-08-06 20:30:47 +02:00
wm4 77ad49411a win32: never call GetClientRect(0, ...)
Sometimes GetClientRect() appeared to fail during init, and since we
don't check GetClientRect() calls (because they're on our own window,
and logically can never fail), bogus resizes were triggered. This could
cause vo_direct3d to fail initialization.

The reason was that w32->window was set to 0 during early window
initialization: CreateWindow*() can send messages to the new window,
even though it hasn't returned yet. This means w32->window is not yet
set to our window handle, and functions in WndProc may accidentally pass
hwnd=0 to win32 API functions.

Fix it by initializing w32->window on opportunity. This also means we
always strictly expect that the WndProc is used with our own window
only.
2014-08-06 20:30:47 +02:00
wm4 64e1132d39 demux: make track switching asynchronous
Because why not.

This can lead to reordering of operations between seeking and track
switching (happens when the demuxer wakes up after seek and track
switching operations were queued). Do the track switching strictly
before seeks if there is a chance of reordering, which guarantees that
the seek position will always start with key frames. The reverse
(seeking, then switching) does not really have any advantages.

(Not sure if the player relies on this behavior.)
2014-08-06 20:30:47 +02:00
wm4 b38ac38aec client API: trigger MPV_EVENT_VIDEO_RECONFIG on vf recreation
Until now, it was done only on VO reconfig, but this easily can miss
some events, in case the VO output format doesn't change.
2014-08-06 20:30:47 +02:00
wm4 be64535a4e audio: fix inverted condition
Recent regression. Could perhaps make gapless audio fail to work
correctly.
2014-08-06 20:30:46 +02:00
Alexander Preisinger 6ec39b4641 wayland: remove redundant line 2014-08-06 12:58:39 +02:00
Alexander Preisinger f175f2c38f wayland: changes for nested compositors
Adds necessary checks for nested compositors which only have limited
interfaces. Might also be useful for other minimal compositors.
2014-08-06 12:55:51 +02:00
Stefano Pigozzi 2e241c0a47 build: allow to disable building the cplayer 2014-08-06 09:31:59 +02:00
Stefano Pigozzi 212374149f build: expose waf variants to the user
This allows the user to execute multiple configuration and build steps. It
can be used for several scenarios where you need different compiler flags.
2014-08-06 09:31:59 +02:00
Stefano Pigozzi c8cf864bff cocoa: fix build by using the correct HAVE_* macro
This builds but both the libmpv example and the cplayer block infinitely when
building libmpv. That's because we wait inifinitely in `dispatch_sync` as
there's no event loop in the main thread that allows for libdispatch to work..

Whiel we are at it, we should probably investigate how to use mp_dispatch
instead since it is a little lower level and could give us higher control in
building and event loop.
2014-08-06 09:31:59 +02:00
FRAU KOUJIRO b8a431c892 cocoa: macosx_application needs cocoa-application 2014-08-06 09:31:59 +02:00
FRAU KOUJIRO 022a43de8e build: cocoa-application config target
I had to put it after video options because it depends on cocoa;
is there anywhere better to put it rather than making a new group?
2014-08-06 09:31:59 +02:00
FRAU KOUJIRO 0be25a8dbf cocoa: move handleFilesArray: to macosx_events 2014-08-06 09:31:58 +02:00
FRAU KOUJIRO 4fc8dcde2a cocoa: move set_input_context to macosx_events 2014-08-06 09:31:58 +02:00
FRAU KOUJIRO 78a2d99de1 cocoa: sync inputContext inside EventsResponder 2014-08-06 09:31:58 +02:00
FRAU KOUJIRO 78a266d599 cocoa: decouple events from application somewhat 2014-08-06 09:31:58 +02:00
wm4 ff6c387a73 win32: fix build 2014-08-05 23:43:40 +02:00
wm4 5a0db9bf8a build: move def file to libmpv/
This is more consistent with mpv.pc, which is also in libmpv/.
2014-08-05 20:02:41 +02:00
wm4 210c83ab31 win32: create OpenGL context on the GUI thread
This fixes the fullscreen issues on Intel for me. I'm baffled by it and
don't understand why this suddenly works. Intel drivers being shit?
Windows being shit? HWND or HDC being only 97% thread-safe instead of
98%? Me missing something subtle that is not documented anywhere?

Who knows.

Now instead of creating the HDC and OpenGL context on the renderer
thread, they're created on the GUI thread. The renderer thread will
then only call wglMakeCurrent, SwapBuffers, and OpenGL standard
functions.

Probably fixes github issue #968.
2014-08-05 20:02:23 +02:00
wm4 afcbee8305 win32: cleanup OpenGL context creation
Might handle some corner cases better. In particular, always call
wglMakeCurrent() with non-NULL HDC argument.
2014-08-05 19:59:32 +02:00
Stefano Pigozzi 8af0d9fec8 build: syms: reindent
We avoided reindenting this in the past to allow merging upstream changes.
In hindsight these are very unlikely and we are actually doing changes on
the code, so it's better to have the correct indentation and formatting in
our source file.
2014-08-05 12:57:34 +02:00
Stefano Pigozzi b34621e1b1 build: syms: fix *.def file for mach-o binary format
There was a missing trailing newline which caused some warnings when calling
`ld`.
2014-08-05 12:13:27 +02:00
wm4 9a6d7af074 options: fix key-value-list options
The parser can be called with dst (the target) set to NULL if the option
should be verified only. The code didn't respect this, and could result
in crashes when used in config profiles or filter sub-options.

Fixes #981.
2014-08-05 02:24:45 +02:00
wm4 43ddf2099b client API: add and use the MPV_MAKE_VERSION macro
This is probably nicer. The actual version number doesn't change (other
than the minor being incremented).

The "| 0UL" is to make the type unsigned long int, like it was before.
2014-08-05 02:23:14 +02:00
wm4 bdf607ea5f build: list exported symbols explicitly
Instead of using a regex to match names to be exported from the libmpv
dynamic shared library, use a libmpv.def file, which lists all exported
functions explicitly.

This reduces the platform specifics in syms.py. I'm not sure if the
separate compile_sym task is still needed (it could probably be
collapsed, which would concentrate the platform specifics into one
place).
2014-08-05 02:21:29 +02:00
wm4 62a79ae556 build: fix export of libmpv symbols on mingw
The _ usually prefixed to functions on Windows was unexpectedly missing.
2014-08-05 01:02:54 +02:00
wm4 91fbaa7d34 build: fix cross-compilation of libmpv
libmpv requires nm for creating the list of exported symbols (this is
done in syms.py). We should probably just make this list static instead,
but since this involves platform-specific code, for now this quick-fix
will do.
2014-08-05 00:20:31 +02:00
wm4 d634f7b01a vdpau: don't crash on flipped images
It seems the vdpau API does not support these.

Do a semi-expensive emulation of it. On the other hand, it's not like
this is a commonly-used feature. (It might be better to make --vf=flip
always copy instead of flipping it via pointer tricks - but everything
allows flipped images, and even decoders or libavfilter filters could
output them.)
2014-08-05 00:18:57 +02:00
wm4 ee6df2f76c sub: fix subtitle timing for TS
The subtitle timing logic always used the demuxer's start time as video
offset. This made external subtitle files "just work" with file formats
like TS, which usually have a non-0 start time. But it was wrong for
subtitles muxed with the TS, so adjust the time offset explicitly with
external files only.
2014-08-04 18:17:30 +02:00
wm4 922b1d8504 sub: don't read packets if video and audio are disabled
Although disabling both video and audio is surely an obscure corner
case, it's allowed, and we don't want the demuxer to skip arbitrary
packets.

Basically, make the heuristic for checking interleaved files affect
external files only.
2014-08-04 18:17:30 +02:00
Michael Forney 618361c697 gl_wayland: Don't try to resize the egl_window before it exists
If the compositor sends a configure event immediately after a window is
created (for example, if it implements tiling window management), mpv
will attempt to call wl_egl_window_resize before it has actually created
the egl_window, causing a crash.
2014-08-04 09:50:24 +02:00
wm4 913b49fcbc input.conf: remap 2 keys
Nobody uses 'c' (except accidentally) - remove.

Everyone agrees that OSD level cycling on 'o' is dumb, so map it to
show_progress instead. Cycling the OSD level is now available on 'O'.
No reason to ummap 'P' yet.

Also see issue #973.
2014-08-03 21:15:33 +02:00
wm4 0f5aed9c62 player: some further playloop cleanups
Handle --term-playing-msg at a better place.

Move MPV_EVENT_TICK hack into a separate function. Also add some words
to the client API that you shouldn't use it. (But better leave breaking
it for later.)

Handle --frames and frame_step differently. Remove the mess from the
playloop, and do it after frame display. Give up on the weird semantics
for audio-only mode (they didn't make sense anyway), and adjust the
manpage accordingly.
2014-08-03 20:31:00 +02:00
wm4 0ddbf92d06 player: make quit exit immediately
Stopping playback canceled waiting, but executed the remainder of the
playloop, including things like executing pointless seeks.
2014-08-03 20:30:39 +02:00
wm4 575314eafa player: allow redrawing screen during seeks
If seeks take very long, it's better not to freeze up the display.

(This doesn't handle the case when decoding video frames is extremely
slow; just if hr-seek is used, or the demuxer is threaded and blocks on
network I/O.)
2014-08-03 20:30:34 +02:00
wm4 27301ee691 manpage: be more explicit where input.conf is located 2014-08-02 06:57:36 +02:00
wm4 d68a759fa4 Improve setting AVOptions
Use OPT_KEYVALUELIST() for all places where AVOptions are directly set
from mpv command line options. This allows escaping values, better
diagnostics (also no more "pal"), and somehow reduces code size.

Remove the old crappy option parser (av_opts.c).
2014-08-02 03:12:33 +02:00
wm4 0c6c2da8bc manpage: explain how to replace --slave-broken 2014-08-02 03:12:33 +02:00
wm4 c94e8bcdd6 player: don't show the path part for external subtitle files
Show the filename only. Feature request on IRC.
2014-08-02 03:12:31 +02:00
wm4 733bdebcb9 client API: minor optimizations for property notification
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...)
2014-08-02 01:53:22 +02:00
wm4 82a223e4e0 TOOLS: add test script for property change notifications 2014-08-02 01:53:21 +02:00
wm4 be337aa415 command: add a property that returns a list of all properties
Also remove the undocumented Lua mp.property_list() function.
2014-08-02 01:53:21 +02:00
wm4 16e5ec88e1 manpage: remove duplicated misplaced description of a command 2014-08-02 01:53:18 +02:00
wm4 aa46968ed0 win32: fix assertion failure
If OpenGL 3.x doesn't work, the fallback to legacy GL will call the
function to create the DC again, and it will assert. Just make it not
to, and also simplify the code a bit.

Fixes #974.
2014-08-01 23:03:52 +02:00
wm4 bf5b1e9a05 Remove the last remains of slave mode
Almost nothing was left of it.

The only thing this commit actually removes is support for reading
input commands from stdin. But you can emulate this via:

 --input-file=/dev/stdin --input-terminal=no

However, this won't work on Windows. Just use a named pipe.
2014-08-01 22:57:56 +02:00
Stefano Pigozzi 6aac17cebb vda: only support the new hwaccel 1.2 API (remove old code)
Since the new hwaccel API is now merged in ffmpeg's stable release, we can
finally remove support for the old API.

I pretty much kept lu_zero's new code unchanged and just added some error
printing (that we had with the old glue code) to make the life of our users
less miserable.
2014-08-01 10:38:18 +02:00
Stefano Pigozzi 33137606e9 travis: use homebrew to build ffmpeg on OS X
This allows us to use a newer version of ffmpeg and to test the build of our
VDA code.
2014-08-01 10:38:18 +02:00
wm4 33f465d9a7 player: don't ignore first chapter
It's a mystery why this was done this way. If the first chapter starts
later than the current position, we do have to return -1.
2014-07-31 22:54:57 +02:00
wm4 de8e9ca9d2 video: fix attached picture mode
Playing audio files with embedded cover art broke due to some of the
recent changes. Treat video EOF properly, and don't burn the CPU.
Disable hrseek for video in attached picture mode, since the decoder
will always produce a new image, which makes hrseek never terminate.

Fixes #970.
2014-07-31 21:57:11 +02:00
wm4 4cf3f3ca2c audio: simplify condition
The expression added with the previous commit (0cce8fe6) looked slightly
more complicated than it has to be. The code is equivalent.
2014-07-31 21:11:49 +02:00
wm4 0cce8fe64f audio: fix A/V sync in encoding mode
In encoding mode, the AO pretends to be infinitely fast (it will take
whatever we write, without ever rejecting input). Commit 261506e3 broke
this somehow. It turns out an old hack dealing with this was accidentally
dropped.

This is the hunk of code whose semantics were (partially) dropped:

    if (mpctx->d_audio && (mpctx->restart_playback ? !video_left :
                           ao_untimed(mpctx->ao) && (mpctx->delay <= 0 ||
                                                     !video_left)))
    {
        int status = fill_audio_out_buffers(mpctx, endpts);
        // Not at audio stream EOF yet
        audio_left = status > -2;
    }

This if condition is pretty wild, and it looked like it was pretty much
for audio-only mode, rather than subtle handling for encoding mode.
2014-07-31 04:49:44 +02:00
wm4 a1b54d3b89 client API: don't send internal events to the clients
"Internal" events were added in the previous commits to leverage the
client API property mechanism, without making weird properties public.

But they were sent to clients too (and returned by mpv_wait_event()).
2014-07-31 04:35:23 +02:00
wm4 c1b64cc693 command: add cache-idle property 2014-07-31 04:25:39 +02:00
wm4 b4f24544bb client API: make "cache" property and similar observable
Achieve this by polling. Will be used by the OSC. Basically a bad hack -
but the point is that the mpv core itself is in the best position to
improve this later.
2014-07-31 04:19:41 +02:00
wm4 aaa90e1a33 client API: fix deadlock when calling mpv_terminate_destroy before init
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
2014-07-31 03:12:18 +02:00
wm4 dacbaea1a8 player: rename a variable
Make it clear that this condition happens when switching to a new
timeline segment. It doesn't even need to coincide with a chapter.
2014-07-30 23:29:01 +02:00
wm4 1423bd0bfd player: move video display code out of the playloop
Basically move the code from playloop.c to video.c. The new function
write_video() now contains the code that was part of run_playloop().

There are no functional changes, except handling "new_frame_shown"
slightly differently. This is done so that we don't need new a new
MPContext field or a return value for write_video() to signal this
condition. Instead, it's handled indirectly.
2014-07-30 23:29:00 +02:00
wm4 8f2e9f1d61 player: split seek_reset()
This also reduces some code duplication with other parts of the code.

The changfe is mostly cosmetic, although there are also some subtle
changes in behavior. At least one change is that the big desync message
is now printed after every seek.
2014-07-30 23:29:00 +02:00
wm4 c38013bffb video: actually flush filter chain
Frames buffered in filters weren't flushed, so on EOF, the last frames
were dropped, depending on how much filters buffered. Oops.

Test case: "mpv something.jpg --vf=buffer"
2014-07-30 23:29:00 +02:00
wm4 f8ab732ac3 video/filter: add vf_buffer
Mostly useful for debugging.
2014-07-30 23:29:00 +02:00
wm4 8d990408d7 audio: better sync behavior on bogus EOF
In situations when the demuxer reports EOF, but immediately "recovers"
after that and returns new data, it could happen that audio sync was
skipped. Deal with this by actually entering the EOF state, instead of
assuming this will happen later.
2014-07-30 23:29:00 +02:00
wm4 6afa1a2afc ao_alsa: disable use of non-interleaved formats by default
Some ALSA plugins take non-interleaved audio, but treat it as
interleaved, which results in various funny bugs. Users keep hitting
this issue, and it just doesn't seem worth the trouble.

CC: @mpv-player/stable
2014-07-30 23:28:44 +02:00
Stefano Pigozzi c3d15b50b4 cocoa: fix key equivalent dispatching
Prior to this commit we had a list of key modifiers and checked against that.
Actually, the Cocoa framework has a built in way to do it and it involves
calling performKeyEquivalent: on the menu instance.

Fixes #946

cc @mpv-player/stable: this should apply with no conflicts
2014-07-30 11:26:49 +02:00
wm4 471dfba018 client API: fix typos in documentation 2014-07-30 03:33:37 +02:00
wm4 0dd5228626 demux_lavf: don't consider EAGAIN as EOF condition
This happens apparently randomly with rtmp:// and after seeks. This
eventually leads to audio decoding returning an EOF status, which
basically disables audio sync. This will lead to audio desync, even if
audio decoding later "recovers" when the demuxer actually returns audio
packets.

Hack-fix this by special-casing EAGAIN.
2014-07-30 03:32:56 +02:00
wm4 6856d81c68 stream: hack-fix rtmp-level seeking
This didn't work, because the timebase was wrong. According to the
ffmpeg doxygen, if the stream index is -1 (which is what we used), the
timebase is AV_TIME_BASE. But this didn't work, and it really expected
the stream's timebase. Quite "surprising", since this feature
(avio_seek_time) is used by rtmp only.

Fixing this properly is too hard, so hack-fix our way around it.
STREAM_CTRL_SEEK_TO_TIME is also used by DVD/BD, so a new
STREAM_CTRL_AVSEEK is added. We simply pass-through the request
verbatim.
2014-07-30 02:21:51 +02:00
wm4 26d973ce82 stream_lavf: allow setting AVOptions with --stream-lavf-o
This commit also creates a private option struct for stream_lavf.c, but
since I'm lazy, I'm not moving any existing options to it.
2014-07-30 01:15:42 +02:00
wm4 da780309d7 audio: better initial sync for files where audio starts later
Some files have the first audio much later into the video (for whatever
reasons). Instead of appending large amounts of silence to the audio
buffer (and refusing to sync if the audio to append is "too large"),
just wait until enough video has played.
2014-07-30 00:40:45 +02:00
wm4 1cd2b5976d audio: cosmetics: remove unused return value 2014-07-30 00:24:57 +02:00
wm4 6b928fa2a0 demux_mf: allow seeking past the end
How's this for a corner case.
2014-07-30 00:23:16 +02:00
wm4 593ad996e0 player: fix time display wheen seeking past EOF with --keep-open
Regression since commit 261506e3. Internally speaking, playback was
often not properly terminated, and the main part of handle_keep_open()
was just executed once, instead of any time the user tries to seek. This
means playback_pts was not set, and the "current time" was determined by
the seek target PTS.

So fix this aspect of video EOF handling, and also remove the now
unnecessary eof_reached field.

The pause check before calling pause_player() is a lazy workaround for
a strange event feedback loop that happens on EOF with --keep-open.
2014-07-30 00:22:38 +02:00
wm4 b6a7c321db player: let explicitly imprecise seeks cancel precise seeks
If an imprecise seek is issues while a precise seek is ongoing,
don't wait up to 300ms (herustistic which usually improves user
experience), but instead let it cancel the seek.

Improves responsiveness of the OSC after the previous commit.

Note that we don't do this on "default-precise" seeks, because we
don't know if they're going to be precise or not.
2014-07-29 20:04:08 +02:00
ChrisK2 48f4f791f4 osc: Do precise seeks on simple clicks on seekbar 2014-07-29 19:26:32 +02:00
wm4 63d1d53d2f audio: ignore (some) decoding errors on initialization
It probably happens relatively often that the first packet (or even the
first N packets) of a stream will fail to decode, but decoding will
eventually succeed at a later point. Before commit 261506e3, this was
handled by an explicit retry loop (although this was also for other
purposes), but with then was changed to abort on the first error. This
makes it impossible to decode some audio streams.

Change this so that errors are ignored for the first 50 packets, which
should make it equivalent to the old code.
2014-07-29 18:05:55 +02:00
wm4 862d7d8a1a player: fix desync when seeking and switching external tracks
If you for example use --audio-file, disable the external track, seek,
and enable the external track again, the playback position of the
external file was off, and you would get major A/V desync. This was
actually supposed to work, but broke at some time ago (probably commit
2b87415f). It didn't work, because it attempted to seek the stream if it
was already selected, which was always true due to
reselect_demux_streams() being called before that.

Fix by putting the initial selection and the seek together.
2014-07-29 17:55:28 +02:00
wm4 6d15c491b0 player: remove a pointless field 2014-07-29 01:00:54 +02:00
wm4 25ceb3289d player: disable hr-seek in .ts files
Seeking in .ts files (and some other formats) is too unreliable, so
there's a separate code path for this case. But it breaks hr-seek.

Maybe hr-seek could actually be enabled in this case if we're careful
enough about timestamp resets, but for now nothing changes.
2014-07-29 00:59:00 +02:00
wm4 d6445d7ab6 player: allow precise seeking with percent seeks
I'm not sure why this was explicitly disabled. It's from mplayer2 times.
2014-07-29 00:26:52 +02:00
wm4 ecad4a20de manpage: lua: document timer timeout and oneshot fields
Might be useful for scripts, so document them. (Which means scripts
are allowed to use them, without risking breakage.)
2014-07-29 00:22:21 +02:00
wm4 fa34b4920a vdpau: don't upload video images in advance
With software decoding, images were uploaded to vdpau surfaces as they
were queued to the VO. This makes it slightly more complicated
(especially later on), and has no advantages - so stop doing it.

The only reason why this was done explicitly was due to attempts to keep
the code equivalent (instead of risking performance regressions). The
original code did this naturally for certain reasons, but now that we
can measure that it has no advantages and just requires extra code, we
can just drop it.
2014-07-29 00:21:02 +02:00
wm4 d563dc8cb9 player: update playback position on seek
If the actual PTS is not known yet right after a seek, the "time-pos"
property will just return the seek target PTS. For this purpose, trigger
a change event to make the client API update the "time-pos" and related
properties. (MPV_EVENT_TICK triggers this update.)
2014-07-29 00:20:54 +02:00
wm4 846257da13 player: logically speed up seek logic
Commit 261506e3 made constant seeking feel slower, because a subtle
change in the restart logic makes it now waste time showing another
video frame. The slowdown is about 20%.

(Background: the seek logic explicitly waits until a video frame is
displayed, because this makes it easier for the user to search for
something in the video. Without this logic, the display would freeze
until the user stops giving seek commands.)

Fix this by letting the seek logic issue another seek as soon as the
first video frame is displayed. This will prevent it from showing a
(useless, slow) second frame. Now it seems to be as fast as before the
change.

One side-effect is that the next seek happens after the first video
frame, but _before_ audio is restarted. Seeking is now silent. I guess
this is ok, so we don't do anything about it. Actually, I think whether
this happens is probably random; the seeking logic simply doesn't make
this explicit, so anything can happen.
2014-07-28 22:13:42 +02:00
wm4 26bfcc9c82 vo_x11: fix build with older Libav versions
Why does this happen everytime...
2014-07-28 21:48:43 +02:00
Niklas Haas d0a8b571c9 video: add a default color space for files with no video
Usually mp_image_params_guess_csp takes care of finding *some* default
for a video channel, but files with no video (or with extremely broken
configurations) end up leaving the colorspace information as
MP_CSP_PRIM_AUTO, which has no associated primaries.

As a result of this, color managed OSD messages could not display
because they were being color managed to match the (non-existing/absurd)
video channel. With this change, such non-spaces will have BT.709
primaries as far as color management and the OSD is concerned.

This fixes #961.

CC: @mpv-player/stable

Signed-off-by: wm4 <wm4@nowhere>
2014-07-28 21:24:44 +02:00
wm4 261506e36e audio: change playback restart and resyncing
This commit makes audio decoding non-blocking. If e.g. the network is
too slow the playloop will just go to sleep, instead of blocking until
enough data is available.

For video, this was already done with commit 7083f88c. For audio, it's
unfortunately much more complicated, because the audio decoder was used
in a blocking manner. Large changes are required to get around this.
The whole playback restart mechanism must be turned into a statemachine,
especially since it has close interactions with video restart. Lots of
video code is thus also changed.

(For the record, I don't think switching this code to threads would
make this conceptually easier: the code would still have to deal with
external input while blocked, so these in-between states do get visible
[and thus need to be handled] anyway. On the other hand, it certainly
should be possible to modularize this code a bit better.)

This will probably cause a bunch of regressions.
2014-07-28 21:20:37 +02:00
wm4 58255e0e2b input: be stricter about rejecting mouse input with --no-input-cursor
Apparently this switch means all mouse input should be strictly
rejected. Some VO backends (such as X11) explicitly disable all mouse
events if this option is set, but others don't. So check them in
input.c, which increases consistency.
2014-07-27 22:00:55 +02:00
wm4 4c533fbb16 vo: remove vo_mouse_movement() wrapper
So that VO backends don't have to access the VO just for that.
2014-07-27 21:53:29 +02:00
wm4 89391e7c94 vo: different hack for VOs which need to mangle mouse input
Follow up on commit 760548da. Mouse handling is a bit confusing, because
there are at least 3 coordinate systems associated with it, and it
should be cleaned up. But that is hard, so just apply a hack which gets
the currently-annoying issue (VO backends needing access to the VO) out
of the way.
2014-07-27 21:33:11 +02:00
wm4 bc6359313f ao_pulse: allow disabling timing bug workarounds
Add an option that enables using native PulseAudio auto-updated timing
information, instead of the manual calculations added in mplayer2 times.
You can use --ao=pulse:no-latency-hacks to enable the new code. The code
is almost the same as the code that was removed with commit de435ed5,
but I didn't readd some bits I didn't understand. Likewise, the option
will disable the code added with that commit.

In my tests this seemed to work well, though the A/V sync display looks
funny when seeking.

The default is still the old behavior.

See issue #959.
2014-07-26 23:20:09 +02:00
wm4 77d9e4b8a9 ao_pulse: remove hacks for ancient PulseAudio versions
This was needed by very old (0.9) versions only. Get rid of it.

Unfortunately, I can't cross-check with the original bug report, since
the bug URL leads to this:

Internal Server Error

TracError: IOError: [Errno 2] No such file or directory: '/home/lennart/svn/trac/pulseaudio/VERSION'
2014-07-26 23:19:48 +02:00
wm4 3c7675ae9a manpage: eliminate the word "movie"
It's evil and sounds outdated. Use the words "media" and "video"
instead.

Closes #935.
2014-07-26 23:19:47 +02:00
wm4 025431a7ae win32: remove minor non-sense
This is done in the wrong thread. Was harmless and had no effect at all.
2014-07-26 23:19:43 +02:00
wm4 97a82bcd56 win32: move window handling to a separate thread
The windows message loop now runs in a separate thread. Rendering,
such as with Direct3D or OpenGL, still happens in the main thread.

In particular, this should prevent the video from freezing if the
window is dragged. (The reason was that the message dispatcher won't
return while the dragging is active, so mpv couldn't update the
video at all.)

This is pretty "rough" and just hacked in, and there's no API yet to
make this easier for other backends. It will be cleaned up later
once we're sure that it works, or when we know how exactly it should
work. One oddity is that OpenGL is actually completely managed in the
renderer thread, while e.g. Cocoa (which has its own threading code)
creates the context in the GUI thread, and then lets the renderer
thread access it.

One strange issue is that we now have to stop WM_CLOSE from actually
closing the window. Instead, we wait until the playloop handles the
close command, and requests the VO to shutdown. This is done mainly
because closing the window apparently destroys it, and then WM_USER
can't be handled anymore - which means the playloop has no way to
wakeup the GUI thread. It seems you can't really win here... maybe
there's a better way to have a thread receive messages with and
without a window, but I didn't find one yet.

Dragging the window (by clicking into the middle of it) behaves
strangely in wine, but didn't before the change. Reason unknown.
2014-07-26 20:36:46 +02:00
wm4 760548da28 vo: hack to avoid threading issues with mouse input
VO backends which are or will run in their own thread have a problem
with vo_mouse_movement() calling vo_control(). Restrict this to VOs
which actually need this.
2014-07-26 20:31:26 +02:00
wm4 3f268cc4f2 win32: use gcc TLS instead of WM_NCCREATE tricks for window context
win32 does not provide a proper per-window context pointer. Although it
does allow passing a user-chosen value to WM_CREATE/WM_NCCREATE, this
is not enough - the first message doesn't even have to be WM_NCCREATE.
This gets us in trouble later on, so go the easy route and just use a
TLS variable.

__thread is gcc specific, but Windows is a very "special" platform
anyway. We support only MinGW and Cygwin on it, so who cares. (C11
standardizes __thread as _Thread_local; we can use that later.)
2014-07-26 20:30:52 +02:00
wm4 559fe1daac Add Plan 9-style barriers
Plan 9 has a very interesting synchronization mechanism, the
rendezvous() call. A good property of this is that you don't need to
explicitly initialize and destroy a barrier object, unlike as with e.g.
POSIX barriers (which are mandatory to begin with). Upon "meeting", they
can exchange a value.

This mechanism will be nice to synchronize certain stages of
initialization between threads in the following commit.

Unlike Plan 9 rendezvous(), this is not implemented with a hashtable,
because that would require additional effort (especially if you want to
make it actually scele). Unlike the Plan 9 variant, we use intptr_t
instead of void* as type for the value, because I expect that we will be
mostly passing a status code as value and not a pointer. Converting an
integer to void* requires two cast (because the integer needs to be
intptr_t), the other way around it's only one cast.

We don't particularly care about performance in this case either. It's
simply not important for our use-case. So a simple linked list is used
for waiters, and on wakeup, all waiters are temporarily woken up.
2014-07-26 20:29:48 +02:00
wm4 8ed6d298c5 win32: make a flag explicit
This shouldn't change anything. But it's worth making this explicit,
since it's very subtle and unintuitive: if the X parameter is the
magic value CW_USEDEFAULT, then the Y parameter is used as nCmdShow
parameter to ShowWindow(). And in our case, this is SW_HIDE (0),
because we want to create a hidden window.
2014-07-26 20:29:18 +02:00
wm4 9969694ece win32: simplify some --wid embedding code
This looked a bit overcomplicated. We don't care about the window
position (it should always be 0/0, unless the parent program moved it,
which it shouldn't). We don't care about the global on-screen position.
Also, we will just retrieve a WM_SIZE message if our window is resized,
and we don't need to update it manually.

The only thing we have to do is making sure our window fills the parent
window completely.
2014-07-26 20:28:36 +02:00
wm4 9a3f1f24ca win32: don't use CS_OWNDC
CS_OWNDC will make GetDC() always return the same HDC. This might
become a problem when OpenGL rendering and window management are
on different threads. Although I'm not too sure about this; our
code never requests a HDC outside of the OpenGL backend, and it
depends on whether win32 will internally request DCs. But in any
case, this seems to be cleaner.

Move the GL pixelformat setup code to gl_w32.c, where it's actually
needed. This also fixes that SetPixelFormat() should be called only
once, and not every time video params change.
2014-07-26 20:28:01 +02:00
wm4 7f0d9a95fa win32: remove worthless doxygen comments
These mostly describe self-explanatory things, and fail to explain
actually tricky things. Which means you just waste your time reading
this, and have to figure it out from the code anyway.
2014-07-26 20:27:57 +02:00
wm4 b3169390f5 win32: make private struct private, refactor
Preparation for moving win32 windowing to a separate thread.

The codesize is reduced a bit, because some small functions are
inlined, which reduces noise.

The main change is that now most functions use the private struct
directly, instead of accessing it indirectly through vo->w32.
Accesses to vo are minimalized.

The final goal is adding some sort of new windowing backend API. It
would be cleaner to use that as context pointer for all functions
(like struct vo was previously used), but since this is work in
progress, we just go with this commit.
2014-07-26 20:27:03 +02:00
wm4 7077526ffb ao_null: never fail at initialization
ao_null is used to stop autoprobing (if all AOs before fail to init).
After it come things like ao_pcm, which should never be automatically
selected.

Remove a certain theoretically possible failure case, and force "some"
fallback.
2014-07-26 20:26:57 +02:00
wm4 ac62244983 audio/out: fix initialization failure with win32
mp_make_wakeup_pipe() always fails on win32. If this call fails on Linux
(and e.g. ao_alsa is used), this will probably burn CPU since poll()
won't work on the invalid file descriptor, but whatever, the failure
case is obscure enough.
2014-07-26 20:26:27 +02:00
wm4 ef600041ba audio, client API: check mp_make_wakeup_pipe() return value
Could fail e.g. due to FD exhaustion.
2014-07-25 14:32:45 +02:00
wm4 18c432b83a osdep: don't assume errno is positive
Apparently this is not necessarily the case, so just drop the silly idea
that depended on this assumption.
2014-07-25 14:32:45 +02:00
wm4 f24f960ec7 command: fix and simplify overlay_add
Actually free the old mmap region when readding an overlay of the same
ID without removing it before. (This is explicitly documented as
working.)

Replace the OSD atomically. Before this commit, the overlays were
removed and then readded to avoid synchronization problems.

Simplify the code: now there is no weird mapping between index and ID.
The OSD sub-bitmap list still needs to be prepared to skip unused IDs
(since each sub-bitmap list entry must be in use), but the code for this
is relatively separated now.

Fixes issue #956.
2014-07-25 14:32:45 +02:00
Alessandro Ghedini 08415933db command: append entries to the end of the playlist with loadlist append
Currently entries are added after the current playlist element. This is kinda
confusing, more so given that "loadfile append" appends at the end of the
playlist.
2014-07-25 14:32:34 +02:00
wm4 623eac2b1b audio: cosmetics: collapse a function
There's no need for build_afilter_chain() to be a separate function
anymore.
2014-07-24 15:27:40 +02:00
wm4 69eb056333 audio: fix timestamps
Accidentally broken in b6af44d3. For ad_lavc (and in general), the PTS
was not updated correctly when filtering only parts of audio frames,
and for ad_mpg123 and ad_spdif the PTS was additionally offset by the
frame size.

This could lead to incorrect time display, and possibly broken A/V sync.
2014-07-24 15:27:31 +02:00
wm4 fc28e4af4d audio: adjust format change code
Execute the format change based on whether we logically detected EOF
(after filters), instead of when the decode buffer was drained. It's
slightly cleaner. (The requirement of len>0 existed before.)
2014-07-24 15:26:43 +02:00
wm4 986099d323 audio: fix race condition in EOF code
Don't return an EOF code if there's still buffered data.

Also, don't call demux_stream_eof() in the playloop. There's probably
nothing wrong with it, but it's cleaner not to use it.

Also give AD_EOF its own value, so that a decoding error doesn't drain
audio by causing an EOF condition.
2014-07-24 15:26:07 +02:00
wm4 b77dab0f6e audio: cosmetics
Move a function call, which does not change semantics.

Write the extra buffer sample count in a more straight-forward way; the
old code was not meaningful in any way (anymore).
2014-07-24 15:25:48 +02:00
wm4 6455bcc1da audio: remove unnecessary code
It's true that the decoder can successfully decode, but return no data
(for various reasons). We don't need to handle this specially, though.
We just let the decoder decode some more data. This doesn't increase the
danger of an endless loop either, because audio_decode() already calls
this function until enough is decoded.
2014-07-24 15:25:36 +02:00
wm4 cb4aa2df92 manpage: fix a typo 2014-07-24 15:25:24 +02:00
Rudolf Polzer c19ec6f6f6 encode: deal even more with codec->time_base deprecation.
I assume this works too with Libav 10 and FFmpeg d3e51b41.
2014-07-23 16:09:44 +02:00
wm4 843f5f4723 command: add append-play loadfile mode
"loadfile filename append-play" will now always append the file to the
playlist, and if nothing is playing yet, start playback. I don't want to
change the semantics of "append" mode, so a new mode is needed.

Probably fixes issue #950.
2014-07-23 00:20:53 +02:00
wm4 10debffc06 player: remove something DVD specific
This is not needed anymore, because demux_disc isolates us from this
crap.
2014-07-22 23:49:23 +02:00
wm4 870dc84839 sub: offset subtitle timing to video start PTS
This allows using external subtitle files with e.g. transport stream
files that don't start at time 0.

Note that if the .ts file has timestamp resets, everything goes south.
But I guess this was already the case before, unless there are external
subtitle files that also include timestamp resets, which is unlikely.
(On the other hand, you could for example expect that it works with
embedded DVB subtitles, that were somehow captured from the same stream
and use the same timestamps.)
2014-07-22 23:48:29 +02:00
wm4 aa1a383342 sub: add detection via BOM
Useful for Windows stuff. Actually, ENCA support should catch this, but,
well, whatever, everyone seems to hate ENCA.

Detection with BOM is trivial, although it needs some hackery to
integrate it with the existing autodetection support. For one, change
the default value of --sub-codepage to make this easier.

Probably fixes issue #937 (the second part).
2014-07-22 23:40:48 +02:00
wm4 63373ca424 encode: deal with codec->time_base deprecation
This seems to work with both Libav 10 and FFmpeg d3e51b41.
2014-07-22 23:04:12 +02:00
wm4 1041850523 video: fix corner case with accidental EOF
The video flushing logic was broken: if there are no more packets,
decode_image() will feed flush packets to the decoder. Even if an image
was produced, it will return the demuxer EOF state, and since commit
7083f88c, this EOF state is returned to the caller, which is incorrect.

Revert this part of the change, and explicitly check for VD_WAIT (the
bogus change was intended to forward this error code to the caller).

Also, turn the "r < 1" into something equivalent that doesn't rely on
the exact value of VD_EOF. "r < 0" is ok, because at least here, errors
are always negative.
2014-07-22 21:08:42 +02:00
wm4 8f8d524112 ass: remove some pointless ifdeffery
This will print compiler warnings about unused variables with older
libass versions, but that's harmless.
2014-07-22 20:49:01 +02:00
wm4 6b51b73a04 player: fix idle mode event handling 2014-07-22 19:33:24 +02:00
wm4 80d36a0aa2 ao_pulse: fix potential compilation problem
It seems at least on some platforms (OSX 10.9), the POSIX wait()
function becomes visible, and conflicts with this unrelated function.
Just rename it.
2014-07-22 19:26:53 +02:00
Stefano Pigozzi 12b2465c1e travis: add OS X continous integration
The travis guys were so nice to activate multi OS support for us (it's a beta
feature). So now we build on OS X ass well to check for OS X specific breakage.

Later I might investigate further and build with the minimum supported SDK
version so that we don't break older systems by using newer Cocoa features.
2014-07-21 20:43:39 +02:00
wm4 17256f13dc osd: properly handle OSD bar timeout
This could just remain stuck on the screen, until the playloop happened
to be run again.
2014-07-21 19:35:20 +02:00
wm4 a84517c1d8 player: don't sleep after seeks 2014-07-21 19:31:25 +02:00
wm4 b6af44d31e audio: move initial decode to generic code
This commit mainly moves the initial decoding of data (done to probe the
audio format) to generic code. This will make it easier to make audio
decoding non-blocking in a later commit.

This commit also changes how decoders return data: instead of having
them write the data into a prepared buffer, they return a reference to
an internal buffer (by setting dec_audio.decoded). This makes it
significantly easier to handle audio format changes, since the decoders
don't really need to care anymore.
2014-07-21 19:29:58 +02:00
wm4 1f9e0a15a1 ad_lavc: drop questionable fallback code
If the decoder didn't set a samplerate, it was initialized from the
container samplerate.

This probably didn't make much sense, because it's passed to the
decoder on initialization (so it could definitely use it). It's an
artifact from commit 66a9eb57 (which removed some Matroska-specific non-
sense), and I've never seen it actually happen since it was made into a
warning. Just get rid of it.
2014-07-21 19:29:58 +02:00
wm4 967add9f0f audio: remove unused metadata field
This was used for replaygain at some point, until replaygain info was
passed through explicitly.
2014-07-21 19:29:58 +02:00
wm4 d1bb1bf8af demux: fix timestamp type for seek calls
mpv/mplayer2/MPlayer use double for timestamps, but the demuxer API used
float.
2014-07-21 19:29:58 +02:00
wm4 4b4bd9e5f7 demux: asynchronous seeking
This tells the demuxer thread that it should seek, instead of waiting
until the demuxer thread is ready.

Care has to be taken about the state between seek request and actual
seeking: newly demuxed packets have to be discarded. We can't just
flush when doing the actual seek, because the user thread could read
these packets.

I'm wondering if this could lead to issues due to relaxed ordering of
operations. But it should be fine, since seeking influences packet
reading only, and seeking is always strictly done before that.

Currently, this will have no advantages; unless audio is disabled. Then
seeking as well as normal playback can be non-blocking.
2014-07-21 19:29:50 +02:00
wm4 b6dd1341d2 manpage: correct the --mf options
The MPlayer style syntax ("-mf fps=10:type=png") was removed a while
ago, and now only the flat variants ("--mf-fps=10" etc.) work.

CC: @mpv-player/stable
2014-07-21 19:27:15 +02:00
wm4 0248de84ea player: simplify a condition
Move a condition somewhere else, which makes it conceptually simpler.

Also, the assignment to full_audio_buffers removed with this commit was
dead, and its value never used.
2014-07-20 20:47:30 +02:00
wm4 ba621ac140 manpage: fix wording for --aid 2014-07-20 20:47:03 +02:00
wm4 da1925ae2e player: simplify logic on video errors
Fatal errors in the vidoe chain (such as failing to initialize the video
chain) disable video decoding. Restart the playloop, instead of just
continuing the current iteration.

The resulting behavior should be the same, but it gets rid of possible
corner cases.
2014-07-20 20:43:06 +02:00
wm4 9736f3309a audio: use symbolic constants instead of magic integers
Similar to commit 26468743.
2014-07-20 20:42:03 +02:00
wm4 e982b5b287 player: readd code accidentally removed with commit 61efe87e
Oops.
2014-07-20 20:41:20 +02:00
wm4 5526603a43 demux: don't start reading if no packets were requested yet
Instead of starting to fill the packet queue if at least 1 stream is
selected, wait until there is at least 1 stream had new packets
requested.

In theory this is cleaner, because it allows you to e.g. do a seek and
then reselect streams without losing packets. Seeking marks all streams
as inactive, and without this new logic, the thread would read new
packets anyway right after seek.
2014-07-20 20:13:08 +02:00
wm4 61efe87e48 player: fix regression with ordered chapters
Broken by commit 1301a907. This commit added demuxer threading, and
changed some other things to make them simpler and more orthogonal. One
of these things was ntofications about streams that appear during
playback. That's an obscure corner case, but the change made handling of
it as natural as normal initialization.

This didn't work for two reasons:
1. When playing an ordered chapters file where the initial segment was
not from the main file, its streams were added to the track list. So
they were printed twice, and switching to the next segment didn't work,
because the right streams were not selected.
2. EDL, CUE, as well as possibly certain Matroska files don't have any
data or tracks in the "main" demuxer, so normally the first segment is
picked for the track list. This was simply broken.

Fix by sprinkling the code with various hacks.
2014-07-20 20:13:08 +02:00
wm4 d320695207 command: potentially fix dvd angle setting
This called demux_flush(), but that doesn't make any sense with an
asynchronously running demuxer. It would just keep reading and add new
packets again. Explicitly pause the demuxer, so that this can't happen.
Also, when flushing, data will be missing, so the decoders should
always be reinitialized, even if the operation fails.
2014-07-20 20:13:07 +02:00
foo86 6a556f524e input: enable wakeup on LIRC socket
Commit dc00b14 removed playloop polling. Enable wakeup on LIRC socket,
otherwise remote control doesn't work when paused.
2014-07-20 13:52:06 +02:00
wm4 ded02bb78c demux: make the cache refresh cached STREAM_CTRLs
This fixes the same symptom as the previous commit, but when the demuxer
thread is enabled. In this case, if nothing was read from the demuxer,
the STREAM_CTRLs weren't updated either. To the player, this looked like
the stream cache was never making progress, so playback was kept paused.
2014-07-20 00:19:58 +02:00
wm4 1313d38efb player: don't wait forever with --cache-pause-below behavior
Commit dc00b146, which disables polling by default, missed another
instance of polling: when the player pauses automatically on low cache.

This could lead to apparent freezes when playing network streams.
2014-07-20 00:16:43 +02:00
Tsukasa OMOTO b0ff0527a3 build: enable compiler optimization by default 2014-07-20 00:08:36 +02:00
wm4 887140b7d4 demux: fix a corner case (2)
It can happen that read_packet() doesn't read a packet, even if it
succeeds. Typically this is because a packet was read, but then thrown
away, because it's not part of a selected stream. The result would be a
bogus EOF condition.

Fix by explicitly checking for EOF.
2014-07-19 12:34:07 +02:00
wm4 cfdb1312da demux: ensure demux_read_packet_async() always reads
In corner cases, it might be possible that a demux_read_packet_async()
call fails to make the demuxer thread to read more packets.

If a packet is queued, the function will simply return a packet, without
marking the stream as active. As a consequence, read_packet() might
decide not to read any further packets, and the demuxer will never read
a packet and wake up the playback thread.

This was originally done to align it with demux_read_packet() semantics;
just drop this.
2014-07-19 12:27:25 +02:00
wm4 24efaa3ad7 demux: fix a corner case
demux_read_any_packet() attempts to call read_packet(), but if no stream
is active, it can decide not to read anything. The function will return
NULL, which implies EOF. Fix this by explicitly
setting demux_stream->active if needed.

Also use dequeue_packet() instead of demux_read_packet(), because it's
cleaner. (Shouldn't change behavior.)

Possibly fixes #938.
2014-07-19 12:27:21 +02:00
Stefano Pigozzi c76958d20c cocoa: don't send messages to uninitialized gl contexts
This should fix some crashes where we sent makeCurrentContext to a context that
was being freed from another thread.

/cc @mpv-player/stable
2014-07-19 12:01:53 +02:00
wm4 1942e424e3 demux: fix opening pipes with demux_lavf
We told the demuxer that a pipe (if stream cache is enabled) is
seekable. This is because the stream cache is technically seekable, it's
just that seeking may fail at runtime if a non-cached byte range is
requested.

This caused libavformat to issue seeks on initialization (at least when
piping mp4 youtube videos). Initialization failed completely after
spamming tons of error messages.

So, if an unseekable stream is cached, tell the demuxer that the file is
not seekable. This gets reversed later (when printing a message about
caching an unseekable stream), so the user can still try his luck by
issuing a seek command. The important part is that libavformat
initialization will not take code paths that will unnecessarily seek for
whatever reasons.

CC: @mpv-player/stable: regression from 0.3.x
2014-07-18 16:16:05 +02:00
wm4 2646874369 video: use symbolic constants instead of magic integers
In my opinion this is not really necessary, since there's only a single
user of update_video(), but others reading this code would probably hate
me for using magic integer values instead of symbolic constants.

This should be a purely cosmetic commit; any changes in behavior are
bugs.
2014-07-18 15:11:21 +02:00
wm4 7083f88ca8 video: don't block when reading video packets
Instead of blocking on the demuxer when reading a packet, let packets be
read asynchronously. Basically, it polls whether a packet is available,
and if not, the playloop goes to sleep until the demuxer thread wakes it
up.

Note that the player will still block for I/O, because audio is still
read synchronously. It's much harder to do the same change for audio
(because of the design of the audio decoding path and especially
initialization), so audio will have to be done later.
2014-07-18 15:10:28 +02:00
wm4 848546f2de demux: fix problems with EOF
It was easy to get into a wakeup feedback loop on EOF. The reason that
EOF is complicated is that we try to retry reading when EOF is reached,
in case the EOF state actually disappears (e.g. when watching a
currently downloaded file).

This feature is probably worthless, since in practice you have to do a
seek to "unstuck" it anyway, but since the old code also did this, we
want to keep this behavior for now.

Avoid the feedback loop by introducing another EOF flag (last_eof), that
contains the actual previous EOF state, and is not overwritten when
retrying reading. Wakeup is skipped if the EOF state didn't change.

Also, actually call the wakeup callback when EOF is detected.

The line that adds "ds->active = false;" actually does nothing, but in
theory it's cleaner.
2014-07-18 15:08:38 +02:00
wm4 152a099c3a demux: add function to read packets asychronously 2014-07-18 15:08:31 +02:00
wm4 dc00b146c4 player: remove the last instances of polling
Mouse cursor handling, --heartbeat-cmd, and OSD messages basically
relied on polling. For this reason, the playloop always used a small
timeout (not more than 500ms).

Fix these cases, and raise the timeout to 100 seconds. There is no
reason behind this number; for this specific purpose it's as close to
infinity as any other number.

On MS Windows, or if vo_sdl is used, the timeout remains very small.
In these cases the GUI code doesn't do proper event handling in the
first place, and fixing it requires much more effort.

getch2_poll() still does polling, because as far as I'm aware no event-
based way to detect this state change exists.
2014-07-18 15:04:46 +02:00
wm4 34fdf082d8 dvd, bd: fix A/V sync
Slightly less robust, but simpler, and usually guarantees that audio
and video are properly in sync.
2014-07-18 01:26:46 +02:00
wm4 1d7a68d75c demux: fix debug log output
It printed the PTS instead of the DTS.
2014-07-17 22:03:12 +02:00
wm4 9faa131959 demux: drop some unused definitions 2014-07-17 21:53:44 +02:00
wm4 11944e0b83 manpage: fix documented default for --demuxer-thread 2014-07-17 01:50:29 +02:00
wm4 30542456c3 demux_lavf: reverse rotation direction with new API
The old FFmpeg API and the new Libav API disagree about mp4 display
rotation direction. Well, whatever, fix it trial-and-error-style.

CC: @mpv-player/stable: add
2014-07-17 00:30:03 +02:00
wm4 1301a90761 demux: add a demuxer thread
This adds a thread to the demuxer which reads packets asynchronously.
It will do so until a configurable minimum packet queue size is
reached. (See options.rst additions.)

For now, the thread is disabled by default. There are some corner cases
that have to be fixed, such as fixing cache behavior with webradios.

Note that most interaction with the demuxer is still blocking, so if
e.g. network dies, the player will still freeze. But this change will
make it possible to remove most causes for freezing.

Most of the new code in demux.c actually consists of weird caches to
compensate for thread-safety issues (with the previously single-threaded
design), or to avoid blocking by having to wait on the demuxer thread.

Most of the changes in the player are due to the fact that we must not
access the source stream directly. the demuxer thread already accesses
it, and the stream stuff is not thread-safe.

For timeline stuff (like ordered chapters), we enable the thread for the
current segment only. We also clear its packet queue on seek, so that
the remaining (unconsumed) readahead buffer doesn't waste memory.

Keep in mind that insane subtitles (such as ASS typesetting muxed into
mkv files) will practically disable the readahead, because the total
queue size is considered when checking whether the minimum queue size
was reached.
2014-07-16 23:25:56 +02:00
wm4 69a8f08f3e tags: add copy function 2014-07-16 22:40:12 +02:00
Rudolf Polzer 073b2becfe ao_lavc: Fix design of audio pts handling.
There was confusion about what should go into audio pts calculation and
what not (mainly due to the audio push thread). This has been fixed by
using the playing - not written - audio pts (which properly takes into
account the ao's buffer), and incrementing the samples count only by the
amount of samples actually taken from the buffer (unfortunately this
now forces us to keep the lock too long for my taste).
2014-07-16 16:18:34 +02:00
Rudolf Polzer e257cbfdbb ao_lavc: Add a missing newline for the log. 2014-07-16 16:18:34 +02:00
Rudolf Polzer 2a985716cd ao_lavc: Fix advancing of audio pts. 2014-07-16 16:18:34 +02:00
Rudolf Polzer 35c20c3094 idet.sh: Fix a typo. 2014-07-16 16:15:12 +02:00
Tsukasa OMOTO 1c850ff559 osxbundle: fix detection of user libraries
Previous code would detect for example `libcaca.0.dylib` as a system library,
because it matched the `libc` condition.
2014-07-16 08:36:34 +02:00
Stefano Pigozzi 135ba132a8 cocoa: fix regression preventing window resize
I introduced this bug in b5bbb49. Sorry!
This could fix #943 and #930 even though I can't reproduce those specific bugs.
2014-07-15 21:33:19 +02:00
Rudolf Polzer f5449870e0 idet.sh: Fix telecine detection. 2014-07-15 11:10:24 +02:00
wm4 23a7257cca Revert "Remove DVD and Bluray support"
This reverts commit 4b93210e0c.

*shrug*
2014-07-15 01:49:02 +02:00
wm4 4b93210e0c Remove DVD and Bluray support
It never worked well. Just remux your DVD and BD images to mkv.
2014-07-14 14:34:14 +02:00
wm4 c129e3f666 demux_lavf: don't let metadata update mess up ogm playback
For OGG audio files, we usually merge the per-stream metadata back to
the file-global metadata. Don't do that for OGM, because with OGM most
metadata is actually per-stream.
2014-07-14 14:34:14 +02:00
Stefano Pigozzi ac71cb8611 cocoa: fix compilation on OS X 10.8 2014-07-14 07:21:44 +02:00
wm4 9fadc92eb1 command: don't show VO information in colorspace properties
Until now, changing the properties showed the VO colorspace parameters
on OSD. This didn't work quite well, because it showed the VO parameters
_before_ the change. This is because at least one video frame with the
new parameters has to be shown, and this doesn't happen right after
changing the property, but a bit later.

Also fix a random typo in unrelated code.
2014-07-13 20:12:55 +02:00
wm4 417ffa8b40 Remove some mp_msg calls with no trailing \n
The final goal is all mp_msg calls produce complete lines. We want this
because otherwise, race conditions could corrupt the terminal output,
and it's inconvenient for the client API too. This commit works towards
this goal. There's still code that has this not fixed yet, though.
2014-07-13 20:12:13 +02:00
wm4 d54d21cbd5 config: adjust config parser messages
Some cleanup. Also, try not to call mp_msg multiple times for 1 line.
2014-07-13 20:11:46 +02:00
wm4 9b654fd540 player: remove some inactive code
demux_seek() actually doesn't return seek success. Instead, it fails if
the demuxer is flagged as unseekable (but this is checked explicitly at
the beginning of this function), or if the seek target PTS is
MP_NOPTS_VALUE (which can never happen).
2014-07-13 20:07:29 +02:00
wm4 ae7228c6a3 audio: drop buffered audio when switching tracks or filters
No reason to wait until the audio has been played. This isn't a problem
with gapless audio disabled, and since gapless is now default, this
behavior might be perceived as regression.

CC: @mpv-player/stable
2014-07-13 20:07:14 +02:00
wm4 fb54a1436a audio: don't wait for draining if paused
Logic for this was missing from pull.c. For push.c it was missing if the
driver didn't support it. But even if the driver supported it (such as
with ao_alsa), strange behavior was observed by users. See issue #933.

Always check explicitly whether the AO is in paused mode, and if so,
don't drain.

Possibly fixes #933.

CC: @mpv-player/stable
2014-07-13 20:06:33 +02:00
wm4 b505cab597 dvdnav: fix time display when starting in the middle of the DVD
libdvdnav can actually jump into the middle of the DVD (e.g. scene
selection menus do that). Then time display is incorrect: we start from
0, even though playback time is somewhere else. This really matters when
seeking. If the display time mismatches, a small relative seek will
apparently jump to the beginning of the movie.

Fix this by initializing the PTS stuff on opening. We have to do this
after some small amount of data has been read from the stream (because
libdvdnav is crap and doesn't always update the time between seeks and
the first read; also see STREAM_CTRL_GET_CURRENT_TIME remarks in
cache.c; although this was not observed when testing with scene
selection menus). On the other hand, we want to do it before opening the
demuxer, because that will read large amounts of data and likely will
change the stream position.

Also see commit 49813670.
2014-07-13 20:05:25 +02:00
Alessandro Ghedini 1f98bb3adc stream_dvdnav: suspend read on vts change even if the requested title is not found 2014-07-13 18:26:08 +02:00
Alessandro Ghedini 712cf3342e DOCS/release-policy: mention the release version in the RELEASE_NOTES template
Also suggest adding changes in point releases to RELEASE_NOTES as well.
2014-07-13 15:03:47 +02:00
wm4 a09329bcf7 input: skip BOM in input.conf 2014-07-12 21:25:32 +02:00
wm4 fed69f3637 config: skip BOM 2014-07-12 21:24:55 +02:00
wm4 5b820ff1b4 dvd: potentially fix video aspect ratio
This overwrote the source stream header, instead of the stream header
exported to the decoder.
2014-07-12 20:17:19 +02:00
wm4 c37956b364 stream: don't sleep for reconnecting network if playback is stopped
Also silences the bogus message if that happens.

CC: @mpv-player/stable
2014-07-12 19:19:04 +02:00
wm4 64e3b07a9d cache_file: fix operation if stream size is unknown
Happens when playing from a pipe.

Note that seeking forward doesn't work. It would be possible to create a
workaround for that by reading and skipping data until the target
position is reached (and writing the skipped data into the cache file),
but I'm not sure about that.

Fixes #928.

CC: @mpv-player/stable
2014-07-12 19:18:21 +02:00
ChrisK2 1e8b98af73 osc: improve previous commit 2014-07-10 11:22:05 +02:00
ChrisK2 549afdb9c5 osc: round displayed cache value
Fixes #919
2014-07-10 11:17:51 +02:00
wm4 d68d4dd984 Revert "build: avoid defining _GNU_SOURCE"
This reverts commit 2e6a8f260c.

Too many problems for now, such as with OSX and asprintf().
2014-07-10 09:25:37 +02:00
wm4 f8c2dd1b78 build: include <strings.h> for strcasecmp()
It happens to work without strings.h on glibc or with _GNU_SOURCE, but
the POSIX standard requires including <strings.h>.

Hopefully fixes OSX build.
2014-07-10 08:29:32 +02:00
wm4 e1f2540ede video/out: use strcmp() instead of strcasecmp() for equalizers
This makes it more consistent with the more important VOs.
2014-07-10 08:27:15 +02:00
wm4 1a1e631ccd build: deal with endian mess
There is no standard mechanism for detecting endianess. Doing it at
compile time in a portable way is probably hard. Doing it properly
with a configure check is probably hard too. Using the endian
definitions in <sys/types.h> (usually includes <endian.h>, which is
not available everywhere) works under circumstances, but the previous
commit broke it on OSX.

Ideally all code should be endian dependent, but that is not possible
due to the dependencies (such as FFmpeg, some video output APIs, some
audio output APIs).

Create a header osdep/endian.h, which contains various fallbacks.
Note that the last fallback uses libavutil; however, it's not clear
whether AV_HAVE_BIGENDIAN is a public symbol, or whether including
<libavutil/bswap.h> really makes it visible. And in fact we don't want
to pollute the namespace with libavutil definitions either. Thus it's
only the last fallback.
2014-07-10 00:58:56 +02:00
wm4 2e6a8f260c build: avoid defining _GNU_SOURCE
_GNU_SOURCE defines the kitchen sink, and also prefers glibc definitions
where glibc and POSIX conflict. Even though POSIX is worth less than
toilet paper, we still prefer the POSIX definitions.

rar.c needs asprintf(), which is _GNU_SOURCE-only. So we define
_GNU_SOURCE too specifically for this file.
2014-07-09 22:10:33 +02:00
wm4 5d3f1a17a7 DOCS/tech-overview: minor updates 2014-07-09 02:14:23 +02:00
wm4 93f63214e0 demux: remove accurate_seek field
It's unused now. (Only the dvd code used it until recently.)
2014-07-08 22:20:39 +02:00
Stefano Pigozzi 609187082f cocoa: simplify logic that returns used bits per color 2014-07-08 22:06:57 +02:00
Stefano Pigozzi b5bbb49a1a cocoa: move CGL context creation to gl_cocoa
This approach is similar to what other vo_opengl backends do. It can also be
used in the future to create another cocoa backend that renders offscreen
with IOSurfaces or FBOs.
2014-07-08 21:06:57 +02:00
wm4 469ec23f85 demux_disc: flush slave demuxer packet queue on resync
Technically needed, but not strictly. It seems it works without in
practice, because demux_lavf.c reads exactly one packet for fill_buffer
call, so there are never packets queued.
2014-07-07 19:24:22 +02:00
wm4 4981367021 cache, dvd, bluray: simplify stream time handling
We used a complicated and approximate method to cache the stream
timestamp, which is basically per-byte. (To reduce overhead, it was only
cached per 8KB-block, so it was approximate.)

Simplify this, and read/keep the timestamp only on discontinuities. This
is when demux_disc.c actually needs the timestamp.

Note that caching is currently disabled for dvdnav, but we still read
the timestamp only after some data is read. libdvdread behaves well, but
I don't know about libbluray, and the previous code also read the
timestamp only after reading data, so try to keep it safe.

Also drop the start_time offset. It wouldn't be correct anymore if used
with the cache, and the idea behind it wasn't very sane either (making
the player to offset the initial playback time to 0).
2014-07-07 19:09:37 +02:00
wm4 4d829d750c input: restore ability to combine mouse buttons
Key bindings are decided on the "down" event, so if the prefix is not
unique, the first/shortest will be used (e.g. when both "a" and "a-b"
are mapped, "a" will always be chosen).

This also breaks combining multiple mouse buttons. But it seems users
expect it to work, and it's indeed a bit strange that it shouldn't work,
as mouse bindings are emitted on the key "up" event, not "down" (if the
shorter binding didn't emit a command yet, why shouldn't it be
combinable).

Deal with this by clearing the key history when a command is actually
emitted, instead of when a command is decided. This means if both
MOUSE_BTN0 and MOUSE_BTN0-MOUSE_BTN1 are mapped, the sequence of holding
down BTN0 and then BTN1 will redecide the current command. On the other
hand, if BTN0 is released before BTN1 is pressed, the command is
emitted, and the key history is deleted. So the BTN1 press will not
trigger BTN0-BTN1.

For normal keys, nothing should change, because commands are emitted on
the "down" event already, so the key history is always cleared.

Might fix #902.

CC: @mpv-player/stable (if this fix is successful)
2014-07-07 18:18:41 +02:00
wm4 c07bae02e2 ao_null: disable latency emulation
Doesn't work quite right, and will pause for the latency duration after
seeking. Some users use --ao=null to disable audio (even though they
should probably use --no-audio), and this use-case is broken by this
issue too.

CC: @mpv-player/stable
2014-07-07 18:00:48 +02:00
wm4 19dde186a0 demux: print initial metadata
This was accidentally broken in 7e209185, and metadata was printed only
when it changed.
2014-07-07 18:00:41 +02:00
wm4 e2b0416ae1 osc: fix failure when using DVD menus
[osc] Lua error: mp.assdraw:31: attempt to concatenate local 's' (a nil value)
2014-07-07 18:00:41 +02:00
wm4 02ca42c7f1 lua: redo error handling, print backtraces
The original goal was just adding backtraces, however making the code
safe (especially wrt. to out of memory Lua errors) was hard. So this
commit also restructures error handling to make it conceptually simpler.
Now all Lua code is run inside a Lua error handling, except the calls
for creating and destroying the Lua context, and calling the wrapper C
function in a safe way.

The new error handling is actually conceptually simpler and more
correct, because you can just call any Lua function at initialization,
without having to worry whwther it throws errors or not.

Unfortunately, Lua 5.2 removes lua_cpcall(), so we have to emulate it.
There isn't any way to emulate it in a way that works the same on 5.1
and 5.2 with the same semantics in error cases, so ifdeffery is needed.
The debug.traceback() function also behaves weirdly differently between
the Lua versions, so its output is not as nice as it could be (empty
extra line).
2014-07-07 18:00:41 +02:00
wm4 0ea2bc2778 old-configure: fix Lua tests
This added every Lua that was found on the system.
2014-07-07 18:00:41 +02:00
wm4 acd60736ef Remove stream_pts stuff
This was used by DVD/BD, but its usage was removed with one of the
previous commits.
2014-07-06 19:05:59 +02:00
wm4 a90b5cfddf DOCS/client-api-changes: try to fix rst formatting again 2014-07-06 19:05:45 +02:00
wm4 f512604f02 dvd, bd: enable precise seeking
This should work now, at least kind of. Note that actual success depends
on the behavior of the underlying lib{dvd{nav,read},bluray}
implementation, which could go very wrong.

In the worst case, it could happen that the underlying implementation
seeks a long time before the seek target time. In this case, the player
will just decode video until the target time is reached, even if that
requires e.g. decoding 30 mintues of video before refreshing.

In the not-so-bad but still bad case, it would just miss the seek
target, and seek past it.

In my tests, it works mostly ok, though. Seeking backwards usually
fails, unless something like --hr-seek-demuxer-offset=1 is used (this
makes it seek to 1 second before the target, which may or may not be
enough to compensate for the DVD/BD imprecision).
2014-07-06 19:03:43 +02:00
wm4 7bf090ad24 dvd, bluray: handle playback display time handling differently
This is a pretty big change. Instead of doing a half-hearted passthrough
of the playback timestamp, we attempt to rewrite the raw MPEG timestamps
such that they match with the playback time.

We add the offset between raw start timestamp and playback time to the
packet timestamps. This is the easy part; but the problem is with
timestamp resets. We simply detect timestamp discontinuities by checking
whether they are more than 500ms apart (large enough for all video
faster than 2 FPS and audio with reasonable framesizes/samplerates), and
adjust the timestamp offset accordingly.

This should work pretty well. There may be some problems with subtitles.
If the first packet after a timestamp reset is a subtitle instead of
video, it will fail. Also, selecting multiple audio or video streams
won't work (but mpv doesn't allow selecting several anyway). Trying to
demux subtitles with no video stream enabled will probably fail.

Untested with Bluray, because I have no Bluray sample.

Background:

libdvdnav/libdvdread/libbluray make this relatively hard. They return a
raw MPEG (PS/TS) byte stream, and additionally to that provide a
function to retrieve the current "playback" time. The playback time is
what should be displayed to the user, while the MPEG timestamps can be
completely different. Even worse, the MPEG timestamps can reset. Since
we use the libavformat demuxer (instead of parsing the MPEG packets in
the DVD/BD code), it's hard to associate between these timestamps. As a
result, the time display is special cased in the playloop, and of low
quality (updates only all 1 or 2 seconds, sometimes is incorrect). The
fact that the stream cache can be between demuxer and the stream source
makes things worse.

All the libs seem to provide an event that tells whether timestamps are
resetting. But since this signalling is byte based, it's hard to connect
it to the demuxed MPEG packets. It might be possible to create some sort
of table mapping file positions to discontinuities and new timestamps.
(For simplicity, this table could be 2 entries large, sufficient to
catch all discontinuities if the distance between them is larger than
the total buffering.)
2014-07-06 19:03:12 +02:00
wm4 361be8385b stream_dvdnav: more debugging output 2014-07-06 19:03:05 +02:00
wm4 f3604fc3fb demux: fix a corner case related to demux_disc
It can happen that demux_fill_buffer() adds more than 1 packet, and then
the packets would add up. Affects demux_disc.c only (nothing else uses
this function).
2014-07-06 19:02:58 +02:00
wm4 e3a3b764c8 dvd: fix first subtitle with delayed subtitle streams
This was accidentally broken with moving the DVD code to demux_disc.c.

Also remove an abort() call meant for debugging.
2014-07-06 19:02:49 +02:00
wm4 1d55547adf stream: remove now unused STREAM_CTRL_GET_START_TIME
demux_disc.c takes care of this now.
2014-07-06 19:02:33 +02:00
wm4 de28876222 demux: minor simplification
Oops, should have been part of commit 37085788.
2014-07-06 19:02:21 +02:00
atomnuker e6643abc98 ao_pulse: set icon name
Will replace the generic XDG video icon inherited from media role.
2014-07-05 17:07:16 +02:00
wm4 6fcb34d887 vf_vapoursynth: reset error state on seeking
When seeking, we violently destroy the filter, because vapoursynth has
no proper API for terminating a video with unknown frame count. This
looks like an error to vapoursynth, and the error is returned via the
frame callbacks. The bug is that we remember this error state across
reinitialization, so on the first filter call after reinitialization, we
thought filtering the current frame failed. This caused a shift by 1
frame on each seek.

CC: @mpv-player/stable
2014-07-05 17:07:16 +02:00
wm4 d27a2bc546 build: allow compilation without any atomics
Not all compilers on all platforms have atomics available (even if they
could, technically speaking).

We don't use atomics that much, only the following things rely on it:
1. the audio pull code, and all audio outputs using it
2. updating global msg levels
3. reading log messages through the client API

Just disable 1. and 3. if atomics are not available. For 2., using fake-
atomics isn't too bad; at worst, message levels won't properly update
under certain situations (but most likely, it will work just fine).

This means if atomics are not available, the client API function
mpv_request_log_messages() will do nothing.

CC: @mpv-player/stable
2014-07-05 17:07:16 +02:00
wm4 49df035514 options: remove bogus replacement message for --fstype
CC: @mpv-player/stable
2014-07-05 17:07:16 +02:00
wm4 962b928192 options: add --autosub-match to option replacement list
CC: @mpv-player/stable
2014-07-05 17:07:16 +02:00
wm4 4f00c74491 player: don't use stream position as fallback for percent-pos
This should be unneeded, and the packet position is already sufficient
for this case.

Accessing the stream position directly is going to be a problem when the
stream is accessed from another thread later.
2014-07-05 17:07:15 +02:00
wm4 54a4a25fe9 tv: move demuxer parts to separate file
Now all demuxer implementations (at least demuxer API-wise) are in the
demux directory.
2014-07-05 17:07:15 +02:00
wm4 37085788e4 demux: minor simplification to internal API
Also some other unrelated minor changes.
2014-07-05 17:07:15 +02:00
wm4 de71b50249 dvd: move angle switching code
No need to provide a "nice" API for it; just do this stuff directly in
the command code.
2014-07-05 17:07:15 +02:00
wm4 0cc3594623 dvd: flush buffers properly on seek
Suggested by tholin on github issue #882.

This is not entirely clean, but the fields we're accessing might be
considered internal to libavformat. On the other hand, existence of the
fields is guaranteed by the ABI, and nothing in the libavformat doxygen
suggestes they're not allowed to be accessed.

CC: @mpv-player/stable
2014-07-05 17:07:15 +02:00
wm4 338004bcfc dvd, bluray, cdda: add demux_disc containing all related hacks
DVD and Bluray (and to some extent cdda) require awful hacks all over
the codebase to make them work. The main reason is that they act like
container, but are entirely implemented on the stream layer. The raw
mpeg data resulting from these streams must be "extended" with the
container-like metadata transported via STREAM_CTRLs. The result were
hacks all over demux.c and some higher-level parts.

Add a "disc" pseudo-demuxer, and move all these hacks and special-cases
to it.
2014-07-05 17:07:15 +02:00
wm4 4d2a4afdef discnav: fix a comment 2014-07-05 17:07:15 +02:00
wm4 942619c779 demux: set filepos field when dequeuing a packet
Otherwise the position can be too far ahead.
2014-07-05 17:07:15 +02:00
wm4 85eb2bee3a demux: cosmetics: minimize code 2014-07-05 17:07:15 +02:00
wm4 8d40b1e8ab demux: make start time a simple field
Simpler, especially for later changes.
2014-07-05 17:07:15 +02:00
wm4 7e209185f1 demux, stream: change metadata notification
(Again.)

This time, we simply make it event-based, as it should be. This is done
for both demuxer metadata and stream metadata.

For some ogg-over-icy streams, 2 updates are reported on stream start.
This is because libavformat reports an update right on start, while
including the same info in the "static" metadata. I don't know if that's
a bug or a feature.
2014-07-05 17:07:14 +02:00
wm4 58880c00ee demux: make replaygain per-track
It's unlikely that files with multiple audio tracks and with replaygain
actually happen, but this change might help avoid minor corner cases
with later changes.
2014-07-05 17:07:14 +02:00
wm4 a97256c1d5 demux: move packet functions to a separate source file 2014-07-05 17:07:14 +02:00
wm4 e4221f3189 demux: move packet list functions
Move them to the only place where they are used, demux_subreader.c.
2014-07-05 17:07:14 +02:00
wm4 18e6d07612 demux_lavf: for now, ignore the new libavformat image demuxers
Recently, libavformat added demuxers to open image files like normal
demuxers. This is a good thing, but for now they interfere with the
operation of demux_mf. Add them to the blacklist until there is a proper
solution.

(The list doesn't contain _all_ recognized image formats, just those
that might interfere with demux_mf.)

CC: @mpv-player/stable
2014-07-05 17:07:14 +02:00
wm4 5eb9039c6b demux_lavf: support OTF fonts in Matroska
Apparently it's FFmpeg only.
2014-07-05 17:07:14 +02:00
wm4 1713dc58f1 demux_lavf: don't dump transport stream programs
Probably useless.
2014-07-05 17:07:14 +02:00
wm4 78f3ba73b9 demux_lavf: cleanup debug output
Remove unnecessary prefix, remove some messages.
2014-07-05 17:07:14 +02:00
wm4 bc29e17bcf demux_lavf: fix read_seek return value
This returned a stream error value directly to libavformat, which can't
make sense. For example STREAM_ERROR (0) means success in libavformat
error codes. (The meaning of the libavformat read_seek return value is
underdocumented too.)
2014-07-05 17:07:14 +02:00
wm4 44d7499190 demux_mkv: cosmetics 2014-07-05 17:07:14 +02:00
wm4 e21ecaa18d DOCS, client API: add mpv release versions
The intention is to make it obvious which mpv releases certain changes
will apply to.

Also attempt to fix RST formatting of the list. This is not very proper,
but probably good enough.
2014-07-05 17:07:14 +02:00
Stefano Pigozzi 055bc74ed4 Merge pull request #909 from Nyx0uf/patch-1
OS X bundle: Add more imported UTI
2014-07-05 10:15:14 +02:00
Nyx0uf 22c3de3f8a OS X bundle: Add more imported UTI
Not that there are widely used formats, but it will allow to play them directly from the Finder.
2014-07-04 10:05:52 +02:00
tholin bc5e539d3b stream_dvdnav: check the length of all titles with dvdnav://longest
The last title was ignored before.

CC: @mpv-player/stable

Signed-off-by: wm4 <wm4@nowhere>
2014-07-04 02:24:50 +02:00
tholin f8a7517fb7 stream_dvdnav: free pointer to priv->filename on close
CC: @mpv-player/stable

Signed-off-by: wm4 <wm4@nowhere>
2014-07-04 02:24:50 +02:00
tholin 4bd75313d1 stream_dvdnav: make sure seeking bounds are within range
libdvdnav returns an error is the seek position is out of range.

CC: @mpv-player/stable

Signed-off-by: wm4 <wm4@nowhere>
2014-07-04 02:24:50 +02:00
wm4 fe4fbb5775 DOCS/client_api_examples: add a Qt example
This is pretty dumb and extremely basic. The main purpose is
demonstrating how to integrate mpv into the Qt GUI thread.
2014-07-04 02:24:49 +02:00
wm4 4fedf86b8a client API: allow calling mpv_terminate_destroy(NULL)
This is an oversight and a bug.

CC: @mpv-player/stable
2014-07-04 02:24:49 +02:00
wm4 4a5cfb4323 x11: avoid obscure behavior when --wid is partially garbage
Cast away the "extra" bits (since apparently Window/XID is always
32 bit unsigned). This is not striclty needed, because you're not
supposed to pass garbage to --wid, just because the upper bits are
possibly not interpreted. But if you do so, this change increases
consistency in behavior and removes a strange behavior that was
thought to be a bug.

Also see github issue #906.
2014-07-04 02:23:05 +02:00
Stefano Pigozzi 97f6d7f4ec ao_coreaudio: report hardware latency to ao_read_data
Commit a6a4cd2c88 added reporting of playout latency, this commit also adds
support for reporting hardware and constant audio unit latency.
2014-07-03 20:05:15 +02:00
Alessandro Ghedini 29b047da6f TOOLS/zsh.pl: complete URL schemes based on --list-protocols 2014-07-03 11:03:56 +02:00
Alessandro Ghedini 17d65f9aff TOOLS/zsh.pl: sort options in reverse order by length
This stops options that are prefixes of other options from blocking
completion of values for the longer ones.
2014-07-03 11:03:56 +02:00
Philip Sequeira e940afec15 TOOLS/zsh.pl: untabify 2014-07-03 11:03:56 +02:00
Philip Sequeira 7450a7f531 TOOLS/zsh.pl: fix _arguments line
Don't use _x_arguments, as we don't support X arguments.

Get rid of -s, because we don't support multiple single-letter options
in one argument.

Add -S, because we ignore options after "--".
2014-07-03 11:03:56 +02:00
Philip Sequeira bbc005825a TOOLS/zsh.pl: don't consume extra arguments
Completion now uses "--opt=value" instead of "--opt value". Once the
user presses space and starts a new argument, the option just
completed is out of the picture, whether or not it was given an
argument. This handles options with no arguments or optional arguments
much better; previously, completing such an option would effectively
disable completion for the next argument.

Custom completed options such as "--ao" and friends will no longer
claim to consume an extra argument.
2014-07-03 11:03:56 +02:00
Philip Sequeira fd09578f0f TOOLS/zsh.pl: escape all colons in option descriptions 2014-07-03 11:03:56 +02:00
wm4 4d9ce2993f command: include new "playback-time" property in update mechanism 2014-07-03 01:26:19 +02:00
wm4 0004aaf788 DOCS: add a file listing API changes for the client API 2014-07-03 01:26:19 +02:00
Stefano Pigozzi 0bda8f48e2 manpage: reflect new coreaudio changes 2014-07-02 23:17:44 +02:00
Stefano Pigozzi a6a4cd2c88 ao_coreaudio: report latency more correctly
Previous code was completly wrong. This still doesn't report the device
latency, but we report the buffer latency (as before the AO refactoring) and
the AudioUnit's latency (this is a new 'feature').

Apparently we can also report the device actual latency and we should also
calculate the actual sample rate of the audio device instead of using the
nominal sample rate, but I'll leave this for a later commit.
2014-07-02 23:17:44 +02:00
wm4 703de5d84e cache_file: use unicode on windows
This enables the MinGW Windows crap wrapper for fopen().
2014-07-02 22:01:56 +02:00
Stefano Pigozzi 4f5f034ba2 ao_coreaudio: move channel mapping away from utils
Channel mapping functions are only used in the AUHAL based coreaudio, so move
them there.
2014-07-02 21:43:08 +02:00
Stefano Pigozzi c8fc02612e ao_coreaudio: use mpv's internal pull API 2014-07-02 21:43:08 +02:00
Stefano Pigozzi d16e4b836a ao_coreaudio: remove useless comments 2014-07-02 21:43:08 +02:00
Stefano Pigozzi 0ffbd05e99 ao_coreaudio: rename init_lpcm -> init_audiounit 2014-07-02 21:43:08 +02:00
Stefano Pigozzi 80ec0ba6d0 ao_coreaudio: fill asbd with an helper function 2014-07-02 21:43:07 +02:00
Stefano Pigozzi fa85bfde69 ao_coreaudio: split control to helper functions 2014-07-02 21:43:07 +02:00
Stefano Pigozzi f317d24a39 ao_coreaudio: move device related functions to the new AO 2014-07-02 21:43:07 +02:00
Stefano Pigozzi a8ef70b0f8 ao_coreaudio: remove useless call to print_asbd 2014-07-02 21:43:07 +02:00
Stefano Pigozzi 041557b639 ao_coreaudio: move spdif code to a new AO
The mplayer1/2/mpv CoreAudio audio output historically contained both usage
of AUHAL APIs (these go through the CoreAudio audio server) and the Device
based APIs (used only for output of compressed formats in exclusive mode).

The latter is a very unwieldy and low level API and pretty much forces us to
write a lot of code for little workr. Also with the widespread of HDMI, the
actual need for outputting compressed audio directly to the device is getting
lower (it was very useful with S/PDIF for bandwidth constraints not allowing
a number if channels transmitted in LPCM).

Considering how invasive it is (uses hog/exclusive mode), the new AO
(`ao_coreaudio_device`) is not going to be autoprobed but the user will have
to select it.
2014-07-02 21:43:07 +02:00
wm4 7084e800be cache: clear DVD timestamps
When resizing the cache, the buffer for the DVD timestamps is
initialized with 0. This causes the player to always return playback
position 0 with any file format (not just DVD), and also makes all
relative seeks relative to position 0. Fix this by clearing the
timestamps explicitly.

Closes #899.

CC: @mpv-player/stable
2014-07-02 19:01:47 +02:00
wm4 6d38ad1410 x11: clear window only on initial map
Apparently clearing on every map can cause problems with vdpau when
switching virtual desktops and such. This was observed with at least
XMonad and nvidia-340.17. It's not observed on some other setups without
XMonad.

It's not clear why this happens. Normally, the window background is not
saved, so clearing should have no additional affect. It's a complete
mystery. Possible, the use of legacy X drawing commands (used to clear
the window) interferes with vdpau operation in non-trivial ways.

Work this around by clearing on initial map only. This probably only
hides the underlying issue, but good enough.

Closes #897.

CC: @mpv-player/stable
2014-07-02 02:07:06 +02:00
wm4 4b5fbb3ee0 command: remove some code duplication in cache properties
This also means that the printed size is always rounded to KBs, because
the cache properties are returned in KB. I think this doesn't matter
much. But if it does, the cache properties should probably changed to
return bytes in the first place.
2014-07-02 01:46:04 +02:00
wm4 94450bf410 command: cache can actually have full-size 0
Then it's simply empty.
2014-07-02 01:32:05 +02:00
Andrey Morozov b1969c0eba command: change cache perentage to float, add cache-free and cache-used 2014-07-02 01:28:11 +02:00
wm4 9fee8fd3b3 demux: drop AVI special code
I'm pretty sure libavformat does this automatically, and we don't have
other demuxers where this could happen.

Still, slightly "risky" - so let's see.
2014-07-02 00:32:46 +02:00
wm4 bb131f4c66 demux_mkv: minor improvement to overflow check
CC: @mpv-player/stable
2014-07-02 00:14:18 +02:00
wm4 9a210ca2d5 Audit and replace all ctype.h uses
Something like "char *s = ...; isdigit(s[0]);" triggers undefined
behavior, because char can be signed, and thus s[0] can be a negative
value. The is*() functions require unsigned char _or_ EOF. EOF is a
special value outside of unsigned char range, thus the argument to the
is*() functions can't be a char.

This undefined behavior can actually trigger crashes if the
implementation of these functions e.g. uses lookup tables, which are
then indexed with out-of-range values.

Replace all <ctype.h> uses with our own custom mp_is*() functions added
with misc/ctype.h. As a bonus, these functions are locale-independent.
(Although currently, we _require_ C locale for other reasons.)
2014-07-01 23:11:08 +02:00
wm4 0208ad4f3b demux: minor cleanups 2014-07-01 21:53:23 +02:00
Alessandro Ghedini 2224ac5190 README: fix link to release policy document 2014-06-30 23:23:50 +02:00
Alessandro Ghedini ab241c05c8 options: add --list-protocols option 2014-06-30 23:20:10 +02:00
Alessandro Ghedini 211ca98e9c build: set default cdrom and dvd devices on linux 2014-06-30 23:19:53 +02:00
wm4 1c0939cb80 options: fix --gapless-audio default value
It was intended to be set to "weak" (and that was even documented), but
the actual setting was "no".

Closes #890.

CC: @mpv-player/stable
2014-06-30 18:24:35 +02:00
wm4 dd9420471f demux_mkv: cosmetics 2014-06-29 23:28:47 +02:00
wm4 37251cef69 demux_mkv: add some overflow checks etc.
Some of these might be security relevant.

The RealAudio code was especially bad. I'm not sure if all RealAudio
stuff still plays correctly; I didn't have that many samples for
testing. Some checks might be unnecessary or overcomplicated compared
to the (obfuscated) nature of the code.

CC: @mpv-player/stable
2014-06-29 23:27:28 +02:00
Tsukasa OMOTO 1646584058 player: fix start position when specifying with percent 2014-06-29 20:39:49 +02:00
Tsukasa OMOTO 1aef780b6c options: support setting start time relative to start PTS
Signed-off-by: wm4 <wm4@nowhere>
2014-06-29 20:39:49 +02:00
Tsukasa OMOTO a73415584c player: make the time display relative to start PTS
This commit makes the playback start time always at time 0.

Signed-off-by: wm4 <wm4@nowhere>
2014-06-29 20:39:49 +02:00
wm4 7412257305 av_common: remove unneeded field
This is actually needed for encoding only, and not decoding. Drop it.
2014-06-29 20:39:32 +02:00
Mohammad Alsaleh 8b06fc86f3 af_volume: fix calculations including replay-gain
rgain is not an additive value. It's a multiplier/gain.

Previous behaviour produced negative level values in some cases
(when rgain < 1.0) which caused volume to be louder when its value
was lowered.

CC: @mpv-player/stable

Signed-off-by: Mohammad Alsaleh <CE.Mohammad.AlSaleh@gmail.com>
Signed-off-by: wm4 <wm4@nowhere>
2014-06-28 15:56:16 +02:00
wm4 88225d0afb sub: fix undefined behavior with dvd://
The string could get reallocated.

CC: @mpv-player/stable
2014-06-28 15:55:24 +02:00
wm4 6eb955e274 manpage: update config file locations
Also add some explanations how the config paths are determined.
2014-06-28 15:55:09 +02:00
wm4 07bc199e35 scripting: shorten a line
Also allows it to deal with NULL return values, which currently is not
needed, but may or may not be required at some point in the future (what
if malloc fails).
2014-06-26 19:56:45 +02:00
wm4 3e631b9cb8 config: use the same signature for win32/OSX specific path functions
Seems like a good idea, even if it's basically unused (yet).

Also document requirements on the functions (they're not obvious).

OSX changes untested.
2014-06-26 19:56:45 +02:00
wm4 7f55a39646 config: handle --no-config case directly in mp_config_dirs()
Requires less special-casing, and probably also avoids that starting mpv
with --no-config creates a config dir (even if nothing is loaded).
2014-06-26 19:56:45 +02:00
wm4 b4d64ac434 config, player: avoid some temporary talloc contexts
IMO a semi-bad concept, that the mpv code unfortunately uses way too
much.
2014-06-26 19:56:45 +02:00
wm4 3e1c0e5853 config: make passing talloc context optional for some functions
Until now, the config functions added various allocations to the user-
provided talloc context. Make it so that they're all under the returned
allocation instead. This allows avoiding having to create an extra
temporary context for some callers, and also avoids adding random memory
leaks by accidentally passing a NULL context.

mp_find_all_config_files() has to be changed not to return a pointer
into the middle array for this to work. Make it add paths in order
(instead of reverse), and then reverse the array entries after that.

Also remove the declarations for the win-specific private functions.
Remove STRNULL(); it's barely needed anymore and the functions are
not called with NULL filenames anymore.
2014-06-26 19:56:45 +02:00
wm4 0dcde951b9 player: create config dir if it doesn't exist
This was dropped in the commit adding XDG support, probably
accidentally.

Also normalize some whitespace.
2014-06-26 19:43:23 +02:00
wm4 236fcd3648 config: prefer the old config dir if it exists, but XDG doesn't
This means normally the XDG config dir will be used. But if the old
config dir (~/.mpv) exists and the XDG config dir does not, then don't
create it.

To simplify the code, also make mp_path_exists() accept NULL paths. In
that case it's considered as not existing. (Funnily, on Linux this
already worked, because the string is passed directly to the kernel,
and the kernel will just return EFAULT on invalid memory.)
2014-06-26 19:41:48 +02:00
wm4 c63378d41c player: remove some minor code duplication in config loader code
It's better to keep the logic in one place.

Also drop that a broken config file aborts loading of the player. I
don't see much reason for this, and it inflates the code slightly.
2014-06-26 19:37:26 +02:00
Kenneth Zhou cb250d490c Basic xdg directory implementation
Search $XDG_CONFIG_HOME and $XDG_CONFIG_DIRS for config files.
This also negates the need to have separate user and global variants of
mp_find_config_file()

Closes #864, #109.

Signed-off-by: wm4 <wm4@nowhere>
2014-06-26 19:37:25 +02:00
340 changed files with 17723 additions and 13040 deletions

No files matched your search

+6 -6
View File
@@ -20,12 +20,12 @@
/demux/ebml_types.h
/sub/osd_font.h
/player/lua/*.inc
/DOCS/man/*/mpv.1
/DOCS/man/*/mpv.aux
/DOCS/man/*/mpv.log
/DOCS/man/*/mpv.out
/DOCS/man/*/mpv.pdf
/DOCS/man/*/mpv.toc
/DOCS/man/mpv.1
/DOCS/man/mpv.aux
/DOCS/man/mpv.log
/DOCS/man/mpv.out
/DOCS/man/mpv.pdf
/DOCS/man/mpv.toc
/waf
/build
+15 -5
View File
@@ -1,5 +1,8 @@
language: c
os:
- linux
- osx
env:
- LIBAV=libav-stable
- LIBAV=libav-git
@@ -7,24 +10,31 @@ env:
- LIBAV=ffmpeg-git
compiler:
- clang
branches:
only:
- master
- ci
matrix:
exclude:
- os: osx
env: LIBAV=libav-stable
- os: osx
env: LIBAV=libav-git
- os: osx
env: LIBAV=ffmpeg-git
before_install: ./travis-deps libass-stable $LIBAV
script:
- ./bootstrap.py
- ./waf configure
- ./waf build
notifications-policy: &notifications-policy
on_success: change
on_failure: always
notifications:
email: false
irc:
channels:
- "irc.freenode.org#mpv-player-dev"
<<: *notifications-policy
on_success: change
on_failure: always
+49
View File
@@ -0,0 +1,49 @@
Introduction
============
This file lists all changes that can cause compatibility issues when using
mpv through the client API (libmpv and ``client.h``). Since the client API
interfaces to input handling (commands, properties) as well as command line
options, this list is interesting for other uses of mpv, such as the Lua
scripting interface, key bindings in ``input.rst``, or plain command line
usage.
Normally, changes to the C API that are incompatible to previous iterations
receive a major version bump (i.e. the first version number is increased),
while C API additions bump the minor version (i.e. the second number is
increased). Changes to properties/commands/options may also lead to a minor
version bump, in particular if they are incompatible.
The version number is the same as used for MPV_CLIENT_API_VERSION (see
``client.h`` how to convert between major/minor version numbers and the flat
32 bit integer).
Also, read the section ``Compatibility`` in ``client.h``.
API changes
===========
::
--- 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
measure until XEmbed is implemented and confirmed working.
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 is released ---
1.3 - add MPV_MAKE_VERSION()
1.2 - remove "stream-time-pos" property (no replacement)
1.1 - remap dvdnav:// to dvd://
- add "--cache-file", "--cache-file-size"
- add "--colormatrix-primaries" (and property)
- add "primaries" sub-field to image format properties
- add "playback-time" property
- extend the "--start" option; a leading "+", which was previously
insignificant is now significant
- add "cache-free" and "cache-used" properties
- OSX: the "coreaudio" AO spdif code is split into a separate AO
--- mpv 0.4.0 is released ---
1.0 - the API is declared stable
+117
View File
@@ -0,0 +1,117 @@
// 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.
#include "../../libmpv/client.h"
#include "shared.h"
#import <Cocoa/Cocoa.h>
@interface AppDelegate : NSObject <NSApplicationDelegate>
{
mpv_handle *mpv;
dispatch_queue_t queue;
}
@end
static void wakeup(void *);
@implementation AppDelegate
- (void) applicationDidFinishLaunching:(NSNotification *)notification {
// Read filename
NSArray *args = [NSProcessInfo processInfo].arguments;
if (args.count < 2) {
NSLog(@"Expected filename on command line");
exit(1);
}
NSString *filename = args[1];
// 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);
}
// 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"));
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:
// Clean up and shut down.
mpv_terminate_destroy(mpv);
mpv = NULL;
dispatch_async(dispatch_get_main_queue(), ^{
[[NSApplication sharedApplication] terminate:nil];
});
break;
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
{
[self shutdown];
return YES;
}
- (void) shutdown
{
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 new];
AppDelegate *delegate = [AppDelegate new];
app.delegate = delegate;
[app run];
}
return EXIT_SUCCESS;
}
+159
View File
@@ -0,0 +1,159 @@
// License: pick one of: public domain, WTFPL, ISC, Ms-PL, AGPLv3
// This example can be built with: qmake && make
#include <sstream>
#include <QFileDialog>
#include <QStatusBar>
#include <QMenuBar>
#include <QMenu>
#include <QGridLayout>
#include <QApplication>
#include "qtexample.h"
static void wakeup(void *ctx)
{
// This callback is invoked from any mpv thread (but possibly also
// recursively from a thread that is calling the mpv API). Just notify
// the Qt GUI thread to wake up (so that it can process events with
// mpv_wait_event()), and return as quickly as possible.
MainWindow *mainwindow = (MainWindow *)ctx;
QCoreApplication::postEvent(mainwindow, new QEvent(QEvent::User));
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
QMenu *menu = menuBar()->addMenu(tr("&File"));
QAction *on_open = new QAction(tr("&Open"), this);
on_open->setShortcuts(QKeySequence::Open);
on_open->setStatusTip(tr("Open a file"));
connect(on_open, SIGNAL(triggered()), this, SLOT(on_file_open()));
menu->addAction(on_open);
statusBar();
mpv = mpv_create();
if (!mpv)
throw "can't create mpv instance";
// Create a video child window. Force Qt to create a native window, and
// pass the window ID to the mpv wid option. This doesn't work on OSX,
// because Cocoa doesn't support this form of embedding.
mpv_container = new QWidget(this);
setCentralWidget(mpv_container);
mpv_container->setAttribute(Qt::WA_NativeWindow);
// 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-x11-keyboard on the manpage.
mpv_set_option_string(mpv, "input-x11-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);
// From this point on, the wakeup function will be called. The callback
// can come from any thread, so we use the Qt QEvent mechanism to relay
// the wakeup in a thread-safe way.
mpv_set_wakeup_callback(mpv, wakeup, this);
if (mpv_initialize(mpv) < 0)
throw "mpv failed to initialize";
}
void MainWindow::handle_mpv_event(mpv_event *event)
{
switch (event->event_id) {
case MPV_EVENT_PROPERTY_CHANGE: {
mpv_event_property *prop = (mpv_event_property *)event->data;
if (strcmp(prop->name, "time-pos") == 0) {
if (prop->format == MPV_FORMAT_DOUBLE) {
double time = *(double *)prop->data;
std::stringstream ss;
ss << "At: " << time;
statusBar()->showMessage(QString::fromStdString(ss.str()));
} else if (prop->format == MPV_FORMAT_NONE) {
// The property is unavailable, which probably means playback
// was stopped.
statusBar()->showMessage("");
}
}
break;
}
case MPV_EVENT_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_SHUTDOWN: {
mpv_terminate_destroy(mpv);
mpv = NULL;
break;
}
default: ;
// Ignore uninteresting or unknown events.
}
}
bool MainWindow::event(QEvent *event)
{
// QEvent::User is sent by wakeup().
if (event->type() == QEvent::User) {
// Process all events, until the event queue is empty.
while (mpv) {
mpv_event *event = mpv_wait_event(mpv, 0);
if (event->event_id == MPV_EVENT_NONE)
break;
handle_mpv_event(event);
}
return true;
}
return QMainWindow::event(event);
}
void MainWindow::on_file_open()
{
QString filename = QFileDialog::getOpenFileName(this, "Open file");
if (mpv) {
const QByteArray c_filename = filename.toUtf8();
const char *args[] = {"loadfile", c_filename.data(), NULL};
mpv_command_async(mpv, 0, args);
}
}
MainWindow::~MainWindow()
{
if (mpv)
mpv_terminate_destroy(mpv);
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
return a.exec();
}
+30
View File
@@ -0,0 +1,30 @@
#ifndef QTEXAMPLE_H
#define QTEXAMPLE_H
#include <QMainWindow>
#include <mpv/client.h>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
protected:
virtual bool event(QEvent *event);
private slots:
void on_file_open();
private:
QWidget *mpv_container;
mpv_handle *mpv;
void create_player();
void handle_mpv_event(mpv_event *event);
};
#endif // QTEXAMPLE_H
+12
View File
@@ -0,0 +1,12 @@
QT += core gui
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = qtexample
TEMPLATE = app
CONFIG += link_pkgconfig
PKGCONFIG = mpv
SOURCES += qtexample.cpp
HEADERS += qtexample.h
+1
View File
@@ -21,6 +21,7 @@ int main(int argc, char *argv[])
// 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-x11-keyboard", "yes");
int val = 1;
check_error(mpv_set_option(ctx, "osc", MPV_FORMAT_FLAG, &val));
+9
View File
@@ -26,6 +26,15 @@ created scripts to help ease the process. These are the two recommended methods:
Note that MinGW environments included in Linux distributions are often broken,
outdated and useless, and usually don't use MinGW-w64.
Additional dependencies
-----------------------
You need a pthread wrapper. It must be interoperable with native Windows
threads. pthreads-win32 or MinGW pthreads might work.
If you want ``--input-file=...`` to work, you need libwaio. It's available
from: git://midipix.org/waio
Example with MXE
----------------
+1 -1
View File
@@ -25,7 +25,7 @@ from the input video. Note that not all codecs and not all formats support VFR
encoding, and some which do have bugs when a target bitrate is specified - use
-ofps or -oautofps to force CFR encoding in these cases.
Of course, the options can be stored in a profile, like this .mpv/config
Of course, the options can be stored in a profile, like this .config/mpv/mpv.conf
section::
[myencprofile]
+20 -19
View File
@@ -72,15 +72,17 @@ Available filters are:
``tospdif=<yes|no>``
Output raw AC-3 stream if ``no``, output to S/PDIF for
passthrough if ``yes`` (default).
pass-through if ``yes`` (default).
``bitrate=<rate>``
The bitrate use for the AC-3 stream. Set it to 384 to get 384 kbps.
The default is 640. Some receivers might not be able to handle this.
Valid values: 32, 40, 48, 56, 64, 80, 96, 112, 128,
160, 192, 224, 256, 320, 384, 448, 512, 576, 640.
The special value ``default`` selects a default bitrate based on the
The special value ``auto`` selects a default bitrate based on the
input channel number:
:1ch: 96
@@ -92,7 +94,7 @@ Available filters are:
``minchn=<n>``
If the input channel number is less than ``<minchn>``, the filter will
detach itself (default: 5).
detach itself (default: 3).
``sweep[=speed]``
Produces a sine sweep.
@@ -101,7 +103,7 @@ Available filters are:
Sine function delta, use very low values to hear the sweep.
``sinesuppress[=freq:decay]``
Remove a sine at the specified frequency. Useful to get rid of the 50/60Hz
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>``
@@ -182,7 +184,7 @@ Available filters are:
``mpv --af=equalizer=11:11:10:5:0:-12:0:5:12:12 media.avi``
Would amplify the sound in the upper and lower frequency region
while canceling it almost completely around 1kHz.
while canceling it almost completely around 1 kHz.
``channels=nch[:routes]``
Can be used for adding, removing, routing and copying audio channels. If
@@ -263,9 +265,8 @@ Available filters are:
Filter for internal use only. Converts between 24-bit and 32-bit sample
formats.
``convertsignendian``
Filter for internal use only. Converts between signed/unsigned formats
and formats with different endian.
``convertsign``
Filter for internal use only. Converts between signed/unsigned formats.
``volume[=<volumedb>[:...]]``
Implements software volume control. Use this filter with caution since it
@@ -277,8 +278,8 @@ Available filters are:
once for every audio stream.
``<volumedb>``
Sets the desired gain in dB for all channels in the stream from -200dB
to +60dB, where -200dB mutes the sound completely and +60dB equals a
Sets the desired gain in dB for all channels in the stream from -200 dB
to +60 dB, where -200 dB mutes the sound completely and +60 dB equals a
gain of 1000 (default: 0).
``replaygain-track``
Adjust volume gain according to the track-gain replaygain value stored
@@ -311,7 +312,7 @@ Available filters are:
.. admonition:: Example
``mpv --af=volume=10.1 media.avi``
Would amplify the sound by 10.1dB and hard-clip if the sound level
Would amplify the sound by 10.1 dB and hard-clip if the sound level
is too high.
``pan=n:[<matrix>]``
@@ -368,8 +369,8 @@ Available filters are:
to the subwoofer.
``<fc>``
cutoff frequency in Hz for the low-pass filter (20Hz to 300Hz)
(default: 60Hz) For the best result try setting the cutoff frequency
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>``
@@ -381,7 +382,7 @@ Available filters are:
.. admonition:: Example
``mpv --af=sub=100:4 --audio-channels=5 media.avi``
Would add a subwoofer channel with a cutoff frequency of 100Hz to
Would add a subwoofer channel with a cutoff frequency of 100 Hz to
output channel 4.
``center``
@@ -409,7 +410,7 @@ Available filters are:
.. admonition:: Example
``mpv --af=surround=15 --audio-channels=4 media.avi``
Would add surround sound decoding with 15ms delay for the sound to
Would add surround sound decoding with 15 ms delay for the sound to
the rear speakers.
``delay[=[ch1,ch2,...]]``
@@ -437,8 +438,8 @@ Available filters are:
.. admonition:: Example
``mpv --af=delay=[10.5,10.5,0,0,7,0] media.avi``
Would delay front left and right by 10.5ms, the two rear channels
and the subwoofer by 0ms and the center channel by 7ms.
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
@@ -588,7 +589,7 @@ Available filters are:
tempo.
``mpv --af=scaletempo=stride=30:overlap=.50:search=10 media.ogg``
Would tweak the quality and performace parameters.
Would tweak the quality and performance parameters.
``mpv --af=format=float,scaletempo media.ogg``
Would make scaletempo use float code. Maybe faster on some
@@ -600,7 +601,7 @@ Available filters are:
1.2x.
``lavfi=graph``
Filter audio using ffmpeg's libavfilter.
Filter audio using FFmpeg's libavfilter.
``<graph>``
Libavfilter graph. See ``lavfi`` video filter for details - the graph
+27 -2
View File
@@ -23,7 +23,7 @@ normal driver parameters.
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 OSX systems, use ``--ao=coreaudio``.
(the latter being experimental). On OS X systems, use ``--ao=coreaudio``.
.. admonition:: Examples
@@ -53,6 +53,10 @@ Available audio output drivers are:
Set the index of the mixer channel (default: 0). Consider the output of
"``amixer scontrols``", then the index is the number that follows the
name of the element.
``non-interleaved``
Allow output of non-interleaved formats (if the audio decoder uses
this format). Currently disabled by default, because some popular
ALSA plugins are utterly broken with non-interleaved formats.
.. note::
@@ -110,7 +114,19 @@ Available audio output drivers are:
with fixed setups.
``coreaudio`` (Mac OS X only)
Native Mac OS X audio output driver
Native Mac OS X audio output driver using the AudioUnits and the CoreAudio
sound server.
``device_id=<id>``
ID of output device to use (0 = default device)
``help``
List all available output devices with their IDs.
``coreaudio_device`` (Mac OS X only)
Native Mac OS X audio output driver using direct device access and
exclusive mode (bypasses the sound server).
Supports only compressed formats (AC3 and DTS).
``device_id=<id>``
ID of output device to use (0 = default device)
@@ -137,6 +153,12 @@ Available audio output drivers are:
value makes the audio stream react faster, e.g. to playback speed
changes. Default: 250.
``latency-hacks=<yes|no>``
Enable hacks to workaround PulseAudio timing bugs (default: yes). If
enabled, mpv will do elaborate latency calculations on its own. If
disabled, it will use PulseAudio automatically updated timing
information. Disabling this might help with e.g. networked audio.
``portaudio``
PortAudio audio output driver. This works on all platforms, and has
extensive MS Windows support.
@@ -159,6 +181,9 @@ Available audio output drivers are:
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
1.2, but may require the ``SDL_AUDIODRIVER`` environment variable to be set
+37 -25
View File
@@ -19,14 +19,14 @@ General Changes for MPlayer to mpv
Linux 2.4 (including VIDIX)
* Large internal cleanups
* Removal of support for dead platforms
* New buildsystem
* No embedded copy of ffmpeg and other libraries
* New build system
* No embedded copy of FFmpeg and other libraries
* Better pause handling (do not unpause on a command)
* Better MKV support (such as ordered chapters)
* vo_vdpau improvements
* Precise seeking support
* Native OpenGL backend for OSX
* General OSX improvements
* Native OpenGL backend for OS X
* General OS X improvements
* Improvements in audio/video sync handling
* Cleaned up terminal output
* Gapless audio support (``--gapless-audio``)
@@ -35,14 +35,14 @@ General Changes for MPlayer to mpv
* OSS4 volume control
* More correct color reproduction (color matrix generation)
* Use libass for subtitle rendering by default (better quality)
* Generally preferring ffmpeg/libav over internal demuxers and decoders
* Generally preferring FFmpeg/Libav over internal demuxers and decoders
* Improvements when playing multiple files (``--fixed-vo``)
* Screenshot improvements (instant screenshots without 1-frame delay, allow
taking screenshots even with hardware decoding)
* Improved support for PulseAudio
* Generally improved MS Windows support (dealing with unicode filenames,
* Generally improved MS Windows support (dealing with Unicode file names,
improved ``--vo=direct3d``, improved window handling)
* Better OSD rendering (using libass). This has full unicode support, and
* Better OSD rendering (using libass). This has full Unicode support, and
languages like Arabic should be better supported.
* Cleaned up terminal output (nicer status line, less useless noise)
* Support for playing URLs of popular streaming sites directly
@@ -50,19 +50,19 @@ General Changes for MPlayer to mpv
* Improved OpenGL output (``--vo=opengl-hq``)
* Make ``--softvol`` default (**mpv** is not a mixer control panel)
* Improved support for .cue files
* Screenshot improvements (can save screenshots as JPG or PNG, configurable
filenames, support for taking screenshots with or without subtitles - the
* Screenshot improvements (can save screenshots as JPEG or PNG, configurable
file names, support for taking screenshots with or without subtitles - the
``screenshot`` video filter is not needed anymore, and should not be put
into the mpv config file)
* Removal of teletext support
* Removal of most builtin demuxers, using libavformat instead
* Removal of builtin network support, using libavformat instead (also,
* Removal of most built-in demuxers, using libavformat instead
* Removal of built-in network support, using libavformat instead (also,
support https via libavformat)
* Replace image VOs (``--vo=jpeg`` etc.) with ``--vo=image``
* Do not lose settings when playing a new file in the same player instance
* New location for config files, new name for the binary.
* Slave mode compatibility broken (see below)
* Encoding functionality (replacement for mencoder, see ``DOCS/encoding.rst``)
* Encoding functionality (replacement for MEncoder, see ``DOCS/encoding.rst``)
* Remove ``--vo=gif89a``, ``--vo=md5sum``, ``--vo=yuv4mpeg``, as encoding can
handle these use cases. For yuv4mpeg, for example, use:
``mpv input.mkv -o output.y4m --no-audio --oautofps --oneverdrop``.
@@ -71,10 +71,10 @@ General Changes for MPlayer to mpv
* Wayland support
* Support for precise scrolling which scales the parameter of commands. If the
input doesn't support precise scrolling the scale factor stays 1.
* OSX: Cocoa event loop is independent from mplayer's event loop, so user
* OS X: Cocoa event loop is independent from MPlayer's event loop, so user
actions like accessing menus and live resizing do not block the playback.
* OSX: Apple Remote support.
* OSX: Media Keys support.
* OS X: Apple Remote support.
* OS X: Media Keys support.
* Windows: Added WASAPI audio output.
* New OSD bar with chapter marks and not positioned in the middle of the video
(though this can be customized with the ``--osd-bar-align-y`` option).
@@ -99,7 +99,7 @@ General Changes for MPlayer to mpv
* Allow changing/adjusting video filters at runtime. (This is also used to make
the ``D`` key insert vf_yadif if deinterlacing is not supported otherwise.)
* Native VAAPI support
* OSX: VDA support using libavcodec hwaccel API insted of FFmpeg's decoder. Up
* OS X: VDA support using libavcodec hwaccel API instead of FFmpeg's decoder. Up
to 2-2.5x reduction in CPU usage.
* Make hardware decoding in general work with the ``opengl`` video output.
* Lua scripting (see `LUA SCRIPTING`_)
@@ -308,28 +308,40 @@ input.conf and Slave Commands
Slave mode
~~~~~~~~~~
* Slave mode is broken. This mode is entirely insane in the ``old`` versions of
MPlayer. A proper slave mode application needed tons of code and hacks to get
* Slave mode was removed. A proper slave mode application needed tons of code
and hacks to get
it right. The main problem is that slave mode is a bad and incomplete
interface, and to get around that, applications parsed output messages
intended for users. It is hard to know which messages exactly are parsed by
slave mode applications. This makes it virtually impossible to improve
terminal output intended for users without possibly breaking something.
This is absolutely insane, and **mpv** will not try to keep slave mode
compatible. If you are a developer of a slave mode application, contact us,
and a new and better protocol can be developed.
This is absolutely insane, and since initial improvements to **mpv** quickly
made slave mode incompatible to most applications, it was removed as useless
cruft. The client API (see below) is provided instead.
``--identify`` was already removed (``TOOLS/mpv_identify.sh`` is provided
instead), and ``--slave-broken`` might be removed in the future.
``--identify`` was replaced by the ``TOOLS/mpv_identify.sh`` wrapper script.
* For some time (until including release 0.4.x), mpv supported a
``--slave-broken`` option. The following options are equivalent:
::
--input-file=/dev/stdin --input-terminal=no
Assuming the system supports ``/dev/stdin``.
(The option was readded in 0.5.1 and sets exactly these options.)
* A JSON RPC protocol giving access to the client API is planned, but nothing
has emerged yet.
* **mpv** also provides a client API, which can be used to embed the player
by loading it as shared library. (See ``libmpv/client.h`` in the sources.)
It might also be possible to implement a custom slave mode-like protocol
using Lua scripting.
* A slave protocol is planned, but nothing has emerged yet.
Policy for Removed Features
---------------------------
+2 -2
View File
@@ -38,7 +38,7 @@ You can encode files from one format/codec to another using this facility.
``--oautofps``
Sets the output format time base to the guessed frame rate of the input
video (simulates mencoder behavior, useful for AVI; may cause frame drops).
video (simulates MEncoder behavior, useful for AVI; may cause frame drops).
Note that not all codecs and not all formats support VFR encoding, and some
which do have bugs when a target bitrate is specified - use ``--ofps`` or
``--oautofps`` to force CFR encoding in these cases.
@@ -74,7 +74,7 @@ You can encode files from one format/codec to another using this facility.
.. admonition:: Example
"``--oac=libmp3lame --oacopts=b=128000``"
selects 128kbps MP3 encoding.
selects 128 kbps MP3 encoding.
Options are managed in lists. There are a few commands to manage the
options list.
+110 -35
View File
@@ -4,12 +4,19 @@ INPUT.CONF
The input.conf file consists of a list of key bindings, for example::
s screenshot # take a screenshot with the s key
LEFT seek 15 # map the left-arrow key to seeking forward by 15 seconds
Each line maps a key to an input command. Keys are specified with their literal
value (upper case if combined with ``Shift``), or a name for special keys. For
example, ``a`` maps to the ``a`` key without shift, and ``A`` maps to ``a``
with shift.
The file is located in the mpv configuration directory (normally at
``~/.config/mpv/input.conf`` depending on platform). The default bindings are
defined here::
https://github.com/mpv-player/mpv/blob/master/etc/input.conf
A list of special keys can be obtained with
``mpv --input-keylist``
@@ -101,14 +108,14 @@ List of Input Commands
``revert_seek`` command itself.
``frame_step``
Play one frame, then pause.
Play one frame, then pause. Does nothing with audio-only playback.
``frame_back_step``
Go back by one frame, then pause. Note that this can be very slow (it tries
to be precise, not fast), and sometimes fails to behave as expected. How
well this works depends on whether precise seeking works correctly (e.g.
see the ``--hr-seek-demuxer-offset`` option). Video filters or other video
postprocessing that modifies timing of frames (e.g. deinterlacing) should
post-processing that modifies timing of frames (e.g. deinterlacing) should
usually work, but might make backstepping silently behave incorrectly in
corner cases. Using ``--hr-seek-framedrop=no`` should help, although it
might make precise seeking slower.
@@ -153,7 +160,9 @@ List of Input Commands
Take a single screenshot.
<each-frame>
Take a screenshot each frame. Issue this command again to stop taking
screenshots.
screenshots. Note that you should disable frame-dropping when using
this mode - or you might receive duplicate images in cases when a
frame was dropped.
``screenshot_to_file "<filename>" [subtitles|video|window]``
Take a screenshot and save it to a given file. The format of the file will
@@ -193,6 +202,8 @@ List of Input Commands
Stop playback of the current file, and play the new file immediately.
<append>
Append the file to the playlist.
<append-play>
Append the file, and if nothing is currently playing, start playback.
The third argument is a list of options and values which should be set
while the file is playing. It is of the form ``opt1=value1,opt2=value2,..``.
@@ -250,7 +261,7 @@ List of Input Commands
exactly as in the ``quit`` command.
``sub_add "<file>"``
Load the given subtitle file. It is not selected as current subtitle after
Load the given subtitle file. It is selected as current subtitle after
loading.
``sub_remove [<id>]``
@@ -258,7 +269,7 @@ List of Input Commands
the current track. (Works on external subtitle files only.)
``sub_reload [<id>]``
Reload the given subtitle tracks. If the ``id`` argument is missing, remove
Reload the given subtitle tracks. If the ``id`` argument is missing, reload
the current track. (Works on external subtitle files only.)
This works by unloading and re-adding the subtitle track.
@@ -317,6 +328,12 @@ List of Input Commands
Write the resume config file that the ``quit_watch_later`` command writes,
but continue playback normally.
``stop``
Stop playback and clear playlist. With default settings, this is
essentially like ``quit``. Useful for the client API: playback can be
stopped without terminating the player.
Input Commands that are Possibly Subject to Change
--------------------------------------------------
@@ -493,8 +510,8 @@ Input Commands that are Possibly Subject to Change
be used in input.conf to reassign such bindings.)
Undocumented commands: ``tv_last_channel`` (TV/DVB only), ``stop`` (questionable
use), ``get_property`` (?), ``vo_cmdline`` (experimental).
Undocumented commands: ``tv_last_channel`` (TV/DVB only), ``get_property`` (?),
``vo_cmdline`` (experimental).
Input Command Prefixes
----------------------
@@ -564,7 +581,7 @@ Property list
See ``--osd-level``.
``osd-scale`` (RW)
OSD font size multiplicator, see ``--osd-scale``.
OSD font size multiplier, see ``--osd-scale``.
``loop`` (RW)
See ``--loop``.
@@ -586,6 +603,18 @@ Property list
``${stream-end}``. For ordered chapters and such, the
size of the currently played segment is returned.)
``estimated-frame-count``
Total number of frames in current file.
.. note:: This is only an estimate. (It's computed from two unreliable
quantities: fps and stream length.)
``estimated-frame-number``
Number of current frame in current stream.
.. note:: This is only an estimate. (It's computed from two unreliable
quantities: fps and possibly rounded timestamps.)
``path``
Full path of the currently played file.
@@ -613,11 +642,6 @@ Property list
``stream-end``
Raw end position in bytes in source stream.
``stream-time-pos`` (RW)
Time position in source stream. This only works for DVD and Bluray. This
is probably never different from ``time-pos``, because ``time-pos`` is
forced to this value anyway.
``length``
Length of the current file in seconds. If the length is unknown, the
property is unavailable. Note that the file duration is not always exactly
@@ -632,8 +656,12 @@ Property list
disabled.
``drop-frame-count``
Frames dropped because they arrived to late. Unavailable if video
is disabled
Frames dropped because they arrived too late. Doesn't necessarily indicate
actual frame-drops, just the number of times the decoder was asked to drop.
Unavailable if video is disabled
``vo-drop-frame-count``
Frames dropped by VO (when using ``--framedrop=vo``).
``percent-pos`` (RW)
Position in current file (0-100). The advantage over using this instead of
@@ -641,9 +669,6 @@ Property list
estimating the playback position from the byte position, if the file
duration is not known.
``ratio-pos`` (RW)
Position in current file (0.0-1.0). higher precision that ``percent-pos``.
``time-pos`` (RW)
Position in current file in seconds.
@@ -658,6 +683,9 @@ Property list
``playtime-remaining``
``time-remaining`` scaled by the the current ``speed``.
``playback-time``
Return the playback time, which is the time difference between start PTS and current PTS.
``chapter`` (RW)
Current chapter number. The number of the first chapter is 0.
@@ -759,7 +787,7 @@ Property list
::
MPV_FORMAT_NODE_MAP
(key and string value for each metdata entry)
(key and string value for each metadata entry)
``chapter-metadata``
Metadata of current chapter. Works similar to ``metadata`` property. It
@@ -791,7 +819,7 @@ Property list
pauses itself due to low network cache.
``cache``
Network cache fill state (0-100).
Network cache fill state (0-100.0).
``cache-size`` (RW)
Total network cache size in KB. This is similar to ``--cache``. This allows
@@ -803,7 +831,26 @@ Property list
this easier, the cache resizing code will allocate the new cache while the
old cache is still allocated.
Don't use this when playing DVD or Bluray.
Don't use this when playing DVD or Blu-ray.
``cache-free`` (R)
Total free cache size in KB.
``cache-used`` (R)
Total used cache size in KB.
``cache-idle`` (R)
Returns ``yes`` if the cache is idle, which means the cache is filled as
much as possible, and is currently not reading more data.
``demuxer-cache-duration``
Approximate duration of video buffered in the demuxer, in seconds. The
guess is very unreliable, and often the property will not be available
at all, even if data is buffered.
``demuxer-cache-idle``
Returns ``yes`` if the demuxer is idle, which means the demuxer cache is
filled to the requested amount, and is currently not reading more data.
``paused-for-cache``
Returns ``yes`` when playback is paused because of waiting for the cache.
@@ -815,6 +862,12 @@ Property list
or enter idle mode), and in these cases the ``eof-reached`` property will
logically be cleared immediately after it's set.
``seeking``
Returns ``yes`` if the player is currently seeking, or otherwise trying
to restart playback. (It's possible that it returns ``yes`` while a file
is loaded, or when switching ordered chapter segments. This is because
the same underlying code is used for seeking and resyncing.)
``pts-association-mode`` (RW)
See ``--pts-association-mode``.
@@ -978,19 +1031,24 @@ Property list
"par" MPV_FORMAT_DOUBLE
"colormatrix" MPV_FORMAT_STRING
"colorlevels" MPV_FORMAT_STRING
"primaries" MPV_FORMAT_STRING
"chroma-location" MPV_FORMAT_STRING
"rotate" MPV_FORMAT_INT64
``dwidth``, ``dheight``
Video display size. This is the video size after filters and aspect scaling
have been applied. The actual video window size can still be different
from this.
from this, e.g. if the user resized the video window manually.
These have the same values as ``video-out-params/dw`` and
``video-out-params/dh``.
``video-out-params``
Same as ``video-params``, but after video filters have been applied. If
there are no video filters in use, this will contain the same values as
``video-params``. Note that this is still not necessarily what the video
window uses, since all real VOs do their own scaling.
window uses, since the user can change the window size, and all real VOs
do their own scaling independently from the filter chain.
Has the same sub-properties as ``video-params``.
@@ -1002,7 +1060,7 @@ Property list
Estimated/measured FPS of the video filter chain output. (If no filters
are used, this corresponds to decoder output.) This uses the average of
the 10 past frame durations to calculate the FPS. It will be inaccurate
if framedropping is involved (such as when framedrop is explicitly
if frame-dropping is involved (such as when framedrop is explicitly
enabled, or after precise seeking). Files with imprecise timestamps (such
as Matroska) might lead to unstable results.
@@ -1010,7 +1068,7 @@ Property list
Window size multiplier. Setting this will resize the video window to the
values contained in ``dwidth`` and ``dheight`` multiplied with the value
set with this property. Setting ``1`` will resize to original video size
(or to be exactly, the size the video filters output). ``2`` will set the
(or to be exact, the size the video filters output). ``2`` will set the
double size, ``0.5`` halves the size.
``video-aspect`` (RW)
@@ -1067,7 +1125,7 @@ Property list
See ``--sub-forced-only``.
``sub-scale`` (RW)
Subtitle font size multiplicator.
Subtitle font size multiplier.
``ass-use-margins`` (RW)
See ``--ass-use-margins``.
@@ -1079,8 +1137,8 @@ Property list
See ``--ass-style-override``.
``stream-capture`` (RW)
A filename, see ``--capture``. Setting this will start capture using the
given filename. Setting it to an empty string will stop it.
A filename, see ``--stream-capture``. Setting this will start capture using
the given filename. Setting it to an empty string will stop it.
``tv-brightness``, ``tv-contrast``, ``tv-saturation``, ``tv-hue`` (RW)
TV stuff.
@@ -1211,11 +1269,6 @@ Property list
"title" MPV_FORMAT_STRING
"time" MPV_FORMAT_DOUBLE
``quvi-format`` (RW)
See ``--quvi-format``. Cycling this property (``cycle``) will attempt to
cycle through known format, although currently this feature doesn't work
well at all.
``af`` (RW)
See ``--af`` and the ``af`` command.
@@ -1241,14 +1294,36 @@ Property list
``seekable``
Return whether it's generally possible to seek in the current file.
``osd-sym-cc``
Inserts the current OSD symbol as opaque OSD control code (cc). This makes
sense only with the ``show_text`` command or options which set OSD messages.
The control code is implementation specific and is useless for anything else.
``osd-ass-cc``
``${osd-ass-cc/0}`` disables escaping ASS sequences of text in OSD,
``${osd-ass-cc/1}`` enables it again. By default, ASS sequences are
escaped to avoid accidental formatting, and this property can disable
this behavior. Note that the properties return an opaque OSD control
code, which only makes sense for the ``show_text`` command or options
which set OSD messages.
.. admonition:: Example
--osd-status-msg='This is ${osd-ass-cc/0}{\\b1}bold text'
Any ASS override tags as understood by libass can be used.
Note that you need to escape the ``\`` character, because the string is
processed for C escape sequences before passing it to the OSD code.
``options/<name>`` (RW)
Read-only access to value of option ``--<name>``. Most options can be
changed at runtime by writing to this property. Note that many options
require reloading the file for changes to take effect. If there is an
equivalent property, prefer setting the property instead.
``write_watch_later_config``
Saves current playback position.
``property-list``
Return the list of top-level properties.
Property Expansion
------------------
+55 -17
View File
@@ -1,10 +1,16 @@
LUA SCRIPTING
=============
mpv can load Lua scripts. Scripts in ``~/.mpv/lua/`` will be loaded on program
start, or if passed to ``--lua``. mpv provides the builtin module ``mp``, which
provides functions to send commands to the mpv core and to retrieve information
about playback state, user settings, file information, and so on.
mpv can load Lua scripts. Scripts passed to the ``--lua`` option, or found in
the ``lua`` subdirectory of the mpv configuration directory (usually
``~/.config/mpv/lua/``) will be loaded on program start. mpv also appends the
``lua`` subdirectory to the end of Lua's path so you can import scripts from
there too. Since it's added to the end, don't name scripts you want to import
the same as Lua libraries because they will be overshadowed by them.
mpv provides the built-in module ``mp``, which provides functions to send
commands to the mpv core and to retrieve information about playback state, user
settings, file information, and so on.
These scripts can be used to control mpv in a similar way to slave mode.
Technically, the Lua code uses the client API internally.
@@ -27,12 +33,13 @@ allow users implement features which are not going to be added to the mpv core.
Mode of operation
-----------------
Your script will be loaded by the player at program start from ``~/.mpv/lua/``,
or ``--lua``, or in some cases, internally (like ``--osc``). Each script runs
in its own thread. Your script is first run "as is", and once that is done,
the event loop is entered. This event loop will dispatch events received by mpv
and call your own event handlers which you have registered with
``mp.register_event``, or timers added with ``mp.add_timeout`` or similar.
Your script will be loaded by the player at program start from the ``lua``
configuration subdirectory, from a path specified with the ``--lua`` option, or
in some cases, internally (like ``--osc``). Each script runs in its own
thread. Your script is first run "as is", and once that is done, the event loop
is entered. This event loop will dispatch events received by mpv and call your
own event handlers which you have registered with ``mp.register_event``, or
timers added with ``mp.add_timeout`` or similar.
When the player quits, all scripts will be asked to terminate. This happens via
a ``shutdown`` event, which by default will make the event loop return. If your
@@ -47,6 +54,15 @@ The event loop will wait for events and dispatch events registered with
``mp.register_event``. It will also handle timers added with ``mp.add_timeout``
and similar (by waiting with a timeout).
Since mpv 0.6.0, the player will wait until the script is fully loaded before
continuing normal operation. The player considers a script as fully loaded as
soon as it starts waiting for mpv events (or it exits). In practice this means
the player will more or less hang until the script returns from the main chunk
(and ``mp_event_loop`` is called), or the script calls ``mp_event_loop`` or
``mp.dispatch_events`` directly. This is done to make it possible for a script
to fully setup event handlers etc. before playback actually starts. In older
mpv versions, this happened asynchronously.
mp functions
------------
@@ -74,6 +90,10 @@ The ``mp`` module is preloaded, although it can be loaded manually with
These two commands are equivalent, except that the first version breaks
if the filename contains spaces or certain special characters.
Note that properties are *not* expanded. You can use either ``mp.command``,
the ``expand-properties`` prefix, or the ``mp.get_property`` family of
functions.
``mp.get_property(name [,def])``
Return the value of the given property as string. These are the same
properties as used in input.conf. See `Properties`_ for a list of
@@ -94,9 +114,9 @@ The ``mp`` module is preloaded, although it can be loaded manually with
will always result in a string.
``mp.get_property_bool(name [,def])``
Similar to ``mp.get_property``, but return the property value as boolean.
Similar to ``mp.get_property``, but return the property value as Boolean.
Returns a boolean on success, or ``def, error`` on error.
Returns a Boolean on success, or ``def, error`` on error.
``mp.get_property_number(name [,def])``
Similar to ``mp.get_property``, but return the property value as number.
@@ -109,7 +129,7 @@ The ``mp`` module is preloaded, although it can be loaded manually with
``mp.get_property_native(name [,def])``
Similar to ``mp.get_property``, but return the property value using the best
Lua type for the property. Most time, this will return a string, boolean,
Lua type for the property. Most time, this will return a string, Boolean,
or number. Some properties (for example ``chapter-list``) are returned as
tables.
@@ -124,7 +144,7 @@ The ``mp`` module is preloaded, although it can be loaded manually with
``mp.set_property_bool(name, value)``
Similar to ``mp.set_property``, but set the given property to the given
boolean value.
Boolean value.
``mp.set_property_number(name, value)``
Similar to ``mp.set_property``, but set the given property to the given
@@ -159,7 +179,7 @@ The ``mp`` module is preloaded, although it can be loaded manually with
(e.g. ``ctrl+a``).
After calling this function, key presses will cause the function ``fn`` to
be called (unless the user overmapped the key with another binding).
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``
@@ -197,7 +217,7 @@ The ``mp`` module is preloaded, although it can be loaded manually with
This will print the message when the key ``y`` is pressed. (``x`` will
still work, unless the user overmaps it.)
still work, unless the user remaps it.)
You can also explicitly send a message to a named script only. Assume the
above script was using the filename ``fooscript.lua``:
@@ -299,6 +319,20 @@ The ``mp`` module is preloaded, although it can be loaded manually with
with ``add_timeout()``), this starts the timer from the beginning,
using the initially configured timeout.
``timeout`` (RW)
This field contains the current timeout period. This value is not
updated as time progresses. It's only used to calculate when the
timer should fire next when the timer expires.
If you write this, you can call ``t:kill() ; t:resume()`` to reset
the current timeout to the new one. (``t:stop()`` won't use the
new timeout.)
``oneshot`` (RW)
Whether the timer is periodic (``false``) or fires just once
(``true``). This value is used when the timer expires (but before
the timer callback function fn is run).
``mp.get_opt(key)``
Return a setting from the ``--lua-opts`` option. It's up to the user and
@@ -359,7 +393,7 @@ are useful only in special situations.
control what the Lua script does (instead of being called by the default
event loop), you can set the global variable ``mp_event_loop`` to your
own function running the event loop. From your event loop, you should call
``mp.dispatch_events()`` to unqueue and dispatch mpv events.
``mp.dispatch_events()`` to dequeue and dispatch mpv events.
If the ``allow_wait`` parameter is set to ``true``, the function will block
until the next event is received or the next timer expires. Otherwise (and
@@ -468,6 +502,10 @@ This built-in module provides generic helper functions for Lua, and have
strictly speaking nothing to do with mpv or video/audio playback. They are
provided for convenience. Most compensate for Lua's scarce standard library.
``utils.getcwd()``
Returns the directory that mpv was launched from. On error, ``nil, error``
is returned.
``utils.readdir(path [, filter])``
Enumerate all entries at the given path on the filesystem, and return them
as array. Each entry is a directory entry (without the path).
+101 -63
View File
@@ -2,7 +2,7 @@ mpv
###
##############
a movie player
a media player
##############
:Copyright: GPLv2+
@@ -19,7 +19,7 @@ SYNOPSIS
DESCRIPTION
===========
**mpv** is a movie player based on MPlayer and mplayer2. It supports a wide variety of video
**mpv** is a media player based on MPlayer and mplayer2. It supports a wide variety of video
file formats, audio and video codecs, and subtitle types. Special input URL
types are available to read input from a variety of sources other than disk
files. Depending on platform, a variety of different video and audio output
@@ -40,16 +40,13 @@ Keyboard Control
----------------
LEFT and RIGHT
Seek backward/forward 10 seconds. Shift+arrow does a 1 second exact seek
Seek backward/forward 5 seconds. Shift+arrow does a 1 second exact seek
(see ``--hr-seek``).
UP and DOWN
Seek forward/backward 1 minute. Shift+arrow does a 5 second exact seek (see
``--hr-seek``).
PGUP and PGDWN
Seek forward/backward 10 minutes.
[ and ]
Decrease/increase current playback speed by 10%.
@@ -69,35 +66,26 @@ p / SPACE
Pause (pressing again unpauses).
\.
Step forward. Pressing once will pause movie, every consecutive press will
Step forward. Pressing once will pause, every consecutive press will
play one frame and then go into pause mode again.
,
Step backward. Pressing once will pause movie, every consecutive press will
Step backward. Pressing once will pause, every consecutive press will
play one frame in reverse and then go into pause mode again.
q / ESC
q
Stop playing and quit.
Q
Like ``q``, but store the current playback position. Playing the same file
later will resume at the old playback position if possible.
U
Stop playing (and quit if ``--idle`` is not used).
\+ and -
Adjust audio delay by +/- 0.1 seconds.
/ and *
Decrease/increase volume.
9 and 0
Decrease/increase volume.
( and )
Adjust audio balance in favor of left/right channel.
m
Mute sound.
@@ -107,19 +95,22 @@ m
\#
Cycle through the available audio tracks.
TAB (MPEG-TS and libavformat only)
Cycle through the available programs.
f
Toggle fullscreen (see also ``--fs``).
ESC
Exit fullscreen mode.
T
Toggle stay-on-top (see also ``--ontop``).
w and e
Decrease/increase pan-and-scan range.
o
o (also P)
Show progression bar, elapsed time and total duration on the OSD.
O
Toggle OSD states: none / seek / seek + timer / seek + timer + total time.
d
@@ -132,12 +123,12 @@ v
j and J
Cycle through the available subtitles.
F
Toggle displaying "forced subtitles".
x and z
Adjust subtitle delay by +/- 0.1 seconds.
Ctrl + and Ctrl -
Adjust audio delay by +/- 0.1 seconds.
V
Toggle subtitle VSFilter aspect compatibility mode. See
``--ass-vsfilter-aspect-compat`` for more info.
@@ -155,23 +146,18 @@ S
I
Show filename on the OSD.
P
Show progression bar, elapsed time and total duration on the OSD.
! and @
PGUP and PGDWN
Seek to the beginning of the previous/next chapter. In most cases,
"previous" will actually go to the beginning of the current chapter; see
``--chapter-seek-threshold``.
D (``--vo=vdpau``, ``--vf=yadif`` only)
Shift+PGUP and Shift+PGDWN
Seek backward or forward by 10 minutes. (This used to be mapped to
PGUP/PGDWN without Shift.)
D
Activate/deactivate deinterlacer.
A
Cycle through the available DVD angles.
c
Change YUV colorspace.
(The following keys are valid only when using a video output that supports the
corresponding adjustment, or the software equalizer (``--vf=eq``).)
@@ -187,24 +173,24 @@ corresponding adjustment, or the software equalizer (``--vf=eq``).)
7 and 8
Adjust saturation.
(The following keys are valid only on OSX.)
(The following keys are valid only on OS X.)
command + 0
Resize movie window to half its original size.
Resize video window to half its original size.
(On other platforms, you can bind keys to change the ``window-scale``
property.)
command + 1
Resize movie window to its original size.
Resize video window to its original size.
command + 2
Resize movie window to double its original size.
Resize video window to double its original size.
command + f
Toggle fullscreen (see also ``--fs``).
command + [ and command + ]
Set movie window alpha.
Set video window alpha.
(The following keys are valid if you have a keyboard with multimedia keys.)
@@ -223,12 +209,6 @@ support.)
h and k
Select previous/next channel.
n
Change norm.
u
Change channel list.
Mouse Control
-------------
@@ -285,7 +265,7 @@ need to escape special characters. To work this around, the path can be
additionally wrapped in the ``%n%string_of_length_n`` syntax (see above).
Some mpv options interpret paths starting with ``~``. Currently, the prefix
``~~/`` expands to the mpv configuration directory (usually ``~/.mpv/``).
``~~/`` expands to the mpv configuration directory (usually ``~/.config/mpv/``).
``~/`` expands to the user's home directory. (The trailing ``/`` is always
required.)
@@ -338,7 +318,7 @@ Location and Syntax
You can put all of the options in configuration files which will be read every
time mpv is run. The system-wide configuration file 'mpv.conf' is in your
configuration directory (e.g. ``/etc/mpv`` or ``/usr/local/etc/mpv``), the
user-specific one is ``~/.mpv/config``.
user-specific one is ``~/.config/mpv/mpv.conf``.
User-specific options override system-wide options and options given on the
command line override either. The syntax of the configuration files is
``option=<value>``; everything after a *#* is considered a comment. Options
@@ -373,13 +353,13 @@ File-specific Configuration Files
---------------------------------
You can also write file-specific configuration files. If you wish to have a
configuration file for a file called 'movie.avi', create a file named
'movie.avi.conf' with the file-specific options in it and put it in
``~/.mpv/``. You can also put the configuration file in the same directory
configuration file for a file called 'video.avi', create a file named
'video.avi.conf' with the file-specific options in it and put it in
``~/.config/mpv/``. You can also put the configuration file in the same directory
as the file to be played, as long as you give the ``--use-filedir-conf``
option (either on the command line or in your global config file). If a
file-specific configuration file is found in the same directory, no
file-specific configuration is loaded from ``~/.mpv``. In addition, the
file-specific configuration is loaded from ``~/.config/mpv``. In addition, the
``--use-filedir-conf`` option enables directory-specific configuration files.
For this, mpv first tries to load a mpv.conf from the same directory
as the file played and then tries to load any file-specific configuration.
@@ -434,6 +414,51 @@ taking screenshots is handled by the VOs, and adding the screenshot filter will
break hardware decoding. (The filter may still be useful for taking screenshots
at a certain point within the video chain when using multiple video filters.)
TERMINAL STATUS LINE
====================
During playback, mpv shows the playback status on the terminal. It looks like
something like this:
``AV: 00:03:12 / 00:24:25 (13%) A-V: -0.000``
The status line can be overridden with the ``--term-status-msg`` option.
The following is a list of things that can show up in the status line. Input
properties, that can be used to get the same information manually, are also
listed.
- ``AV:`` or ``V:`` (video only) or ``A:`` (audio only)
- The current time position in ``HH:MM:SS`` format (``playback-time`` property)
- The total file duration (or ``00:00:00`` if unknown) (``length`` property)
- Playback speed, e.g. `` x2.0``. Only visible if the speed is not normal. This
is the user-requested speed, and not the actual speed (usually they should
be the same, unless playback is too slow). (``speed`` property.)
- Playback percentage, e.g. ``(13%)``. How much of the file has been played.
Normally calculated out of playback position and duration, but can fallback
to other methods (like byte position) if these are not available.
(``percent-pos`` property.)
- The audio/video sync as ``A-V: 0.000``. This is the difference between
audio and video time. Normally it should be 0 or close to 0. If it's growing,
it might indicate a playback problem. (``avsync`` property.)
- Total A/V sync change, e.g. ``ct: -0.417``. Normally invisible. Can show up
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.
- Decoder-dropped video frames, e.g. ``SD: 2``. Shows up only if the count is
not 0. Normally should never show up, unless ``--framedrop`` is set to enable
this mode, and your CPU is too slow. (``drop-frame-count`` property.)
- VO-dropped video frames, e.g. ``D: 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. Also can be incremented on "hiccups" and when
the video frame couldn't be displayed on time. (``vo-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,
the second value shows *additional* data buffered in the stream cache in
kilobytes. (``demuxer-cache-duration`` and ``cached-used`` properties.)
PROTOCOLS
=========
@@ -449,8 +474,8 @@ 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,
you must mount the iso file as filesystem, and point ``--bluray-device``
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 directly.
``bdnav://[title][/device]``
@@ -539,15 +564,23 @@ ENVIRONMENT VARIABLES
There are a number of environment variables that can be used to control the
behavior of mpv.
``HOME``
Used to determine mpv config directory: ``$HOME/.mpv``
``HOME``, ``XDG_CONFIG_HOME``
Used to determine mpv config directory. If ``XDG_CONFIG_HOME`` is not set,
``$HOME/.config/mpv`` is used.
``$HOME/.mpv`` is always added to the list of config search paths with a
lower priority.
``XDG_CONFIG_DIRS``
If set, XDG-style system configuration directories are used. Otherwise,
the UNIX convention (``PREFIX/etc/mpv/``) is used.
``TERM``
Used to determine terminal type.
``MPV_HOME``
Directory where mpv looks for user settings. Overrides ``HOME``, and mpv
will try to load the config file as ``$MPV_HOME/config``.
will try to load the config file as ``$MPV_HOME/mpv.conf``.
``MPV_VERBOSE`` (see also ``-v`` and ``--msg-level``)
Set the initial verbosity level across all message modules (default: 0).
@@ -660,18 +693,23 @@ FILES
``/usr/local/etc/mpv/mpv.conf``
mpv system-wide settings (depends on ``--prefix`` passed to configure)
``~/.mpv/config``
``~/.config/mpv/mpv.conf``
mpv user settings
``~/.mpv/input.conf``
input bindings (see ``--input-keylist`` for the full list)
``~/.config/mpv/input.conf``
key bindings (see `INPUT.CONF`_ section)
``~/.mpv/lua/``
``~/.config/mpv/lua/``
All files in this directly are loaded as if they were passed to the
``--lua`` option. They are loaded in alphabetical order, and sub-directories
and files with no ``.lua`` extension are ignored. The ``--load-scripts=no``
option disables loading these files.
Note that the environment variables ``$XDG_CONFIG_HOME`` and ``$MPV_HOME`` can
override the standard directory ``~/.config/mpv/``.
Also, the old config location at ``~/.mpv/`` is still read, and if the XDG
variant does not exist, will still be preferred.
EXAMPLES OF MPV USAGE
=====================
@@ -689,7 +727,7 @@ Play only chapters 5, 6, 7:
Play only titles 5, 6, 7:
``mpv dvd://5-7``
Play a multiangle DVD:
Play a multi-angle DVD:
``mpv dvd://1 --dvd-angle=2``
Play from a different DVD device:
+1983 -1710
View File
File diff suppressed because it is too large. Load diff
+5 -5
View File
@@ -122,11 +122,11 @@ time remaining
left-click toggle between total and remaining time
============= ================================================
Keybindings
~~~~~~~~~~~
Key Bindings
~~~~~~~~~~~~
These keybindings are active by default if nothing else is already bound to
these keys. In case of collosision, the function needs to be bound to a
These key bindings are active by default if nothing else is already bound to
these keys. In case of collision, the function needs to be bound to a
different key. See `Script Commands`_ section.
============= ================================================
@@ -161,7 +161,7 @@ To avoid collisions with other scripts, all options need to be prefixed with
Example::
--lua-opts=osc-optionA=value1:osc-optionB=value2
--lua-opts=osc-optionA=value1,osc-optionB=value2
Configurable Options
+36 -24
View File
@@ -47,7 +47,7 @@ Available filters are:
``crop[=w:h:x:y]``
Crops the given part of the image and discards the rest. Useful to remove
black bands from widescreen movies.
black bands from widescreen videos.
``<w>,<h>``
Cropped width and height, defaults to original width and height.
@@ -55,7 +55,7 @@ Available filters are:
Position of the cropped picture, defaults to center.
``expand[=w:h:x:y:aspect:round]``
Expands (not scales) movie resolution to the given value and places the
Expands (not scales) video resolution to the given value and places the
unscaled original at coordinates x, y.
``<w>,<h>``
@@ -93,7 +93,7 @@ Available filters are:
``scale[=w:h:param:param2:chr-drop:noup:arnd``
Scales the image with the software scaler (slow) and performs a YUV<->RGB
colorspace conversion (see also ``--sws``).
color space conversion (see also ``--sws``).
All parameters are optional.
@@ -120,9 +120,9 @@ Available filters are:
0.33:0.33 Mitchell-Netravali spline
1.00:0.00 cubic B-spline
--sws=7 (gaussian): sharpness (0 (soft) - 100 (sharp))
--sws=7 (Gaussian): sharpness (0 (soft) - 100 (sharp))
--sws=9 (lanczos): filter length (1-10)
--sws=9 (Lanczos): filter length (1-10)
``<chr-drop>``
chroma skipping
@@ -222,8 +222,8 @@ Available filters are:
====================== =====================
``noformat[=fmt]``
Restricts the colorspace for the next filter without doing any conversion.
Unlike the format filter, this will allow any colorspace except the one
Restricts the color space for the next filter without doing any conversion.
Unlike the format filter, this will allow any color space except the one
you specify.
.. note:: For a list of available formats, see ``noformat=fmt=help``.
@@ -231,12 +231,23 @@ Available filters are:
``<fmt>``
Format name, e.g. rgb15, bgr24, 420p, etc. (default: 420p).
``pp[=[filter1[:option1[:option2...]]/[-]filter2...]]``
Enables the specified chain of postprocessing subfilters. Subfilters must
``pp=[filter string]``
Enables the specified chain of post-processing subfilters. Subfilters must
be separated by '/' and can be disabled by prepending a '-'. Each
subfilter and some options have a short and a long name that can be used
interchangeably, i.e. ``dr``/``dering`` are the same. All subfilters share
common options to determine their scope:
interchangeably, i.e. ``dr``/``dering`` are the same.
.. note::
Unlike in MPlayer or in earlier versions, you must quote the pp string
if it contains ``:`` characters, e.g. ``'--vf=pp=[...]'``.
.. admonition:: Warning
This filter is most likely useless on modern HD video. It might be
helpful with old low-resolution files.
All subfilters share common options to determine their scope:
``a/autoq``
Automatically switch the subfilter off if the CPU is too slow.
@@ -251,11 +262,6 @@ Available filters are:
``--vf=pp:help`` shows a list of available subfilters.
.. note::
Unlike in MPlayer or in earlier versions, you must quote the pp string
if it contains ``:`` characters, e.g. ``'--vf=pp=[...]'``.
Available subfilters are:
``hb/hdeblock[:difference[:flatness]]``
@@ -336,7 +342,7 @@ Available filters are:
filtering every second line with a (-1 4 2 4 -1) filter.
``l5/lowpass5``
Vertically applied FIR lowpass deinterlacing filter that deinterlaces
Vertically applied FIR low-pass deinterlacing filter that deinterlaces
the given block by filtering all lines with a (-1 2 6 2 -1) filter.
``fq/forceQuant[:quantizer]``
@@ -356,7 +362,7 @@ Available filters are:
.. note::
This filter is only available if FFmpeg/libav has been compiled
This filter is only available if FFmpeg/Libav has been compiled
with libpostproc enabled.
.. admonition:: Examples
@@ -443,7 +449,7 @@ Available filters are:
temporal noise (noise pattern changes between frames)
``uniform``
uniform noise (gaussian otherwise)
uniform noise (Gaussian otherwise)
``hq``
high quality (slightly better looking, slightly slower) - not available
@@ -503,7 +509,7 @@ Available filters are:
:1: linear interpolation (default)
``unsharp[=lx:ly:la:cx:cy:ca]``
unsharp mask / gaussian blur
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.
@@ -617,7 +623,7 @@ Available filters are:
``phase[=t|b|p|a|u|T|B|A|U][:v]``
Delay interlaced video by one field time so that the field order changes.
The intended use is to fix PAL movies that have been captured with the
The intended use is to fix PAL videos that have been captured with the
opposite field order to the film-to-video transfer. The options are:
``t``
@@ -769,8 +775,8 @@ Available filters are:
anaglyph red/cyan color (red filter on left eye, cyan filter on
right eye)
``arcd`` or ``anaglyph_red_cyan_dubois``
anaglyph red/cyan color optimized with the least squares
projection of dubois (red filter on left eye, cyan filter on right
anaglyph red/cyan color optimized with the least-squares
projection of Dubois (red filter on left eye, cyan filter on right
eye)
``agmg`` or ``anaglyph_green_magenta_gray``
anaglyph green/magenta gray (green filter on left eye, magenta
@@ -803,7 +809,7 @@ Available filters are:
``gradfun[=strength[:radius|:size=<size>]]``
Fix the banding artifacts that are sometimes introduced into nearly flat
regions by truncation to 8bit color depth. Interpolates the gradients that
regions by truncation to 8-bit color depth. Interpolates the gradients that
should go where the bands are, and dithers them.
``<strength>``
@@ -969,3 +975,9 @@ Available filters are:
Use default VDPAU scaling (default).
1-9
Apply high quality VDPAU scaling (needs capable hardware).
``buffer=<num>``
Buffer ``<num>`` frames in the filter chain. This filter is probably pretty
useless, except for debugging. (Note that this won't help smoothing out
latencies with decoding, because the filter will never output a frame if
the buffer isn't full, except on EOF.)
+61 -33
View File
@@ -38,36 +38,36 @@ Available video output drivers are:
.. note:: This driver is for compatibility with old systems.
``adaptor=<number>``
Select a specific XVideo adaptor (check xvinfo results).
Select a specific XVideo adapter (check xvinfo results).
``port=<number>``
Select a specific XVideo port.
``ck=<cur|use|set>``
Select the source from which the colorkey is taken (default: cur).
Select the source from which the color key is taken (default: cur).
cur
The default takes the colorkey currently set in Xv.
The default takes the color key currently set in Xv.
use
Use but do not set the colorkey from mpv (use the ``--colorkey``
Use but do not set the color key from mpv (use the ``--colorkey``
option to change it).
set
Same as use but also sets the supplied colorkey.
Same as use but also sets the supplied color key.
``ck-method=<man|bg|auto>``
Sets the colorkey drawing method (default: man).
Sets the color key drawing method (default: man).
man
Draw the colorkey manually (reduces flicker in some cases).
Draw the color key manually (reduces flicker in some cases).
bg
Set the colorkey as window background.
Set the color key as window background.
auto
Let Xv draw the colorkey.
Let Xv draw the color key.
``colorkey=<number>``
Changes the colorkey to an RGB value of your choice. ``0x000000`` is
Changes the color key to an RGB value of your choice. ``0x000000`` is
black and ``0xffffff`` is white.
``no-colorkey``
Disables colorkeying.
Disables color-keying.
``x11`` (X11 only)
Shared memory video output driver without hardware acceleration that works
@@ -82,7 +82,7 @@ Available video output drivers are:
.. note::
Earlier versions of mpv (and MPlayer, mplayer2) provided sub-options
to tune vdpau postprocessing, like ``deint``, ``sharpen``, ``denoise``,
to tune vdpau post-processing, like ``deint``, ``sharpen``, ``denoise``,
``chroma-deint``, ``pullup``, ``hqscaling``. These sub-options are
deprecated, and you should use the ``vdpaupp`` video filter instead.
@@ -173,7 +173,7 @@ Available video output drivers are:
to a YUV format before the VO. Sometimes useful to force availability
of certain YUV-only features, like video equalizer or deinterlacing.
Using the VDPAU frame queueing functionality controlled by the queuetime
Using the VDPAU frame queuing functionality controlled by the queuetime
options makes mpv's frame flip timing less sensitive to system CPU load and
allows mpv to start decoding the next frame(s) slightly earlier, which can
reduce jitter caused by individual slow-to-decode frames. However, the
@@ -259,13 +259,6 @@ Available video output drivers are:
.. note:: This driver is for compatibility with old systems.
``corevideo`` (Mac OS X 10.6 and later)
Mac OS X CoreVideo video output driver. Uses the CoreVideo APIs to fill
PixelBuffers and generate OpenGL textures from them (useful as a fallback
for ``opengl``).
.. note:: This driver is for compatibility with old systems.
``opengl``
OpenGL video output driver. It supports extended scaling methods, dithering
and color management.
@@ -282,7 +275,7 @@ Available video output drivers are:
Hardware decoding over OpenGL-interop is supported to some degree. Note
that in this mode, some corner case might not be gracefully handled, and
colorspace conversion and chroma upsampling is generally in the hand of
color space conversion and chroma upsampling is generally in the hand of
the hardware decoder APIs.
``lscale=<filter>``
@@ -297,6 +290,9 @@ Available video output drivers are:
``lanczos3``
Lanczos with radius=3.
``lanczos``
Generic Lanczos scaling filter. Set radius with ``lradius``.
``spline36``
This is the default when using ``opengl-hq``.
@@ -316,6 +312,14 @@ Available video output drivers are:
Mitchell-Netravali. The ``b`` and ``c`` parameters can be set with
``lparam1`` and ``lparam2``. Both are set to 1/3 by default.
``gaussian``
Gaussian filter with a parameter ``p`` for sharpness control.
``p`` can be set to float number between 1(blurry) and 100(sharp)
and has a default value of about 28.8 (see ``lparam1``).
Note that for extremely small value of ``p``, a large filter radius
might be required to avoid unintended artifacts (see ``lradius``).
There are some more filters. For a complete list, pass ``help`` as
value, e.g.::
@@ -329,6 +333,16 @@ Available video output drivers are:
``lparam2=<value>``
See ``lparam1``.
``lradius=<r>``
Set radius for filters listed below, must be a float number between 1.0
and 8.0. Defaults to be 2.0 if not specified.
``sinc``, ``lanczos``, ``blackman``, ``gaussian``
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).
``scaler-resizes-only``
Disable the scaler if the video image is not resized. In that case,
``bilinear`` is used instead whatever is set with ``lscale``. Bilinear
@@ -349,7 +363,7 @@ Available video output drivers are:
green-magenta
Convert side by side input to full-color green-magenta stereo.
quadbuffer
Convert side by side input to quadbuffered stereo. Only supported
Convert side by side input to quad buffered stereo. Only supported
by very few OpenGL cards.
``srgb``
@@ -430,6 +444,11 @@ Available video output drivers are:
RGB. If chroma is not subsampled, this option is ignored, and the
luma scaler is used instead. Setting this option is often useless.
``cparam1``, ``cparam2``, ``cradius``
Set filter parameters and radius for ``cscale``.
See ``lparam1``, ``lparam2`` and ``lradius``.
``fancy-downscaling``
When using convolution based filters, extend the filter size
when downscaling. Trades quality for reduced downscaling performance.
@@ -439,7 +458,16 @@ Available video output drivers are:
Borders will be distorted due to filtering.
``glfinish``
Call ``glFinish()`` before swapping buffers
Call ``glFinish()`` before and after swapping buffers (default: disabled).
Slower, but might help getting better results when doing framedropping.
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 only.
``sw``
Continue even if a software renderer is detected.
@@ -452,7 +480,7 @@ Available video output drivers are:
auto
auto-select (default)
cocoa
Cocoa/OSX
Cocoa/OS X
win
Win32/WGL
x11
@@ -479,7 +507,7 @@ Available video output drivers are:
``gamma=<0.0..10.0>``
Set a gamma value. If gamma is adjusted in other ways (like with
the ``--gamma`` option or keybindings and the ``gamma`` property), the
the ``--gamma`` option or key bindings and the ``gamma`` property), the
value is multiplied with the other gamma value.
Setting this value to 1.0 can be used to always enable gamma control.
@@ -487,7 +515,7 @@ Available video output drivers are:
``icc-profile=<file>``
Load an ICC profile and use it to transform linear RGB to screen output.
Needs LittleCMS2 support compiled in. This option overrides the ``srgb``
Needs LittleCMS 2 support compiled in. This option overrides the ``srgb``
property, as using both is somewhat redundant. It also enables linear
light scaling.
@@ -500,12 +528,12 @@ Available video output drivers are:
``icc-cache=<file>``
Store and load the 3D LUT created from the ICC profile in this file.
This can be used to speed up loading, since LittleCMS2 can take a while
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 transformations between colorspaces.
Specifies the ICC Intent used for transformations between color spaces.
This affects the rendering when using ``icc-profile`` or ``srgb`` and
also affects the way DCP XYZ content gets converted to RGB.
@@ -524,7 +552,7 @@ Available video output drivers are:
for mastering instead of the true curve. Most notably, anything in the
Apple ecosystem uses this approximation - including all programs
compatible with it. It's a sound idea to try enabling this flag first
when watching movies and shows to see if things look better that way.
when watching videos and shows to see if things look better that way.
This only affects the output when using either ``icc-profile`` or ``srgb``.
@@ -562,7 +590,7 @@ Available video output drivers are:
This is equivalent to::
--vo=opengl:lscale=spline36:dither-depth=auto:fbo-format=rgb16
--vo=opengl:lscale=spline36:dither-depth=auto:fbo-format=rgba16
Note that some cheaper LCDs do dithering that gravely interferes with
``opengl``'s dithering. Disabling dithering with ``dither-depth=no`` helps.
@@ -571,7 +599,7 @@ Available video output drivers are:
can achieve better quality or performance by changing the ``fbo-format``
suboption to ``rgb16f``, ``rgb32f`` or ``rgb``. Known problems include
Mesa/Intel not accepting ``rgb16``, Mesa sometimes not being compiled with
float texture support, and some OSX setups being very slow with ``rgb16``
float texture support, and some OS X setups being very slow with ``rgb16``
but fast with ``rgb32f``.
``opengl-old``
@@ -706,7 +734,7 @@ Available video output drivers are:
2
Convert side by side input to full-color green-magenta stereo.
3
Convert side by side input to quadbuffered stereo. Only supported
Convert side by side input to quad buffered stereo. Only supported
by very few OpenGL cards.
The following options are only useful if writing your own fragment programs.
@@ -748,7 +776,7 @@ Available video output drivers are:
auto
auto-select (default)
cocoa
Cocoa/OSX
Cocoa/OS X
win
Win32/WGL
x11
+15 -1
View File
@@ -24,11 +24,14 @@ Release procedure
- Create and/or update the ``VERSION`` file.
- 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``.
- Create a new GitHub release using the content of ``RELEASE_NOTES`` related to
the new version.
Release notes template
----------------------
@@ -36,6 +39,9 @@ Release notes template
Here is a template that can be used for writing the ``RELEASE_NOTES`` file.
```markdown
Release 0.X.Y
=============
Changes
-------
@@ -55,3 +61,11 @@ This listing is not complete. There are many more bug fixes and changes. The
complete change log can be viewed by running ``git log <start>..<end>`` in
the git repository.
```
Note that the "Release 0.X.Y" title should be removed when creating a new GitHub
release.
When creating a new point release its changes should be added on top of the
``RELEASE_NOTES`` file (with the appropriate title) so that all the changes in
the current 0.X branch will be included. This way the ``RELEASE_NOTES`` file
can be used by distributors as changelog for point releases too.
+47 -29
View File
@@ -1,4 +1,4 @@
This file intends to give a big picture of how mpv is structured.
This file intends to give a big picture overview of how mpv is structured.
player/*.c:
Essentially makes up the player applications, including the main() function
@@ -17,12 +17,12 @@ player/*.c:
* check help options etc. (call handle_help_options()), possibly exit
* call play_files() function that works down the playlist:
* run idle loop (idle_loop()), until there are files in the
playlist or an exit command was given (slave mode only)
playlist or an exit command was given (only if --idle it set)
* actually load and play a file in play_current_file():
* run all the dozens of functions to load the file and
initialize playback
* run a small loop that does normal playback, until the file is
done or a slave command terminates playback
done or a command terminates playback
(on each iteration, run_playloop() is called, which is rather
big and complicated - it decodes some audio and video on
each frame, waits for input, etc.)
@@ -31,15 +31,28 @@ player/*.c:
* loop, or exit if no next file or quit is requested
(see enum stop_play_reason)
* call exit_player_with_rc()
* run_playloop():
* calls fill_audio_out_buffers()
This checks whether new audio needs to be decoded, and pushes it
to the AO.
* calls write_video()
Decode new video, and push it to the VO.
* determines whether playback of the current file has ended
* determines when to start playback after seeks
* and calls a whole lot of other stuff
(Really, this function does everything.)
Things worth saying about the playback core:
- the currently played tracks are in sh_video and sh_audio
- most state is in MPContext (core.h), which is not available to the
subsystems
- the currently played tracks are in mpctx->current_tracks, and decoder
state in d_video/d_audio/d_sub
- the timeline stuff is used only with MKV ordered chapters (and some other
minor features: cue, edl)
- most state is in MPContext (mp_core.h), which is not available to the
subsystems
- the other subsystems rarely call back into the frontend, and the frontend
polls them instead (probably a good thing)
- one exceptions are wakeup callbacks, which notify a "higher" component
of a changed situation in a subsystem
I like to call the player/*.c files the "frontend".
@@ -82,7 +95,7 @@ talloc.h & talloc.c:
(See ta/README for details.)
player/command.c:
This contains the implementation for slave commands and properties.
This contains the implementation for client API commands and properties.
Properties are essentially dynamic variables changed by certain commands.
This is basically responsible for all user commands, like initiating
seeking, switching tracks, etc. It calls into other player/*.c files,
@@ -92,9 +105,10 @@ player/core.h:
Data structures and function prototypes for most of player/*.c. They are
usually not accessed by other parts of mpv for the sake of modularization.
Note that there are lots of global variables floating around everywhere
else. This is an ongoing transition, and eventually there should be no
global variables anymore.
player/client.c:
This implements the client API (libmpv/client.h). For the most part, this
just calls into other parts of the player. This also manages a ringbuffer
of events from player to clients.
options/options.h, options/options.c
options.h contains the global option struct MPOpts. The option declarations
@@ -102,7 +116,7 @@ options/options.h, options/options.c
options.c. Most default values for options and MPOpts are in
mp_default_opts at the end of options.c.
MPOpts is unfortunarely quite monolithic, and virtually accessed by
MPOpts is unfortunately quite monolithic, and virtually accessed by
everything.But some components (like video outputs and video filters) have
their own sub-option tables separate from MPOpts.
@@ -110,19 +124,18 @@ options/options.h, options/options.c
parser-mpcmd.c, and uses the option table in options.c.
input/input.c:
This translates keyboard input comming from libvo and other sources (such
as remote control devices like Apple IR or slave mode commands) to the
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
by playloop.c. They get pushed with run_command() to command.c.
Note that keyboard input and slave mode input are essentially the same
things. Just looking at input.conf should make this clear. (The other
direction of slave mode communication, mpv to application, consists of
random mp_msg() calls all over the code in all parts of the player.)
Note that keyboard input and commands used by the client API are the same.
The client API only uses the command parser though, and has its own queue
of input commands somewhere else.
common/msg.h:
All terminal output should go through mp_msg().
All terminal output must go through mp_msg().
stream/*:
File input is implemented here. stream.h/.c provides a simple stream based
@@ -181,7 +194,7 @@ video/out/:
vo_opengl can pick a windowing system at runtime, e.g. the same binary can
provide both X11 and Cocoa support on OSX.
VOs can be reconfigured at runtime. A config() call can change the video
VOs can be reconfigured at runtime. A vo_config() call can change the video
resolution and format, without destroying the window.
vo_vdpau and vo_opengl should be taken as reference.
@@ -203,9 +216,12 @@ audio/filter/:
audio/out/:
Audio outputs.
Unlike VOs, AOs can't be reconfigured on a format change. Without
--gapless-audio, even playing a new file will close and re-open the audio
device.
Unlike VOs, AOs can't be reconfigured on a format change. On audio format
changes, the AO will simply be closed and re-opened.
There are wrappers to support for two types of audio APIs: push.c and
pull.c. ao.c calls into one of these. They contain generic code to deal
with the data flow these APIs impose.
Note that mpv synchronizes the video to the audio. That's the reason
why buggy audio drivers can have a bad influence on playback quality.
@@ -213,17 +229,19 @@ audio/out/:
sub/:
Contains subtitle and OSD rendering.
sub.c/.h is actually the OSD code. It queries dec_sub.c to retrieve
osd.c/.h is actually the OSD code. It queries dec_sub.c to retrieve
decoded/rendered subtitles. osd_libass.c is the actual implementation of
the OSD text renderer (which uses libass, and takes care of all the tricky
fontconfig/freetype API usage and text layouting).
Subtitle loading is now in demux/ instead. demux_libass.c wraps loading
.ass subtitles via libass. demux_lavf.c loads most subtitle types via
FFmpeg. demux_subreader.c is the old MPlayer code. It's used as last
fallback, or to handle some text subtitle types on Libav. (It also can
load UTF-16 encoded subtitles without requiring the use of -sub-codepage.)
demux_subreader.c should eventually go away (maybe).
The VOs call osd.c to render OSD and subtitle (via e.g. osd_draw()). osd.c
in turn asks dec_sub.c for subtitle overlay bitmaps, which relays the
request to one of the sd_*.c subtitle decoders/renderers.
Subtitle loading is in demux/. The MPlayer subreader.c is mostly gone - parts
of it survive in demux_subreader.c. It's used as last fallback, or to handle
some text subtitle types on Libav. It should go away eventually. Normally,
subtitles are loaded via demux_lavf.c.
The subtitles are passed to dec_sub.c and the subtitle decoders in sd_*.c
as they are demuxed. All text subtitles are rendered by sd_ass.c. If text
+1 -1
View File
@@ -136,4 +136,4 @@ To contact the `mpv` team in private write to `mpv-team@googlegroups.com`.
[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/release-policy.md
[release-policy]: https://github.com/mpv-player/mpv/blob/master/DOCS/release-policy.md
+126
View File
@@ -0,0 +1,126 @@
Release 0.6.2
=============
Changes
-------
- The --ass-style-override option now requires a newer version of libass.
Bug fixes
---------
- Correctly signal EOF when using --frames.
- Strictly endorce the limit imposed by --frames (i.e. avoid producing an extra
frame at the end).
- Fix \x-style escaping when parsing commands.
- Correctly handle ^h key on the terminal (this should fix the when inserted
fromBackspace key on new versions of xterm).
- Don't put the player to sleep after audio reinit.
- Properly exit if both audio and video fail to initialize.
This listing is not complete. There are many more bug fixes and changes. The
complete change log can be viewed by running ``git log a6eb071..0a40fb0`` in
the git repository.
Release 0.6.1
=============
Changes
-------
- Don't show message on "osd" command by default (this essentially reverts a
change introduced in the last release).
- Add an alternative input configuration that reverts the key binding changes
introduced by previous releases (see etc/restore-old-bindings.conf in the
sources).
- Automatically install example input configuration files.
Bug fixes
---------
- Make stream language work with Bluray as well (the previous release
introduced this for DVDs, but it didn't work for Blurays).
- Don't try to create surfaces of size 0 in the VDPAU vo.
- Don't print audio/video init failure message twice.
- Fix playback on the root window on X11 (i.e. when using --wid=0).
- Fix the autodetection of the input format in the vf_stereo3d filter when mpv
is built against libav (this makes --video-stereo-mode work with libav as
well).
- Fix compilation with PulseAudio 1.0.
- Fix compilation with clang.
- Try harder to decode cover art picture only once.
- Fix cursor autohide (--cursor-autohide) with audio-only files on file change
(e.g. when skipping to the next playlist file).
This listing is not complete. There are many more bug fixes and changes. The
complete change log can be viewed by running ``git log 061f509..2ffdc0d`` in
the git repository.
Release 0.6.0
=============
Changes
-------
- Map ESC to exiting fullscreen.
- Run the vo inside its own thread.
- Enable the demuxer thread by default.
- Prefer the opengl vo over the vdpau one.
- Complete profile names in the zsh completion script.
- Raise dsound ao buffer size to 200ms and make it configurable.
- Bind ctrl+c to quit, so that it works both in the terminal and the player
window.
- Automatically load playlists without needing --load-unsafe-playlists or
--playlist. Unsafe URLs are still rejected (e.g. remote playlists can't load
local files).
- Remove quvi-format property (which never really worked).
- Wait until all Lua scripts are loaded on start.
- Use separate threads for input sources (terminal, lirc, joystick) instead of
using a central I/O loop.
- Complete values for options that take file names in the zsh completion script.
- Use libwaio for pipe input on Windows (if you want --input-file to work on
Windows you need libwaio as an additional dependency).
- Remove the --volstep option (users should change the argument to the "add"
function in input.conf instead).
- Always show the OSD message when changing volume, gamma, panscan, etc along
with the OSD bar.
- When changing a property always show it on the OSD (except for "pause" and
"fullscreen").
- Prefer the libavcodec decoder over libmpg123 for mp3 decoding (ffmpeg/libav
support for gapless audio works better for mpv's use-case).
- Allow passing number of loops to --loop-file.
- Change --keep-open option semantics to not terminate the player when playing
or seeking past the end of the file and there's no next file to be played.
- Disable the sndio ao by default and prefer other outputs even if it's enabled.
New features
------------
- Add new framedrop mode that limits the frequency of new video frames displayed
based on the display framerate (this is enabled by default, the old
decoder-based mode can be enabled with --framedrop=decoder).
- Add --demuxer-readahead-secs option to control the readahead buffer using a
duration value.
- Add estimated-frame-count and estimated-frame-number properties.
- Add --cache-secs option which overrides the value of --demuxer-readahead-secs
if the stream cache is active.
- Add demuxer-cache-duration and demuxer-cache-idle properties.
- Make --cache-file create a temporary file if the string "TMP" is passed
instead of a file name.
- Add support for Matroska 3D (if a file is marked as 3D using the StereoMode
element, an automatic conversion filter is added).
- Add --osd-playing-msg option to show a message on the OSD when the playback
starts.
- Add --media-title option to force the content of the media-title property.
- Add --osd-msg1, --osd-msg2 and --osd-msg3 options to override the OSD message
for the corresponding OSD level (before only level 3 could be overridden with
--osd-status-message).
- Add support for digital passthrough in the pulse ao.
- Add support for opening DVD and Bluray directories directly.
- Add --input-x11-keyboard option to control whether keyboard input should be
enabled on the X11 window ot not (this is disabled by default when using the
libmpv library).
This listing is not complete. There are many more bug fixes and changes. The
complete change log can be viewed by running ``git log a1be3cf..61ebe61`` in
the git repository.
+4 -4
View File
@@ -15,10 +15,10 @@ def is_user_lib(objfile, libname):
return not sys_re.match(libname) and \
not usr_re.match(libname) and \
not exe_re.match(libname) and \
not "libobjc" in libname and \
not "libSystem" in libname and \
not "libc" in libname and \
not "libgcc" in libname and \
not "libobjc." in libname and \
not "libSystem." in libname and \
not "libc." in libname and \
not "libgcc." in libname and \
not os.path.basename(objfile) in libname
def otool(objfile):
+2 -2
View File
@@ -5,8 +5,8 @@
conv() {
echo
identify -format "icon: %w %h" $1
convert $1 -depth 8 rgba:-
identify -format "icon: %w %h" "$1"
convert "$1" -depth 8 rgba:-
}
(echo "# File generated by gen-x11-icon.sh" ;
+59 -58
View File
@@ -1,23 +1,15 @@
#!/bin/sh
case "$0" in
*/*)
MYDIR=${0%/*}
;;
*)
MYDIR=.
;;
esac
: "${MPV:=mpv}"
: "${ILDETECT_MPV:=$MPV}"
: "${ILDETECT_MPVFLAGS:=--start=35% --length=35}"
: "${ILDETECT_DRY_RUN:=}"
: "${ILDETECT_QUIET:=}"
: "${ILDETECT_RUN_INTERLACED_ONLY:=}"
: "${ILDETECT_FORCE_RUN:=}"
: ${MPV:=mpv}
: ${ILDETECT_MPV:=$MPV}
: ${ILDETECT_MPV:=$MPV}
: ${ILDETECT_MPVFLAGS:=--start=35% --length=35}
: ${ILDETECT_DRY_RUN:=}
: ${ILDETECT_QUIET:=}
: ${ILDETECT_RUN_INTERLACED_ONLY:=}
: ${ILDETECT_FORCE_RUN:=}
: ${MAKE:=make}
# This script uses ffmpeg's "idet" filter for interlace detection. In the
# long run this should replace ildetect.sh+ildetect.so.
# exit status:
# 0 progressive
@@ -30,126 +22,135 @@ esac
testfun()
{
$ILDETECT_MPV "$@" \
--vf=lavfi="[idet]" --msg-level ffmpeg=v \
--vf-add=lavfi="[idet]" --msg-level ffmpeg=v \
--o= --vo=null --no-audio --untimed \
$ILDETECT_MPVFLAGS \
| { if [ -n "$ILDETECT_QUIET" ]; then cat; else tee /dev/stderr; fi } \
| grep "Parsed_idet_0: Multi frame detection: " | tail -n 1
| grep "Parsed_idet_0: Multi frame detection: "
}
judge()
{
out=`testfun "$@"`
tff=${out##* TFF:}; tff=${tff%% *}
bff=${out##* BFF:}; bff=${bff%% *}
progressive=${out##* Progressive:}; progressive=${progressive%% *}
undetermined=${out##* Undetermined:}; undetermined=${undetermined%% *}
case "$tff$bff$progressive$undetermined" in
*[!0-9]*)
echo >&2 "ERROR: Unrecognized idet output: $out"
exit 16
;;
esac
tff=0
bff=0
progressive=0
undetermined=0
while IFS= read -r out; do
tff1=${out##* TFF:}; tff1=${tff1%% *}
bff1=${out##* BFF:}; bff1=${bff1%% *}
progressive1=${out##* Progressive:}; progressive1=${progressive1%% *}
undetermined1=${out##* Undetermined:}; undetermined1=${undetermined1%% *}
case "$tff1$bff1$progressive1$undetermined1" in
*[!0-9]*)
printf >&2 'ERROR: Unrecognized idet output: %s\n' "$out"
exit 16
;;
esac
tff=$((tff + tff1))
bff=$((bff + bff1))
progressive=$((progressive + progressive1))
undetermined=$((undetermined + undetermined1))
done <<EOF
$(testfun "$@")
EOF
interlaced=$((bff + tff))
determined=$((interlaced + progressive))
if [ $undetermined -gt $determined ] || [ $determined -lt 250 ]; then
if [ "$undetermined" -gt "$determined" ] || [ "$determined" -lt 250 ]; then
echo >&2 "ERROR: Less than 50% or 250 frames are determined."
[ -n "$ILDETECT_FORCE_RUN" ] || exit 8
echo >&2 "Assuming interlacing."
if [ $tff -gt $((bff * 10)) ]; then
verdict=interlaced-tff
elif [ $bff -gt $((tff * 10)) ]; then
verdict=interlaced-bff
if [ "$tff" -gt $((bff * 10)) ]; then
verdict="interlaced-tff"
elif [ "$bff" -gt $((tff * 10)) ]; then
verdict="interlaced-bff"
else
verdict=interlaced
verdict="interlaced"
fi
elif [ $((interlaced * 20)) -gt $progressive ]; then
elif [ $((interlaced * 20)) -gt "$progressive" ]; then
# At least 5% of the frames are interlaced!
if [ $tff -gt $((bff * 10)) ]; then
verdict=interlaced-tff
elif [ $bff -gt $((tff * 10)) ]; then
verdict=interlaced-bff
if [ "$tff" -gt $((bff * 10)) ]; then
verdict="interlaced-tff"
elif [ "$bff" -gt $((tff * 10)) ]; then
verdict="interlaced-bff"
else
echo >&2 "ERROR: Content is interlaced, but can't determine field order."
[ -n "$ILDETECT_FORCE_RUN" ] || exit 8
echo >&2 "Assuming interlacing with default field order."
verdict=interlaced
verdict="interlaced"
fi
else
# Likely progrssive.
verdict=progressive
# Likely progressive
verdict="progressive"
fi
echo "$verdict"
printf '%s\n' "$verdict"
}
judge "$@"
judge "$@" --vf-clr
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
[ -n "$ILDETECT_RUN_INTERLACED_ONLY" ] || \
$ILDETECT_MPV "$@"
r=$?
[ $r -eq 0 ] || exit $(($r | 16))
[ $r -eq 0 ] || exit $((r | 16))
exit 0
;;
interlaced-tff)
judge "$@" --vf-pre=pullup --field-dominance=top
judge "$@" --vf-clr --vf-pre=pullup --field-dominance=top
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=pullup --field-dominance=top
r=$?
[ $r -eq 0 ] || exit $(($r | 16))
[ $r -eq 0 ] || exit $((r | 16))
exit 1
;;
*)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=yadif --field-dominance=top
r=$?
[ $r -eq 0 ] || exit $(($r | 16))
[ $r -eq 0 ] || exit $((r | 16))
exit 2
;;
esac
;;
interlaced-bff)
judge "$@" --vf-pre=pullup --field-dominance=bottom
judge "$@" --vf-clr --vf-pre=pullup --field-dominance=bottom
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=pullup --field-dominance=bottom
r=$?
[ $r -eq 0 ] || exit $(($r | 16))
[ $r -eq 0 ] || exit $((r | 16))
exit 1
;;
*)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=yadif --field-dominance=bottom
r=$?
[ $r -eq 0 ] || exit $(($r | 16))
[ $r -eq 0 ] || exit $((r | 16))
exit 2
;;
esac
;;
interlaced)
judge "$@" --vf-pre=pullup
judge "$@" --vf-clr --vf-pre=pullup
case "$verdict" in
progressive)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=pullup
r=$?
[ $r -eq 0 ] || exit $(($r | 16))
[ $r -eq 0 ] || exit $((r | 16))
exit 1
;;
*)
[ -n "$ILDETECT_DRY_RUN" ] || \
$ILDETECT_MPV "$@" --vf-pre=yadif
r=$?
[ $r -eq 0 ] || exit $(($r | 16))
[ $r -eq 0 ] || exit $((r | 16))
exit 2
;;
esac
+1
View File
@@ -265,6 +265,7 @@ sub define_matroska {
elem('DisplayUnit', '54b2', 'uint'),
elem('FrameRate', '2383e3', 'float'),
elem('ColourSpace', '2eb524', 'binary'),
elem('StereoMode', '53b8', 'uint'),
}),
elem('Audio', 'e1', {
elem('SamplingFrequency', 'b5', 'float'),
+16
View File
@@ -0,0 +1,16 @@
-- Test script for property change notification mechanism.
function format_property_val(v)
if type(v) == "table" then
return mp.format_table(v) -- undocumented function; might be removed
else
return tostring(v)
end
end
for i,name in ipairs(mp.get_property_native("property-list")) do
mp.observe_property(name, "native", function(name, val)
print("property '" .. name .. "' changed to '" ..
format_property_val(val) .. "'")
end)
end
@@ -1,4 +1,4 @@
-- Rebuild the status line as a lua script
-- Rebuild the terminal status line as a lua script
-- Be aware that this will require more cpu power!
-- Add a string to the status line
+127 -150
View File
@@ -17,157 +17,134 @@
# When multiple files were specified, their info will be put into FOO_* for the
# first file, FOO_1_* for the second file, FOO_2_* for the third file, etc.
case "$0" in
mpv_identify.sh|*/mpv_identify.sh)
# we are NOT being sourced
case "$1" in
'')
__midentify__main() {
case "$0" in
mpv_identify.sh|*/mpv_identify.sh)
# we are NOT being sourced
[ -n "$1" ] && set -- '' "$@"
;;
esac
if [ "$#" -lt 2 ]; then
cat >&2 <<EOF
Usage 1 (for humans only): $0 filename.mkv
will print all property values.
Note that this output really shouldn't be parsed, as the
format is subject to change.
Usage 2 (for use by scripts): see top of this file
NOTE: for mkv with ordered chapters, this may
not always identify the specified file, but the
file providing the first chapter. Specify
--no-ordered-chapters to prevent this.
EOF
return 2
fi
local LF="
"
local nextprefix="$1"
shift
if [ -n "$nextprefix" ]; then
# in case of error, we always want this unset
unset "${nextprefix}path"
fi
local allprops="
filename
path
stream-start
stream-end
stream-length
demuxer
length
chapters
editions
titles
audio
audio-bitrate
audio-codec
audio-format
channels
samplerate
video
angle
video-bitrate
video-codec
video-format
video-aspect
fps
width
height
dwidth
dheight
sub
"
# TODO add metadata support once mpv can do it
local propstr="X-MIDENTIFY-START:$LF"
local key
for key in $allprops; do
propstr="${propstr}X-MIDENTIFY: $key \${=$key}$LF"
key="$(printf '%s\n' "$key" | tr - _)"
unset "$nextprefix$key"
done
local fileindex=0
local prefix=
local line
while IFS= read -r line; do
case "$line" in
X-MIDENTIFY-START:)
if [ -n "$nextprefix" ]; then
prefix="$nextprefix"
if [ "$fileindex" -gt 0 ]; then
nextprefix="${prefix%${fileindex}_}"
fi
fileindex="$((fileindex+1))"
nextprefix="${nextprefix}${fileindex}_"
for key in $allprops; do
key="$(printf '%s\n' "$key" | tr - _)"
unset "$nextprefix$key"
done
else
if [ "$fileindex" -gt 0 ]; then
printf '\n'
fi
fileindex="$((fileindex+1))"
fi
;;
*)
set -- '' "$@"
X-MIDENTIFY:\ *)
local key="${line#X-MIDENTIFY: }"
local value="${key#* }"
key="${key%% *}"
key="$(printf '%s\n' "$key" | tr - _)"
if [ -n "$nextprefix" ]; then
if [ -z "$prefix" ]; then
echo >&2 "Got X-MIDENTIFY: without X-MIDENTIFY-START:"
elif [ -n "$value" ]; then
eval "$prefix$key"='"$value"'
fi
else
if [ -n "$value" ]; then
printf '%s=%s\n' "$key" "$value"
fi
fi
;;
esac
;;
esac
done <<EOF
$(${MPV:-mpv} --term-playing-msg="$propstr" --vo=null --ao=null \
--frames=1 --quiet --no-cache --no-config -- "$@")
EOF
}
if [ $# -lt 2 ]; then
echo >&2 "Usage 1 (for humans only): $0 filename.mkv"
echo >&2 "will print all property values."
echo >&2 "Note that this output really shouldn't be parsed, as the"
echo >&2 "format is subject to change."
echo >&2
echo >&2 "Usage 2 (for use by scripts): see top of this file"
echo >&2
echo >&2 "NOTE: for mkv with ordered chapters, this may"
echo >&2 "not always identify the specified file, but the"
echo >&2 "file providing the first chapter. Specify"
echo >&2 "--no-ordered-chapters to prevent this."
exit 1
fi
if [ -z "$MPV" ]; then
MPV="mpv"
fi
__midentify__LF="
"
__midentify__nextprefix=$1
shift
if [ -n "$__midentify__nextprefix" ]; then
# in case of error, we always want this unset
eval unset $__midentify__nextprefix'path'
fi
__midentify__allprops="
filename
path
stream-start
stream-end
stream-length
demuxer
length
chapters
editions
titles
audio
audio-bitrate
audio-codec
audio-format
channels
samplerate
video
angle
video-bitrate
video-codec
video-format
video-aspect
fps
width
height
dwidth
dheight
sub
"
# TODO add metadata support once mpv can do it
__midentify__propstr="X-MIDENTIFY-START:$__midentify__LF"
for __midentify__key in $__midentify__allprops; do
__midentify__propstr=$__midentify__propstr"X-MIDENTIFY: $__midentify__key \${=$__midentify__key}$__midentify__LF"
__midentify__key=`echo "$__midentify__key" | tr - _`
eval unset $__midentify__nextprefix$__midentify__key
done
__midentify__output=`$MPV --term-playing-msg="$__midentify__propstr" --vo=null --ao=null --frames=1 --quiet --no-cache --no-config "$@"`
__midentify__fileindex=0
__midentify__prefix=
while :; do
case "$__midentify__output" in
'')
break
;;
*$__midentify__LF*)
__midentify__line=${__midentify__output%%$__midentify__LF*}
__midentify__output=${__midentify__output#*$__midentify__LF}
;;
*)
__midentify__line=$__midentify__output
__midentify__output=
;;
esac
case "$__midentify__line" in
X-MIDENTIFY-START:)
if [ -n "$__midentify__nextprefix" ]; then
__midentify__prefix=$__midentify__nextprefix
if [ $__midentify__fileindex -gt 0 ]; then
__midentify__nextprefix=${__midentify__prefix%$__midentify__fileindex\_}
fi
__midentify__fileindex=$(($__midentify__fileindex+1))
__midentify__nextprefix=$__midentify__nextprefix$__midentify__fileindex\_
for __midentify__key in $__midentify__allprops; do
__midentify__key=`echo "$__midentify__key" | tr - _`
eval unset $__midentify__nextprefix$__midentify__key
done
else
if [ $__midentify__fileindex -gt 0 ]; then
echo
fi
__midentify__fileindex=$(($__midentify__fileindex+1))
fi
;;
X-MIDENTIFY:\ *)
__midentify__key=${__midentify__line#X-MIDENTIFY:\ }
__midentify__value=${__midentify__key#* }
__midentify__key=${__midentify__key%% *}
__midentify__key=`echo "$__midentify__key" | tr - _`
if [ -n "$__midentify__nextprefix" ]; then
if [ -z "$__midentify__prefix" ]; then
echo >&2 "Got X-MIDENTIFY: without X-MIDENTIFY-START:"
elif [ -n "$__midentify__value" ]; then
eval $__midentify__prefix$__midentify__key=\$__midentify__value
fi
else
if [ -n "$__midentify__value" ]; then
echo "$__midentify__key=$__midentify__value"
fi
fi
;;
esac
done
unset __midentify__fileindex
unset __midentify__allprops
unset __midentify__key
unset __midentify__LF
unset __midentify__line
unset __midentify__output
unset __midentify__nextprefix
unset __midentify__prefix
unset __midentify__propstr
unset __midentify__value
__midentify__main "$@"
@@ -624,6 +624,90 @@
</array>
</dict>
</dict>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.movie</string>
</array>
<key>UTTypeDescription</key>
<string>AVC raw stream</string>
<key>UTTypeIconFile</key>
<string>document.icns</string>
<key>UTTypeIdentifier</key>
<string>io.mpv.h264</string>
<key>UTTypeReferenceURL</key>
<string>http://www.itu.int/rec/T-REC-H.264</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>264</string>
</array>
</dict>
</dict>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.movie</string>
</array>
<key>UTTypeDescription</key>
<string>HEVC raw stream</string>
<key>UTTypeIconFile</key>
<string>document.icns</string>
<key>UTTypeIdentifier</key>
<string>io.mpv.hevc</string>
<key>UTTypeReferenceURL</key>
<string>http://hevc.info</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>hevc</string>
</array>
</dict>
</dict>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.movie</string>
</array>
<key>UTTypeDescription</key>
<string>YUV stream</string>
<key>UTTypeIconFile</key>
<string>document.icns</string>
<key>UTTypeIdentifier</key>
<string>io.mpv.yuv</string>
<key>UTTypeReferenceURL</key>
<string>http://en.wikipedia.org/wiki/YUV</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>yuv</string>
</array>
</dict>
</dict>
<dict>
<key>UTTypeConformsTo</key>
<array>
<string>public.movie</string>
</array>
<key>UTTypeDescription</key>
<string>YUV4MPEG2 stream</string>
<key>UTTypeIconFile</key>
<string>document.icns</string>
<key>UTTypeIdentifier</key>
<string>io.mpv.y4m</string>
<key>UTTypeReferenceURL</key>
<string>http://wiki.multimedia.cx/index.php?title=YUV4MPEG2</string>
<key>UTTypeTagSpecification</key>
<dict>
<key>public.filename-extension</key>
<array>
<string>y4m</string>
</array>
</dict>
</dict>
<dict>
<key>UTTypeConformsTo</key>
<array>
+31 -18
View File
@@ -18,10 +18,11 @@ e.g.:
Currently, the following event types are supported:
'start' <name> start of the named event
'end' <name> end of the named event
'value' <float> <name> a normal value (as opposed to event)
<event> singular event
'start' <name> start of the named event
'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
<name> singular event
"""
@@ -29,19 +30,32 @@ class G:
events = {}
sevents = [] # events, deterministically sorted
start = None
# 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:
return "o"
m = G.markers[0]
G.markers = G.markers[1:]
return m
class Event:
pass
def get_event(event):
def get_event(event, evtype):
if event not in G.events:
e = Event()
G.events[event] = e
e.name = event
e.vals = []
e.type = "unknown"
e.type = evtype
e.marker = "o"
e.numid = len(G.events)
G.sevents = list(G.events.values())
G.sevents.sort(key=lambda x: x.name)
if e.type == "event-signal":
e.marker = find_marker()
return G.events[event]
for line in [line.split("#")[0].strip() for line in open(filename, "r")]:
@@ -54,30 +68,29 @@ for line in [line.split("#")[0].strip() for line in open(filename, "r")]:
G.start = ts
ts = ts - G.start
if event.startswith("start "):
e = get_event(event[6:])
e.type = "event"
e = get_event(event[6:], "event")
e.vals.append((ts, 0))
e.vals.append((ts, 1))
elif event.startswith("end "):
e = get_event(event[4:])
e.type = "event"
e = get_event(event[4:], "event")
e.vals.append((ts, 1))
e.vals.append((ts, 0))
elif event.startswith("value "):
_, val, name = event.split(" ", 2)
val = float(val)
e = get_event(name)
e.type = "value"
e = get_event(name, "value")
e.vals.append((ts, val))
elif event.startswith("event-timed "):
_, val, name = event.split(" ", 2)
val = int(val) / 1000 - G.start
e = get_event(name, "event-signal")
e.vals.append((val, 1))
else:
e = get_event(event)
e.type = "event-signal"
e = get_event(event, "event-signal")
e.vals.append((ts, 1))
ao_events = ["ao fill", "audio wait"]
for e in G.sevents:
if e.name in ao_events:
e.vals = [(x, y * 0.5) for (x, y) in e.vals]
e.vals = [(x, y * e.numid / len(G.events)) for (x, y) in e.vals]
plot.hold(True)
mainpl = plot.subplot(2, 1, 1)
@@ -89,7 +102,7 @@ for e in G.sevents:
plot.subplot(2, 1, 1)
pl, = plot.plot([x for x,y in e.vals], [y for x,y in e.vals], label=e.name)
if e.type == "event-signal":
plot.setp(pl, marker = "o", linestyle = "None")
plot.setp(pl, marker = e.marker, linestyle = "None")
legend.append(pl)
plot.subplot(2, 1, 1)
plot.legend(legend, [pl.get_label() for pl in legend])
+15 -20
View File
@@ -23,10 +23,11 @@ Note that you can control the mpv instance by writing to the command fifo:
echo "cycle fullscreen" > /tmp/umpv-fifo-*
Note: you can supply custom options with the UMPV_OPTIONS environment variable.
The environment variable will be split on whitespace, and each item is
passed as option to mpv _if_ the script starts mpv. If mpv is not started
by the script (i.e. mpv is already running), the options will be ignored.
Note: you can supply custom mpv path and options with the MPV environment
variable. The environment variable will be split on whitespace, and the
first item is used as path to mpv binary and the rest is passed as options
_if_ the script starts mpv. If mpv is not started by the script (i.e. mpv
is already running), this will be ignored.
Warning:
@@ -45,21 +46,17 @@ import fcntl
import stat
import string
if len(sys.argv) < 1:
sys.exit(1)
files = sys.argv[1:]
# this is about the same method mpv uses to decide this
# this is the same method mpv uses to decide this
def is_url(filename):
parts = filename.split(":", 1)
parts = filename.split("://", 1)
if len(parts) < 2:
return False
# protocol prefix has no special characters => it's an URL
allowed_symbols = string.ascii_letters + string.digits + '_'
prefix = parts[0]
for c in prefix:
if string.ascii_letters.find(c) < 0:
return False
return True
return all(map(lambda c: c in allowed_symbols, prefix))
# make them absolute; also makes them safe against interpretation as options
def make_abs(filename):
@@ -68,9 +65,6 @@ def make_abs(filename):
return filename
files = [make_abs(f) for f in files]
opts_env = os.getenv("UMPV_OPTIONS")
opts_env = opts_env.split() if opts_env else []
FIFO = "/tmp/umpv-fifo-" + os.getenv("USER")
fifo_fd = -1
@@ -89,7 +83,8 @@ if fifo_fd >= 0:
if (((st.st_mode & (stat.S_IRWXG | stat.S_IRWXO)) != 0) or
(not stat.S_ISFIFO(st.st_mode)) or
(st.st_uid != os.getuid())):
print("error: command FIFO is not a FIFO or has bogus permissions")
sys.stderr.write("error: command FIFO is not a FIFO or has bogus "
"permissions\n")
sys.exit(1)
if fifo_fd >= 0:
@@ -112,11 +107,11 @@ else:
pass
else:
raise e
os.mkfifo(FIFO, int("0600", 8))
os.mkfifo(FIFO, 0o600)
opts = ["mpv", "--no-terminal", "--force-window", "--input-file=" + FIFO]
opts.extend(opts_env)
opts.append("--")
opts = (os.getenv("MPV") or "mpv").split()
opts.extend(["--no-terminal", "--force-window", "--input-file=" + FIFO,
"--"])
opts.extend(files)
subprocess.check_call(opts)
+1 -2
View File
@@ -90,8 +90,7 @@ int vf_dlopen_getcontext(struct vf_dlopen_context *ctx, int argc, const char **a
if (argc != 1 && argc != 2)
return -1;
framestep_data_t *framestep = malloc(sizeof(framestep_data_t));
memset(framestep, 0, sizeof(*framestep));
framestep_data_t *framestep = calloc(1,sizeof(framestep_data_t));
framestep->step = atoi(argv[0]);
framestep->pos = (argc >= 2) ? atoi(argv[1]) : 0;
+1 -2
View File
@@ -267,8 +267,7 @@ int vf_dlopen_getcontext(struct vf_dlopen_context *ctx, int argc, const char **a
(void) argc;
(void) argv;
ildetect_data_t *il = malloc(sizeof(ildetect_data_t));
memset(il, 0, sizeof(*il));
ildetect_data_t *il = calloc(1,sizeof(ildetect_data_t));
#define A(i,d) ((argc>(i) && *argv[i]) ? atof(argv[i]) : (d))
il->method = A(0, 0);
+1 -2
View File
@@ -348,8 +348,7 @@ int vf_dlopen_getcontext(struct vf_dlopen_context *ctx, int argc, const char **a
{ "yuv420p", "yuv420p" },
{ NULL, NULL }
};
privdata *priv = malloc(sizeof(privdata));
memset(priv, 0, sizeof(*priv));
privdata *priv = calloc(1,sizeof(privdata));
priv->step = 8;
if(argc >= 1)
priv->w = atoi(argv[0]);
+1 -2
View File
@@ -237,8 +237,7 @@ int vf_dlopen_getcontext(struct vf_dlopen_context *ctx, int argc, const char **a
if (!a0[0] || a0[1] || !a1[0] || argc > 2)
return -1;
tc_data_t *tc = malloc(sizeof(tc_data_t));
memset(tc, 0, sizeof(*tc));
tc_data_t *tc = calloc(1,sizeof(tc_data_t));
if (a0[0] == 't')
tc->firstfield = 0;
+1 -2
View File
@@ -150,8 +150,7 @@ int vf_dlopen_getcontext(struct vf_dlopen_context *ctx, int argc, const char **a
if (argc != 2)
return -1;
tile_data_t *tile = malloc(sizeof(tile_data_t));
memset(tile, 0, sizeof(*tile));
tile_data_t *tile = calloc(1,sizeof(tile_data_t));
tile->cols = atoi(argv[0]);
tile->rows = atoi(argv[1]);
+4 -5
View File
@@ -10,14 +10,13 @@ video_url="$(youtube-dl \
--user-agent="$user_agent" \
--cookies="$cookies_file" \
--get-url \
"$1")"
"$@")"
shift
mpv \
set -f
${MPV:-mpv} \
--cookies \
--cookies-file="$cookies_file" \
--user-agent="$user_agent" \
"$@" -- $video_url
-- $video_url
rm -rf "$cookies_dir"
+106 -33
View File
@@ -7,7 +7,7 @@ use warnings;
my $mpv = $ARGV[0] || 'mpv';
my @opts = parse_opts("$mpv --list-options", '^ (\-\-[^\s\*]*)\*?\s*(.*)');
my @opts = parse_opts("$mpv --list-options", '^ (\-\-[^\s\*]*)\*?\s*(.*)', 1);
my @ao = parse_opts("$mpv --ao=help", '^ ([^\s\:]*)\s*: (.*)');
my @vo = parse_opts("$mpv --vo=help", '^ ([^\s\:]*)\s*: (.*)');
@@ -15,9 +15,11 @@ my @vo = parse_opts("$mpv --vo=help", '^ ([^\s\:]*)\s*: (.*)');
my @af = parse_opts("$mpv --af=help", '^ ([^\s\:]*)\s*: (.*)');
my @vf = parse_opts("$mpv --vf=help", '^ ([^\s\:]*)\s*: (.*)');
my ($opts_str, $ao_str, $vo_str, $af_str, $vf_str);
my @protos = parse_opts("$mpv --list-protocols", '^ ([^\s]*)');
$opts_str .= qq{ '$_': \\\n} foreach (@opts);
my ($opts_str, $ao_str, $vo_str, $af_str, $vf_str, $protos_str);
$opts_str .= qq{ '$_' \\\n} foreach (@opts);
chomp $opts_str;
$ao_str .= qq{ '$_' \\\n} foreach (@ao);
@@ -32,14 +34,52 @@ chomp $af_str;
$vf_str .= qq{ '$_' \\\n} foreach (@vf);
chomp $vf_str;
$protos_str .= qq{$_ } foreach (@protos);
chomp $protos_str;
my $profile_comp = <<'EOS';
local -a profiles
local current
for current in "${(@f)$($words[1] --profile=help)}"; do
current=${current//\*/\\\*}
current=${current//\:/\\\:}
current=${current//\[/\\\[}
current=${current//\]/\\\]}
if [[ $current =~ $'\t'([^$'\t']*)$'\t'(.*) ]]; then
if [[ -n $match[2] ]]; then
current="$match[1][$match[2]]"
else
current="$match[1]"
fi
profiles=($profiles $current)
fi
done
if [[ $state == profile ]]; then
# For --show-profile, only one allowed
if (( ${#profiles} > 0 )); then
_values 'profile' $profiles && rc=0
fi
else
# For --profile, multiple allowed
profiles=($profiles 'help[list profiles]')
_values -s , 'profile(s)' $profiles && rc=0
fi
EOS
chomp $profile_comp;
my $tmpl = <<"EOS";
#compdef mpv
# mpv zsh completion
_x_arguments -C -s \\
local curcontext="\$curcontext" state state_descr line
typeset -A opt_args
local rc=1
_arguments -C -S \\
$opts_str
'*:files:->mfiles'
'*:files:->mfiles' && rc=0
case \$state in
ao)
@@ -48,7 +88,7 @@ case \$state in
$ao_str
)
_describe -t values 'audio outputs' values
_describe -t values 'audio outputs' values && rc=0
;;
vo)
@@ -57,7 +97,7 @@ $ao_str
$vo_str
)
_describe -t values 'video outputs' values
_describe -t values 'video outputs' values && rc=0
;;
af)
@@ -66,7 +106,7 @@ $vo_str
$af_str
)
_describe -t values 'audio filters' values
_describe -t values 'audio filters' values && rc=0
;;
vf)
@@ -75,55 +115,88 @@ $af_str
$vf_str
)
_describe -t values 'video filters' values
_describe -t values 'video filters' values && rc=0
;;
profile|profiles)
$profile_comp
;;
files)
compset -P '*,'
compset -S ',*'
_files -r ',/ \\t\\n\\-' && rc=0
;;
mfiles)
local expl
_tags files urls
while _tags; do
_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)(-.)" && ret=0
"*.(#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[@]" && ret=0
compadd -S '' "\$expl[@]" \{dvd,vcd,cdda,cddb,tv\}:// && ret=0
_urls "\$expl[@]" && rc=0
compadd -S '' "\$expl[@]" $protos_str && rc=0
done
fi
(( ret )) || return 0
(( rc )) || return 0
done
;;
esac
return rc
EOS
print $tmpl;
sub parse_opts {
my ($cmd, $regex) = @_;
my ($cmd, $regex, $parsing_main_options) = @_;
my @list;
my @lines = split /\n/, `$cmd`;
my @list;
my @lines = split /\n/, `$cmd`;
foreach my $line (@lines) {
if ($line !~ /^$regex/) {
next;
}
foreach my $line (@lines) {
if ($line !~ /^$regex/) {
next;
}
my $entry = "$1:";
my $entry = $1;
if (defined $2) {
my $desc = $2;
$desc =~ s/\:/\\:/;
if ($parsing_main_options) {
$entry .= '=-';
}
$entry .= $desc;
}
if (defined $2) {
my $desc = $2;
$desc =~ s/\:/\\:/g;
$entry .= ':->ao' if ($1 eq '--ao');
$entry .= ':->vo' if ($1 eq '--vo');
$entry .= ':->af' if ($1 eq '--af');
$entry .= ':->vf' if ($1 eq '--vf');
$entry .= ':' . $desc;
}
push @list, $entry if ($line =~ /^$regex/)
}
if ($parsing_main_options) {
$entry .= ':';
return @list;
$entry .= '->ao' if ($1 eq '--ao');
$entry .= '->vo' if ($1 eq '--vo');
$entry .= '->af' if ($1 eq '--af');
$entry .= '->vf' if ($1 eq '--vf');
$entry .= '->profiles' if ($1 eq '--profile');
$entry .= '->profile' if ($1 eq '--show-profile');
$entry .= '->files' if ($line =~ /\[file\]/);
}
push @list, $entry
}
if ($parsing_main_options) {
@list = sort {
$a =~ /(.*?)\:/; my $ma = $1;
$b =~ /(.*?)\:/; my $mb = $1;
length($mb) <=> length($ma)
} @list;
}
return @list;
}
+1
View File
@@ -0,0 +1 @@
0.6.2
+1 -1
View File
@@ -20,7 +20,7 @@
#include <inttypes.h>
#include <stdbool.h>
#include "bstr/bstr.h"
#include "misc/bstr.h"
#define MP_NUM_CHANNELS 8
+1 -1
View File
@@ -36,7 +36,7 @@ struct ad_functions {
int (*init)(struct dec_audio *da, const char *decoder);
void (*uninit)(struct dec_audio *da);
int (*control)(struct dec_audio *da, int cmd, void *arg);
int (*decode_audio)(struct dec_audio *da, struct mp_audio *buffer, int maxlen);
int (*decode_packet)(struct dec_audio *da);
};
enum ad_ctrl {
+29 -172
View File
@@ -33,13 +33,10 @@
#include "common/codecs.h"
#include "common/msg.h"
#include "options/options.h"
#include "common/av_opts.h"
#include "ad.h"
#include "audio/fmt-conversion.h"
#include "compat/libav.h"
struct priv {
AVCodecContext *avctx;
AVFrame *avframe;
@@ -49,14 +46,13 @@ struct priv {
};
static void uninit(struct dec_audio *da);
static int decode_new_packet(struct dec_audio *da);
#define OPT_BASE_STRUCT struct ad_lavc_params
struct ad_lavc_params {
float ac3drc;
int downmix;
int threads;
char *avopt;
char **avopts;
};
const struct m_sub_options ad_lavc_conf = {
@@ -64,7 +60,7 @@ const struct m_sub_options ad_lavc_conf = {
OPT_FLOATRANGE("ac3drc", ac3drc, 0, 0, 2),
OPT_FLAG("downmix", downmix, 0),
OPT_INTRANGE("threads", threads, 0, 1, 16),
OPT_STRING("o", avopt, 0),
OPT_KEYVALUELIST("o", avopts, 0),
{0}
},
.size = sizeof(struct ad_lavc_params),
@@ -75,79 +71,10 @@ const struct m_sub_options ad_lavc_conf = {
},
};
struct pcm_map
{
int tag;
const char *codecs[6]; // {any, 1byte, 2bytes, 3bytes, 4bytes, 8bytes}
};
// NOTE: these are needed to make rawaudio with demux_mkv work.
static const struct pcm_map tag_map[] = {
// Microsoft PCM
{0x0, {NULL, "pcm_u8", "pcm_s16le", "pcm_s24le", "pcm_s32le"}},
{0x1, {NULL, "pcm_u8", "pcm_s16le", "pcm_s24le", "pcm_s32le"}},
// MS PCM, Extended
{0xfffe, {NULL, "pcm_u8", "pcm_s16le", "pcm_s24le", "pcm_s32le"}},
// IEEE float
{0x3, {"pcm_f32le", [5] = "pcm_f64le"}},
// 'raw '
{0x20776172, {"pcm_s16be", [1] = "pcm_u8"}},
// 'twos', used by demux_mkv.c internally
{MKTAG('t', 'w', 'o', 's'),
{NULL, "pcm_s8", "pcm_s16be", "pcm_s24be", "pcm_s32be"}},
{-1},
};
// For demux_rawaudio.c; needed because ffmpeg doesn't have these sample
// formats natively.
static const struct pcm_map af_map[] = {
{AF_FORMAT_U8, {"pcm_u8"}},
{AF_FORMAT_S8, {"pcm_u8"}},
{AF_FORMAT_U16_LE, {"pcm_u16le"}},
{AF_FORMAT_U16_BE, {"pcm_u16be"}},
{AF_FORMAT_S16_LE, {"pcm_s16le"}},
{AF_FORMAT_S16_BE, {"pcm_s16be"}},
{AF_FORMAT_U24_LE, {"pcm_u24le"}},
{AF_FORMAT_U24_BE, {"pcm_u24be"}},
{AF_FORMAT_S24_LE, {"pcm_s24le"}},
{AF_FORMAT_S24_BE, {"pcm_s24be"}},
{AF_FORMAT_U32_LE, {"pcm_u32le"}},
{AF_FORMAT_U32_BE, {"pcm_u32be"}},
{AF_FORMAT_S32_LE, {"pcm_s32le"}},
{AF_FORMAT_S32_BE, {"pcm_s32be"}},
{AF_FORMAT_FLOAT_LE, {"pcm_f32le"}},
{AF_FORMAT_FLOAT_BE, {"pcm_f32be"}},
{AF_FORMAT_DOUBLE_LE, {"pcm_f64le"}},
{AF_FORMAT_DOUBLE_BE, {"pcm_f64be"}},
{-1},
};
static const char *find_pcm_decoder(const struct pcm_map *map, int format,
int bits_per_sample)
{
int bytes = (bits_per_sample + 7) / 8;
if (bytes == 8)
bytes = 5; // 64 bit entry
for (int n = 0; map[n].tag != -1; n++) {
const struct pcm_map *entry = &map[n];
if (entry->tag == format) {
const char *dec = NULL;
if (bytes >= 1 && bytes <= 5)
dec = entry->codecs[bytes];
if (!dec)
dec = entry->codecs[0];
if (dec)
return dec;
}
}
return NULL;
}
static int setup_format(struct dec_audio *da)
static void set_data_from_avframe(struct dec_audio *da)
{
struct priv *priv = da->priv;
AVCodecContext *lavc_context = priv->avctx;
struct sh_audio *sh_audio = da->header->audio;
// Note: invalid parameters are rejected by dec_audio.c
@@ -157,12 +84,6 @@ static int setup_format(struct dec_audio *da)
MP_FATAL(da, "unsupported lavc format %s", av_get_sample_fmt_name(fmt));
da->decoded.rate = lavc_context->sample_rate;
if (!da->decoded.rate && sh_audio->wf) {
// If not set, try container samplerate.
// (Maybe this can't happen, and it's an artifact from the past.)
da->decoded.rate = sh_audio->wf->nSamplesPerSec;
MP_WARN(da, "using container rate.\n");
}
struct mp_chmap lavc_chmap;
mp_chmap_from_lavc(&lavc_chmap, lavc_context->channel_layout);
@@ -170,24 +91,15 @@ static int setup_format(struct dec_audio *da)
if (lavc_chmap.num != lavc_context->channels)
mp_chmap_from_channels(&lavc_chmap, lavc_context->channels);
if (priv->force_channel_map) {
struct sh_audio *sh_audio = da->header->audio;
if (lavc_chmap.num == sh_audio->channels.num)
lavc_chmap = sh_audio->channels;
}
mp_audio_set_channels(&da->decoded, &lavc_chmap);
return 0;
}
static void set_from_wf(AVCodecContext *avctx, MP_WAVEFORMATEX *wf)
{
avctx->channels = wf->nChannels;
avctx->sample_rate = wf->nSamplesPerSec;
avctx->bit_rate = wf->nAvgBytesPerSec * 8;
avctx->block_align = wf->nBlockAlign;
avctx->bits_per_coded_sample = wf->wBitsPerSample;
if (wf->cbSize > 0)
mp_lavc_set_extradata(avctx, wf + 1, wf->cbSize);
da->decoded.samples = priv->avframe->nb_samples;
for (int n = 0; n < da->decoded.num_planes; n++)
da->decoded.planes[n] = priv->avframe->data[n];
}
static int init(struct dec_audio *da, const char *decoder)
@@ -202,13 +114,7 @@ static int init(struct dec_audio *da, const char *decoder)
struct priv *ctx = talloc_zero(NULL, struct priv);
da->priv = ctx;
if (sh_audio->wf && strcmp(decoder, "pcm") == 0) {
decoder = find_pcm_decoder(tag_map, sh->format,
sh_audio->wf->wBitsPerSample);
} else if (sh_audio->wf && strcmp(decoder, "mp-pcm") == 0) {
decoder = find_pcm_decoder(af_map, sh->format, 0);
ctx->force_channel_map = true;
}
ctx->force_channel_map = sh_audio->force_channels;
lavc_codec = avcodec_find_decoder_by_name(decoder);
if (!lavc_codec) {
@@ -233,23 +139,18 @@ static int init(struct dec_audio *da, const char *decoder)
av_opt_set_double(lavc_context, "drc_scale", opts->ac3drc,
AV_OPT_SEARCH_CHILDREN);
if (opts->avopt) {
if (parse_avopts(lavc_context, opts->avopt) < 0) {
MP_ERR(da, "setting AVOptions '%s' failed.\n", opts->avopt);
uninit(da);
return 0;
}
}
mp_set_avopts(da->log, lavc_context, opts->avopts);
lavc_context->codec_tag = sh->format;
lavc_context->sample_rate = sh_audio->samplerate;
lavc_context->bit_rate = sh_audio->bitrate;
lavc_context->channel_layout = mp_chmap_to_lavc(&sh_audio->channels);
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);
if (sh_audio->wf)
set_from_wf(lavc_context, sh_audio->wf);
// demux_mkv, demux_mpg
// demux_mkv
if (sh_audio->codecdata_len && sh_audio->codecdata &&
!lavc_context->extradata) {
mp_lavc_set_extradata(lavc_context, sh_audio->codecdata,
@@ -267,27 +168,9 @@ static int init(struct dec_audio *da, const char *decoder)
uninit(da);
return 0;
}
MP_VERBOSE(da, "INFO: libavcodec \"%s\" init OK!\n",
lavc_codec->name);
// Decode at least 1 sample: (to get header filled)
for (int tries = 1; ; tries++) {
int x = decode_new_packet(da);
if (x >= 0 && ctx->frame.samples > 0) {
MP_VERBOSE(da, "Initial decode succeeded after %d packets.\n", tries);
break;
}
if (tries >= 50) {
MP_ERR(da, "initial decode failed\n");
uninit(da);
return 0;
}
}
if (lavc_context->bit_rate != 0)
da->bitrate = lavc_context->bit_rate;
else if (sh_audio->wf && sh_audio->wf->nAvgBytesPerSec)
da->bitrate = sh_audio->wf->nAvgBytesPerSec * 8;
return 1;
}
@@ -314,7 +197,7 @@ static int control(struct dec_audio *da, int cmd, void *arg)
switch (cmd) {
case ADCTRL_RESET:
avcodec_flush_buffers(ctx->avctx);
ctx->frame.samples = 0;
mp_audio_set_null_data(&da->decoded);
talloc_free(ctx->packet);
ctx->packet = NULL;
return CONTROL_TRUE;
@@ -322,16 +205,18 @@ static int control(struct dec_audio *da, int cmd, void *arg)
return CONTROL_UNKNOWN;
}
static int decode_new_packet(struct dec_audio *da)
static int decode_packet(struct dec_audio *da)
{
struct priv *priv = da->priv;
AVCodecContext *avctx = priv->avctx;
priv->frame.samples = 0;
mp_audio_set_null_data(&da->decoded);
struct demux_packet *mpkt = priv->packet;
if (!mpkt)
mpkt = demux_read_packet(da->header);
if (!mpkt) {
if (demux_read_packet_async(da->header, &mpkt) == 0)
return AD_WAIT;
}
priv->packet = talloc_steal(priv, mpkt);
@@ -364,22 +249,16 @@ static int decode_new_packet(struct dec_audio *da)
}
// LATM may need many packets to find mux info
if (ret == AVERROR(EAGAIN))
return 0;
return AD_OK;
}
if (ret < 0) {
MP_VERBOSE(da, "lavc_audio: error\n");
return -1;
MP_ERR(da, "Error decoding audio.\n");
return AD_ERR;
}
if (!got_frame)
return mpkt ? 0 : -1; // -1: eof
return mpkt ? AD_OK : AD_EOF;
if (setup_format(da) < 0)
return -1;
priv->frame.samples = priv->avframe->nb_samples;
mp_audio_copy_config(&priv->frame, &da->decoded);
for (int n = 0; n < priv->frame.num_planes; n++)
priv->frame.planes[n] = priv->avframe->data[n];
set_data_from_avframe(da);
double out_pts = mp_pts_from_av(priv->avframe->pkt_pts, NULL);
if (out_pts != MP_NOPTS_VALUE) {
@@ -387,35 +266,13 @@ static int decode_new_packet(struct dec_audio *da)
da->pts_offset = 0;
}
MP_DBG(da, "Decoded %d -> %d samples\n", in_len,
priv->frame.samples);
return 0;
}
static int decode_audio(struct dec_audio *da, struct mp_audio *buffer, int maxlen)
{
struct priv *priv = da->priv;
if (!priv->frame.samples) {
if (decode_new_packet(da) < 0)
return -1;
}
if (!mp_audio_config_equals(buffer, &priv->frame))
return 0;
buffer->samples = MPMIN(priv->frame.samples, maxlen);
mp_audio_copy(buffer, 0, &priv->frame, 0, buffer->samples);
mp_audio_skip_samples(&priv->frame, buffer->samples);
da->pts_offset += buffer->samples;
MP_DBG(da, "Decoded %d -> %d samples\n", in_len, da->decoded.samples);
return 0;
}
static void add_decoders(struct mp_decoder_list *list)
{
mp_add_lavc_decoders(list, AVMEDIA_TYPE_AUDIO);
mp_add_decoder(list, "lavc", "pcm", "pcm", "Raw PCM");
mp_add_decoder(list, "lavc", "mp-pcm", "mp-pcm", "Raw PCM");
}
const struct ad_functions ad_lavc = {
@@ -424,5 +281,5 @@ const struct ad_functions ad_lavc = {
.init = init,
.uninit = uninit,
.control = control,
.decode_audio = decode_audio,
.decode_packet = decode_packet,
};
+73 -147
View File
@@ -35,9 +35,7 @@
struct ad_mpg123_context {
mpg123_handle *handle;
bool new_format;
int sample_size;
bool need_data;
/* Running mean for bit rate, stream length estimation. */
float mean_rate;
unsigned int mean_count;
@@ -58,7 +56,7 @@ static void uninit(struct dec_audio *da)
/* This initializes libmpg123 and prepares the handle, including funky
* parameters. */
static int preinit(struct dec_audio *da)
static int init(struct dec_audio *da, const char *decoder)
{
int err;
struct ad_mpg123_context *con;
@@ -111,15 +109,18 @@ static int preinit(struct dec_audio *da)
* We need at least 1152 samples. dec_audio.c normally guarantees this. */
mpg123_param(con->handle, MPG123_REMOVE_FLAGS, MPG123_AUTO_RESAMPLE, 0.);
err = mpg123_open_feed(con->handle);
if (err != MPG123_OK)
goto bad_end;
return 1;
bad_end:
if (!con->handle)
MP_ERR(da, "mpg123 preinit error: %s\n",
mpg123_plain_strerror(err));
else
MP_ERR(da, "mpg123 preinit error: %s\n",
mpg123_strerror(con->handle));
if (!con->handle) {
MP_ERR(da, "mpg123 preinit error: %s\n", mpg123_plain_strerror(err));
} else {
MP_ERR(da, "mpg123 preinit error: %s\n", mpg123_strerror(con->handle));
}
uninit(da);
return 0;
@@ -140,111 +141,6 @@ static int mpg123_format_to_af(int mpg123_encoding)
return 0;
}
/* libmpg123 has a new format ready; query and store, return return value
of mpg123_getformat() */
static int set_format(struct dec_audio *da)
{
struct ad_mpg123_context *con = da->priv;
int ret;
long rate;
int channels;
int encoding;
ret = mpg123_getformat(con->handle, &rate, &channels, &encoding);
if (ret == MPG123_OK) {
mp_audio_set_num_channels(&da->decoded, channels);
da->decoded.rate = rate;
int af = mpg123_format_to_af(encoding);
if (!af) {
/* This means we got a funny custom build of libmpg123 that only supports an unknown format. */
MP_ERR(da, "Bad encoding from mpg123: %i.\n", encoding);
return MPG123_ERR;
}
mp_audio_set_format(&da->decoded, af);
con->sample_size = channels * af_fmt2bps(af);
con->new_format = 0;
}
return ret;
}
static int feed_new_packet(struct dec_audio *da)
{
struct ad_mpg123_context *con = da->priv;
int ret;
struct demux_packet *pkt = demux_read_packet(da->header);
if (!pkt)
return -1; /* EOF. */
/* Next bytes from that presentation time. */
if (pkt->pts != MP_NOPTS_VALUE) {
da->pts = pkt->pts;
da->pts_offset = 0;
}
/* Have to use mpg123_feed() to avoid decoding here. */
ret = mpg123_feed(con->handle, pkt->buffer, pkt->len);
talloc_free(pkt);
if (ret == MPG123_ERR)
return -1;
if (ret == MPG123_NEW_FORMAT)
con->new_format = 1;
return 0;
}
/* Now we really start accessing some data and determining file format.
* Format now is allowed to change on-the-fly. Here is the only point
* that has MPlayer react to errors. We have to pray that exceptional
* erros in other places simply cannot occur. */
static int init(struct dec_audio *da, const char *decoder)
{
if (!preinit(da))
return 0;
struct ad_mpg123_context *con = da->priv;
int ret;
ret = mpg123_open_feed(con->handle);
if (ret != MPG123_OK)
goto fail;
for (int n = 0; ; n++) {
if (feed_new_packet(da) < 0) {
ret = MPG123_NEED_MORE;
goto fail;
}
size_t got_now = 0;
ret = mpg123_decode_frame(con->handle, NULL, NULL, &got_now);
if (ret == MPG123_OK || ret == MPG123_NEW_FORMAT) {
ret = set_format(da);
if (ret == MPG123_OK)
break;
}
if (ret != MPG123_NEED_MORE)
goto fail;
// max. 16 retries (randomly chosen number)
if (n > 16) {
ret = MPG123_NEED_MORE;
goto fail;
}
}
return 1;
fail:
if (ret == MPG123_NEED_MORE) {
MP_ERR(da, "Could not find mp3 stream.\n");
} else {
MP_ERR(da, "mpg123 init error: %s\n",
mpg123_strerror(con->handle));
}
uninit(da);
return 0;
}
/* Compute bitrate from frame size. */
static int compute_bitrate(struct mpg123_frameinfo *i)
{
@@ -290,57 +186,86 @@ static void update_info(struct dec_audio *da)
}
}
static int decode_audio(struct dec_audio *da, struct mp_audio *buffer, int maxlen)
/* libmpg123 has a new format ready; query and store, return return value
of mpg123_getformat() */
static int set_format(struct dec_audio *da)
{
struct ad_mpg123_context *con = da->priv;
int ret;
long rate;
int channels;
int encoding;
ret = mpg123_getformat(con->handle, &rate, &channels, &encoding);
if (ret == MPG123_OK) {
mp_audio_set_num_channels(&da->decoded, channels);
da->decoded.rate = rate;
int af = mpg123_format_to_af(encoding);
if (!af) {
/* This means we got a funny custom build of libmpg123 that only supports an unknown format. */
MP_ERR(da, "Bad encoding from mpg123: %i.\n", encoding);
return MPG123_ERR;
}
mp_audio_set_format(&da->decoded, af);
con->sample_size = channels * af_fmt2bps(af);
}
return ret;
}
static int decode_packet(struct dec_audio *da)
{
struct ad_mpg123_context *con = da->priv;
void *buf = buffer->planes[0];
int ret;
if (con->new_format) {
ret = set_format(da);
if (ret == MPG123_OK) {
return 0; // let caller handle format change
} else if (ret == MPG123_NEED_MORE) {
con->need_data = true;
} else {
goto mpg123_fail;
}
mp_audio_set_null_data(&da->decoded);
struct demux_packet *pkt;
if (demux_read_packet_async(da->header, &pkt) == 0)
return AD_WAIT;
if (!pkt)
return AD_EOF;
/* Next bytes from that presentation time. */
if (pkt->pts != MP_NOPTS_VALUE) {
da->pts = pkt->pts;
da->pts_offset = 0;
}
if (con->need_data) {
if (feed_new_packet(da) < 0)
return -1;
}
/* Have to use mpg123_feed() to avoid decoding here. */
ret = mpg123_feed(con->handle, pkt->buffer, pkt->len);
talloc_free(pkt);
if (!mp_audio_config_equals(&da->decoded, buffer))
return 0;
size_t got_now = 0;
ret = mpg123_replace_buffer(con->handle, buf, maxlen * con->sample_size);
if (ret != MPG123_OK)
goto mpg123_fail;
ret = mpg123_decode_frame(con->handle, NULL, NULL, &got_now);
unsigned char *audio = NULL;
size_t bytes = 0;
ret = mpg123_decode_frame(con->handle, NULL, &audio, &bytes);
int got_samples = got_now / con->sample_size;
buffer->samples += got_samples;
da->pts_offset += got_samples;
if (ret == MPG123_NEED_MORE)
return 0;
if (ret == MPG123_NEW_FORMAT) {
con->new_format = true;
} else if (ret == MPG123_NEED_MORE) {
con->need_data = true;
} else if (ret != MPG123_OK && ret != MPG123_DONE) {
if (ret != MPG123_OK && ret != MPG123_DONE && ret != MPG123_NEW_FORMAT)
goto mpg123_fail;
ret = set_format(da);
if (ret != MPG123_OK)
goto mpg123_fail;
if (con->sample_size < 1) {
MP_ERR(da, "no sample size\n");
return AD_ERR;
}
int got_samples = bytes / con->sample_size;
da->decoded.planes[0] = audio;
da->decoded.samples = got_samples;
update_info(da);
return 0;
mpg123_fail:
MP_ERR(da, "mpg123 decoding error: %s\n",
mpg123_strerror(con->handle));
return -1;
MP_ERR(da, "mpg123 decoding error: %s\n", mpg123_strerror(con->handle));
return AD_ERR;
}
static int control(struct dec_audio *da, int cmd, void *arg)
@@ -349,6 +274,7 @@ static int control(struct dec_audio *da, int cmd, void *arg)
switch (cmd) {
case ADCTRL_RESET:
mp_audio_set_null_data(&da->decoded);
mpg123_close(con->handle);
if (mpg123_open_feed(con->handle) != MPG123_OK) {
@@ -373,5 +299,5 @@ const struct ad_functions ad_mpg123 = {
.init = init,
.uninit = uninit,
.control = control,
.decode_audio = decode_audio,
.decode_packet = decode_packet,
};
+22 -25
View File
@@ -38,8 +38,7 @@ struct spdifContext {
AVFormatContext *lavf_ctx;
int iec61937_packet_size;
int out_buffer_len;
int out_buffer_size;
uint8_t *out_buffer;
uint8_t out_buffer[OUTBUF_SIZE];
bool need_close;
};
@@ -47,7 +46,7 @@ static int write_packet(void *p, uint8_t *buf, int buf_size)
{
struct spdifContext *ctx = p;
int buffer_left = ctx->out_buffer_size - ctx->out_buffer_len;
int buffer_left = OUTBUF_SIZE - ctx->out_buffer_len;
if (buf_size > buffer_left) {
MP_ERR(ctx, "spdif packet too large.\n");
buf_size = buffer_left;
@@ -118,13 +117,13 @@ static int init(struct dec_audio *da, const char *decoder)
switch (stream->codec->codec_id) {
case AV_CODEC_ID_AAC:
spdif_ctx->iec61937_packet_size = 16384;
sample_format = AF_FORMAT_IEC61937_LE;
sample_format = AF_FORMAT_S_AAC;
samplerate = 48000;
num_channels = 2;
break;
case AV_CODEC_ID_AC3:
spdif_ctx->iec61937_packet_size = 6144;
sample_format = AF_FORMAT_AC3_LE;
sample_format = AF_FORMAT_S_AC3;
samplerate = 48000;
num_channels = 2;
break;
@@ -132,31 +131,31 @@ static int init(struct dec_audio *da, const char *decoder)
if (da->opts->dtshd) {
av_dict_set(&format_opts, "dtshd_rate", "768000", 0); // 4*192000
spdif_ctx->iec61937_packet_size = 32768;
sample_format = AF_FORMAT_IEC61937_LE;
sample_format = AF_FORMAT_S_DTSHD;
samplerate = 192000;
num_channels = 2*4;
} else {
spdif_ctx->iec61937_packet_size = 32768;
sample_format = AF_FORMAT_AC3_LE;
sample_format = AF_FORMAT_S_DTS;
samplerate = 48000;
num_channels = 2;
}
break;
case AV_CODEC_ID_EAC3:
spdif_ctx->iec61937_packet_size = 24576;
sample_format = AF_FORMAT_IEC61937_LE;
sample_format = AF_FORMAT_S_EAC3;
samplerate = 192000;
num_channels = 2;
break;
case AV_CODEC_ID_MP3:
spdif_ctx->iec61937_packet_size = 4608;
sample_format = AF_FORMAT_MPEG2;
sample_format = AF_FORMAT_S_MP3;
samplerate = 48000;
num_channels = 2;
break;
case AV_CODEC_ID_TRUEHD:
spdif_ctx->iec61937_packet_size = 61440;
sample_format = AF_FORMAT_IEC61937_LE;
sample_format = AF_FORMAT_S_TRUEHD;
samplerate = 192000;
num_channels = 8;
break;
@@ -183,24 +182,21 @@ fail:
return 0;
}
static int decode_audio(struct dec_audio *da, struct mp_audio *buffer, int maxlen)
static int decode_packet(struct dec_audio *da)
{
struct spdifContext *spdif_ctx = da->priv;
AVFormatContext *lavf_ctx = spdif_ctx->lavf_ctx;
int sstride = 2 * da->decoded.channels.num;
assert(sstride == buffer->sstride);
if (maxlen * sstride < spdif_ctx->iec61937_packet_size)
return 0;
mp_audio_set_null_data(&da->decoded);
spdif_ctx->out_buffer_len = 0;
spdif_ctx->out_buffer_size = maxlen * sstride;
spdif_ctx->out_buffer = buffer->planes[0];
struct demux_packet *mpkt = demux_read_packet(da->header);
struct demux_packet *mpkt;
if (demux_read_packet_async(da->header, &mpkt) == 0)
return AD_WAIT;
if (!mpkt)
return -1;
return AD_EOF;
AVPacket pkt;
mp_set_av_packet(&pkt, mpkt, NULL);
@@ -211,12 +207,13 @@ static int decode_audio(struct dec_audio *da, struct mp_audio *buffer, int maxle
da->pts_offset = 0;
}
int ret = av_write_frame(lavf_ctx, &pkt);
avio_flush(lavf_ctx->pb);
buffer->samples = spdif_ctx->out_buffer_len / sstride;
da->pts_offset += buffer->samples;
talloc_free(mpkt);
avio_flush(lavf_ctx->pb);
if (ret < 0)
return -1;
return AD_ERR;
da->decoded.planes[0] = spdif_ctx->out_buffer;
da->decoded.samples = spdif_ctx->out_buffer_len / da->decoded.sstride;
return 0;
}
@@ -253,5 +250,5 @@ const struct ad_functions ad_spdif = {
.init = init,
.uninit = uninit,
.control = control,
.decode_audio = decode_audio,
.decode_packet = decode_packet,
};
+56 -53
View File
@@ -28,7 +28,7 @@
#include "config.h"
#include "common/codecs.h"
#include "common/msg.h"
#include "bstr/bstr.h"
#include "misc/bstr.h"
#include "stream/stream.h"
#include "demux/demux.h"
@@ -48,21 +48,14 @@ extern const struct ad_functions ad_lavc;
extern const struct ad_functions ad_spdif;
static const struct ad_functions * const ad_drivers[] = {
&ad_lavc,
#if HAVE_MPG123
&ad_mpg123,
#endif
&ad_lavc,
&ad_spdif,
NULL
};
// ad_mpg123 needs to be able to decode 1152 samples at once
// ad_spdif needs up to 8192
#define DECODE_MAX_UNIT MPMAX(8192, 1152)
// At least 8192 samples, plus hack for ad_mpg123 and ad_spdif
#define DECODE_BUFFER_SAMPLES (8192 + DECODE_MAX_UNIT)
// Drop audio buffer and reinit it (after format change)
// Returns whether the format was valid at all.
static bool reinit_audio_buffer(struct dec_audio *da)
@@ -73,7 +66,6 @@ static bool reinit_audio_buffer(struct dec_audio *da)
return false;
}
mp_audio_buffer_reinit(da->decode_buffer, &da->decoded);
mp_audio_buffer_preallocate_min(da->decode_buffer, DECODE_BUFFER_SAMPLES);
return true;
}
@@ -98,11 +90,6 @@ static int init_audio_codec(struct dec_audio *d_audio, const char *decoder)
}
d_audio->decode_buffer = mp_audio_buffer_create(NULL);
if (!reinit_audio_buffer(d_audio)) {
uninit_decoder(d_audio);
return 0;
}
return 1;
}
@@ -164,9 +151,6 @@ int audio_init_best_codec(struct dec_audio *d_audio, char *audio_decoders)
talloc_asprintf(d_audio, "%s [%s:%s]", decoder->desc, decoder->family,
decoder->decoder);
MP_VERBOSE(d_audio, "Selected audio codec: %s\n", d_audio->decoder_desc);
MP_VERBOSE(d_audio, "AUDIO: %d Hz, %d ch, %s\n",
d_audio->decoded.rate, d_audio->decoded.channels.num,
af_fmt_to_str(d_audio->decoded.format));
} else {
MP_ERR(d_audio, "Failed to initialize an audio decoder for codec '%s'.\n",
d_audio->header->codec ? d_audio->header->codec : "<unknown>");
@@ -209,8 +193,6 @@ int audio_init_filters(struct dec_audio *d_audio, int in_samplerate,
mp_audio_set_channels(&afs->output, out_channels);
mp_audio_set_format(&afs->output, *out_format);
afs->metadata = d_audio->metadata;
afs->replaygain_data = d_audio->replaygain_data;
char *s_from = mp_audio_config_to_str(&afs->input);
@@ -233,61 +215,82 @@ int audio_init_filters(struct dec_audio *d_audio, int in_samplerate,
return 1;
}
/* Decode packets until we know the audio format. Then reinit the buffer.
* Returns AD_OK on success, negative AD_* code otherwise.
* Also returns AD_OK if already initialized (and does nothing).
*/
int initial_audio_decode(struct dec_audio *da)
{
while (!mp_audio_config_valid(&da->decoded)) {
if (da->decoded.samples > 0)
return AD_ERR; // invalid format, rather than uninitialized
int ret = da->ad_driver->decode_packet(da);
if (ret < 0)
return ret;
}
if (mp_audio_buffer_samples(da->decode_buffer) > 0) // avoid accidental flush
return AD_OK;
return reinit_audio_buffer(da) ? AD_OK : AD_ERR;
}
// Filter len bytes of input, put result into outbuf.
static int filter_n_bytes(struct dec_audio *da, struct mp_audio_buffer *outbuf,
int len)
{
bool format_change = false;
int error = 0;
struct mp_audio config;
mp_audio_buffer_get_format(da->decode_buffer, &config);
assert(len > 0); // would break EOF logic below
while (mp_audio_buffer_samples(da->decode_buffer) < len) {
int maxlen = mp_audio_buffer_get_write_available(da->decode_buffer);
if (maxlen < DECODE_MAX_UNIT)
break;
struct mp_audio buffer;
mp_audio_buffer_get_write_buffer(da->decode_buffer, maxlen, &buffer);
buffer.samples = 0;
error = da->ad_driver->decode_audio(da, &buffer, maxlen);
if (error < 0)
break;
// Commit the data just read as valid data
mp_audio_buffer_finish_write(da->decode_buffer, buffer.samples);
// Format change
if (!mp_audio_config_equals(&da->decoded, &config)) {
// If there are still samples left in the buffer, let them drain
// first, and don't signal a format change to the caller yet.
if (mp_audio_buffer_samples(da->decode_buffer) > 0)
break;
error = -2;
// Check for a format change
struct mp_audio config;
mp_audio_buffer_get_format(da->decode_buffer, &config);
format_change = !mp_audio_config_equals(&da->decoded, &config);
if (format_change) {
error = AD_EOF; // drain remaining data left in the current buffer
break;
}
if (da->decoded.samples > 0) {
int copy = MPMIN(da->decoded.samples, len);
struct mp_audio append = da->decoded;
append.samples = copy;
mp_audio_buffer_append(da->decode_buffer, &append);
mp_audio_skip_samples(&da->decoded, copy);
da->pts_offset += copy;
continue;
}
error = da->ad_driver->decode_packet(da);
if (error < 0)
break;
}
if (error == AD_WAIT)
return error;
// Filter
struct mp_audio filter_data;
mp_audio_buffer_peek(da->decode_buffer, &filter_data);
filter_data.rate = da->afilter->input.rate; // due to playback speed change
len = MPMIN(filter_data.samples, len);
filter_data.samples = len;
bool eof = filter_data.samples == 0 && error < 0;
bool eof = error == AD_EOF && filter_data.samples == 0;
if (af_filter(da->afilter, &filter_data, eof ? AF_FILTER_FLAG_EOF : 0) < 0)
return -1;
return AD_ERR;
mp_audio_buffer_append(outbuf, &filter_data);
if (eof && filter_data.samples > 0)
if (error == AD_EOF && filter_data.samples > 0)
error = 0; // don't end playback yet
// remove processed data from decoder buffer:
mp_audio_buffer_skip(da->decode_buffer, len);
// Assume the filter chain is drained from old data at this point.
// (If not, the remaining old data is discarded.)
if (error == -2) {
// if format was changed, and all data was drained, execute the format change
if (format_change && eof) {
error = AD_NEW_FMT;
if (!reinit_audio_buffer(da))
error = -1; // switch to invalid format
error = AD_ERR; // switch to invalid format
}
return error;
@@ -295,17 +298,17 @@ static int filter_n_bytes(struct dec_audio *da, struct mp_audio_buffer *outbuf,
/* Try to get at least minsamples decoded+filtered samples in outbuf
* (total length including possible existing data).
* Return 0 on success, -1 on error/EOF (not distinguidaed).
* Return 0 on success, or negative AD_* error code.
* In the former case outbuf has at least minsamples buffered on return.
* In case of EOF/error it might or might not be. */
int audio_decode(struct dec_audio *d_audio, struct mp_audio_buffer *outbuf,
int minsamples)
{
if (!d_audio->afilter)
return AD_ERR;
// Indicates that a filter seems to be buffering large amounts of data
int huge_filter_buffer = 0;
// Decoded audio must be cut at boundaries of this many samples
// (Note: the reason for this is unknown, possibly a refactoring artifact)
int unitsize = 16;
/* Filter output size will be about filter_multiplier times input size.
* If some filter buffers audio in big blocks this might only hold
@@ -322,8 +325,8 @@ int audio_decode(struct dec_audio *d_audio, struct mp_audio_buffer *outbuf,
prev_buffered = buffered;
int decsamples = (minsamples - buffered) / filter_multiplier;
// + some extra for possible filter buffering
decsamples += unitsize << 5;
// + some extra for possible filter buffering, and avoid 0
decsamples += 512;
if (huge_filter_buffer) {
/* Some filter must be doing significant buffering if the estimated
+11 -4
View File
@@ -36,12 +36,10 @@ struct dec_audio {
struct mp_audio_buffer *decode_buffer;
struct af_stream *afilter;
char *decoder_desc;
struct mp_tags *metadata;
struct replaygain_data *replaygain_data;
int init_retries;
// set by decoder
struct mp_audio decoded; // format of decoded audio (no data, temporarily
// different from decode_buffer during format
// changes)
struct mp_audio decoded; // decoded audio set by last decode_packet() call
int bitrate; // input bitrate, can change with VBR sources
// last known pts value in output from decoder
double pts;
@@ -51,10 +49,19 @@ struct dec_audio {
void *priv;
};
enum {
AD_OK = 0,
AD_ERR = -1,
AD_EOF = -2,
AD_NEW_FMT = -3,
AD_WAIT = -4,
};
struct mp_decoder_list *audio_decoder_list(void);
int audio_init_best_codec(struct dec_audio *d_audio, char *audio_decoders);
int audio_decode(struct dec_audio *d_audio, struct mp_audio_buffer *outbuf,
int minsamples);
int initial_audio_decode(struct dec_audio *d_audio);
void audio_reset_decoding(struct dec_audio *d_audio);
void audio_uninit(struct dec_audio *d_audio);
+6 -7
View File
@@ -204,7 +204,6 @@ static struct af_instance *af_create(struct af_stream *s, char *name,
.mul = 1,
.data = talloc_zero(af, struct mp_audio),
.log = mp_log_new(af, s->log, name),
.metadata = s->metadata,
.replaygain_data = s->replaygain_data,
};
struct m_config *config = m_config_from_obj_desc(af, s->log, &desc);
@@ -311,22 +310,22 @@ static void af_print_filter_chain(struct af_stream *s, struct af_instance *at,
struct af_instance *af = s->first;
while (af) {
MP_MSG(s, msg_level, " [%s] ", af->info->name);
char b[128] = {0};
mp_snprintf_cat(b, sizeof(b), " [%s] ", af->info->name);
if (af->data) {
char *info = mp_audio_config_to_str(af->data);
MP_MSG(s, msg_level, "%s", info);
mp_snprintf_cat(b, sizeof(b), "%s", info);
talloc_free(info);
}
if (af == at)
MP_MSG(s, msg_level, " <-");
MP_MSG(s, msg_level, "\n");
mp_snprintf_cat(b, sizeof(b), " <-");
MP_MSG(s, msg_level, "%s\n", b);
af = af->next;
}
MP_MSG(s, msg_level, " [ao] ");
char *info = mp_audio_config_to_str(&s->output);
MP_MSG(s, msg_level, "%s\n", info);
MP_MSG(s, msg_level, " [ao] %s\n", info);
talloc_free(info);
}
-2
View File
@@ -59,7 +59,6 @@ struct af_info {
struct af_instance {
const struct af_info *info;
struct mp_log *log;
struct mp_tags *metadata;
struct replaygain_data *replaygain_data;
int (*control)(struct af_instance *af, int cmd, void *arg);
void (*uninit)(struct af_instance *af);
@@ -92,7 +91,6 @@ struct af_stream {
struct mp_log *log;
struct MPOpts *opts;
struct mp_tags *metadata;
struct replaygain_data *replaygain_data;
};
+20 -49
View File
@@ -48,20 +48,12 @@ static int filter_##name(struct af_instance *af, struct mp_audio *data, int f) \
}
FILTER(f, float)
FILTER(fbe, float)
FILTER(fle, float)
FILTER(s32be, int32_t)
FILTER(u32be, uint32_t)
FILTER(s32le, int32_t)
FILTER(u32le, uint32_t)
FILTER(s24be, bs2b_int24_t)
FILTER(u24be, bs2b_uint24_t)
FILTER(s24le, bs2b_int24_t)
FILTER(u24le, bs2b_uint24_t)
FILTER(s16be, int16_t)
FILTER(u16be, uint16_t)
FILTER(s16le, int16_t)
FILTER(u16le, uint16_t)
FILTER(s32, int32_t)
FILTER(u32, uint32_t)
FILTER(s24, bs2b_int24_t)
FILTER(u24, bs2b_uint24_t)
FILTER(s16, int16_t)
FILTER(u16, uint16_t)
FILTER(s8, int8_t)
FILTER(u8, uint8_t)
@@ -85,47 +77,26 @@ static int control(struct af_instance *af, int cmd, void *arg)
/* check for formats supported by libbs2b
and assign corresponding handlers */
switch (format) {
case AF_FORMAT_FLOAT_BE:
af->filter = filter_fbe;
case AF_FORMAT_FLOAT:
af->filter = filter_f;
break;
case AF_FORMAT_FLOAT_LE:
af->filter = filter_fle;
case AF_FORMAT_S32:
af->filter = filter_s32;
break;
case AF_FORMAT_S32_BE:
af->filter = filter_s32be;
case AF_FORMAT_U32:
af->filter = filter_u32;
break;
case AF_FORMAT_U32_BE:
af->filter = filter_u32be;
case AF_FORMAT_S24:
af->filter = filter_s24;
break;
case AF_FORMAT_S32_LE:
af->filter = filter_s32le;
case AF_FORMAT_U24:
af->filter = filter_u24;
break;
case AF_FORMAT_U32_LE:
af->filter = filter_u32le;
case AF_FORMAT_S16:
af->filter = filter_s16;
break;
case AF_FORMAT_S24_BE:
af->filter = filter_s24be;
break;
case AF_FORMAT_U24_BE:
af->filter = filter_u24be;
break;
case AF_FORMAT_S24_LE:
af->filter = filter_s24le;
break;
case AF_FORMAT_U24_LE:
af->filter = filter_u24le;
break;
case AF_FORMAT_S16_BE:
af->filter = filter_s16be;
break;
case AF_FORMAT_U16_BE:
af->filter = filter_u16be;
break;
case AF_FORMAT_S16_LE:
af->filter = filter_s16le;
break;
case AF_FORMAT_U16_LE:
af->filter = filter_u16le;
case AF_FORMAT_U16:
af->filter = filter_u16;
break;
case AF_FORMAT_S8:
af->filter = filter_s8;
+1
View File
@@ -20,6 +20,7 @@
#include "audio/format.h"
#include "af.h"
#include "osdep/endian.h"
static bool test_conversion(int src_format, int dst_format)
{
+9 -41
View File
@@ -20,21 +20,16 @@
#include "af.h"
#include "audio/format.h"
#include "compat/mpbswap.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;
int src_noend = src_format & ~AF_FORMAT_END_MASK;
int dst_noend = dst_format & ~AF_FORMAT_END_MASK;
// We can swap endian for all formats, but sign only for integer formats.
if (src_noend == dst_noend)
return true;
if (((src_noend & ~AF_FORMAT_SIGN_MASK) ==
(dst_noend & ~AF_FORMAT_SIGN_MASK)) &&
((src_noend & AF_FORMAT_POINT_MASK) == AF_FORMAT_I))
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;
}
@@ -63,34 +58,11 @@ static int control(struct af_instance *af, int cmd, void *arg)
return AF_UNKNOWN;
}
static void endian(void *data, int len, int bps)
{
switch (bps) {
case 2:
for (int i = 0; i < len; i++) {
((uint16_t*)data)[i] = bswap_16(((uint16_t *)data)[i]);
}
break;
case 3:
for(int i = 0; i < len; i++) {
uint8_t s = ((uint8_t *)data)[3 * i];
((uint8_t *)data)[3 * i] = ((uint8_t *)data)[3 * i + 2];
((uint8_t *)data)[3 * i + 2] = s;
}
break;
case 4:
for(int i = 0; i < len; i++) {
((uint32_t*)data)[i] = bswap_32(((uint32_t *)data)[i]);
}
break;
}
}
static void si2us(void *data, int len, int bps, bool le)
static void si2us(void *data, int len, int bps)
{
ptrdiff_t i = -(len * bps);
uint8_t *p = &((uint8_t *)data)[len * bps];
if (le && bps > 1)
if (BYTE_ORDER == LITTLE_ENDIAN && bps > 1)
p += bps - 1;
if (len <= 0)
return;
@@ -105,12 +77,8 @@ static int filter(struct af_instance *af, struct mp_audio *data, int flags)
int outfmt = af->data->format;
size_t len = data->samples * data->nch;
if ((infmt & AF_FORMAT_END_MASK) != (outfmt & AF_FORMAT_END_MASK))
endian(data->planes[0], len, data->bps);
if ((infmt & AF_FORMAT_SIGN_MASK) != (outfmt & AF_FORMAT_SIGN_MASK))
si2us(data->planes[0], len, data->bps,
(outfmt & AF_FORMAT_END_MASK) == AF_FORMAT_LE);
si2us(data->planes[0], len, data->bps);
mp_audio_set_format(data, outfmt);
return 0;
@@ -124,8 +92,8 @@ static int af_open(struct af_instance *af)
}
const struct af_info af_info_convertsignendian = {
.info = "Convert between sample format sign/endian",
.name = "convertsignendian",
.info = "Convert between sample format sign",
.name = "convertsign",
.open = af_open,
.test_conversion = test_conversion,
};
+34 -16
View File
@@ -284,6 +284,27 @@ static inline void update_ch(af_hrtf_t *s, short *in, const int k)
s->ba_r[k] = in[4] + in[1] + 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)
{
@@ -292,30 +313,27 @@ static int control(struct af_instance *af, int cmd, void* arg)
switch(cmd) {
case AF_CONTROL_REINIT:
af->data->rate = ((struct mp_audio*)arg)->rate;
if(af->data->rate != 48000) {
// automatic samplerate adjustment in the filter chain
// is not yet supported.
MP_ERR(af, "ERROR: Sampling rate is not 48000 Hz (%d)!\n",
af->data->rate);
return AF_ERROR;
}
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;
}
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);
} 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;
+17 -8
View File
@@ -30,6 +30,7 @@
#include <libavutil/audioconvert.h>
#include <libavutil/intreadwrite.h>
#include <libavutil/common.h>
#include <libavutil/bswap.h>
#include <libavutil/mem.h>
#include "common/common.h"
@@ -87,7 +88,7 @@ static int control(struct af_instance *af, int cmd, void *arg)
if (in->nch > AC3_MAX_CHANNELS)
mp_audio_set_num_channels(in, AC3_MAX_CHANNELS);
mp_audio_set_format(af->data, AF_FORMAT_AC3_BE);
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))
@@ -150,6 +151,12 @@ static void uninit(struct af_instance* af)
}
}
static void swap_16(uint16_t *ptr, size_t size)
{
for (size_t n = 0; n < size; n++)
ptr[n] = av_bswap16(ptr[n]);
}
// Filter data through filter
static int filter(struct af_instance* af, struct mp_audio* audio, int flags)
{
@@ -223,11 +230,11 @@ static int filter(struct af_instance* af, struct mp_audio* audio, int flags)
frame_size = AC3_FRAME_SIZE * 2 * 2;
header_len = 8;
AV_WB16(hdr, 0xF872); // iec 61937 syncword 1
AV_WB16(hdr + 2, 0x4E1F); // iec 61937 syncword 2
hdr[4] = bsmod; // bsmod
hdr[5] = 0x01; // data-type ac3
AV_WB16(hdr + 6, len << 3); // number of bits in payload
AV_WL16(hdr, 0xF872); // iec 61937 syncword 1
AV_WL16(hdr + 2, 0x4E1F); // iec 61937 syncword 2
hdr[5] = bsmod; // bsmod
hdr[4] = 0x01; // data-type ac3
AV_WL16(hdr + 6, len << 3); // number of bits in payload
}
size_t max_size = (max_out_samples - out->samples) * out->sstride;
@@ -239,6 +246,7 @@ static int filter(struct af_instance* af, struct mp_audio* audio, int flags)
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;
}
@@ -312,12 +320,13 @@ const struct af_info af_info_lavcac3enc = {
.priv_size = sizeof(struct af_ac3enc_s),
.priv_defaults = &(const struct af_ac3enc_s){
.cfg_add_iec61937_header = 1,
.cfg_min_channel_num = 5,
.cfg_bit_rate = 640,
.cfg_min_channel_num = 3,
},
.options = (const struct m_option[]) {
OPT_FLAG("tospdif", cfg_add_iec61937_header, 0),
OPT_CHOICE_OR_INT("bitrate", cfg_bit_rate, 0, 32, 640,
({"default", 0})),
({"auto", 0}, {"default", 0})),
OPT_INTRANGE("minch", cfg_min_channel_num, 0, 2, 6),
{0}
},
+5 -7
View File
@@ -38,8 +38,9 @@
#include "audio/fmt-conversion.h"
#include "af.h"
#include "common/av_common.h"
#include "options/m_option.h"
#include "common/av_opts.h"
// FFmpeg and Libav have slightly different APIs, just enough to cause us
// unnecessary pain. <Expletive deleted.>
@@ -62,7 +63,7 @@ struct priv {
// options
char *cfg_graph;
char *cfg_avopts;
char **cfg_avopts;
};
static void destroy_graph(struct af_instance *af)
@@ -90,11 +91,8 @@ static bool recreate_graph(struct af_instance *af, struct mp_audio *config)
if (!graph)
goto error;
if (parse_avopts(graph, p->cfg_avopts) < 0) {
MP_FATAL(af, "lavfi: could not set opts: '%s'\n",
p->cfg_avopts);
if (mp_set_avopts(af->log, graph, p->cfg_avopts) < 0)
goto error;
}
AVFilterInOut *outputs = avfilter_inout_alloc();
AVFilterInOut *inputs = avfilter_inout_alloc();
@@ -306,7 +304,7 @@ const struct af_info af_info_lavfi = {
.priv_size = sizeof(struct priv),
.options = (const struct m_option[]) {
OPT_STRING("graph", cfg_graph, 0),
OPT_STRING("o", cfg_avopts, 0),
OPT_KEYVALUELIST("o", cfg_avopts, 0),
{0}
},
};
+9 -12
View File
@@ -52,9 +52,9 @@
#error "config.h broken or no resampler found"
#endif
#include "common/av_common.h"
#include "common/msg.h"
#include "options/m_option.h"
#include "common/av_opts.h"
#include "audio/filter/af.h"
#include "audio/fmt-conversion.h"
@@ -74,7 +74,7 @@ struct af_resample_opts {
struct af_resample {
int allow_detach;
char *avopts;
char **avopts;
struct AVAudioResampleContext *avrctx;
struct AVAudioResampleContext *avrctx_out; // for output channel reordering
struct af_resample_opts ctx; // opts in the context
@@ -164,10 +164,8 @@ static int configure_lavrr(struct af_instance *af, struct mp_audio *in,
av_opt_set_double(s->avrctx, "cutoff", s->ctx.cutoff, 0);
if (parse_avopts(s->avrctx, s->avopts) < 0) {
MP_FATAL(af, "af_lavrresample: could not set opts: '%s'\n", s->avopts);
if (mp_set_avopts(af->log, s->avrctx, s->avopts) < 0)
return AF_ERROR;
}
struct mp_chmap map_in = in->channels;
struct mp_chmap map_out = out->channels;
@@ -216,8 +214,7 @@ static int configure_lavrr(struct af_instance *af, struct mp_audio *in,
if (avresample_open(s->avrctx) < 0 ||
avresample_open(s->avrctx_out) < 0)
{
MP_ERR(af, "Cannot open "
"Libavresample Context. \n");
MP_ERR(af, "Cannot open Libavresample Context. \n");
return AF_ERROR;
}
return AF_OK;
@@ -341,7 +338,7 @@ static int filter(struct af_instance *af, struct mp_audio *data, int flags)
if (needs_reorder(s->reorder_out, out->nch)) {
if (af_fmt_is_planar(out->format)) {
reorder_planes(data, s->reorder_out);
} else {
} else if (out->samples) {
int out_size = out->samples * out->sstride;
if (talloc_get_size(s->reorder_buffer) < out_size)
s->reorder_buffer = talloc_realloc_size(s, s->reorder_buffer, out_size);
@@ -349,7 +346,8 @@ static int filter(struct af_instance *af, struct mp_audio *data, int flags)
int out_samples = avresample_convert(s->avrctx_out,
(uint8_t **) data->planes, out_size, out->samples,
(uint8_t **) out->planes, out_size, out->samples);
assert(out_samples == data->samples);
if (out_samples < 0)
MP_ERR(af, "Reordering failed.\n");
}
}
@@ -373,8 +371,7 @@ static int af_open(struct af_instance *af)
if (s->avrctx && s->avrctx_out) {
return AF_OK;
} else {
MP_ERR(af, "Cannot initialize "
"Libavresample Context. \n");
MP_ERR(af, "Cannot initialize Libavresample Context. \n");
uninit(af);
return AF_ERROR;
}
@@ -402,7 +399,7 @@ const struct af_info af_info_lavrresample = {
OPT_FLAG("linear", opts.linear, 0),
OPT_DOUBLE("cutoff", opts.cutoff, M_OPT_RANGE, .min = 0, .max = 1),
OPT_FLAG("detach", allow_detach, 0),
OPT_STRING("o", avopts, 0),
OPT_KEYVALUELIST("o", avopts, 0),
{0}
},
};
+2 -2
View File
@@ -79,7 +79,7 @@ static int control(struct af_instance *af, int cmd, void *arg)
if (!s->rgain_clip) // clipping prevention
s->rgain = MPMIN(s->rgain, 1.0 / peak);
}
if (s->detach && fabs(s->level + s->rgain - 2.0) < 0.00001)
if (s->detach && fabs(s->level * s->rgain - 1.0) < 0.00001)
return AF_DETACH;
return af_test_output(af, in);
}
@@ -97,7 +97,7 @@ static void filter_plane(struct af_instance *af, void *ptr, int num_samples)
{
struct priv *s = af->priv;
float level = s->level + s->rgain - 1.0;
float level = s->level * s->rgain;
if (af_fmt_from_planar(af->data->format) == AF_FORMAT_S16) {
int16_t *a = ptr;
+26 -38
View File
@@ -30,9 +30,6 @@
int af_fmt2bps(int format)
{
if (AF_FORMAT_IS_AC3(format)) return 2;
if (format == AF_FORMAT_UNKNOWN)
return 0;
switch (format & AF_FORMAT_BITS_MASK) {
case AF_FORMAT_8BIT: return 1;
case AF_FORMAT_16BIT: return 2;
@@ -62,7 +59,7 @@ static int bits_to_mask(int bits)
int af_fmt_change_bits(int format, int bits)
{
if (!af_fmt_is_valid(format) || (format & AF_FORMAT_SPECIAL_MASK))
if (!af_fmt_is_valid(format))
return 0;
int mask = bits_to_mask(bits);
format = (format & ~AF_FORMAT_BITS_MASK) | mask;
@@ -109,35 +106,31 @@ bool af_fmt_is_planar(int format)
return !!(format & AF_FORMAT_PLANAR);
}
#define FMT(string, id) \
{string, id},
#define FMT_ENDIAN(string, id) \
{string, id}, \
{string "le", MP_CONCAT(id, _LE)}, \
{string "be", MP_CONCAT(id, _BE)}, \
const struct af_fmt_entry af_fmtstr_table[] = {
FMT("mpeg2", AF_FORMAT_MPEG2)
FMT_ENDIAN("ac3", AF_FORMAT_AC3)
FMT_ENDIAN("iec61937", AF_FORMAT_IEC61937)
{"u8", AF_FORMAT_U8},
{"s8", AF_FORMAT_S8},
{"u16", AF_FORMAT_U16},
{"s16", AF_FORMAT_S16},
{"u24", AF_FORMAT_U24},
{"s24", AF_FORMAT_S24},
{"u32", AF_FORMAT_U32},
{"s32", AF_FORMAT_S32},
{"float", AF_FORMAT_FLOAT},
{"double", AF_FORMAT_DOUBLE},
FMT("u8", AF_FORMAT_U8)
FMT("s8", AF_FORMAT_S8)
FMT_ENDIAN("u16", AF_FORMAT_U16)
FMT_ENDIAN("s16", AF_FORMAT_S16)
FMT_ENDIAN("u24", AF_FORMAT_U24)
FMT_ENDIAN("s24", AF_FORMAT_S24)
FMT_ENDIAN("u32", AF_FORMAT_U32)
FMT_ENDIAN("s32", AF_FORMAT_S32)
FMT_ENDIAN("float", AF_FORMAT_FLOAT)
FMT_ENDIAN("double", AF_FORMAT_DOUBLE)
{"u8p", AF_FORMAT_U8P},
{"s16p", AF_FORMAT_S16P},
{"s32p", AF_FORMAT_S32P},
{"floatp", AF_FORMAT_FLOATP},
{"doublep", AF_FORMAT_DOUBLEP},
FMT("u8p", AF_FORMAT_U8P)
FMT("s16p", AF_FORMAT_S16P)
FMT("s32p", AF_FORMAT_S32P)
FMT("floatp", AF_FORMAT_FLOATP)
FMT("doublep", AF_FORMAT_DOUBLEP)
{"spdif-aac", AF_FORMAT_S_AAC},
{"spdif-ac3", AF_FORMAT_S_AC3},
{"spdif-dts", AF_FORMAT_S_DTS},
{"spdif-dtshd", AF_FORMAT_S_DTSHD},
{"spdif-eac3", AF_FORMAT_S_EAC3},
{"spdif-mp3", AF_FORMAT_S_MP3},
{"spdif-truehd",AF_FORMAT_S_TRUEHD},
{0}
};
@@ -199,22 +192,17 @@ int af_format_conversion_score(int dst_format, int src_format)
return INT_MIN;
if (dst_format == src_format)
return 1024;
// Just endian swapping (separate because it works for special formats)
if ((dst_format & ~AF_FORMAT_END_MASK) == (src_format & ~AF_FORMAT_END_MASK))
return 1024 - 2;
// Can't be normally converted
if (AF_FORMAT_IS_SPECIAL(dst_format) || AF_FORMAT_IS_SPECIAL(src_format))
return INT_MIN;
int score = 1024;
if (FMT_DIFF(AF_FORMAT_INTERLEAVING_MASK, dst_format, src_format))
score -= 1; // has to (de-)planarize
if (FMT_DIFF(AF_FORMAT_END_MASK, dst_format, src_format))
score -= 2; // has to swap endian
if (FMT_DIFF(AF_FORMAT_SIGN_MASK, dst_format, src_format))
score -= 4; // has to swap sign
if (FMT_DIFF(AF_FORMAT_POINT_MASK, dst_format, src_format)) {
if (FMT_DIFF(AF_FORMAT_TYPE_MASK, dst_format, src_format)) {
int dst_bits = dst_format & AF_FORMAT_BITS_MASK;
if ((dst_format & AF_FORMAT_POINT_MASK) == AF_FORMAT_F) {
if ((dst_format & AF_FORMAT_TYPE_MASK) == AF_FORMAT_F) {
// For int->float, always prefer 32 bit float.
score -= dst_bits == AF_FORMAT_32BIT ? 8 : 0;
} else {
@@ -230,7 +218,7 @@ int af_format_conversion_score(int dst_format, int src_format)
}
}
// Consider this the worst case.
if (FMT_DIFF(AF_FORMAT_POINT_MASK, dst_format, src_format))
if (FMT_DIFF(AF_FORMAT_TYPE_MASK, dst_format, src_format))
score -= 2048; // has to convert float<->int
return score;
}
+47 -91
View File
@@ -24,122 +24,78 @@
#define MPLAYER_AF_FORMAT_H
#include <stdbool.h>
#include <sys/types.h>
#include "bstr/bstr.h"
#if BYTE_ORDER == BIG_ENDIAN
#define AF_SELECT_LE_BE(LE, BE) BE
#else
#define AF_SELECT_LE_BE(LE, BE) LE
#endif
// Endianness
#define AF_FORMAT_BE (0<<0) // Big Endian
#define AF_FORMAT_LE (1<<0) // Little Endian
#define AF_FORMAT_END_MASK (1<<0)
#define AF_FORMAT_NE AF_SELECT_LE_BE(AF_FORMAT_LE, AF_FORMAT_BE)
#include "misc/bstr.h"
// Signed/unsigned
#define AF_FORMAT_SI (0<<1) // Signed
#define AF_FORMAT_US (1<<1) // Unsigned
#define AF_FORMAT_SIGN_MASK (1<<1)
#define AF_FORMAT_SI (0<<0) // Signed
#define AF_FORMAT_US (1<<0) // Unsigned
#define AF_FORMAT_SIGN_MASK (1<<0)
// Bits used
// Some code assumes they're sorted by size.
#define AF_FORMAT_8BIT (0<<3)
#define AF_FORMAT_16BIT (1<<3)
#define AF_FORMAT_24BIT (2<<3)
#define AF_FORMAT_32BIT (3<<3)
#define AF_FORMAT_64BIT (4<<3)
#define AF_FORMAT_BITS_MASK (7<<3)
#define AF_FORMAT_8BIT (0<<1)
#define AF_FORMAT_16BIT (1<<1)
#define AF_FORMAT_24BIT (2<<1)
#define AF_FORMAT_32BIT (3<<1)
#define AF_FORMAT_64BIT (4<<1)
#define AF_FORMAT_BITS_MASK (7<<1)
// Special flags refering to non pcm data (note: 1<<6, 2<<6, 5<<6 unused)
#define AF_FORMAT_S_MPEG2 (3<<6) // MPEG(2) audio
#define AF_FORMAT_S_AC3 (4<<6) // Dolby Digital AC3
#define AF_FORMAT_S_IEC61937 (6<<6)
#define AF_FORMAT_SPECIAL_MASK (7<<6)
// Fixed or floating point
#define AF_FORMAT_I (1<<9) // Int
#define AF_FORMAT_F (2<<9) // Foating point
#define AF_FORMAT_POINT_MASK (3<<9)
// Fixed/floating point/special
#define AF_FORMAT_I (1<<4) // Int
#define AF_FORMAT_F (2<<4) // Foating point
#define AF_FORMAT_S (4<<4) // special (IEC61937)
#define AF_FORMAT_TYPE_MASK (7<<4)
// Interleaving (planar formats have data for each channel in separate planes)
#define AF_FORMAT_INTERLEAVED (0<<11) // must be 0
#define AF_FORMAT_PLANAR (1<<11)
#define AF_FORMAT_INTERLEAVING_MASK (1<<11)
#define AF_FORMAT_INTERLEAVED (0<<7) // must be 0
#define AF_FORMAT_PLANAR (1<<7)
#define AF_FORMAT_INTERLEAVING_MASK (1<<7)
#define AF_FORMAT_S_CODEC(n) ((n)<<8)
#define AF_FORMAT_S_CODEC_MASK (15 <<8) // 16 codecs max.
#define AF_FORMAT_MASK ((1<<12)-1)
#define AF_INTP (AF_FORMAT_I|AF_FORMAT_PLANAR)
#define AF_FLTP (AF_FORMAT_F|AF_FORMAT_PLANAR)
#define AF_FORMAT_S_(n) (AF_FORMAT_S_CODEC(n)|AF_FORMAT_S|AF_FORMAT_16BIT)
// actual sample formats
enum af_format {
AF_FORMAT_UNKNOWN = 0,
AF_FORMAT_U8 = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_8BIT|AF_FORMAT_NE),
AF_FORMAT_S8 = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_8BIT|AF_FORMAT_NE),
AF_FORMAT_U16_LE = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_16BIT|AF_FORMAT_LE),
AF_FORMAT_U16_BE = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_16BIT|AF_FORMAT_BE),
AF_FORMAT_S16_LE = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_16BIT|AF_FORMAT_LE),
AF_FORMAT_S16_BE = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_16BIT|AF_FORMAT_BE),
AF_FORMAT_U24_LE = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_24BIT|AF_FORMAT_LE),
AF_FORMAT_U24_BE = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_24BIT|AF_FORMAT_BE),
AF_FORMAT_S24_LE = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_24BIT|AF_FORMAT_LE),
AF_FORMAT_S24_BE = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_24BIT|AF_FORMAT_BE),
AF_FORMAT_U32_LE = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_32BIT|AF_FORMAT_LE),
AF_FORMAT_U32_BE = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_32BIT|AF_FORMAT_BE),
AF_FORMAT_S32_LE = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_32BIT|AF_FORMAT_LE),
AF_FORMAT_S32_BE = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_32BIT|AF_FORMAT_BE),
AF_FORMAT_U8 = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_8BIT),
AF_FORMAT_S8 = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_8BIT),
AF_FORMAT_U16 = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_16BIT),
AF_FORMAT_S16 = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_16BIT),
AF_FORMAT_U24 = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_24BIT),
AF_FORMAT_S24 = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_24BIT),
AF_FORMAT_U32 = (AF_FORMAT_I|AF_FORMAT_US|AF_FORMAT_32BIT),
AF_FORMAT_S32 = (AF_FORMAT_I|AF_FORMAT_SI|AF_FORMAT_32BIT),
AF_FORMAT_FLOAT_LE = (AF_FORMAT_F|AF_FORMAT_32BIT|AF_FORMAT_LE),
AF_FORMAT_FLOAT_BE = (AF_FORMAT_F|AF_FORMAT_32BIT|AF_FORMAT_BE),
AF_FORMAT_DOUBLE_LE = (AF_FORMAT_F|AF_FORMAT_64BIT|AF_FORMAT_LE),
AF_FORMAT_DOUBLE_BE = (AF_FORMAT_F|AF_FORMAT_64BIT|AF_FORMAT_BE),
AF_FORMAT_AC3_LE = (AF_FORMAT_S_AC3|AF_FORMAT_16BIT|AF_FORMAT_LE),
AF_FORMAT_AC3_BE = (AF_FORMAT_S_AC3|AF_FORMAT_16BIT|AF_FORMAT_BE),
AF_FORMAT_IEC61937_LE = (AF_FORMAT_S_IEC61937|AF_FORMAT_16BIT|AF_FORMAT_LE),
AF_FORMAT_IEC61937_BE = (AF_FORMAT_S_IEC61937|AF_FORMAT_16BIT|AF_FORMAT_BE),
AF_FORMAT_MPEG2 = (AF_FORMAT_S_MPEG2),
AF_FORMAT_FLOAT = (AF_FORMAT_F|AF_FORMAT_32BIT),
AF_FORMAT_DOUBLE = (AF_FORMAT_F|AF_FORMAT_64BIT),
// Planar variants
AF_FORMAT_U8P = (AF_INTP|AF_FORMAT_US|AF_FORMAT_8BIT|AF_FORMAT_NE),
AF_FORMAT_S16P = (AF_INTP|AF_FORMAT_SI|AF_FORMAT_16BIT|AF_FORMAT_NE),
AF_FORMAT_S32P = (AF_INTP|AF_FORMAT_SI|AF_FORMAT_32BIT|AF_FORMAT_NE),
AF_FORMAT_FLOATP = (AF_FLTP|AF_FORMAT_32BIT|AF_FORMAT_NE),
AF_FORMAT_DOUBLEP = (AF_FLTP|AF_FORMAT_64BIT|AF_FORMAT_NE),
AF_FORMAT_U8P = (AF_INTP|AF_FORMAT_US|AF_FORMAT_8BIT),
AF_FORMAT_S16P = (AF_INTP|AF_FORMAT_SI|AF_FORMAT_16BIT),
AF_FORMAT_S32P = (AF_INTP|AF_FORMAT_SI|AF_FORMAT_32BIT),
AF_FORMAT_FLOATP = (AF_FLTP|AF_FORMAT_32BIT),
AF_FORMAT_DOUBLEP = (AF_FLTP|AF_FORMAT_64BIT),
// Native endian variants
AF_FORMAT_U16 = AF_SELECT_LE_BE(AF_FORMAT_U16_LE, AF_FORMAT_U16_BE),
AF_FORMAT_S16 = AF_SELECT_LE_BE(AF_FORMAT_S16_LE, AF_FORMAT_S16_BE),
AF_FORMAT_U24 = AF_SELECT_LE_BE(AF_FORMAT_U24_LE, AF_FORMAT_U24_BE),
AF_FORMAT_S24 = AF_SELECT_LE_BE(AF_FORMAT_S24_LE, AF_FORMAT_S24_BE),
AF_FORMAT_U32 = AF_SELECT_LE_BE(AF_FORMAT_U32_LE, AF_FORMAT_U32_BE),
AF_FORMAT_S32 = AF_SELECT_LE_BE(AF_FORMAT_S32_LE, AF_FORMAT_S32_BE),
AF_FORMAT_FLOAT = AF_SELECT_LE_BE(AF_FORMAT_FLOAT_LE, AF_FORMAT_FLOAT_BE),
AF_FORMAT_DOUBLE = AF_SELECT_LE_BE(AF_FORMAT_DOUBLE_LE, AF_FORMAT_DOUBLE_BE),
AF_FORMAT_AC3 = AF_SELECT_LE_BE(AF_FORMAT_AC3_LE, AF_FORMAT_AC3_BE),
AF_FORMAT_IEC61937 = AF_SELECT_LE_BE(AF_FORMAT_IEC61937_LE, AF_FORMAT_IEC61937_BE),
// All of these use IEC61937 framing, and otherwise pretend to be like PCM.
AF_FORMAT_S_AAC = AF_FORMAT_S_(0),
AF_FORMAT_S_AC3 = AF_FORMAT_S_(1),
AF_FORMAT_S_DTS = AF_FORMAT_S_(2),
AF_FORMAT_S_DTSHD = AF_FORMAT_S_(3),
AF_FORMAT_S_EAC3 = AF_FORMAT_S_(4),
AF_FORMAT_S_MP3 = AF_FORMAT_S_(5),
AF_FORMAT_S_TRUEHD = AF_FORMAT_S_(6),
};
#define AF_FORMAT_IS_AC3(fmt) \
(((fmt) & AF_FORMAT_SPECIAL_MASK) == AF_FORMAT_S_AC3)
#define AF_FORMAT_IS_IEC61937(fmt) \
(AF_FORMAT_IS_AC3(fmt) || \
((fmt) & AF_FORMAT_SPECIAL_MASK) == AF_FORMAT_S_IEC61937)
#define AF_FORMAT_IS_SPECIAL(fmt) \
((fmt & AF_FORMAT_SPECIAL_MASK) != 0)
#define AF_FORMAT_IS_IEC61937(f) (((f) & AF_FORMAT_TYPE_MASK) == AF_FORMAT_S)
#define AF_FORMAT_IS_SPECIAL(f) AF_FORMAT_IS_IEC61937(f)
struct af_fmt_entry {
const char *name;
+8 -6
View File
@@ -37,6 +37,7 @@ struct mixer {
struct af_stream *af;
// Static, dependent on ao/softvol settings
bool softvol; // use AO (true) or af_volume (false)
bool ao_softvol; // AO has private or per-app volume
bool emulate_mute; // if true, emulate mute with volume=0
// Last known values (possibly out of sync with reality)
float vol_l, vol_r;
@@ -245,11 +246,13 @@ char *mixer_get_volume_restore_data(struct mixer *mixer)
static void probe_softvol(struct mixer *mixer)
{
mixer->ao_softvol =
ao_control(mixer->ao, AOCONTROL_HAS_SOFT_VOLUME, 0) == 1 ||
ao_control(mixer->ao, AOCONTROL_HAS_PER_APP_VOLUME, 0) == 1;
if (mixer->opts->softvol == SOFTVOL_AUTO) {
// No system-wide volume => fine with AO volume control.
mixer->softvol =
ao_control(mixer->ao, AOCONTROL_HAS_TEMP_VOLUME, 0) != 1 ||
ao_control(mixer->ao, AOCONTROL_HAS_PER_APP_VOLUME, 0) != 1;
mixer->softvol = !mixer->ao_softvol;
} else {
mixer->softvol = mixer->opts->softvol == SOFTVOL_YES;
}
@@ -282,8 +285,7 @@ static void restore_volume(struct mixer *mixer)
const char *prev_driver = mixer->driver;
mixer->driver = mixer->softvol ? "softvol" : ao_get_name(ao);
bool restore =
mixer->softvol || ao_control(ao, AOCONTROL_HAS_TEMP_VOLUME, 0) == 1;
bool restore = mixer->softvol || mixer->ao_softvol;
// Restore old parameters if volume won't survive reinitialization.
// But not if volume scale is possibly different.
@@ -361,7 +363,7 @@ void mixer_uninit_audio(struct mixer *mixer)
return;
checkvolume(mixer);
if (mixer->muted_by_us) {
if (mixer->muted_by_us && !mixer->softvol && !mixer->ao_softvol) {
/* Current audio output API combines playing the remaining buffered
* audio and uninitializing the AO into one operation, even though
* ideally unmute would happen between those two steps. We can't do
+12 -28
View File
@@ -31,13 +31,13 @@
#include "options/options.h"
#include "options/m_config.h"
#include "osdep/timer.h"
#include "common/msg.h"
#include "common/common.h"
#include "common/global.h"
extern const struct ao_driver audio_out_oss;
extern const struct ao_driver audio_out_coreaudio;
extern const struct ao_driver audio_out_coreaudio_exclusive;
extern const struct ao_driver audio_out_rsound;
extern const struct ao_driver audio_out_sndio;
extern const struct ao_driver audio_out_pulse;
@@ -60,9 +60,6 @@ static const struct ao_driver * const audio_out_drivers[] = {
#if HAVE_PULSE
&audio_out_pulse,
#endif
#if HAVE_SNDIO
&audio_out_sndio,
#endif
#if HAVE_ALSA
&audio_out_alsa,
#endif
@@ -87,6 +84,9 @@ static const struct ao_driver * const audio_out_drivers[] = {
#endif
#if HAVE_SDL1 || HAVE_SDL2
&audio_out_sdl,
#endif
#if HAVE_SNDIO
&audio_out_sndio,
#endif
&audio_out_null,
// should not be auto-selected:
@@ -94,6 +94,9 @@ static const struct ao_driver * const audio_out_drivers[] = {
#if HAVE_ENCODING
&audio_out_lavc,
#endif
#if HAVE_COREAUDIO
&audio_out_coreaudio_exclusive,
#endif
#if HAVE_RSOUND
&audio_out_rsound,
#endif
@@ -149,6 +152,7 @@ static struct ao *ao_create(bool probing, struct mpv_global *global,
.channels = channels,
.format = format,
.log = mp_log_new(ao, log, name),
.def_buffer = global->opts->audio_buffer,
};
if (ao->driver->encode != !!ao->encode_lavc_ctx)
goto error;
@@ -184,7 +188,7 @@ static struct ao *ao_create(bool probing, struct mpv_global *global,
ao->device_buffer = ao->driver->get_space(ao);
MP_VERBOSE(ao, "device buffer: %d samples.\n", ao->device_buffer);
}
ao->buffer = MPMAX(ao->device_buffer, MIN_BUFFER * ao->samplerate);
ao->buffer = MPMAX(ao->device_buffer, ao->def_buffer * ao->samplerate);
MP_VERBOSE(ao, "using soft-buffer of %d samples.\n", ao->buffer);
if (ao->api->init(ao) < 0)
@@ -255,16 +259,7 @@ int ao_play(struct ao *ao, void **data, int samples, int flags)
int ao_control(struct ao *ao, enum aocontrol cmd, void *arg)
{
switch (cmd) {
case AOCONTROL_HAS_TEMP_VOLUME:
return !ao->no_persistent_volume;
case AOCONTROL_HAS_PER_APP_VOLUME:
return !!ao->per_application_mixer;
default:
if (ao->api->control)
return ao->api->control(ao, cmd, arg);
}
return CONTROL_UNKNOWN;
return ao->api->control ? ao->api->control(ao, cmd, arg) : CONTROL_UNKNOWN;
}
// Return size of the buffered data in seconds. Can include the device latency.
@@ -309,27 +304,16 @@ void ao_resume(struct ao *ao)
ao->api->resume(ao);
}
// Be careful with locking
void ao_wait_drain(struct ao *ao)
{
// This is probably not entirely accurate, but good enough.
mp_sleep_us(ao_get_delay(ao) * 1000000);
ao_reset(ao);
}
// Block until the current audio buffer has played completely.
void ao_drain(struct ao *ao)
{
if (ao->api->drain) {
if (ao->api->drain)
ao->api->drain(ao);
} else {
ao_wait_drain(ao);
}
}
bool ao_eof_reached(struct ao *ao)
{
return ao_get_delay(ao) < AO_EOF_DELAY;
return ao->api->get_eof ? ao->api->get_eof(ao) : true;
}
bool ao_chmap_sel_adjust(struct ao *ao, const struct mp_chmap_sel *s,
+4 -2
View File
@@ -21,7 +21,7 @@
#include <stdbool.h>
#include "bstr/bstr.h"
#include "misc/bstr.h"
#include "common/common.h"
#include "audio/chmap.h"
#include "audio/chmap_sel.h"
@@ -36,7 +36,9 @@ enum aocontrol {
AOCONTROL_SET_MUTE,
// Has char* as argument, which contains the desired stream title.
AOCONTROL_UPDATE_STREAM_TITLE,
AOCONTROL_HAS_TEMP_VOLUME,
// the AO does the equivalent of af_volume (return CONTROL_TRUE if yes)
AOCONTROL_HAS_SOFT_VOLUME,
// like above, but volume persists (per app), mpv won't restore volume
AOCONTROL_HAS_PER_APP_VOLUME,
};
+31 -30
View File
@@ -31,7 +31,6 @@
#include <sys/time.h>
#include <stdlib.h>
#include <stdarg.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
@@ -39,6 +38,7 @@
#include "options/options.h"
#include "options/m_option.h"
#include "common/msg.h"
#include "osdep/endian.h"
#define ALSA_PCM_NEW_HW_PARAMS_API
#define ALSA_PCM_NEW_SW_PARAMS_API
@@ -64,6 +64,7 @@ struct priv {
char *cfg_mixer_name;
int cfg_mixer_index;
int cfg_resample;
int cfg_ni;
};
#define BUFFER_TIME 250000 // 250ms
@@ -99,7 +100,7 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
long get_vol, set_vol;
float f_multi;
if (AF_FORMAT_IS_IEC61937(ao->format))
if (AF_FORMAT_IS_SPECIAL(ao->format))
return CONTROL_FALSE;
//allocate simple id
@@ -208,25 +209,15 @@ alsa_error:
static const int mp_to_alsa_format[][2] = {
{AF_FORMAT_S8, SND_PCM_FORMAT_S8},
{AF_FORMAT_U8, SND_PCM_FORMAT_U8},
{AF_FORMAT_U16_LE, SND_PCM_FORMAT_U16_LE},
{AF_FORMAT_U16_BE, SND_PCM_FORMAT_U16_BE},
{AF_FORMAT_S16_LE, SND_PCM_FORMAT_S16_LE},
{AF_FORMAT_S16_BE, SND_PCM_FORMAT_S16_BE},
{AF_FORMAT_U32_LE, SND_PCM_FORMAT_U32_LE},
{AF_FORMAT_U32_BE, SND_PCM_FORMAT_U32_BE},
{AF_FORMAT_S32_LE, SND_PCM_FORMAT_S32_LE},
{AF_FORMAT_S32_BE, SND_PCM_FORMAT_S32_BE},
{AF_FORMAT_U24_LE, SND_PCM_FORMAT_U24_3LE},
{AF_FORMAT_U24_BE, SND_PCM_FORMAT_U24_3BE},
{AF_FORMAT_S24_LE, SND_PCM_FORMAT_S24_3LE},
{AF_FORMAT_S24_BE, SND_PCM_FORMAT_S24_3BE},
{AF_FORMAT_FLOAT_LE, SND_PCM_FORMAT_FLOAT_LE},
{AF_FORMAT_FLOAT_BE, SND_PCM_FORMAT_FLOAT_BE},
{AF_FORMAT_AC3_LE, SND_PCM_FORMAT_S16_LE},
{AF_FORMAT_AC3_BE, SND_PCM_FORMAT_S16_BE},
{AF_FORMAT_IEC61937_LE, SND_PCM_FORMAT_S16_LE},
{AF_FORMAT_IEC61937_BE, SND_PCM_FORMAT_S16_BE},
{AF_FORMAT_MPEG2, SND_PCM_FORMAT_MPEG},
{AF_FORMAT_U16, SND_PCM_FORMAT_U16},
{AF_FORMAT_S16, SND_PCM_FORMAT_S16},
{AF_FORMAT_U32, SND_PCM_FORMAT_U32},
{AF_FORMAT_S32, SND_PCM_FORMAT_S32},
{AF_FORMAT_U24,
MP_SELECT_LE_BE(SND_PCM_FORMAT_U24_3LE, SND_PCM_FORMAT_U24_3BE)},
{AF_FORMAT_S24,
MP_SELECT_LE_BE(SND_PCM_FORMAT_S24_3LE, SND_PCM_FORMAT_S24_3BE)},
{AF_FORMAT_FLOAT, SND_PCM_FORMAT_FLOAT},
{AF_FORMAT_UNKNOWN, SND_PCM_FORMAT_UNKNOWN},
};
@@ -353,6 +344,9 @@ static int init(struct ao *ao)
struct priv *p = ao->priv;
if (!p->cfg_ni)
ao->format = af_fmt_from_planar(ao->format);
/* switch for spdif
* sets opening sequence for SPDIF
* sets also the playback and other switches 'on the fly'
@@ -406,7 +400,15 @@ static int init(struct ao *ao)
err = snd_pcm_hw_params_any(p->alsa, alsa_hwparams);
CHECK_ALSA_ERROR("Unable to get initial parameters");
p->alsa_fmt = find_alsa_format(ao->format);
if (AF_FORMAT_IS_IEC61937(ao->format)) {
if (ao->format == AF_FORMAT_S_MP3) {
p->alsa_fmt = SND_PCM_FORMAT_MPEG;
} else {
p->alsa_fmt = SND_PCM_FORMAT_S16;
}
} else {
p->alsa_fmt = find_alsa_format(ao->format);
}
if (p->alsa_fmt == SND_PCM_FORMAT_UNKNOWN) {
p->alsa_fmt = SND_PCM_FORMAT_S16;
ao->format = AF_FORMAT_S16;
@@ -414,15 +416,12 @@ static int init(struct ao *ao)
err = snd_pcm_hw_params_test_format(p->alsa, alsa_hwparams, p->alsa_fmt);
if (err < 0) {
if (AF_FORMAT_IS_IEC61937(ao->format))
CHECK_ALSA_ERROR("Unable to set IEC61937 format");
MP_INFO(ao, "Format %s is not supported by hardware, trying default.\n",
af_fmt_to_str(ao->format));
p->alsa_fmt = SND_PCM_FORMAT_S16_LE;
if (AF_FORMAT_IS_AC3(ao->format))
ao->format = AF_FORMAT_AC3_LE;
else if (AF_FORMAT_IS_IEC61937(ao->format))
ao->format = AF_FORMAT_IEC61937_LE;
else
ao->format = AF_FORMAT_S16_LE;
p->alsa_fmt = SND_PCM_FORMAT_S16;
ao->format = AF_FORMAT_S16;
}
err = snd_pcm_hw_params_set_format(p->alsa, alsa_hwparams, p->alsa_fmt);
@@ -672,7 +671,7 @@ static int get_space(struct ao *ao)
unsigned space = snd_pcm_status_get_avail(status);
if (space > p->buffersize) // Buffer underrun?
space = p->buffersize;
return space;
return space / p->outburst * p->outburst;
alsa_error:
return 0;
@@ -755,6 +754,7 @@ const struct ao_driver audio_out_alsa = {
.cfg_mixer_device = "default",
.cfg_mixer_name = "Master",
.cfg_mixer_index = 0,
.cfg_ni = 0,
},
.options = (const struct m_option[]) {
OPT_STRING("device", cfg_device, 0),
@@ -763,6 +763,7 @@ const struct ao_driver audio_out_alsa = {
OPT_STRING("mixer-device", cfg_mixer_device, 0),
OPT_STRING("mixer-name", cfg_mixer_name, 0),
OPT_INTRANGE("mixer-index", cfg_mixer_index, 0, 0, 99),
OPT_FLAG("non-interleaved", cfg_ni, 0),
{0}
},
};
+260 -516
View File
@@ -1,39 +1,21 @@
/*
* CoreAudio audio output driver for Mac OS X
* This file is part of mpv.
*
* original copyright (C) Timothy J. Wood - Aug 2000
* ported to MPlayer libao2 by Dan Christiansen
*
* Chris Roccati
* Stefano Pigozzi
*
* The S/PDIF part of the code is based on the auhal audio output
* module from VideoLAN:
* Copyright (c) 2006 Derk-Jan Hartman <hartman at videolan dot org>
*
* This file is part of MPlayer.
*
* MPlayer is free software; you can redistribute it and/or modify
* mpv is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MPlayer is distributed in the hope that it will be useful,
* mpv is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* along with MPlayer; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
* with mpv. If not, see <http://www.gnu.org/licenses/>.
*/
/*
* The MacOS X CoreAudio framework doesn't mesh as simply as some
* simpler frameworks do. This is due to the fact that CoreAudio pulls
* audio samples rather than having them pushed at it (which is nice
* when you are wanting to do good buffering of audio).
*/
#include <CoreAudio/HostTime.h>
#include "config.h"
#include "ao.h"
@@ -46,61 +28,64 @@
#include "audio/out/ao_coreaudio_properties.h"
#include "audio/out/ao_coreaudio_utils.h"
static void audio_pause(struct ao *ao);
static void audio_resume(struct ao *ao);
static void reset(struct ao *ao);
static void print_buffer(struct ao *ao, struct mp_ring *buffer)
{
void *tctx = talloc_new(NULL);
MP_VERBOSE(ao, "%s\n", mp_ring_repr(buffer, tctx));
talloc_free(tctx);
}
struct priv_d {
// digital render callback
AudioDeviceIOProcID render_cb;
// pid set for hog mode, (-1) means that hog mode on the device was
// released. hog mode is exclusive access to a device
pid_t hog_pid;
// stream selected for digital playback by the detection in init
AudioStreamID stream;
// stream index in an AudioBufferList
int stream_idx;
// format we changed the stream to: for the digital case each application
// sets the stream format for a device to what it needs
AudioStreamBasicDescription stream_asbd;
AudioStreamBasicDescription original_asbd;
bool changed_mixing;
int stream_asbd_changed;
bool muted;
};
struct priv {
AudioDeviceID device; // selected device
bool is_digital; // running in digital mode?
AudioDeviceID device;
AudioUnit audio_unit;
AudioUnit audio_unit; // AudioUnit for lpcm output
bool paused;
struct mp_ring *buffer;
struct priv_d *digital;
uint64_t hw_latency_us;
// options
int opt_device_id;
int opt_list;
};
static int get_ring_size(struct ao *ao)
bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout,
struct mp_chmap *chmap);
static int64_t ca_frames_to_us(struct ao *ao, uint32_t frames)
{
return af_fmt_seconds_to_bytes(
ao->format, 0.5, ao->channels.num, ao->samplerate);
return frames / (float) ao->samplerate * 1e6;
}
static int64_t ca_get_hardware_latency(struct ao *ao) {
struct priv *p = ao->priv;
double audiounit_latency_sec = 0.0;
uint32_t size = sizeof(audiounit_latency_sec);
OSStatus err = AudioUnitGetProperty(
p->audio_unit,
kAudioUnitProperty_Latency,
kAudioUnitScope_Global,
0,
&audiounit_latency_sec,
&size);
CHECK_CA_ERROR("cannot get audio unit latency");
uint32_t frames = 0;
err = CA_GET_O(p->device, kAudioDevicePropertyLatency, &frames);
CHECK_CA_ERROR("cannot get device latency");
uint64_t audiounit_latency_us = audiounit_latency_sec * 1e6;
uint64_t device_latency_us = ca_frames_to_us(ao, frames);
MP_VERBOSE(ao, "audiounit latency [us]: %lld\n", audiounit_latency_us);
MP_VERBOSE(ao, "device latency [us]: %lld\n", device_latency_us);
return audiounit_latency_us + device_latency_us;
coreaudio_error:
return 0;
}
static int64_t ca_get_latency(const AudioTimeStamp *ts)
{
uint64_t out = AudioConvertHostTimeToNanos(ts->mHostTime);
uint64_t now = AudioConvertHostTimeToNanos(AudioGetCurrentHostTime());
if (now > out)
return 0;
return (out - now) * 1e-3;
}
static OSStatus render_cb_lpcm(void *ctx, AudioUnitRenderActionFlags *aflags,
@@ -109,259 +94,126 @@ static OSStatus render_cb_lpcm(void *ctx, AudioUnitRenderActionFlags *aflags,
{
struct ao *ao = ctx;
struct priv *p = ao->priv;
AudioBuffer buf = buffer_list->mBuffers[0];
int requested = buf.mDataByteSize;
if (mp_ring_buffered(p->buffer) < requested) {
MP_VERBOSE(ao, "buffer underrun\n");
audio_pause(ao);
memset(buf.mData, 0, requested);
} else {
mp_ring_read(p->buffer, buf.mData, requested);
}
int64_t end = mp_time_us();
end += p->hw_latency_us + ca_get_latency(ts) + ca_frames_to_us(ao, frames);
ao_read_data(ao, &buf.mData, frames, end);
return noErr;
}
static OSStatus render_cb_digital(
AudioDeviceID device, const AudioTimeStamp *ts,
const void *in_data, const AudioTimeStamp *in_ts,
AudioBufferList *out_data, const AudioTimeStamp *out_ts, void *ctx)
{
struct ao *ao = ctx;
struct priv *p = ao->priv;
struct priv_d *d = p->digital;
AudioBuffer buf = out_data->mBuffers[d->stream_idx];
int requested = buf.mDataByteSize;
static int get_volume(struct ao *ao, struct ao_control_vol *vol) {
struct priv *p = ao->priv;
float auvol;
OSStatus err =
AudioUnitGetParameter(p->audio_unit, kHALOutputParam_Volume,
kAudioUnitScope_Global, 0, &auvol);
if (d->muted)
mp_ring_drain(p->buffer, requested);
else
mp_ring_read(p->buffer, buf.mData, requested);
CHECK_CA_ERROR("could not get HAL output volume");
vol->left = vol->right = auvol * 100.0;
return CONTROL_TRUE;
coreaudio_error:
return CONTROL_ERROR;
}
return noErr;
static int set_volume(struct ao *ao, struct ao_control_vol *vol) {
struct priv *p = ao->priv;
float auvol = (vol->left + vol->right) / 200.0;
OSStatus err =
AudioUnitSetParameter(p->audio_unit, kHALOutputParam_Volume,
kAudioUnitScope_Global, 0, auvol, 0);
CHECK_CA_ERROR("could not set HAL output volume");
return CONTROL_TRUE;
coreaudio_error:
return CONTROL_ERROR;
}
static int control(struct ao *ao, enum aocontrol cmd, void *arg)
{
struct priv *p = ao->priv;
ao_control_vol_t *control_vol;
OSStatus err;
Float32 vol;
switch (cmd) {
case AOCONTROL_GET_VOLUME:
control_vol = (ao_control_vol_t *)arg;
if (p->is_digital) {
struct priv_d *d = p->digital;
// Digital output has no volume adjust.
int digitalvol = d->muted ? 0 : 100;
*control_vol = (ao_control_vol_t) {
.left = digitalvol, .right = digitalvol,
};
return CONTROL_TRUE;
}
err = AudioUnitGetParameter(p->audio_unit, kHALOutputParam_Volume,
kAudioUnitScope_Global, 0, &vol);
CHECK_CA_ERROR("could not get HAL output volume");
control_vol->left = control_vol->right = vol * 100.0;
return CONTROL_TRUE;
return get_volume(ao, arg);
case AOCONTROL_SET_VOLUME:
control_vol = (ao_control_vol_t *)arg;
if (p->is_digital) {
struct priv_d *d = p->digital;
// Digital output can not set volume. Here we have to return true
// to make mixer forget it. Else mixer will add a soft filter,
// that's not we expected and the filter not support ac3 stream
// will cause mplayer die.
// Although not support set volume, but at least we support mute.
// MPlayer set mute by set volume to zero, we handle it.
if (control_vol->left == 0 && control_vol->right == 0)
d->muted = true;
else
d->muted = false;
return CONTROL_TRUE;
}
vol = (control_vol->left + control_vol->right) / 200.0;
err = AudioUnitSetParameter(p->audio_unit, kHALOutputParam_Volume,
kAudioUnitScope_Global, 0, vol, 0);
CHECK_CA_ERROR("could not set HAL output volume");
return set_volume(ao, arg);
case AOCONTROL_HAS_SOFT_VOLUME:
return CONTROL_TRUE;
case AOCONTROL_HAS_PER_APP_VOLUME:
return CONTROL_TRUE;
} // end switch
return CONTROL_UNKNOWN;
coreaudio_error:
return CONTROL_ERROR;
}
static void print_list(struct ao *ao)
{
char *help = talloc_strdup(NULL, "Available output devices:\n");
AudioDeviceID *devs;
size_t n_devs;
OSStatus err =
CA_GET_ARY(kAudioObjectSystemObject, kAudioHardwarePropertyDevices,
&devs, &n_devs);
CHECK_CA_ERROR("Failed to get list of output devices.");
for (int i = 0; i < n_devs; i++) {
char *name;
err = CA_GET_STR(devs[i], kAudioObjectPropertyName, &name);
if (err == noErr)
talloc_steal(devs, name);
else
name = "Unknown";
help = talloc_asprintf_append(
help, " * %s (id: %" PRIu32 ")\n", name, devs[i]);
}
talloc_free(devs);
coreaudio_error:
MP_INFO(ao, "%s", help);
talloc_free(help);
return CONTROL_UNKNOWN;
}
static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd);
static int init_digital(struct ao *ao, AudioStreamBasicDescription asbd);
static bool init_chmap(struct ao *ao);
static bool init_audiounit(struct ao *ao, AudioStreamBasicDescription asbd);
static int init(struct ao *ao)
{
OSStatus err;
struct priv *p = ao->priv;
struct priv *p = ao->priv;
if (p->opt_list) print_list(ao);
if (p->opt_list) ca_print_device_list(ao);
struct priv_d *d = talloc_zero(p, struct priv_d);
OSStatus err = ca_select_device(ao, p->opt_device_id, &p->device);
CHECK_CA_ERROR("failed to select device");
*d = (struct priv_d) {
.muted = false,
.stream_asbd_changed = 0,
.hog_pid = -1,
.stream = 0,
.stream_idx = -1,
.changed_mixing = false,
};
p->digital = d;
ao->per_application_mixer = true;
ao->no_persistent_volume = true;
AudioDeviceID selected_device = 0;
if (p->opt_device_id < 0) {
// device not set by user, get the default one
err = CA_GET(kAudioObjectSystemObject,
kAudioHardwarePropertyDefaultOutputDevice,
&selected_device);
CHECK_CA_ERROR("could not get default audio device");
} else {
selected_device = p->opt_device_id;
}
if (mp_msg_test(ao->log, MSGL_V)) {
char *name;
err = CA_GET_STR(selected_device, kAudioObjectPropertyName, &name);
CHECK_CA_ERROR("could not get selected audio device name");
MP_VERBOSE(ao, "selected audio output device: %s (%" PRIu32 ")\n",
name, selected_device);
talloc_free(name);
}
// Save selected device id
p->device = selected_device;
if (!init_chmap(ao))
goto coreaudio_error;
ao->format = af_fmt_from_planar(ao->format);
bool supports_digital = false;
/* Probe whether device support S/PDIF stream output if input is AC3 stream. */
if (AF_FORMAT_IS_AC3(ao->format)) {
if (ca_device_supports_digital(ao, selected_device))
supports_digital = true;
}
if (!supports_digital) {
AudioChannelLayout *layouts;
size_t n_layouts;
err = CA_GET_ARY_O(selected_device,
kAudioDevicePropertyPreferredChannelLayout,
&layouts, &n_layouts);
CHECK_CA_ERROR("could not get audio device prefered layouts");
struct mp_chmap_sel chmap_sel = {0};
for (int i = 0; i < n_layouts; i++) {
struct mp_chmap chmap = {0};
if (ca_layout_to_mp_chmap(ao, &layouts[i], &chmap))
mp_chmap_sel_add_map(&chmap_sel, &chmap);
}
talloc_free(layouts);
if (ao->channels.num < 3) {
struct mp_chmap chmap;
mp_chmap_from_channels(&chmap, ao->channels.num);
mp_chmap_sel_add_map(&chmap_sel, &chmap);
}
if (!ao_chmap_sel_adjust(ao, &chmap_sel, &ao->channels)) {
MP_ERR(ao, "could not select a suitable channel map among the "
"hardware supported ones. Make sure to configure your "
"output device correctly in 'Audio MIDI Setup.app'\n");
goto coreaudio_error;
}
} // closes if (!supports_digital)
// Build ASBD for the input format
AudioStreamBasicDescription asbd;
asbd.mSampleRate = ao->samplerate;
asbd.mFormatID = supports_digital ?
kAudioFormat60958AC3 : kAudioFormatLinearPCM;
asbd.mChannelsPerFrame = ao->channels.num;
asbd.mBitsPerChannel = af_fmt2bits(ao->format);
asbd.mFormatFlags = kAudioFormatFlagIsPacked;
ca_fill_asbd(ao, &asbd);
if ((ao->format & AF_FORMAT_POINT_MASK) == AF_FORMAT_F)
asbd.mFormatFlags |= kAudioFormatFlagIsFloat;
if (!init_audiounit(ao, asbd))
goto coreaudio_error;
if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_SI)
asbd.mFormatFlags |= kAudioFormatFlagIsSignedInteger;
if ((ao->format & AF_FORMAT_END_MASK) == AF_FORMAT_BE)
asbd.mFormatFlags |= kAudioFormatFlagIsBigEndian;
asbd.mFramesPerPacket = 1;
asbd.mBytesPerPacket = asbd.mBytesPerFrame =
asbd.mFramesPerPacket * asbd.mChannelsPerFrame *
(asbd.mBitsPerChannel / 8);
ca_print_asbd(ao, "source format:", &asbd);
if (supports_digital)
return init_digital(ao, asbd);
else
return init_lpcm(ao, asbd);
return CONTROL_OK;
coreaudio_error:
return CONTROL_ERROR;
}
static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
static bool init_chmap(struct ao *ao)
{
struct priv *p = ao->priv;
OSStatus err;
AudioChannelLayout *layouts;
size_t n_layouts;
err = CA_GET_ARY_O(p->device,
kAudioDevicePropertyPreferredChannelLayout,
&layouts, &n_layouts);
CHECK_CA_ERROR("could not get audio device prefered layouts");
struct mp_chmap_sel chmap_sel = {0};
for (int i = 0; i < n_layouts; i++) {
struct mp_chmap chmap = {0};
if (ca_layout_to_mp_chmap(ao, &layouts[i], &chmap))
mp_chmap_sel_add_map(&chmap_sel, &chmap);
}
talloc_free(layouts);
if (ao->channels.num < 3) {
struct mp_chmap chmap;
mp_chmap_from_channels(&chmap, ao->channels.num);
mp_chmap_sel_add_map(&chmap_sel, &chmap);
}
if (!ao_chmap_sel_adjust(ao, &chmap_sel, &ao->channels)) {
MP_ERR(ao, "could not select a suitable channel map among the "
"hardware supported ones. Make sure to configure your "
"output device correctly in 'Audio MIDI Setup.app'\n");
goto coreaudio_error;
}
return true;
coreaudio_error:
return false;
}
static bool init_audiounit(struct ao *ao, AudioStreamBasicDescription asbd)
{
OSStatus err;
uint32_t size;
@@ -386,7 +238,6 @@ static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
err = AudioComponentInstanceNew(comp, &(p->audio_unit));
CHECK_CA_ERROR("unable to open audio component");
// Initialize AudioUnit
err = AudioUnitInitialize(p->audio_unit);
CHECK_CA_ERROR_L(coreaudio_error_component,
"unable to initialize audio unit");
@@ -399,7 +250,6 @@ static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
CHECK_CA_ERROR_L(coreaudio_error_audiounit,
"unable to set the input format on the audio unit");
//Set the Current Device to the Default Output Unit.
err = AudioUnitSetProperty(p->audio_unit,
kAudioOutputUnitProperty_CurrentDevice,
kAudioUnitScope_Global, 0, &p->device,
@@ -407,8 +257,7 @@ static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
CHECK_CA_ERROR_L(coreaudio_error_audiounit,
"can't link audio unit to selected device");
p->buffer = mp_ring_new(p, get_ring_size(ao));
print_buffer(ao, p->buffer);
p->hw_latency_us = ca_get_hardware_latency(ao);
AURenderCallbackStruct render_cb = (AURenderCallbackStruct) {
.inputProc = render_cb_lpcm,
@@ -423,279 +272,174 @@ static int init_lpcm(struct ao *ao, AudioStreamBasicDescription asbd)
CHECK_CA_ERROR_L(coreaudio_error_audiounit,
"unable to set render callback on audio unit");
reset(ao);
return CONTROL_OK;
return true;
coreaudio_error_audiounit:
AudioUnitUninitialize(p->audio_unit);
coreaudio_error_component:
AudioComponentInstanceDispose(p->audio_unit);
coreaudio_error:
return CONTROL_ERROR;
return false;
}
static int init_digital(struct ao *ao, AudioStreamBasicDescription asbd)
static void stop(struct ao *ao)
{
struct priv *p = ao->priv;
struct priv_d *d = p->digital;
OSStatus err = noErr;
uint32_t is_alive = 1;
err = CA_GET(p->device, kAudioDevicePropertyDeviceIsAlive, &is_alive);
CHECK_CA_WARN("could not check whether device is alive");
if (!is_alive)
MP_WARN(ao , "device is not alive\n");
p->is_digital = 1;
err = ca_lock_device(p->device, &d->hog_pid);
CHECK_CA_WARN("failed to set hogmode");
err = ca_disable_mixing(ao, p->device, &d->changed_mixing);
CHECK_CA_WARN("failed to disable mixing");
AudioStreamID *streams;
size_t n_streams;
/* Get a list of all the streams on this device. */
err = CA_GET_ARY_O(p->device, kAudioDevicePropertyStreams,
&streams, &n_streams);
CHECK_CA_ERROR("could not get number of streams");
for (int i = 0; i < n_streams && d->stream_idx < 0; i++) {
bool digital = ca_stream_supports_digital(ao, streams[i]);
if (digital) {
err = CA_GET(streams[i], kAudioStreamPropertyPhysicalFormat,
&d->original_asbd);
if (!CHECK_CA_WARN("could not get stream's physical format to "
"revert to, getting the next one"))
continue;
AudioStreamRangedDescription *formats;
size_t n_formats;
err = CA_GET_ARY(streams[i],
kAudioStreamPropertyAvailablePhysicalFormats,
&formats, &n_formats);
if (!CHECK_CA_WARN("could not get number of stream formats"))
continue; // try next one
int req_rate_format = -1;
int max_rate_format = -1;
d->stream = streams[i];
d->stream_idx = i;
for (int j = 0; j < n_formats; j++)
if (ca_format_is_digital(formats[j].mFormat)) {
// select the digital format that has exactly the same
// samplerate. If an exact match cannot be found, select
// the format with highest samplerate as backup.
if (formats[j].mFormat.mSampleRate == asbd.mSampleRate) {
req_rate_format = j;
break;
} else if (max_rate_format < 0 ||
formats[j].mFormat.mSampleRate >
formats[max_rate_format].mFormat.mSampleRate)
max_rate_format = j;
}
if (req_rate_format >= 0)
d->stream_asbd = formats[req_rate_format].mFormat;
else
d->stream_asbd = formats[max_rate_format].mFormat;
talloc_free(formats);
}
}
talloc_free(streams);
if (d->stream_idx < 0) {
MP_WARN(ao , "can't find any digital output stream format\n");
goto coreaudio_error;
}
if (!ca_change_format(ao, d->stream, d->stream_asbd))
goto coreaudio_error;
void *changed = (void *) &(d->stream_asbd_changed);
err = ca_enable_device_listener(p->device, changed);
CHECK_CA_ERROR("cannot install format change listener during init");
#if BYTE_ORDER == BIG_ENDIAN
if (!(p->stream_asdb.mFormatFlags & kAudioFormatFlagIsBigEndian))
#else
/* tell mplayer that we need a byteswap on AC3 streams, */
if (d->stream_asbd.mFormatID & kAudioFormat60958AC3)
ao->format = AF_FORMAT_AC3_LE;
else if (d->stream_asbd.mFormatFlags & kAudioFormatFlagIsBigEndian)
#endif
MP_WARN(ao, "stream has non-native byte order, output may fail\n");
ao->samplerate = d->stream_asbd.mSampleRate;
ao->bps = ao->samplerate *
(d->stream_asbd.mBytesPerPacket /
d->stream_asbd.mFramesPerPacket);
p->buffer = mp_ring_new(p, get_ring_size(ao));
print_buffer(ao, p->buffer);
err = AudioDeviceCreateIOProcID(p->device,
(AudioDeviceIOProc)render_cb_digital,
(void *)ao,
&d->render_cb);
CHECK_CA_ERROR("failed to register digital render callback");
reset(ao);
return CONTROL_TRUE;
coreaudio_error:
err = ca_unlock_device(p->device, &d->hog_pid);
CHECK_CA_WARN("can't release hog mode");
return CONTROL_ERROR;
OSStatus err = AudioOutputUnitStop(p->audio_unit);
CHECK_CA_WARN("can't stop audio unit");
}
static int play(struct ao *ao, void **data, int samples, int flags)
{
struct priv *p = ao->priv;
struct priv_d *d = p->digital;
void *output_samples = data[0];
int num_bytes = samples * ao->sstride;
// Check whether we need to reset the digital output stream.
if (p->is_digital && d->stream_asbd_changed) {
d->stream_asbd_changed = 0;
if (ca_stream_supports_digital(ao, d->stream)) {
if (!ca_change_format(ao, d->stream, d->stream_asbd)) {
MP_WARN(ao , "can't restore digital output\n");
} else {
MP_WARN(ao, "restoring digital output succeeded.\n");
reset(ao);
}
}
}
int wrote = mp_ring_write(p->buffer, output_samples, num_bytes);
audio_resume(ao);
return wrote / ao->sstride;
}
static void reset(struct ao *ao)
static void start(struct ao *ao)
{
struct priv *p = ao->priv;
audio_pause(ao);
mp_ring_reset(p->buffer);
OSStatus err = AudioOutputUnitStart(p->audio_unit);
CHECK_CA_WARN("can't start audio unit");
}
static int get_space(struct ao *ao)
{
struct priv *p = ao->priv;
return mp_ring_available(p->buffer) / ao->sstride;
}
static float get_delay(struct ao *ao)
{
// FIXME: should also report the delay of coreaudio itself (hardware +
// internal buffers)
struct priv *p = ao->priv;
return mp_ring_buffered(p->buffer) / (float)ao->bps;
}
static void uninit(struct ao *ao)
{
struct priv *p = ao->priv;
OSStatus err = noErr;
AudioOutputUnitStop(p->audio_unit);
AudioUnitUninitialize(p->audio_unit);
AudioComponentInstanceDispose(p->audio_unit);
}
if (!p->is_digital) {
AudioOutputUnitStop(p->audio_unit);
AudioUnitUninitialize(p->audio_unit);
AudioComponentInstanceDispose(p->audio_unit);
} else {
struct priv_d *d = p->digital;
// Channel Mapping functions
static const int speaker_map[][2] = {
{ kAudioChannelLabel_Left, MP_SPEAKER_ID_FL },
{ kAudioChannelLabel_Right, MP_SPEAKER_ID_FR },
{ kAudioChannelLabel_Center, MP_SPEAKER_ID_FC },
{ kAudioChannelLabel_LFEScreen, MP_SPEAKER_ID_LFE },
{ kAudioChannelLabel_LeftSurround, MP_SPEAKER_ID_BL },
{ kAudioChannelLabel_RightSurround, MP_SPEAKER_ID_BR },
{ kAudioChannelLabel_LeftCenter, MP_SPEAKER_ID_FLC },
{ kAudioChannelLabel_RightCenter, MP_SPEAKER_ID_FRC },
{ kAudioChannelLabel_CenterSurround, MP_SPEAKER_ID_BC },
{ kAudioChannelLabel_LeftSurroundDirect, MP_SPEAKER_ID_SL },
{ kAudioChannelLabel_RightSurroundDirect, MP_SPEAKER_ID_SR },
{ kAudioChannelLabel_TopCenterSurround, MP_SPEAKER_ID_TC },
{ kAudioChannelLabel_VerticalHeightLeft, MP_SPEAKER_ID_TFL },
{ kAudioChannelLabel_VerticalHeightCenter, MP_SPEAKER_ID_TFC },
{ kAudioChannelLabel_VerticalHeightRight, MP_SPEAKER_ID_TFR },
{ kAudioChannelLabel_TopBackLeft, MP_SPEAKER_ID_TBL },
{ kAudioChannelLabel_TopBackCenter, MP_SPEAKER_ID_TBC },
{ kAudioChannelLabel_TopBackRight, MP_SPEAKER_ID_TBR },
void *changed = (void *) &(d->stream_asbd_changed);
err = ca_disable_device_listener(p->device, changed);
CHECK_CA_WARN("can't remove device listener, this may cause a crash");
// unofficial extensions
{ kAudioChannelLabel_RearSurroundLeft, MP_SPEAKER_ID_SDL },
{ kAudioChannelLabel_RearSurroundRight, MP_SPEAKER_ID_SDR },
{ kAudioChannelLabel_LeftWide, MP_SPEAKER_ID_WL },
{ kAudioChannelLabel_RightWide, MP_SPEAKER_ID_WR },
{ kAudioChannelLabel_LFE2, MP_SPEAKER_ID_LFE2 },
err = AudioDeviceStop(p->device, d->render_cb);
CHECK_CA_WARN("failed to stop audio device");
{ kAudioChannelLabel_HeadphonesLeft, MP_SPEAKER_ID_DL },
{ kAudioChannelLabel_HeadphonesRight, MP_SPEAKER_ID_DR },
err = AudioDeviceDestroyIOProcID(p->device, d->render_cb);
CHECK_CA_WARN("failed to remove device render callback");
{ kAudioChannelLabel_Unknown, -1 },
};
if (!ca_change_format(ao, d->stream, d->original_asbd))
MP_WARN(ao, "can't revert to original device format");
static int ca_label_to_mp_speaker_id(AudioChannelLabel label)
{
for (int i = 0; speaker_map[i][1] >= 0; i++)
if (speaker_map[i][0] == label)
return speaker_map[i][1];
return -1;
}
err = ca_enable_mixing(ao, p->device, d->changed_mixing);
CHECK_CA_WARN("can't re-enable mixing");
static void ca_log_layout(struct ao *ao, AudioChannelLayout *layout)
{
if (!mp_msg_test(ao->log, MSGL_V))
return;
err = ca_unlock_device(p->device, &d->hog_pid);
CHECK_CA_WARN("can't release hog mode");
AudioChannelDescription *descs = layout->mChannelDescriptions;
MP_VERBOSE(ao, "layout: tag: <%d>, bitmap: <%d>, "
"descriptions <%d>\n",
layout->mChannelLayoutTag,
layout->mChannelBitmap,
layout->mNumberChannelDescriptions);
for (int i = 0; i < layout->mNumberChannelDescriptions; i++) {
AudioChannelDescription d = descs[i];
MP_VERBOSE(ao, " - description %d: label <%d, %d>, flags: <%u>, "
"coords: <%f, %f, %f>\n", i,
d.mChannelLabel,
ca_label_to_mp_speaker_id(d.mChannelLabel),
d.mChannelFlags,
d.mCoordinates[0],
d.mCoordinates[1],
d.mCoordinates[2]);
}
}
static void audio_pause(struct ao *ao)
bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout,
struct mp_chmap *chmap)
{
struct priv *p = ao->priv;
OSErr err = noErr;
AudioChannelLayoutTag tag = layout->mChannelLayoutTag;
uint32_t layout_size = sizeof(layout);
OSStatus err;
if (p->paused)
return;
if (!p->is_digital) {
err = AudioOutputUnitStop(p->audio_unit);
CHECK_CA_WARN("can't stop audio unit");
} else {
struct priv_d *d = p->digital;
err = AudioDeviceStop(p->device, d->render_cb);
CHECK_CA_WARN("can't stop digital device");
if (tag == kAudioChannelLayoutTag_UseChannelBitmap) {
err = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
sizeof(uint32_t),
&layout->mChannelBitmap,
&layout_size,
layout);
CHECK_CA_ERROR("failed to convert channel bitmap to descriptions");
} else if (tag != kAudioChannelLayoutTag_UseChannelDescriptions) {
err = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
sizeof(AudioChannelLayoutTag),
&layout->mChannelLayoutTag,
&layout_size,
layout);
CHECK_CA_ERROR("failed to convert channel tag to descriptions");
}
p->paused = true;
}
ca_log_layout(ao, layout);
static void audio_resume(struct ao *ao)
{
struct priv *p = ao->priv;
OSErr err = noErr;
// If the channel layout uses channel descriptions, from my
// experiments there are there three possibile cases:
// * The description has a label kAudioChannelLabel_Unknown:
// Can't do anything about this (looks like non surround
// layouts are like this).
// * The description uses positional information: this in
// theory could be used but one would have to map spatial
// positions to labels which is not really feasible.
// * The description has a well known label which can be mapped
// to the waveextensible definition: this is the kind of
// descriptions we process here.
if (!p->paused)
return;
if (!p->is_digital) {
err = AudioOutputUnitStart(p->audio_unit);
CHECK_CA_WARN("can't start audio unit");
} else {
struct priv_d *d = p->digital;
err = AudioDeviceStart(p->device, d->render_cb);
CHECK_CA_WARN("can't start digital device");
for (int n = 0; n < layout->mNumberChannelDescriptions; n++) {
AudioChannelLabel label = layout->mChannelDescriptions[n].mChannelLabel;
uint8_t speaker = ca_label_to_mp_speaker_id(label);
if (label == kAudioChannelLabel_Unknown)
continue;
if (speaker < 0) {
MP_VERBOSE(ao, "channel label=%d unusable to build channel "
"bitmap, skipping layout\n", label);
} else {
chmap->speaker[n] = speaker;
chmap->num = n + 1;
}
}
p->paused = false;
return chmap->num > 0;
coreaudio_error:
ca_log_layout(ao, layout);
return false;
}
#define OPT_BASE_STRUCT struct priv
const struct ao_driver audio_out_coreaudio = {
.description = "CoreAudio (OS X Audio Output)",
.description = "CoreAudio AudioUnit",
.name = "coreaudio",
.uninit = uninit,
.init = init,
.play = play,
.control = control,
.get_space = get_space,
.get_delay = get_delay,
.reset = reset,
.pause = audio_pause,
.resume = audio_resume,
.pause = stop,
.resume = start,
.priv_size = sizeof(struct priv),
.options = (const struct m_option[]) {
OPT_INT("device_id", opt_device_id, 0, OPTDEF_INT(-1)),
+677
View File
@@ -0,0 +1,677 @@
/*
* CoreAudio audio output driver for Mac OS X
*
* original copyright (C) Timothy J. Wood - Aug 2000
* ported to MPlayer libao2 by Dan Christiansen
*
* Chris Roccati
* Stefano Pigozzi
*
* The S/PDIF part of the code is based on the auhal audio output
* module from VideoLAN:
* Copyright (c) 2006 Derk-Jan Hartman <hartman at videolan dot org>
*
* This file is part of MPlayer.
*
* MPlayer is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MPlayer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* along with MPlayer; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
* The MacOS X CoreAudio framework doesn't mesh as simply as some
* simpler frameworks do. This is due to the fact that CoreAudio pulls
* audio samples rather than having them pushed at it (which is nice
* when you are wanting to do good buffering of audio).
*/
#include "config.h"
#include "ao.h"
#include "internal.h"
#include "audio/format.h"
#include "osdep/timer.h"
#include "options/m_option.h"
#include "misc/ring.h"
#include "common/msg.h"
#include "audio/out/ao_coreaudio_properties.h"
#include "audio/out/ao_coreaudio_utils.h"
static void audio_pause(struct ao *ao);
static void audio_resume(struct ao *ao);
static void reset(struct ao *ao);
static bool ca_format_is_digital(AudioStreamBasicDescription asbd)
{
switch (asbd.mFormatID)
case 'IAC3':
case 'iac3':
case kAudioFormat60958AC3:
case kAudioFormatAC3:
return true;
return false;
}
static bool ca_stream_supports_digital(struct ao *ao, AudioStreamID stream)
{
AudioStreamRangedDescription *formats = NULL;
size_t n_formats;
OSStatus err =
CA_GET_ARY(stream, kAudioStreamPropertyAvailablePhysicalFormats,
&formats, &n_formats);
CHECK_CA_ERROR("Could not get number of stream formats.");
for (int i = 0; i < n_formats; i++) {
AudioStreamBasicDescription asbd = formats[i].mFormat;
ca_print_asbd(ao, "supported format:", &(asbd));
if (ca_format_is_digital(asbd)) {
talloc_free(formats);
return true;
}
}
talloc_free(formats);
coreaudio_error:
return false;
}
static bool ca_device_supports_digital(struct ao *ao, AudioDeviceID device)
{
AudioStreamID *streams = NULL;
size_t n_streams;
/* Retrieve all the output streams. */
OSStatus err =
CA_GET_ARY_O(device, kAudioDevicePropertyStreams, &streams, &n_streams);
CHECK_CA_ERROR("could not get number of streams.");
for (int i = 0; i < n_streams; i++) {
if (ca_stream_supports_digital(ao, streams[i])) {
talloc_free(streams);
return true;
}
}
talloc_free(streams);
coreaudio_error:
return false;
}
static OSStatus ca_property_listener(
AudioObjectPropertySelector selector,
AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data)
{
void *talloc_ctx = talloc_new(NULL);
for (int i = 0; i < n_addresses; i++) {
if (addresses[i].mSelector == selector) {
if (data) *(volatile int *)data = 1;
break;
}
}
talloc_free(talloc_ctx);
return noErr;
}
static OSStatus ca_stream_listener(
AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data)
{
return ca_property_listener(kAudioStreamPropertyPhysicalFormat,
object, n_addresses, addresses, data);
}
static OSStatus ca_device_listener(
AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data)
{
return ca_property_listener(kAudioDevicePropertyDeviceHasChanged,
object, n_addresses, addresses, data);
}
static OSStatus ca_lock_device(AudioDeviceID device, pid_t *pid) {
*pid = getpid();
OSStatus err = CA_SET(device, kAudioDevicePropertyHogMode, pid);
if (err != noErr)
*pid = -1;
return err;
}
static OSStatus ca_unlock_device(AudioDeviceID device, pid_t *pid) {
if (*pid == getpid()) {
*pid = -1;
return CA_SET(device, kAudioDevicePropertyHogMode, &pid);
}
return noErr;
}
static OSStatus ca_change_mixing(struct ao *ao, AudioDeviceID device,
uint32_t val, bool *changed) {
*changed = false;
AudioObjectPropertyAddress p_addr = (AudioObjectPropertyAddress) {
.mSelector = kAudioDevicePropertySupportsMixing,
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = kAudioObjectPropertyElementMaster,
};
if (AudioObjectHasProperty(device, &p_addr)) {
OSStatus err;
Boolean writeable = 0;
err = CA_SETTABLE(device, kAudioDevicePropertySupportsMixing,
&writeable);
if (!CHECK_CA_WARN("can't tell if mixing property is settable")) {
return err;
}
if (!writeable)
return noErr;
err = CA_SET(device, kAudioDevicePropertySupportsMixing, &val);
if (err != noErr)
return err;
if (!CHECK_CA_WARN("can't set mix mode")) {
return err;
}
*changed = true;
}
return noErr;
}
static OSStatus ca_disable_mixing(struct ao *ao,
AudioDeviceID device, bool *changed) {
return ca_change_mixing(ao, device, 0, changed);
}
static OSStatus ca_enable_mixing(struct ao *ao,
AudioDeviceID device, bool changed) {
if (changed) {
bool dont_care = false;
return ca_change_mixing(ao, device, 1, &dont_care);
}
return noErr;
}
static OSStatus ca_change_device_listening(AudioDeviceID device,
void *flag, bool enabled)
{
AudioObjectPropertyAddress p_addr = (AudioObjectPropertyAddress) {
.mSelector = kAudioDevicePropertyDeviceHasChanged,
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = kAudioObjectPropertyElementMaster,
};
if (enabled) {
return AudioObjectAddPropertyListener(
device, &p_addr, ca_device_listener, flag);
} else {
return AudioObjectRemovePropertyListener(
device, &p_addr, ca_device_listener, flag);
}
}
static OSStatus ca_enable_device_listener(AudioDeviceID device, void *flag) {
return ca_change_device_listening(device, flag, true);
}
static OSStatus ca_disable_device_listener(AudioDeviceID device, void *flag) {
return ca_change_device_listening(device, flag, false);
}
static bool ca_change_format(struct ao *ao, AudioStreamID stream,
AudioStreamBasicDescription change_format)
{
OSStatus err = noErr;
AudioObjectPropertyAddress p_addr;
volatile int stream_format_changed = 0;
ca_print_asbd(ao, "setting stream format:", &change_format);
/* Install the callback. */
p_addr = (AudioObjectPropertyAddress) {
.mSelector = kAudioStreamPropertyPhysicalFormat,
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = kAudioObjectPropertyElementMaster,
};
err = AudioObjectAddPropertyListener(stream, &p_addr, ca_stream_listener,
(void *)&stream_format_changed);
if (!CHECK_CA_WARN("can't add property listener during format change")) {
return false;
}
/* Change the format. */
err = CA_SET(stream, kAudioStreamPropertyPhysicalFormat, &change_format);
if (!CHECK_CA_WARN("error changing physical format")) {
return false;
}
/* The AudioStreamSetProperty is not only asynchronious,
* it is also not Atomic, in its behaviour.
* Therefore we check 5 times before we really give up. */
bool format_set = false;
for (int i = 0; !format_set && i < 5; i++) {
for (int j = 0; !stream_format_changed && j < 50; j++)
mp_sleep_us(10000);
if (stream_format_changed) {
stream_format_changed = 0;
} else {
MP_VERBOSE(ao, "reached timeout\n");
}
AudioStreamBasicDescription actual_format;
err = CA_GET(stream, kAudioStreamPropertyPhysicalFormat, &actual_format);
ca_print_asbd(ao, "actual format in use:", &actual_format);
if (actual_format.mSampleRate == change_format.mSampleRate &&
actual_format.mFormatID == change_format.mFormatID &&
actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
format_set = true;
}
}
err = AudioObjectRemovePropertyListener(stream, &p_addr, ca_stream_listener,
(void *)&stream_format_changed);
if (!CHECK_CA_WARN("can't remove property listener")) {
return false;
}
return format_set;
}
struct priv {
AudioDeviceID device; // selected device
bool paused;
struct mp_ring *buffer;
// digital render callback
AudioDeviceIOProcID render_cb;
// pid set for hog mode, (-1) means that hog mode on the device was
// released. hog mode is exclusive access to a device
pid_t hog_pid;
// stream selected for digital playback by the detection in init
AudioStreamID stream;
// stream index in an AudioBufferList
int stream_idx;
// format we changed the stream to: for the digital case each application
// sets the stream format for a device to what it needs
AudioStreamBasicDescription stream_asbd;
AudioStreamBasicDescription original_asbd;
bool changed_mixing;
int stream_asbd_changed;
bool muted;
// options
int opt_device_id;
int opt_list;
};
static int get_ring_size(struct ao *ao)
{
return af_fmt_seconds_to_bytes(
ao->format, 0.5, ao->channels.num, ao->samplerate);
}
static OSStatus render_cb_digital(
AudioDeviceID device, const AudioTimeStamp *ts,
const void *in_data, const AudioTimeStamp *in_ts,
AudioBufferList *out_data, const AudioTimeStamp *out_ts, void *ctx)
{
struct ao *ao = ctx;
struct priv *p = ao->priv;
AudioBuffer buf = out_data->mBuffers[p->stream_idx];
int requested = buf.mDataByteSize;
if (p->muted)
mp_ring_drain(p->buffer, requested);
else
mp_ring_read(p->buffer, buf.mData, requested);
return noErr;
}
static int control(struct ao *ao, enum aocontrol cmd, void *arg)
{
struct priv *p = ao->priv;
ao_control_vol_t *control_vol;
switch (cmd) {
case AOCONTROL_GET_VOLUME:
control_vol = (ao_control_vol_t *)arg;
// Digital output has no volume adjust.
int digitalvol = p->muted ? 0 : 100;
*control_vol = (ao_control_vol_t) {
.left = digitalvol, .right = digitalvol,
};
return CONTROL_TRUE;
case AOCONTROL_SET_VOLUME:
control_vol = (ao_control_vol_t *)arg;
// Digital output can not set volume. Here we have to return true
// to make mixer forget it. Else mixer will add a soft filter,
// that's not we expected and the filter not support ac3 stream
// will cause mplayer die.
// Although not support set volume, but at least we support mute.
// MPlayer set mute by set volume to zero, we handle it.
if (control_vol->left == 0 && control_vol->right == 0)
p->muted = true;
else
p->muted = false;
return CONTROL_TRUE;
} // end switch
return CONTROL_UNKNOWN;
}
static int init_digital(struct ao *ao, AudioStreamBasicDescription asbd);
static int init(struct ao *ao)
{
struct priv *p = ao->priv;
if (p->opt_list) ca_print_device_list(ao);
OSStatus err = ca_select_device(ao, p->opt_device_id, &p->device);
CHECK_CA_ERROR("failed to select device");
ao->format = af_fmt_from_planar(ao->format);
bool supports_digital = false;
/* Probe whether device support S/PDIF stream output if input is AC3 stream,
* or anything else IEC61937-framed. */
if (AF_FORMAT_IS_IEC61937(ao->format)) {
if (ca_device_supports_digital(ao, p->device))
supports_digital = true;
}
if (!supports_digital) {
MP_ERR(ao, "selected device doesn't support digital formats\n");
goto coreaudio_error;
} // closes if (!supports_digital)
// Build ASBD for the input format
AudioStreamBasicDescription asbd;
ca_fill_asbd(ao, &asbd);
return init_digital(ao, asbd);
coreaudio_error:
return CONTROL_ERROR;
}
static int init_digital(struct ao *ao, AudioStreamBasicDescription asbd)
{
struct priv *p = ao->priv;
OSStatus err = noErr;
uint32_t is_alive = 1;
err = CA_GET(p->device, kAudioDevicePropertyDeviceIsAlive, &is_alive);
CHECK_CA_WARN("could not check whether device is alive");
if (!is_alive)
MP_WARN(ao , "device is not alive\n");
err = ca_lock_device(p->device, &p->hog_pid);
CHECK_CA_WARN("failed to set hogmode");
err = ca_disable_mixing(ao, p->device, &p->changed_mixing);
CHECK_CA_WARN("failed to disable mixing");
AudioStreamID *streams;
size_t n_streams;
/* Get a list of all the streams on this device. */
err = CA_GET_ARY_O(p->device, kAudioDevicePropertyStreams,
&streams, &n_streams);
CHECK_CA_ERROR("could not get number of streams");
for (int i = 0; i < n_streams && p->stream_idx < 0; i++) {
bool digital = ca_stream_supports_digital(ao, streams[i]);
if (digital) {
err = CA_GET(streams[i], kAudioStreamPropertyPhysicalFormat,
&p->original_asbd);
if (!CHECK_CA_WARN("could not get stream's physical format to "
"revert to, getting the next one"))
continue;
AudioStreamRangedDescription *formats;
size_t n_formats;
err = CA_GET_ARY(streams[i],
kAudioStreamPropertyAvailablePhysicalFormats,
&formats, &n_formats);
if (!CHECK_CA_WARN("could not get number of stream formats"))
continue; // try next one
int req_rate_format = -1;
int max_rate_format = -1;
p->stream = streams[i];
p->stream_idx = i;
for (int j = 0; j < n_formats; j++)
if (ca_format_is_digital(formats[j].mFormat)) {
// select the digital format that has exactly the same
// samplerate. If an exact match cannot be found, select
// the format with highest samplerate as backup.
if (formats[j].mFormat.mSampleRate == asbd.mSampleRate) {
req_rate_format = j;
break;
} else if (max_rate_format < 0 ||
formats[j].mFormat.mSampleRate >
formats[max_rate_format].mFormat.mSampleRate)
max_rate_format = j;
}
if (req_rate_format >= 0)
p->stream_asbd = formats[req_rate_format].mFormat;
else
p->stream_asbd = formats[max_rate_format].mFormat;
talloc_free(formats);
}
}
talloc_free(streams);
if (p->stream_idx < 0) {
MP_WARN(ao , "can't find any digital output stream format\n");
goto coreaudio_error;
}
if (!ca_change_format(ao, p->stream, p->stream_asbd))
goto coreaudio_error;
void *changed = (void *) &(p->stream_asbd_changed);
err = ca_enable_device_listener(p->device, changed);
CHECK_CA_ERROR("cannot install format change listener during init");
if (p->stream_asbd.mFormatFlags & kAudioFormatFlagIsBigEndian)
MP_WARN(ao, "stream has non-native byte order, output may fail\n");
ao->samplerate = p->stream_asbd.mSampleRate;
ao->bps = ao->samplerate *
(p->stream_asbd.mBytesPerPacket /
p->stream_asbd.mFramesPerPacket);
p->buffer = mp_ring_new(p, get_ring_size(ao));
err = AudioDeviceCreateIOProcID(p->device,
(AudioDeviceIOProc)render_cb_digital,
(void *)ao,
&p->render_cb);
CHECK_CA_ERROR("failed to register digital render callback");
reset(ao);
return CONTROL_TRUE;
coreaudio_error:
err = ca_unlock_device(p->device, &p->hog_pid);
CHECK_CA_WARN("can't release hog mode");
return CONTROL_ERROR;
}
static int play(struct ao *ao, void **data, int samples, int flags)
{
struct priv *p = ao->priv;
void *output_samples = data[0];
int num_bytes = samples * ao->sstride;
// Check whether we need to reset the digital output stream.
if (p->stream_asbd_changed) {
p->stream_asbd_changed = 0;
if (ca_stream_supports_digital(ao, p->stream)) {
if (!ca_change_format(ao, p->stream, p->stream_asbd)) {
MP_WARN(ao , "can't restore digital output\n");
} else {
MP_WARN(ao, "restoring digital output succeeded.\n");
reset(ao);
}
}
}
int wrote = mp_ring_write(p->buffer, output_samples, num_bytes);
audio_resume(ao);
return wrote / ao->sstride;
}
static void reset(struct ao *ao)
{
struct priv *p = ao->priv;
audio_pause(ao);
mp_ring_reset(p->buffer);
}
static int get_space(struct ao *ao)
{
struct priv *p = ao->priv;
return mp_ring_available(p->buffer) / ao->sstride;
}
static float get_delay(struct ao *ao)
{
// FIXME: should also report the delay of coreaudio itself (hardware +
// internal buffers)
struct priv *p = ao->priv;
return mp_ring_buffered(p->buffer) / (float)ao->bps;
}
static void uninit(struct ao *ao)
{
struct priv *p = ao->priv;
OSStatus err = noErr;
void *changed = (void *) &(p->stream_asbd_changed);
err = ca_disable_device_listener(p->device, changed);
CHECK_CA_WARN("can't remove device listener, this may cause a crash");
err = AudioDeviceStop(p->device, p->render_cb);
CHECK_CA_WARN("failed to stop audio device");
err = AudioDeviceDestroyIOProcID(p->device, p->render_cb);
CHECK_CA_WARN("failed to remove device render callback");
if (!ca_change_format(ao, p->stream, p->original_asbd))
MP_WARN(ao, "can't revert to original device format");
err = ca_enable_mixing(ao, p->device, p->changed_mixing);
CHECK_CA_WARN("can't re-enable mixing");
err = ca_unlock_device(p->device, &p->hog_pid);
CHECK_CA_WARN("can't release hog mode");
}
static void audio_pause(struct ao *ao)
{
struct priv *p = ao->priv;
if (p->paused)
return;
OSStatus err = AudioDeviceStop(p->device, p->render_cb);
CHECK_CA_WARN("can't stop digital device");
p->paused = true;
}
static void audio_resume(struct ao *ao)
{
struct priv *p = ao->priv;
if (!p->paused)
return;
OSStatus err = AudioDeviceStart(p->device, p->render_cb);
CHECK_CA_WARN("can't start digital device");
p->paused = false;
}
#define OPT_BASE_STRUCT struct priv
const struct ao_driver audio_out_coreaudio_exclusive = {
.description = "CoreAudio Exclusive Mode",
.name = "coreaudio_exclusive",
.uninit = uninit,
.init = init,
.play = play,
.control = control,
.get_space = get_space,
.get_delay = get_delay,
.reset = reset,
.pause = audio_pause,
.resume = audio_resume,
.priv_size = sizeof(struct priv),
.priv_defaults = &(const struct priv){
.muted = false,
.stream_asbd_changed = 0,
.hog_pid = -1,
.stream = 0,
.stream_idx = -1,
.changed_mixing = false,
},
.options = (const struct m_option[]) {
OPT_INT("device_id", opt_device_id, 0, OPTDEF_INT(-1)),
OPT_FLAG("list", opt_list, 0),
{0}
},
};
+1
View File
@@ -37,6 +37,7 @@ OSStatus ca_set(AudioObjectID id, ca_scope scope, ca_sel selector,
#define CA_GET(id, sel, data) ca_get(id, CA_GLOBAL, sel, sizeof(*(data)), data)
#define CA_SET(id, sel, data) ca_set(id, CA_GLOBAL, sel, sizeof(*(data)), data)
#define CA_GET_O(id, sel, data) ca_get(id, CA_OUTPUT, sel, sizeof(*(data)), data)
OSStatus ca_get_ary(AudioObjectID id, ca_scope scope, ca_sel selector,
uint32_t element_size, void **data, size_t *elements);
+92 -374
View File
@@ -25,12 +25,76 @@
#include "audio/out/ao_coreaudio_utils.h"
#include "audio/out/ao_coreaudio_properties.h"
#include "osdep/timer.h"
#include "osdep/endian.h"
#include "audio/format.h"
void ca_print_device_list(struct ao *ao)
{
char *help = talloc_strdup(NULL, "Available output devices:\n");
AudioDeviceID *devs;
size_t n_devs;
OSStatus err =
CA_GET_ARY(kAudioObjectSystemObject, kAudioHardwarePropertyDevices,
&devs, &n_devs);
CHECK_CA_ERROR("Failed to get list of output devices.");
for (int i = 0; i < n_devs; i++) {
char *name;
err = CA_GET_STR(devs[i], kAudioObjectPropertyName, &name);
if (err == noErr)
talloc_steal(devs, name);
else
name = "Unknown";
help = talloc_asprintf_append(
help, " * %s (id: %" PRIu32 ")\n", name, devs[i]);
}
talloc_free(devs);
coreaudio_error:
MP_INFO(ao, "%s", help);
talloc_free(help);
}
OSStatus ca_select_device(struct ao *ao, int selection, AudioDeviceID *device)
{
OSStatus err = noErr;
*device = 0;
if (selection < 0) {
// device not set by user, get the default one
err = CA_GET(kAudioObjectSystemObject,
kAudioHardwarePropertyDefaultOutputDevice,
device);
CHECK_CA_ERROR("could not get default audio device");
} else {
*device = selection;
}
if (mp_msg_test(ao->log, MSGL_V)) {
char *name;
err = CA_GET_STR(*device, kAudioObjectPropertyName, &name);
CHECK_CA_ERROR("could not get selected audio device name");
MP_VERBOSE(ao, "selected audio output device: %s (%" PRIu32 ")\n",
name, *device);
talloc_free(name);
}
coreaudio_error:
return err;
}
char *fourcc_repr(void *talloc_ctx, uint32_t code)
{
// Extract FourCC letters from the uint32_t and finde out if it's a valid
// code that is made of letters.
char fcc[4] = {
unsigned char fcc[4] = {
(code >> 24) & 0xFF,
(code >> 16) & 0xFF,
(code >> 8) & 0xFF,
@@ -39,7 +103,7 @@ char *fourcc_repr(void *talloc_ctx, uint32_t code)
bool valid_fourcc = true;
for (int i = 0; i < 4; i++)
if (!isprint(fcc[i]))
if (fcc[i] >= 32 && fcc[i] < 128)
valid_fourcc = false;
char *repr;
@@ -63,6 +127,32 @@ bool check_ca_st(struct ao *ao, int level, OSStatus code, const char *message)
return false;
}
void ca_fill_asbd(struct ao *ao, AudioStreamBasicDescription *asbd)
{
asbd->mSampleRate = ao->samplerate;
// Set "AC3" for other spdif formats too - unknown if that works.
asbd->mFormatID = AF_FORMAT_IS_IEC61937(ao->format) ?
kAudioFormat60958AC3 :
kAudioFormatLinearPCM;
asbd->mChannelsPerFrame = ao->channels.num;
asbd->mBitsPerChannel = af_fmt2bits(ao->format);
asbd->mFormatFlags = kAudioFormatFlagIsPacked;
if ((ao->format & AF_FORMAT_TYPE_MASK) == AF_FORMAT_F)
asbd->mFormatFlags |= kAudioFormatFlagIsFloat;
if ((ao->format & AF_FORMAT_SIGN_MASK) == AF_FORMAT_SI)
asbd->mFormatFlags |= kAudioFormatFlagIsSignedInteger;
if (BYTE_ORDER == BIG_ENDIAN)
asbd->mFormatFlags |= kAudioFormatFlagIsBigEndian;
asbd->mFramesPerPacket = 1;
asbd->mBytesPerPacket = asbd->mBytesPerFrame =
asbd->mFramesPerPacket * asbd->mChannelsPerFrame *
(asbd->mBitsPerChannel / 8);
}
void ca_print_asbd(struct ao *ao, const char *description,
const AudioStreamBasicDescription *asbd)
{
@@ -87,375 +177,3 @@ void ca_print_asbd(struct ao *ao, const char *description,
talloc_free(format);
}
bool ca_format_is_digital(AudioStreamBasicDescription asbd)
{
switch (asbd.mFormatID)
case 'IAC3':
case 'iac3':
case kAudioFormat60958AC3:
case kAudioFormatAC3:
return true;
return false;
}
bool ca_stream_supports_digital(struct ao *ao, AudioStreamID stream)
{
AudioStreamRangedDescription *formats = NULL;
size_t n_formats;
OSStatus err =
CA_GET_ARY(stream, kAudioStreamPropertyAvailablePhysicalFormats,
&formats, &n_formats);
CHECK_CA_ERROR("Could not get number of stream formats.");
for (int i = 0; i < n_formats; i++) {
AudioStreamBasicDescription asbd = formats[i].mFormat;
ca_print_asbd(ao, "supported format:", &(asbd));
if (ca_format_is_digital(asbd)) {
talloc_free(formats);
return true;
}
}
talloc_free(formats);
coreaudio_error:
return false;
}
bool ca_device_supports_digital(struct ao *ao, AudioDeviceID device)
{
AudioStreamID *streams = NULL;
size_t n_streams;
/* Retrieve all the output streams. */
OSStatus err =
CA_GET_ARY_O(device, kAudioDevicePropertyStreams, &streams, &n_streams);
CHECK_CA_ERROR("could not get number of streams.");
for (int i = 0; i < n_streams; i++) {
if (ca_stream_supports_digital(ao, streams[i])) {
talloc_free(streams);
return true;
}
}
talloc_free(streams);
coreaudio_error:
return false;
}
OSStatus ca_property_listener(AudioObjectPropertySelector selector,
AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data)
{
void *talloc_ctx = talloc_new(NULL);
for (int i = 0; i < n_addresses; i++) {
if (addresses[i].mSelector == selector) {
if (data) *(volatile int *)data = 1;
break;
}
}
talloc_free(talloc_ctx);
return noErr;
}
OSStatus ca_stream_listener(AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data)
{
return ca_property_listener(kAudioStreamPropertyPhysicalFormat,
object, n_addresses, addresses, data);
}
OSStatus ca_device_listener(AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data)
{
return ca_property_listener(kAudioDevicePropertyDeviceHasChanged,
object, n_addresses, addresses, data);
}
OSStatus ca_lock_device(AudioDeviceID device, pid_t *pid) {
*pid = getpid();
OSStatus err = CA_SET(device, kAudioDevicePropertyHogMode, pid);
if (err != noErr)
*pid = -1;
return err;
}
OSStatus ca_unlock_device(AudioDeviceID device, pid_t *pid) {
if (*pid == getpid()) {
*pid = -1;
return CA_SET(device, kAudioDevicePropertyHogMode, &pid);
}
return noErr;
}
static OSStatus ca_change_mixing(struct ao *ao, AudioDeviceID device,
uint32_t val, bool *changed) {
*changed = false;
AudioObjectPropertyAddress p_addr = (AudioObjectPropertyAddress) {
.mSelector = kAudioDevicePropertySupportsMixing,
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = kAudioObjectPropertyElementMaster,
};
if (AudioObjectHasProperty(device, &p_addr)) {
OSStatus err;
Boolean writeable = 0;
err = CA_SETTABLE(device, kAudioDevicePropertySupportsMixing,
&writeable);
if (!CHECK_CA_WARN("can't tell if mixing property is settable")) {
return err;
}
if (!writeable)
return noErr;
err = CA_SET(device, kAudioDevicePropertySupportsMixing, &val);
if (err != noErr)
return err;
if (!CHECK_CA_WARN("can't set mix mode")) {
return err;
}
*changed = true;
}
return noErr;
}
OSStatus ca_disable_mixing(struct ao *ao, AudioDeviceID device, bool *changed) {
return ca_change_mixing(ao, device, 0, changed);
}
OSStatus ca_enable_mixing(struct ao *ao, AudioDeviceID device, bool changed) {
if (changed) {
bool dont_care = false;
return ca_change_mixing(ao, device, 1, &dont_care);
}
return noErr;
}
static OSStatus ca_change_device_listening(AudioDeviceID device,
void *flag, bool enabled)
{
AudioObjectPropertyAddress p_addr = (AudioObjectPropertyAddress) {
.mSelector = kAudioDevicePropertyDeviceHasChanged,
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = kAudioObjectPropertyElementMaster,
};
if (enabled) {
return AudioObjectAddPropertyListener(
device, &p_addr, ca_device_listener, flag);
} else {
return AudioObjectRemovePropertyListener(
device, &p_addr, ca_device_listener, flag);
}
}
OSStatus ca_enable_device_listener(AudioDeviceID device, void *flag) {
return ca_change_device_listening(device, flag, true);
}
OSStatus ca_disable_device_listener(AudioDeviceID device, void *flag) {
return ca_change_device_listening(device, flag, false);
}
bool ca_change_format(struct ao *ao, AudioStreamID stream,
AudioStreamBasicDescription change_format)
{
OSStatus err = noErr;
AudioObjectPropertyAddress p_addr;
volatile int stream_format_changed = 0;
ca_print_asbd(ao, "setting stream format:", &change_format);
/* Install the callback. */
p_addr = (AudioObjectPropertyAddress) {
.mSelector = kAudioStreamPropertyPhysicalFormat,
.mScope = kAudioObjectPropertyScopeGlobal,
.mElement = kAudioObjectPropertyElementMaster,
};
err = AudioObjectAddPropertyListener(stream, &p_addr, ca_stream_listener,
(void *)&stream_format_changed);
if (!CHECK_CA_WARN("can't add property listener during format change")) {
return false;
}
/* Change the format. */
err = CA_SET(stream, kAudioStreamPropertyPhysicalFormat, &change_format);
if (!CHECK_CA_WARN("error changing physical format")) {
return false;
}
/* The AudioStreamSetProperty is not only asynchronious,
* it is also not Atomic, in its behaviour.
* Therefore we check 5 times before we really give up. */
bool format_set = false;
for (int i = 0; !format_set && i < 5; i++) {
for (int j = 0; !stream_format_changed && j < 50; j++)
mp_sleep_us(10000);
if (stream_format_changed) {
stream_format_changed = 0;
} else {
MP_VERBOSE(ao, "reached timeout\n");
}
AudioStreamBasicDescription actual_format;
err = CA_GET(stream, kAudioStreamPropertyPhysicalFormat, &actual_format);
ca_print_asbd(ao, "actual format in use:", &actual_format);
if (actual_format.mSampleRate == change_format.mSampleRate &&
actual_format.mFormatID == change_format.mFormatID &&
actual_format.mFramesPerPacket == change_format.mFramesPerPacket) {
format_set = true;
}
}
err = AudioObjectRemovePropertyListener(stream, &p_addr, ca_stream_listener,
(void *)&stream_format_changed);
if (!CHECK_CA_WARN("can't remove property listener")) {
return false;
}
return format_set;
}
static const int speaker_map[][2] = {
{ kAudioChannelLabel_Left, MP_SPEAKER_ID_FL },
{ kAudioChannelLabel_Right, MP_SPEAKER_ID_FR },
{ kAudioChannelLabel_Center, MP_SPEAKER_ID_FC },
{ kAudioChannelLabel_LFEScreen, MP_SPEAKER_ID_LFE },
{ kAudioChannelLabel_LeftSurround, MP_SPEAKER_ID_BL },
{ kAudioChannelLabel_RightSurround, MP_SPEAKER_ID_BR },
{ kAudioChannelLabel_LeftCenter, MP_SPEAKER_ID_FLC },
{ kAudioChannelLabel_RightCenter, MP_SPEAKER_ID_FRC },
{ kAudioChannelLabel_CenterSurround, MP_SPEAKER_ID_BC },
{ kAudioChannelLabel_LeftSurroundDirect, MP_SPEAKER_ID_SL },
{ kAudioChannelLabel_RightSurroundDirect, MP_SPEAKER_ID_SR },
{ kAudioChannelLabel_TopCenterSurround, MP_SPEAKER_ID_TC },
{ kAudioChannelLabel_VerticalHeightLeft, MP_SPEAKER_ID_TFL },
{ kAudioChannelLabel_VerticalHeightCenter, MP_SPEAKER_ID_TFC },
{ kAudioChannelLabel_VerticalHeightRight, MP_SPEAKER_ID_TFR },
{ kAudioChannelLabel_TopBackLeft, MP_SPEAKER_ID_TBL },
{ kAudioChannelLabel_TopBackCenter, MP_SPEAKER_ID_TBC },
{ kAudioChannelLabel_TopBackRight, MP_SPEAKER_ID_TBR },
// unofficial extensions
{ kAudioChannelLabel_RearSurroundLeft, MP_SPEAKER_ID_SDL },
{ kAudioChannelLabel_RearSurroundRight, MP_SPEAKER_ID_SDR },
{ kAudioChannelLabel_LeftWide, MP_SPEAKER_ID_WL },
{ kAudioChannelLabel_RightWide, MP_SPEAKER_ID_WR },
{ kAudioChannelLabel_LFE2, MP_SPEAKER_ID_LFE2 },
{ kAudioChannelLabel_HeadphonesLeft, MP_SPEAKER_ID_DL },
{ kAudioChannelLabel_HeadphonesRight, MP_SPEAKER_ID_DR },
{ kAudioChannelLabel_Unknown, -1 },
};
static int ca_label_to_mp_speaker_id(AudioChannelLabel label)
{
for (int i = 0; speaker_map[i][1] >= 0; i++)
if (speaker_map[i][0] == label)
return speaker_map[i][1];
return -1;
}
static void ca_log_layout(struct ao *ao, AudioChannelLayout *layout)
{
if (!mp_msg_test(ao->log, MSGL_V))
return;
AudioChannelDescription *descs = layout->mChannelDescriptions;
MP_VERBOSE(ao, "layout: tag: <%d>, bitmap: <%d>, "
"descriptions <%d>\n",
layout->mChannelLayoutTag,
layout->mChannelBitmap,
layout->mNumberChannelDescriptions);
for (int i = 0; i < layout->mNumberChannelDescriptions; i++) {
AudioChannelDescription d = descs[i];
MP_VERBOSE(ao, " - description %d: label <%d, %d>, flags: <%u>, "
"coords: <%f, %f, %f>\n", i,
d.mChannelLabel,
ca_label_to_mp_speaker_id(d.mChannelLabel),
d.mChannelFlags,
d.mCoordinates[0],
d.mCoordinates[1],
d.mCoordinates[2]);
}
}
bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout,
struct mp_chmap *chmap)
{
AudioChannelLayoutTag tag = layout->mChannelLayoutTag;
uint32_t layout_size = sizeof(layout);
OSStatus err;
if (tag == kAudioChannelLayoutTag_UseChannelBitmap) {
err = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForBitmap,
sizeof(uint32_t),
&layout->mChannelBitmap,
&layout_size,
layout);
CHECK_CA_ERROR("failed to convert channel bitmap to descriptions");
} else if (tag != kAudioChannelLayoutTag_UseChannelDescriptions) {
err = AudioFormatGetProperty(kAudioFormatProperty_ChannelLayoutForTag,
sizeof(AudioChannelLayoutTag),
&layout->mChannelLayoutTag,
&layout_size,
layout);
CHECK_CA_ERROR("failed to convert channel tag to descriptions");
}
ca_log_layout(ao, layout);
// If the channel layout uses channel descriptions, from my
// experiments there are there three possibile cases:
// * The description has a label kAudioChannelLabel_Unknown:
// Can't do anything about this (looks like non surround
// layouts are like this).
// * The description uses positional information: this in
// theory could be used but one would have to map spatial
// positions to labels which is not really feasible.
// * The description has a well known label which can be mapped
// to the waveextensible definition: this is the kind of
// descriptions we process here.
for (int n = 0; n < layout->mNumberChannelDescriptions; n++) {
AudioChannelLabel label = layout->mChannelDescriptions[n].mChannelLabel;
uint8_t speaker = ca_label_to_mp_speaker_id(label);
if (label == kAudioChannelLabel_Unknown)
continue;
if (speaker < 0) {
MP_VERBOSE(ao, "channel label=%d unusable to build channel "
"bitmap, skipping layout\n", label);
} else {
chmap->speaker[n] = speaker;
chmap->num = n + 1;
}
}
return chmap->num > 0;
coreaudio_error:
ca_log_layout(ao, layout);
return false;
}
+4 -31
View File
@@ -46,38 +46,11 @@ bool check_ca_st(struct ao *ao, int level, OSStatus code, const char *message);
if (err != noErr) goto label; \
} while (0)
void ca_print_device_list(struct ao *ao);
OSStatus ca_select_device(struct ao *ao, int selection, AudioDeviceID *device);
void ca_fill_asbd(struct ao *ao, AudioStreamBasicDescription *asbd);
void ca_print_asbd(struct ao *ao, const char *description,
const AudioStreamBasicDescription *asbd);
bool ca_format_is_digital(AudioStreamBasicDescription asbd);
bool ca_stream_supports_digital(struct ao *ao, AudioStreamID stream);
bool ca_device_supports_digital(struct ao *ao, AudioDeviceID device);
OSStatus ca_property_listener(AudioObjectPropertySelector selector,
AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data);
OSStatus ca_stream_listener(AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data);
OSStatus ca_device_listener(AudioObjectID object, uint32_t n_addresses,
const AudioObjectPropertyAddress addresses[],
void *data);
OSStatus ca_lock_device(AudioDeviceID device, pid_t *pid);
OSStatus ca_unlock_device(AudioDeviceID device, pid_t *pid);
OSStatus ca_disable_mixing(struct ao *ao, AudioDeviceID device, bool *changed);
OSStatus ca_enable_mixing(struct ao *ao, AudioDeviceID device, bool changed);
OSStatus ca_enable_device_listener(AudioDeviceID device, void *flag);
OSStatus ca_disable_device_listener(AudioDeviceID device, void *flag);
bool ca_change_format(struct ao *ao, AudioStreamID stream,
AudioStreamBasicDescription change_format);
bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout,
struct mp_chmap *chmap);
#endif /* MPV_COREAUDIO_UTILS_H */
+16 -13
View File
@@ -98,6 +98,7 @@ struct priv {
int outburst; ///play in multiple of chunks of this size
int cfg_device;
int cfg_buffersize;
};
static float get_delay(struct ao *ao);
@@ -350,6 +351,8 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
IDirectSoundBuffer_SetVolume(p->hdsbuf, volume);
return CONTROL_OK;
}
case AOCONTROL_HAS_SOFT_VOLUME:
return CONTROL_TRUE;
}
return CONTROL_UNKNOWN;
}
@@ -370,7 +373,6 @@ static int init(struct ao *ao)
if (!InitDirectSound(ao))
return -1;
ao->no_persistent_volume = true;
p->audio_volume = 100;
// ok, now create the buffers
@@ -380,34 +382,33 @@ static int init(struct ao *ao)
int format = af_fmt_from_planar(ao->format);
int rate = ao->samplerate;
if (AF_FORMAT_IS_AC3(format))
format = AF_FORMAT_AC3;
else {
if (!AF_FORMAT_IS_IEC61937(format)) {
struct mp_chmap_sel sel = {0};
mp_chmap_sel_add_waveext(&sel);
if (!ao_chmap_sel_adjust(ao, &sel, &ao->channels))
return -1;
}
switch (format) {
case AF_FORMAT_AC3:
case AF_FORMAT_S24_LE:
case AF_FORMAT_S16_LE:
case AF_FORMAT_S24:
case AF_FORMAT_S16:
case AF_FORMAT_U8:
break;
default:
if (AF_FORMAT_IS_IEC61937(format))
break;
MP_VERBOSE(ao, "format %s not supported defaulting to Signed 16-bit Little-Endian\n",
af_fmt_to_str(format));
format = AF_FORMAT_S16_LE;
format = AF_FORMAT_S16;
}
//set our audio parameters
ao->samplerate = rate;
ao->format = format;
ao->bps = ao->channels.num * rate * af_fmt2bps(format);
int buffersize = ao->bps; // space for 1 sec
int buffersize = ao->bps * p->cfg_buffersize / 1000;
MP_VERBOSE(ao, "Samplerate:%iHz Channels:%i Format:%s\n", rate,
ao->channels.num, af_fmt_to_str(format));
MP_VERBOSE(ao, "Buffersize:%d bytes (%d msec)\n",
buffersize, buffersize / ao->bps * 1000);
MP_VERBOSE(ao, "Buffersize:%d bytes (%f msec)\n",
buffersize, buffersize * 1000.0 / ao->bps);
//fill waveformatex
ZeroMemory(&wformat, sizeof(WAVEFORMATEXTENSIBLE));
@@ -415,7 +416,8 @@ static int init(struct ao *ao)
? sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) : 0;
wformat.Format.nChannels = ao->channels.num;
wformat.Format.nSamplesPerSec = rate;
if (AF_FORMAT_IS_AC3(format)) {
if (AF_FORMAT_IS_IEC61937(format)) {
// Whether it also works with e.g. DTS is unknown, but probably does.
wformat.Format.wFormatTag = WAVE_FORMAT_DOLBY_AC3_SPDIF;
wformat.Format.wBitsPerSample = 16;
wformat.Format.nBlockAlign = 4;
@@ -583,7 +585,7 @@ static int get_space(struct ao *ao)
int space = check_free_buffer_size(ao);
if (space < p->min_free_space)
return 0;
return (space - p->min_free_space) / ao->sstride;
return (space - p->min_free_space) / p->outburst * p->outburst / ao->sstride;
}
/**
@@ -636,6 +638,7 @@ const struct ao_driver audio_out_dsound = {
.priv_size = sizeof(struct priv),
.options = (const struct m_option[]) {
OPT_INT("device", cfg_device, 0),
OPT_INTRANGE("buffersize", cfg_buffersize, 0, 1, 10000, OPTDEF_INT(200)),
{0}
},
};
+12 -11
View File
@@ -28,7 +28,6 @@
#include <libavutil/common.h>
#include <libavutil/audioconvert.h>
#include "compat/libav.h"
#include "config.h"
#include "options/options.h"
#include "common/common.h"
@@ -71,7 +70,7 @@ static void select_format(struct ao *ao, AVCodec *codec)
{
int fmt = af_from_avformat(*sampleformat);
if (!fmt) {
MP_WARN(ao, "unsupported lavc format %s",
MP_WARN(ao, "unsupported lavc format %s\n",
av_get_sample_fmt_name(*sampleformat));
continue;
}
@@ -114,12 +113,11 @@ static int init(struct ao *ao)
codec = encode_lavc_get_codec(ao->encode_lavc_ctx, ac->stream);
// ac->stream->time_base.num = 1;
// ac->stream->time_base.den = ao->samplerate;
// doing this breaks mpeg2ts in ffmpeg
// which doesn't properly force the time base to be 90000
// furthermore, ffmpeg.c doesn't do this either and works
// TODO: Remove this redundancy with encode_lavc_alloc_stream also
// setting the time base.
// Using codec->time_bvase is deprecated, but needed for older lavf.
ac->stream->time_base.num = 1;
ac->stream->time_base.den = ao->samplerate;
ac->stream->codec->time_base.num = 1;
ac->stream->codec->time_base.den = ao->samplerate;
@@ -342,8 +340,7 @@ static int play(struct ao *ao, void **data, int samples, int flags)
}
double pts = ectx->last_audio_in_pts;
pts += ectx->samples_since_last_pts / ao->samplerate;
ectx->samples_since_last_pts += samples;
pts += ectx->samples_since_last_pts / (double)ao->samplerate;
size_t num_planes = af_fmt_is_planar(ao->format) ? ao->channels.num : 1;
@@ -451,6 +448,10 @@ static int play(struct ao *ao, void **data, int samples, int flags)
}
talloc_free(tempdata);
int taken = FFMIN(bufpos, orig_samples);
ectx->samples_since_last_pts += taken;
pthread_mutex_unlock(&ectx->lock);
if (flags & AOPLAY_FINAL_CHUNK) {
@@ -463,7 +464,7 @@ static int play(struct ao *ao, void **data, int samples, int flags)
}
}
return FFMIN(bufpos, orig_samples);
return taken;
}
static void drain(struct ao *ao)
+3 -3
View File
@@ -90,7 +90,7 @@ static int init(struct ao *ao)
struct mp_chmap_sel sel = {0};
mp_chmap_sel_add_any(&sel);
if (!ao_chmap_sel_adjust(ao, &sel, &ao->channels))
return -1;
mp_chmap_from_channels(&ao->channels, 2);
priv->latency = priv->latency_sec * ao->samplerate;
@@ -148,7 +148,8 @@ static int get_space(struct ao *ao)
struct priv *priv = ao->priv;
drain(ao);
return priv->buffersize - priv->latency - priv->buffered;
int samples = priv->buffersize - priv->latency - priv->buffered;
return samples / priv->outburst * priv->outburst;
}
static int play(struct ao *ao, void **data, int samples, int flags)
@@ -210,7 +211,6 @@ const struct ao_driver audio_out_null = {
.priv_size = sizeof(struct priv),
.priv_defaults = &(const struct priv) {
.bufferlen = 0.2,
.latency_sec = 0.5,
.outburst = 256,
.speed = 1,
},
+2 -1
View File
@@ -76,6 +76,8 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
vol->left = vol->right = volume * 100;
return CONTROL_TRUE;
}
case AOCONTROL_HAS_SOFT_VOLUME:
return CONTROL_TRUE;
}
return CONTROL_UNKNOWN;
}
@@ -132,7 +134,6 @@ static int init(struct ao *ao)
return -1;
}
ao_data = ao;
ao->no_persistent_volume = true;
struct mp_chmap_sel sel = {0};
for (i = 0; speaker_pos[i].id != -1; i++)
mp_chmap_sel_add_speaker(&sel, speaker_pos[i].id);
+321 -296
View File
@@ -31,12 +31,16 @@
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <poll.h>
#include <errno.h>
#include <string.h>
#include <strings.h>
#include "config.h"
#include "options/options.h"
#include "common/msg.h"
#include "osdep/timer.h"
#include "osdep/endian.h"
#if HAVE_SYS_SOUNDCARD_H
#include <sys/soundcard.h>
@@ -51,14 +55,20 @@
#include "ao.h"
#include "internal.h"
// Define to 0 if the device must be reopened to reset it (stop all playback,
// clear the buffer), and the device should be closed when unused.
// Define to 1 if SNDCTL_DSP_RESET should be used to reset without close.
#define KEEP_DEVICE (defined(SNDCTL_DSP_RESET) && !defined(__NetBSD__))
struct priv {
int audio_fd;
int prepause_space;
int prepause_samples;
int oss_mixer_channel;
audio_buf_info zz;
int audio_delay_method;
int buffersize;
int outburst;
bool device_failed;
double audio_end;
char *dsp;
char *oss_mixer_device;
@@ -80,53 +90,60 @@ static const struct mp_chmap oss_layouts[MP_NUM_CHANNELS + 1] = {
MP_CHMAP8(FL, FR, BL, BR, FC, LFE, SL, SR), // 7.1
};
#if !defined(AFMT_S16_NE) && defined(AFMT_S16_LE) && defined(AFMT_S16_BE)
#define AFMT_S16_NE MP_SELECT_LE_BE(AFMT_S16_LE, AFMT_S16_BE)
#endif
#if !defined(AFMT_U16_NE) && defined(AFMT_U16_LE) && defined(AFMT_U16_BE)
#define AFMT_U16_NE MP_SELECT_LE_BE(AFMT_U16_LE, AFMT_U16_BE)
#endif
#if !defined(AFMT_U24_NE) && defined(AFMT_U24_LE) && defined(AFMT_U24_BE)
#define AFMT_U24_NE MP_SELECT_LE_BE(AFMT_U24_LE, AFMT_U24_BE)
#endif
#if !defined(AFMT_S24_NE) && defined(AFMT_S24_LE) && defined(AFMT_S24_BE)
#define AFMT_S24_NE MP_SELECT_LE_BE(AFMT_S24_LE, AFMT_S24_BE)
#endif
#if !defined(AFMT_U32_NE) && defined(AFMT_U32_LE) && defined(AFMT_U32_BE)
#define AFMT_U32MP_SELECT_LE_BE(AFMT_U32_LE, AFMT_U32_BE)
#endif
#if !defined(AFMT_S32_NE) && defined(AFMT_S32_LE) && defined(AFMT_S32_BE)
#define AFMT_S32MP_SELECT_LE_BE(AFMT_S32_LE, AFMT_S32_BE)
#endif
static const int format_table[][2] = {
{AFMT_U8, AF_FORMAT_U8},
{AFMT_S8, AF_FORMAT_S8},
{AFMT_U16_LE, AF_FORMAT_U16_LE},
{AFMT_U16_BE, AF_FORMAT_U16_BE},
{AFMT_S16_LE, AF_FORMAT_S16_LE},
{AFMT_S16_BE, AF_FORMAT_S16_BE},
#ifdef AFMT_S24_PACKED
{AFMT_S24_PACKED, AF_FORMAT_S24_LE},
{AFMT_U16_NE, AF_FORMAT_U16},
{AFMT_S16_NE, AF_FORMAT_S16},
#ifdef AFMT_U24_NE
{AFMT_U24_NE, AF_FORMAT_U24},
#endif
#ifdef AFMT_U24_LE
{AFMT_U24_LE, AF_FORMAT_U24_LE},
#ifdef AFMT_S24_NE
{AFMT_S24_NE, AF_FORMAT_S24},
#endif
#ifdef AFMT_U24_BE
{AFMT_U24_BE, AF_FORMAT_U24_BE},
#ifdef AFMT_U32_NE
{AFMT_U32_NE, AF_FORMAT_U32},
#endif
#ifdef AFMT_S24_LE
{AFMT_S24_LE, AF_FORMAT_S24_LE},
#endif
#ifdef AFMT_S24_BE
{AFMT_S24_BE, AF_FORMAT_S24_BE},
#endif
#ifdef AFMT_U32_LE
{AFMT_U32_LE, AF_FORMAT_U32_LE},
#endif
#ifdef AFMT_U32_BE
{AFMT_U32_BE, AF_FORMAT_U32_BE},
#endif
#ifdef AFMT_S32_LE
{AFMT_S32_LE, AF_FORMAT_S32_LE},
#endif
#ifdef AFMT_S32_BE
{AFMT_S32_BE, AF_FORMAT_S32_BE},
#ifdef AFMT_S32_NE
{AFMT_S32_NE, AF_FORMAT_S32},
#endif
#ifdef AFMT_FLOAT
{AFMT_FLOAT, AF_FORMAT_FLOAT},
#endif
// SPECIALS
#ifdef AFMT_MPEG
{AFMT_MPEG, AF_FORMAT_MPEG2},
#endif
#ifdef AFMT_AC3
{AFMT_AC3, AF_FORMAT_AC3},
{AFMT_MPEG, AF_FORMAT_S_MP3},
#endif
{-1, -1}
};
#ifndef AFMT_AC3
#define AFMT_AC3 -1
#endif
static int format2oss(int format)
{
for (int n = 0; format_table[n][0] != -1; n++) {
@@ -142,7 +159,7 @@ static int oss2format(int format)
if (format_table[n][0] == format)
return format_table[n][1];
}
return -1;
return 0;
}
@@ -177,8 +194,7 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
struct priv *p = ao->priv;
switch (cmd) {
case AOCONTROL_GET_VOLUME:
case AOCONTROL_SET_VOLUME:
{
case AOCONTROL_SET_VOLUME: {
ao_control_vol_t *vol = (ao_control_vol_t *)arg;
int fd, v, devs;
@@ -188,7 +204,7 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
return CONTROL_OK;
#endif
if (AF_FORMAT_IS_AC3(ao->format))
if (AF_FORMAT_IS_SPECIAL(ao->format))
return CONTROL_TRUE;
if ((fd = open(p->oss_mixer_device, O_RDONLY)) != -1) {
@@ -209,22 +225,203 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
close(fd);
return CONTROL_OK;
}
}
return CONTROL_ERROR;
}
#ifdef SNDCTL_DSP_GETPLAYVOL
case AOCONTROL_HAS_SOFT_VOLUME:
return CONTROL_TRUE;
#endif
}
return CONTROL_UNKNOWN;
}
// 1: ok, 0: not writable, -1: error
static int device_writable(struct ao *ao)
{
struct priv *p = ao->priv;
struct pollfd fd = {.fd = p->audio_fd, .events = POLLOUT};
return poll(&fd, 1, 0);
}
static void close_device(struct ao *ao)
{
struct priv *p = ao->priv;
p->device_failed = false;
if (p->audio_fd == -1)
return;
#if defined(SNDCTL_DSP_RESET)
ioctl(p->audio_fd, SNDCTL_DSP_RESET, NULL);
#endif
close(p->audio_fd);
p->audio_fd = -1;
}
// close audio device
static void uninit(struct ao *ao)
{
close_device(ao);
}
static bool try_format(struct ao *ao, int *format)
{
struct priv *p = ao->priv;
int oss_format = format2oss(*format);
if (oss_format == -1 && AF_FORMAT_IS_IEC61937(*format))
oss_format = AFMT_AC3;
if (oss_format == -1) {
MP_VERBOSE(ao, "Unknown/not supported internal format: %s\n",
af_fmt_to_str(*format));
*format = 0;
return false;
}
int actual_format = oss_format;
if (ioctl(p->audio_fd, SNDCTL_DSP_SETFMT, &actual_format) < 0)
actual_format = -1;
if (actual_format == oss_format)
return true;
MP_WARN(ao, "Can't set audio device to %s output.\n", af_fmt_to_str(*format));
*format = oss2format(actual_format);
if (actual_format != -1 && !*format)
MP_ERR(ao, "Unknown/Unsupported OSS format: 0x%x.\n", actual_format);
return false;
}
static int reopen_device(struct ao *ao, bool allow_format_changes)
{
struct priv *p = ao->priv;
int samplerate = ao->samplerate;
int format = ao->format;
struct mp_chmap channels = ao->channels;
#ifdef __linux__
p->audio_fd = open(p->dsp, O_WRONLY | O_NONBLOCK);
#else
p->audio_fd = open(p->dsp, O_WRONLY);
#endif
if (p->audio_fd < 0) {
MP_ERR(ao, "Can't open audio device %s: %s\n", p->dsp, strerror(errno));
goto fail;
}
#ifdef __linux__
/* Remove the non-blocking flag */
if (fcntl(p->audio_fd, F_SETFL, 0) < 0) {
MP_ERR(ao, "Can't make file descriptor blocking: %s\n", strerror(errno));
goto fail;
}
#endif
#if defined(FD_CLOEXEC) && defined(F_SETFD)
fcntl(p->audio_fd, F_SETFD, FD_CLOEXEC);
#endif
if (AF_FORMAT_IS_IEC61937(format)) {
ioctl(p->audio_fd, SNDCTL_DSP_SPEED, &samplerate);
// Probably could be fixed by setting number of channels; needs testing.
if (channels.num != 2) {
MP_ERR(ao, "Format %s not implemented.\n", af_fmt_to_str(format));
goto fail;
}
}
int try_formats[] = {format, AF_FORMAT_S32, AF_FORMAT_S24, AF_FORMAT_S16, 0};
for (int n = 0; try_formats[n]; n++) {
format = try_formats[n];
if (try_format(ao, &format))
break;
}
if (!format) {
MP_ERR(ao, "Can't set sample format.\n");
goto fail;
}
MP_VERBOSE(ao, "sample format: %s\n", af_fmt_to_str(format));
if (!AF_FORMAT_IS_IEC61937(format)) {
struct mp_chmap_sel sel = {0};
for (int n = 0; n < MP_NUM_CHANNELS + 1; n++)
mp_chmap_sel_add_map(&sel, &oss_layouts[n]);
if (!ao_chmap_sel_adjust(ao, &sel, &channels))
goto fail;
int reqchannels = channels.num;
// We only use SNDCTL_DSP_CHANNELS for >2 channels, in case some drivers don't have it
if (reqchannels > 2) {
int nchannels = reqchannels;
if (ioctl(p->audio_fd, SNDCTL_DSP_CHANNELS, &nchannels) == -1 ||
nchannels != reqchannels)
{
MP_ERR(ao, "Failed to set audio device to %d channels.\n",
reqchannels);
goto fail;
}
} else {
int c = reqchannels - 1;
if (ioctl(p->audio_fd, SNDCTL_DSP_STEREO, &c) == -1) {
MP_ERR(ao, "Failed to set audio device to %d channels.\n",
reqchannels);
goto fail;
}
if (!ao_chmap_sel_get_def(ao, &sel, &channels, c + 1))
goto fail;
}
MP_VERBOSE(ao, "using %d channels (requested: %d)\n",
channels.num, reqchannels);
// set rate
ioctl(p->audio_fd, SNDCTL_DSP_SPEED, &samplerate);
MP_VERBOSE(ao, "using %d Hz samplerate\n", samplerate);
}
audio_buf_info zz = {0};
if (ioctl(p->audio_fd, SNDCTL_DSP_GETOSPACE, &zz) == -1) {
int r = 0;
MP_WARN(ao, "driver doesn't support SNDCTL_DSP_GETOSPACE\n");
if (ioctl(p->audio_fd, SNDCTL_DSP_GETBLKSIZE, &r) == -1)
MP_VERBOSE(ao, "%d bytes/frag (config.h)\n", p->outburst);
else {
p->outburst = r;
MP_VERBOSE(ao, "%d bytes/frag (GETBLKSIZE)\n", p->outburst);
}
} else {
MP_VERBOSE(ao, "frags: %3d/%d (%d bytes/frag) free: %6d\n",
zz.fragments, zz.fragstotal, zz.fragsize, zz.bytes);
p->buffersize = zz.bytes;
p->outburst = zz.fragsize;
}
if (allow_format_changes) {
ao->format = format;
ao->samplerate = samplerate;
ao->channels = channels;
} else {
if (format != ao->format || samplerate != ao->samplerate ||
!mp_chmap_equals(&channels, &ao->channels))
{
MP_ERR(ao, "Could not reselect previous audio format.\n");
goto fail;
}
}
p->outburst -= p->outburst % (channels.num * af_fmt2bps(format)); // round down
return 0;
fail:
close_device(ao);
return -1;
}
// open & setup audio device
// return: 0=success -1=fail
static int init(struct ao *ao)
{
struct priv *p = ao->priv;
int oss_format;
#ifdef SNDCTL_DSP_GETPLAYVOL
ao->no_persistent_volume = true;
#endif
const char *mchan = NULL;
if (p->cfg_oss_mixer_channel && p->cfg_oss_mixer_channel[0])
@@ -265,178 +462,36 @@ static int init(struct ao *ao)
MP_VERBOSE(ao, "using '%s' mixer device\n", p->oss_mixer_device);
MP_VERBOSE(ao, "using '%s' mixer device\n", mixer_channels[p->oss_mixer_channel]);
#ifdef __linux__
p->audio_fd = open(p->dsp, O_WRONLY | O_NONBLOCK);
#else
p->audio_fd = open(p->dsp, O_WRONLY);
#endif
if (p->audio_fd < 0) {
MP_ERR(ao, "Can't open audio device %s: %s\n", p->dsp, strerror(errno));
return -1;
}
#ifdef __linux__
/* Remove the non-blocking flag */
if (fcntl(p->audio_fd, F_SETFL, 0) < 0) {
MP_ERR(ao, "Can't make file descriptor blocking: %s\n", strerror(errno));
return -1;
}
#endif
#if defined(FD_CLOEXEC) && defined(F_SETFD)
fcntl(p->audio_fd, F_SETFD, FD_CLOEXEC);
#endif
ao->format = af_fmt_from_planar(ao->format);
if (AF_FORMAT_IS_AC3(ao->format)) {
ioctl(p->audio_fd, SNDCTL_DSP_SPEED, &ao->samplerate);
}
ac3_retry:
if (AF_FORMAT_IS_AC3(ao->format))
ao->format = AF_FORMAT_AC3;
oss_format = format2oss(ao->format);
if (oss_format == -1) {
MP_VERBOSE(ao, "Unknown/not supported internal format: %s\n",
af_fmt_to_str(ao->format));
#if defined(AFMT_S32_LE) && defined(AFMT_S32_BE)
#if BYTE_ORDER == BIG_ENDIAN
oss_format = AFMT_S32_BE;
#else
oss_format = AFMT_S32_LE;
#endif
ao->format = AF_FORMAT_S32;
#elif defined(AFMT_S24_LE) && defined(AFMT_S24_BE)
#if BYTE_ORDER == BIG_ENDIAN
oss_format = AFMT_S24_BE;
#else
oss_format = AFMT_S24_LE;
#endif
ao->format = AF_FORMAT_S24;
#else
#if BYTE_ORDER == BIG_ENDIAN
oss_format = AFMT_S16_BE;
#else
oss_format = AFMT_S16_LE;
#endif
ao->format = AF_FORMAT_S16;
#endif
}
if (ioctl(p->audio_fd, SNDCTL_DSP_SETFMT, &oss_format) < 0 ||
oss_format != format2oss(ao->format))
{
MP_WARN(ao, "Can't set audio device %s to %s output, trying %s...\n",
p->dsp, af_fmt_to_str(ao->format),
af_fmt_to_str(AF_FORMAT_S16));
ao->format = AF_FORMAT_S16;
goto ac3_retry;
}
ao->format = oss2format(oss_format);
if (ao->format == -1) {
MP_ERR(ao, "Unknown/Unsupported OSS format: %x.\n", oss_format);
return -1;
}
MP_VERBOSE(ao, "sample format: %s\n", af_fmt_to_str(ao->format));
if (!AF_FORMAT_IS_AC3(ao->format)) {
struct mp_chmap_sel sel = {0};
for (int n = 0; n < MP_NUM_CHANNELS + 1; n++)
mp_chmap_sel_add_map(&sel, &oss_layouts[n]);
if (!ao_chmap_sel_adjust(ao, &sel, &ao->channels))
return -1;
int reqchannels = ao->channels.num;
// We only use SNDCTL_DSP_CHANNELS for >2 channels, in case some drivers don't have it
if (reqchannels > 2) {
int nchannels = reqchannels;
if (ioctl(p->audio_fd, SNDCTL_DSP_CHANNELS, &nchannels) == -1 ||
nchannels != reqchannels)
{
MP_ERR(ao, "Failed to set audio device to %d channels.\n",
reqchannels);
return -1;
}
} else {
int c = reqchannels - 1;
if (ioctl(p->audio_fd, SNDCTL_DSP_STEREO, &c) == -1) {
MP_ERR(ao, "Failed to set audio device to %d channels.\n",
reqchannels);
return -1;
}
if (!ao_chmap_sel_get_def(ao, &sel, &ao->channels, c + 1))
return -1;
}
MP_VERBOSE(ao, "using %d channels (requested: %d)\n",
ao->channels.num, reqchannels);
// set rate
ioctl(p->audio_fd, SNDCTL_DSP_SPEED, &ao->samplerate);
MP_VERBOSE(ao, "using %d Hz samplerate\n", ao->samplerate);
}
if (ioctl(p->audio_fd, SNDCTL_DSP_GETOSPACE, &p->zz) == -1) {
int r = 0;
MP_WARN(ao, "driver doesn't support SNDCTL_DSP_GETOSPACE\n");
if (ioctl(p->audio_fd, SNDCTL_DSP_GETBLKSIZE, &r) == -1)
MP_VERBOSE(ao, "%d bytes/frag (config.h)\n", p->outburst);
else {
p->outburst = r;
MP_VERBOSE(ao, "%d bytes/frag (GETBLKSIZE)\n", p->outburst);
}
} else {
MP_VERBOSE(ao, "frags: %3d/%d (%d bytes/frag) free: %6d\n",
p->zz.fragments, p->zz.fragstotal, p->zz.fragsize, p->zz.bytes);
p->buffersize = p->zz.bytes;
p->outburst = p->zz.fragsize;
}
if (reopen_device(ao, true) < 0)
goto fail;
if (p->buffersize == -1) {
// Measuring buffer size:
void *data;
void *data = malloc(p->outburst);
if (!data) {
MP_ERR(ao, "Out of memory, or broken outburst size.\n");
goto fail;
}
p->buffersize = 0;
#if HAVE_AUDIO_SELECT
data = malloc(p->outburst);
memset(data, 0, p->outburst);
while (p->buffersize < 0x40000) {
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(p->audio_fd, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
if (!select(p->audio_fd + 1, NULL, &rfds, NULL, &tv))
break;
while (p->buffersize < 0x40000 && device_writable(ao) > 0) {
write(p->audio_fd, data, p->outburst);
p->buffersize += p->outburst;
}
free(data);
if (p->buffersize == 0) {
MP_ERR(ao, "*** Your audio driver DOES NOT support select() ***\n");
MP_ERR(ao, "Recompile mpv with #define HAVE_AUDIO_SELECT 0 in config.h!\n");
return -1;
MP_ERR(ao, "Your OSS audio driver DOES NOT support poll().\n");
goto fail;
}
#endif
}
ao->bps = ao->channels.num * af_fmt2bps(ao->format);
p->outburst -= p->outburst % ao->bps; // round down
ao->bps *= ao->samplerate;
return 0;
}
// close audio device
static void uninit(struct ao *ao)
{
struct priv *p = ao->priv;
if (p->audio_fd == -1)
return;
#ifdef SNDCTL_DSP_RESET
ioctl(p->audio_fd, SNDCTL_DSP_RESET, NULL);
#endif
close(p->audio_fd);
p->audio_fd = -1;
fail:
uninit(ao);
return -1;
}
static void drain(struct ao *ao)
@@ -449,104 +504,39 @@ static void drain(struct ao *ao)
#endif
}
#ifndef SNDCTL_DSP_RESET
static void close_device(struct ao *ao)
{
struct priv *p = ao->priv;
close(p->audio_fd);
p->audio_fd = -1;
}
#endif
// stop playing and empty buffers (for seeking/pause)
static void reset(struct ao *ao)
{
#if KEEP_DEVICE
struct priv *p = ao->priv;
int oss_format;
#ifdef SNDCTL_DSP_RESET
ioctl(p->audio_fd, SNDCTL_DSP_RESET, NULL);
#else
close_device(ao);
p->audio_fd = open(p->dsp, O_WRONLY);
if (p->audio_fd < 0) {
MP_ERR(ao, "Fatal error: *** CANNOT "
"RE-OPEN / RESET AUDIO DEVICE *** %s\n", strerror(errno));
return;
}
#if defined(FD_CLOEXEC) && defined(F_SETFD)
fcntl(p->audio_fd, F_SETFD, FD_CLOEXEC);
#endif
#endif
oss_format = format2oss(ao->format);
if (AF_FORMAT_IS_AC3(ao->format))
ioctl(p->audio_fd, SNDCTL_DSP_SPEED, &ao->samplerate);
ioctl(p->audio_fd, SNDCTL_DSP_SETFMT, &oss_format);
if (!AF_FORMAT_IS_AC3(ao->format)) {
int c = ao->channels.num;
if (ao->channels.num > 2)
ioctl(p->audio_fd, SNDCTL_DSP_CHANNELS, &c);
else {
c--;
ioctl(p->audio_fd, SNDCTL_DSP_STEREO, &c);
}
ioctl(p->audio_fd, SNDCTL_DSP_SPEED, &ao->samplerate);
}
}
// return: how many bytes can be played without blocking
static int get_space(struct ao *ao)
{
struct priv *p = ao->priv;
int playsize = p->outburst;
#ifdef SNDCTL_DSP_GETOSPACE
if (ioctl(p->audio_fd, SNDCTL_DSP_GETOSPACE, &p->zz) != -1) {
// calculate exact buffer space:
playsize = p->zz.fragments * p->zz.fragsize;
return playsize / ao->sstride;
}
#endif
// check buffer
#if HAVE_AUDIO_SELECT
{
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(p->audio_fd, &rfds);
tv.tv_sec = 0;
tv.tv_usec = 0;
if (!select(p->audio_fd + 1, NULL, &rfds, NULL, &tv))
return 0; // not block!
}
#endif
return p->outburst / ao->sstride;
}
// stop playing, keep buffers (for pause)
static void audio_pause(struct ao *ao)
{
struct priv *p = ao->priv;
p->prepause_space = get_space(ao) * ao->sstride;
#ifdef SNDCTL_DSP_RESET
ioctl(p->audio_fd, SNDCTL_DSP_RESET, NULL);
#else
close_device(ao);
#endif
}
// plays 'len' bytes of 'data'
// plays 'len' samples of 'data'
// it should round it down to outburst*n
// return: number of bytes played
// return: number of samples played
static int play(struct ao *ao, void **data, int samples, int flags)
{
struct priv *p = ao->priv;
int len = samples * ao->sstride;
if (len == 0)
return len;
if (p->audio_fd < 0 && !p->device_failed && reopen_device(ao, false) < 0)
MP_ERR(ao, "Fatal error: *** CANNOT RE-OPEN / RESET AUDIO DEVICE ***\n");
if (p->audio_fd < 0) {
// Let playback continue normally, even with a closed device.
p->device_failed = true;
double now = mp_time_sec();
if (p->audio_end < now)
p->audio_end = now;
p->audio_end += samples / (double)ao->samplerate;
return samples;
}
if (len > p->outburst || !(flags & AOPLAY_FINAL_CHUNK)) {
len /= p->outburst;
len *= p->outburst;
@@ -555,22 +545,16 @@ static int play(struct ao *ao, void **data, int samples, int flags)
return len / ao->sstride;
}
// resume playing, after audio_pause()
static void audio_resume(struct ao *ao)
{
struct priv *p = ao->priv;
#ifndef SNDCTL_DSP_RESET
reset(ao);
#endif
int fillframes = get_space(ao) - p->prepause_space / ao->sstride;
if (fillframes > 0)
ao_play_silence(ao, fillframes);
}
// return: delay in seconds between first and last sample in buffer
static float get_delay(struct ao *ao)
{
struct priv *p = ao->priv;
if (p->audio_fd < 0) {
double rest = p->audio_end - mp_time_sec();
if (rest > 0)
return rest;
return 0;
}
/* Calculate how many bytes/second is sent out */
if (p->audio_delay_method == 2) {
#ifdef SNDCTL_DSP_GETODELAY
@@ -581,16 +565,57 @@ static float get_delay(struct ao *ao)
p->audio_delay_method = 1; // fallback if not supported
}
if (p->audio_delay_method == 1) {
// SNDCTL_DSP_GETOSPACE
if (ioctl(p->audio_fd, SNDCTL_DSP_GETOSPACE, &p->zz) != -1) {
return ((float)(p->buffersize -
p->zz.bytes)) / (float)ao->bps;
audio_buf_info zz = {0};
if (ioctl(p->audio_fd, SNDCTL_DSP_GETOSPACE, &zz) != -1) {
return ((float)(p->buffersize - zz.bytes)) / (float)ao->bps;
}
p->audio_delay_method = 0; // fallback if not supported
}
return ((float)p->buffersize) / (float)ao->bps;
}
// return: how many samples can be played without blocking
static int get_space(struct ao *ao)
{
struct priv *p = ao->priv;
audio_buf_info zz = {0};
if (ioctl(p->audio_fd, SNDCTL_DSP_GETOSPACE, &zz) != -1) {
// calculate exact buffer space:
return zz.fragments * zz.fragsize / ao->sstride;
}
if (p->audio_fd < 0 && p->device_failed && get_delay(ao) > 0.2)
return 0;
if (p->audio_fd < 0 || device_writable(ao) > 0)
return p->outburst / ao->sstride;
return 0;
}
// stop playing, keep buffers (for pause)
static void audio_pause(struct ao *ao)
{
struct priv *p = ao->priv;
p->prepause_samples = get_delay(ao) * ao->samplerate;
#if KEEP_DEVICE
ioctl(p->audio_fd, SNDCTL_DSP_RESET, NULL);
#else
close_device(ao);
#endif
}
// resume playing, after audio_pause()
static void audio_resume(struct ao *ao)
{
struct priv *p = ao->priv;
p->audio_end = 0;
if (p->prepause_samples > 0)
ao_play_silence(ao, p->prepause_samples);
}
#define OPT_BASE_STRUCT struct priv
const struct ao_driver audio_out_oss = {
+16 -9
View File
@@ -35,6 +35,7 @@
#include "ao.h"
#include "internal.h"
#include "common/msg.h"
#include "osdep/endian.h"
#ifdef __MINGW32__
// for GetFileType to detect pipes
@@ -72,8 +73,7 @@ static void fput32le(uint32_t val, FILE *fp)
static void write_wave_header(struct ao *ao, FILE *fp, uint64_t data_length)
{
bool use_waveex = true;
uint16_t fmt = ao->format == AF_FORMAT_FLOAT_LE ?
WAV_ID_FLOAT_PCM : WAV_ID_PCM;
uint16_t fmt = ao->format == AF_FORMAT_FLOAT ? WAV_ID_FLOAT_PCM : WAV_ID_PCM;
uint32_t fmt_chunk_size = use_waveex ? 40 : 16;
int bits = af_fmt2bits(ao->format);
@@ -124,16 +124,23 @@ static int init(struct ao *ao)
if (priv->waveheader) {
// WAV files must have one of the following formats
// And they don't work in big endian; fixing it would be simple, but
// nobody cares.
if (BYTE_ORDER == BIG_ENDIAN) {
MP_FATAL(ao, "Not supported on big endian.\n");
return -1;
}
switch (ao->format) {
case AF_FORMAT_U8:
case AF_FORMAT_S16_LE:
case AF_FORMAT_S24_LE:
case AF_FORMAT_S32_LE:
case AF_FORMAT_FLOAT_LE:
case AF_FORMAT_AC3_LE:
case AF_FORMAT_S16:
case AF_FORMAT_S24:
case AF_FORMAT_S32:
case AF_FORMAT_FLOAT:
break;
default:
ao->format = AF_FORMAT_S16_LE;
if (!AF_FORMAT_IS_IEC61937(ao->format))
ao->format = AF_FORMAT_S16;
break;
}
}
@@ -203,7 +210,7 @@ static int play(struct ao *ao, void **data, int samples, int flags)
fwrite(data[0], len, 1, priv->fp);
priv->data_length += len;
return len / ao->sstride;
return samples;
}
#define OPT_BASE_STRUCT struct priv
+118 -60
View File
@@ -53,7 +53,6 @@ struct priv {
// temporary during control()
struct pa_sink_input_info pi;
bool broken_pause;
int retval;
// for wakeup handling
@@ -64,6 +63,7 @@ struct priv {
char *cfg_host;
char *cfg_sink;
int cfg_buffer;
int cfg_latency_hacks;
};
#define GENERIC_ERR_MSG(str) \
@@ -113,7 +113,7 @@ static void stream_request_cb(pa_stream *s, size_t length, void *userdata)
pa_threaded_mainloop_signal(priv->mainloop, 0);
}
static int wait(struct ao *ao, pthread_mutex_t *lock)
static int wait_audio(struct ao *ao, pthread_mutex_t *lock)
{
struct priv *priv = ao->priv;
// We don't use this mutex, because pulse like to call stream_request_cb
@@ -169,16 +169,31 @@ static const struct format_map {
int mp_format;
pa_sample_format_t pa_format;
} format_maps[] = {
{AF_FORMAT_S16_LE, PA_SAMPLE_S16LE},
{AF_FORMAT_S16_BE, PA_SAMPLE_S16BE},
{AF_FORMAT_S32_LE, PA_SAMPLE_S32LE},
{AF_FORMAT_S32_BE, PA_SAMPLE_S32BE},
{AF_FORMAT_FLOAT_LE, PA_SAMPLE_FLOAT32LE},
{AF_FORMAT_FLOAT_BE, PA_SAMPLE_FLOAT32BE},
{AF_FORMAT_S16, PA_SAMPLE_S16NE},
{AF_FORMAT_S32, PA_SAMPLE_S32NE},
{AF_FORMAT_FLOAT, PA_SAMPLE_FLOAT32NE},
{AF_FORMAT_U8, PA_SAMPLE_U8},
{AF_FORMAT_UNKNOWN, 0}
};
static pa_encoding_t map_digital_format(int format)
{
switch (format) {
case AF_FORMAT_S_AC3: return PA_ENCODING_AC3_IEC61937;
case AF_FORMAT_S_EAC3: return PA_ENCODING_EAC3_IEC61937;
case AF_FORMAT_S_MP3: return PA_ENCODING_MPEG_IEC61937;
case AF_FORMAT_S_DTS:
case AF_FORMAT_S_DTSHD: return PA_ENCODING_DTS_IEC61937;
#ifdef PA_ENCODING_MPEG2_AAC_IEC61937
case AF_FORMAT_S_AAC: return PA_ENCODING_MPEG2_AAC_IEC61937;
#endif
default:
if (AF_FORMAT_IS_IEC61937(format))
return PA_ENCODING_ANY;
return PA_ENCODING_PCM;
}
}
static const int speaker_map[][2] = {
{PA_CHANNEL_POSITION_FRONT_LEFT, MP_SPEAKER_ID_FL},
{PA_CHANNEL_POSITION_FRONT_RIGHT, MP_SPEAKER_ID_FR},
@@ -274,32 +289,16 @@ static void uninit(struct ao *ao)
static int init(struct ao *ao)
{
struct pa_sample_spec ss;
struct pa_channel_map map;
pa_proplist *proplist = NULL;
pa_format_info *format = NULL;
struct priv *priv = ao->priv;
char *host = priv->cfg_host && priv->cfg_host[0] ? priv->cfg_host : NULL;
char *sink = priv->cfg_sink && priv->cfg_sink[0] ? priv->cfg_sink : NULL;
const char *version = pa_get_library_version();
pthread_mutex_init(&priv->wakeup_lock, NULL);
pthread_cond_init(&priv->wakeup, NULL);
ao->per_application_mixer = true;
priv->broken_pause = false;
/* not sure which versions are affected, assume 0.9.11* to 0.9.14*
* known bad: 0.9.14, 0.9.13
* known good: 0.9.9, 0.9.10, 0.9.15
* To test: pause, wait ca. 5 seconds, framestep and see if MPlayer
* hangs somewhen. */
if (strncmp(version, "0.9.1", 5) == 0 && version[5] >= '1'
&& version[5] <= '4') {
MP_WARN(ao, "working around probably broken pause functionality,\n"
" see http://www.pulseaudio.org/ticket/440\n");
priv->broken_pause = true;
}
if (!(priv->mainloop = pa_threaded_mainloop_new())) {
MP_ERR(ao, "Failed to allocate main loop\n");
goto fail;
@@ -311,6 +310,12 @@ static int init(struct ao *ao)
goto fail;
}
MP_VERBOSE(ao, "Library version: %s\n", pa_get_library_version());
MP_VERBOSE(ao, "Proto: %lu\n",
(long)pa_context_get_protocol_version(priv->context));
MP_VERBOSE(ao, "Server proto: %lu\n",
(long)pa_context_get_server_protocol_version(priv->context));
pa_context_set_state_callback(priv->context, context_state_cb, ao);
if (pa_context_connect(priv->context, host, 0, NULL) < 0)
@@ -327,26 +332,26 @@ static int init(struct ao *ao)
if (pa_context_get_state(priv->context) != PA_CONTEXT_READY)
goto unlock_and_fail;
ss.channels = ao->channels.num;
ss.rate = ao->samplerate;
if (!(format = pa_format_info_new()))
goto unlock_and_fail;
ao->format = af_fmt_from_planar(ao->format);
const struct format_map *fmt_map = format_maps;
while (fmt_map->mp_format != ao->format) {
if (fmt_map->mp_format == AF_FORMAT_UNKNOWN) {
MP_VERBOSE(ao, "Unsupported format, using default\n");
fmt_map = format_maps;
break;
}
fmt_map++;
}
ao->format = fmt_map->mp_format;
ss.format = fmt_map->pa_format;
format->encoding = map_digital_format(ao->format);
if (format->encoding == PA_ENCODING_PCM) {
const struct format_map *fmt_map = format_maps;
if (!pa_sample_spec_valid(&ss)) {
MP_ERR(ao, "Invalid sample spec\n");
goto unlock_and_fail;
while (fmt_map->mp_format != ao->format) {
if (fmt_map->mp_format == AF_FORMAT_UNKNOWN) {
MP_VERBOSE(ao, "Unsupported format, using default\n");
fmt_map = format_maps;
break;
}
fmt_map++;
}
ao->format = fmt_map->mp_format;
pa_format_info_set_sample_format(format, fmt_map->pa_format);
}
if (!select_chmap(ao, &map))
@@ -357,10 +362,20 @@ static int init(struct ao *ao)
goto unlock_and_fail;
}
(void)pa_proplist_sets(proplist, PA_PROP_MEDIA_ROLE, "video");
(void)pa_proplist_sets(proplist, PA_PROP_MEDIA_ICON_NAME,
PULSE_CLIENT_NAME);
if (!(priv->stream = pa_stream_new_with_proplist(priv->context,
"audio stream", &ss,
&map, proplist)))
pa_format_info_set_rate(format, ao->samplerate);
pa_format_info_set_channels(format, ao->channels.num);
pa_format_info_set_channel_map(format, &map);
if (!pa_format_info_valid(format)) {
MP_ERR(ao, "Invalid audio format\n");
goto unlock_and_fail;
}
if (!(priv->stream = pa_stream_new_extended(priv->context, "audio stream",
&format, 1, proplist)))
goto unlock_and_fail;
pa_proplist_free(proplist);
@@ -370,23 +385,38 @@ static int init(struct ao *ao)
pa_stream_set_write_callback(priv->stream, stream_request_cb, ao);
pa_stream_set_latency_update_callback(priv->stream,
stream_latency_update_cb, ao);
int buf_size = af_fmt_seconds_to_bytes(ao->format, priv->cfg_buffer / 1000.0,
ao->channels.num, ao->samplerate);
pa_buffer_attr bufattr = {
.maxlength = -1,
.tlength = priv->cfg_buffer > 0 ?
pa_usec_to_bytes(priv->cfg_buffer * 1000, &ss) : (uint32_t)-1,
.tlength = buf_size > 0 ? buf_size : (uint32_t)-1,
.prebuf = -1,
.minreq = -1,
.fragsize = -1,
};
int flags = PA_STREAM_NOT_MONOTONIC;
if (!priv->cfg_latency_hacks)
flags |= PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_AUTO_TIMING_UPDATE;
if (pa_stream_connect_playback(priv->stream, sink, &bufattr,
PA_STREAM_NOT_MONOTONIC, NULL, NULL) < 0)
flags, NULL, NULL) < 0)
goto unlock_and_fail;
/* Wait until the stream is ready */
pa_threaded_mainloop_wait(priv->mainloop);
while (1) {
int state = pa_stream_get_state(priv->stream);
if (state == PA_STREAM_READY)
break;
if (!PA_STREAM_IS_GOOD(state))
goto unlock_and_fail;
pa_threaded_mainloop_wait(priv->mainloop);
}
if (pa_stream_get_state(priv->stream) != PA_STREAM_READY)
if (pa_stream_is_suspended(priv->stream)) {
MP_ERR(ao, "The stream is suspended. Bailing out.\n");
goto unlock_and_fail;
}
pa_threaded_mainloop_unlock(priv->mainloop);
@@ -398,6 +428,8 @@ unlock_and_fail:
pa_threaded_mainloop_unlock(priv->mainloop);
fail:
if (format)
pa_format_info_free(format);
if (priv->context) {
if (!(pa_context_errno(priv->context) == PA_ERR_CONNECTIONREFUSED
&& ao->probing))
@@ -463,12 +495,6 @@ static void pause(struct ao *ao)
// Resume the audio stream by uncorking it on the server
static void resume(struct ao *ao)
{
struct priv *priv = ao->priv;
/* Without this, certain versions will cause an infinite hang because
* pa_stream_writable_size returns 0 always.
* Note that this workaround causes A-V desync after pause. */
if (priv->broken_pause)
reset(ao);
cork(ao, false);
}
@@ -482,8 +508,7 @@ static int get_space(struct ao *ao)
return space / ao->sstride;
}
// Return the current latency in seconds
static float get_delay(struct ao *ao)
static float get_delay_hackfixed(struct ao *ao)
{
/* This code basically does what pa_stream_get_latency() _should_
* do, but doesn't due to multiple known bugs in PulseAudio (at
@@ -538,6 +563,34 @@ static float get_delay(struct ao *ao)
return latency / 1e6;
}
static float get_delay_pulse(struct ao *ao)
{
struct priv *priv = ao->priv;
pa_usec_t latency = (pa_usec_t) -1;
pa_threaded_mainloop_lock(priv->mainloop);
while (pa_stream_get_latency(priv->stream, &latency, NULL) < 0) {
if (pa_context_errno(priv->context) != PA_ERR_NODATA) {
GENERIC_ERR_MSG("pa_stream_get_latency() failed");
break;
}
/* Wait until latency data is available again */
pa_threaded_mainloop_wait(priv->mainloop);
}
pa_threaded_mainloop_unlock(priv->mainloop);
return latency == (pa_usec_t) -1 ? 0 : latency / 1000000.0;
}
// Return the current latency in seconds
static float get_delay(struct ao *ao)
{
struct priv *priv = ao->priv;
if (priv->cfg_latency_hacks) {
return get_delay_hackfixed(ao);
} else {
return get_delay_pulse(ao);
}
}
/* A callback function that is called when the
* pa_context_get_sink_input_info() operation completes. Saves the
* volume field of the specified structure to the global variable volume.
@@ -567,7 +620,7 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
pa_threaded_mainloop_lock(priv->mainloop);
if (!waitop(priv, pa_context_get_sink_input_info(priv->context, devidx,
info_func, ao))) {
GENERIC_ERR_MSG("pa_stream_get_sink_input_info() failed");
GENERIC_ERR_MSG("pa_context_get_sink_input_info() failed");
return CONTROL_ERROR;
}
// Warning: some information in pi might be unaccessible, because
@@ -630,6 +683,9 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
return CONTROL_OK;
}
case AOCONTROL_HAS_PER_APP_VOLUME:
return CONTROL_TRUE;
case AOCONTROL_UPDATE_STREAM_TITLE: {
char *title = (char *)arg;
pa_threaded_mainloop_lock(priv->mainloop);
@@ -662,16 +718,18 @@ const struct ao_driver audio_out_pulse = {
.pause = pause,
.resume = resume,
.drain = drain,
.wait = wait,
.wait = wait_audio,
.wakeup = wakeup,
.priv_size = sizeof(struct priv),
.priv_defaults = &(const struct priv) {
.cfg_buffer = 250,
.cfg_latency_hacks = 1,
},
.options = (const struct m_option[]) {
OPT_STRING("host", cfg_host, 0),
OPT_STRING("sink", cfg_sink, 0),
OPT_CHOICE_OR_INT("buffer", cfg_buffer, 0, 1, 2000, ({"native", -1})),
OPT_CHOICE_OR_INT("buffer", cfg_buffer, 0, 1, 2000, ({"native", 0})),
OPT_FLAG("latency-hacks", cfg_latency_hacks, 0),
{0}
},
};
+14 -28
View File
@@ -52,40 +52,26 @@ static int set_format(struct ao *ao)
case AF_FORMAT_S8:
rsd_format = RSD_S8;
break;
case AF_FORMAT_S16_LE:
rsd_format = RSD_S16_LE;
case AF_FORMAT_S16:
rsd_format = RSD_S16_NE;
break;
case AF_FORMAT_S16_BE:
rsd_format = RSD_S16_BE;
case AF_FORMAT_U16:
rsd_format = RSD_U16_NE;
break;
case AF_FORMAT_U16_LE:
rsd_format = RSD_U16_LE;
case AF_FORMAT_S24:
case AF_FORMAT_U24:
rsd_format = RSD_S32_NE;
ao->format = AF_FORMAT_S32;
break;
case AF_FORMAT_U16_BE:
rsd_format = RSD_U16_BE;
case AF_FORMAT_S32:
rsd_format = RSD_S32_NE;
break;
case AF_FORMAT_S24_LE:
case AF_FORMAT_S24_BE:
case AF_FORMAT_U24_LE:
case AF_FORMAT_U24_BE:
rsd_format = RSD_S32_LE;
ao->format = AF_FORMAT_S32_LE;
break;
case AF_FORMAT_S32_LE:
rsd_format = RSD_S32_LE;
break;
case AF_FORMAT_S32_BE:
rsd_format = RSD_S32_BE;
break;
case AF_FORMAT_U32_LE:
rsd_format = RSD_U32_LE;
break;
case AF_FORMAT_U32_BE:
rsd_format = RSD_U32_BE;
case AF_FORMAT_U32:
rsd_format = RSD_U32_NE;
break;
default:
rsd_format = RSD_S16_LE;
ao->format = AF_FORMAT_S16_LE;
rsd_format = RSD_S16_NE;
ao->format = AF_FORMAT_S16;
}
return rsd_format;
+32 -44
View File
@@ -38,6 +38,20 @@ struct priv
float buflen;
};
static int fmtmap[][2] = {
{AF_FORMAT_U8, AUDIO_U8},
{AF_FORMAT_S8, AUDIO_S8},
{AF_FORMAT_U16, AUDIO_U16SYS},
{AF_FORMAT_S16, AUDIO_S16SYS},
#ifdef AUDIO_S32SYS
{AF_FORMAT_S32, AUDIO_S32SYS},
#endif
#ifdef AUDIO_F32SYS
{AF_FORMAT_FLOAT, AUDIO_F32SYS},
#endif
{0}
};
static void audio_callback(void *userdata, Uint8 *stream, int len)
{
struct ao *ao = userdata;
@@ -104,26 +118,12 @@ static int init(struct ao *ao)
SDL_AudioSpec desired, obtained;
switch (ao->format) {
case AF_FORMAT_U8: desired.format = AUDIO_U8; break;
case AF_FORMAT_S8: desired.format = AUDIO_S8; break;
case AF_FORMAT_U16_LE: desired.format = AUDIO_U16LSB; break;
case AF_FORMAT_U16_BE: desired.format = AUDIO_U16MSB; break;
default:
case AF_FORMAT_S16_LE: desired.format = AUDIO_S16LSB; break;
case AF_FORMAT_S16_BE: desired.format = AUDIO_S16MSB; break;
#ifdef AUDIO_S32LSB
case AF_FORMAT_S32_LE: desired.format = AUDIO_S32LSB; break;
#endif
#ifdef AUDIO_S32MSB
case AF_FORMAT_S32_BE: desired.format = AUDIO_S32MSB; break;
#endif
#ifdef AUDIO_F32LSB
case AF_FORMAT_FLOAT_LE: desired.format = AUDIO_F32LSB; break;
#endif
#ifdef AUDIO_F32MSB
case AF_FORMAT_FLOAT_BE: desired.format = AUDIO_F32MSB; break;
#endif
desired.format = AUDIO_S16SYS;
for (int n = 0; fmtmap[n][0]; n++) {
if (ao->format == fmtmap[n][0]) {
desired.format = fmtmap[n][1];
break;
}
}
desired.freq = ao->samplerate;
desired.channels = ao->channels.num;
@@ -156,30 +156,18 @@ static int init(struct ao *ao)
// large, this will help.
ao->device_buffer = 3 * obtained.samples;
switch (obtained.format) {
case AUDIO_U8: ao->format = AF_FORMAT_U8; break;
case AUDIO_S8: ao->format = AF_FORMAT_S8; break;
case AUDIO_S16LSB: ao->format = AF_FORMAT_S16_LE; break;
case AUDIO_S16MSB: ao->format = AF_FORMAT_S16_BE; break;
case AUDIO_U16LSB: ao->format = AF_FORMAT_U16_LE; break;
case AUDIO_U16MSB: ao->format = AF_FORMAT_U16_BE; break;
#ifdef AUDIO_S32LSB
case AUDIO_S32LSB: ao->format = AF_FORMAT_S32_LE; break;
#endif
#ifdef AUDIO_S32MSB
case AUDIO_S32MSB: ao->format = AF_FORMAT_S32_BE; break;
#endif
#ifdef AUDIO_F32LSB
case AUDIO_F32LSB: ao->format = AF_FORMAT_FLOAT_LE; break;
#endif
#ifdef AUDIO_F32MSB
case AUDIO_F32MSB: ao->format = AF_FORMAT_FLOAT_BE; break;
#endif
default:
if (!ao->probing)
MP_ERR(ao, "could not find matching format\n");
uninit(ao);
return -1;
ao->format = 0;
for (int n = 0; fmtmap[n][0]; n++) {
if (obtained.format == fmtmap[n][1]) {
ao->format = fmtmap[n][0];
break;
}
}
if (!ao->format) {
if (!ao->probing)
MP_ERR(ao, "could not find matching format\n");
uninit(ao);
return -1;
}
if (!ao_chmap_sel_get_def(ao, &sel, &ao->channels, obtained.channels)) {
+59 -54
View File
@@ -33,6 +33,7 @@ struct priv {
struct sio_hdl *hdl;
struct sio_par par;
int delay;
bool playing;
int vol;
int havevol;
#define SILENCE_NMAX 0x1000
@@ -60,6 +61,8 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
return CONTROL_FALSE;
sio_setvol(p->hdl, vol->left * SIO_MAXVOL / 100);
break;
case AOCONTROL_HAS_SOFT_VOLUME:
return CONTROL_TRUE;
default:
return CONTROL_UNKNOWN;
}
@@ -72,7 +75,7 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
static void movecb(void *addr, int delta)
{
struct priv *p = addr;
p->delay -= delta * (int)(p->par.bps * p->par.pchan);
p->delay -= delta;
}
/*
@@ -107,26 +110,20 @@ static int init(struct ao *ao)
struct priv *p = ao->priv;
struct af_to_par {
int format, bits, sig, le;
int format, bits, sig;
} static const af_to_par[] = {
{AF_FORMAT_U8, 8, 0, 0},
{AF_FORMAT_S8, 8, 1, 0},
{AF_FORMAT_U16_LE, 16, 0, 1},
{AF_FORMAT_U16_BE, 16, 0, 0},
{AF_FORMAT_S16_LE, 16, 1, 1},
{AF_FORMAT_S16_BE, 16, 1, 0},
{AF_FORMAT_U24_LE, 16, 0, 1},
{AF_FORMAT_U24_BE, 24, 0, 0},
{AF_FORMAT_S24_LE, 24, 1, 1},
{AF_FORMAT_S24_BE, 24, 1, 0},
{AF_FORMAT_U32_LE, 32, 0, 1},
{AF_FORMAT_U32_BE, 32, 0, 0},
{AF_FORMAT_S32_LE, 32, 1, 1},
{AF_FORMAT_S32_BE, 32, 1, 0}
{AF_FORMAT_U8, 8, 0},
{AF_FORMAT_S8, 8, 1},
{AF_FORMAT_U16, 16, 0},
{AF_FORMAT_S16, 16, 1},
{AF_FORMAT_U24, 24, 0},
{AF_FORMAT_S24, 24, 1},
{AF_FORMAT_U32, 32, 0},
{AF_FORMAT_S32, 32, 1},
}, *ap;
int i;
p->hdl = sio_open(p->dev, SIO_PLAY, 0);
p->hdl = sio_open(p->dev, SIO_PLAY, 1);
if (p->hdl == NULL) {
MP_ERR(ao, "can't open sndio %s\n", p->dev);
goto error;
@@ -147,7 +144,7 @@ static int init(struct ao *ao)
p->par.bits = ap->bits;
p->par.sig = ap->sig;
if (ap->bits > 8)
p->par.le = ap->le;
p->par.le = SIO_LE_NATIVE;
if (ap->bits != SIO_BPS(ap->bits))
p->par.bps = ap->bits / 8;
break;
@@ -173,30 +170,25 @@ static int init(struct ao *ao)
MP_ERR(ao, "couldn't get params\n");
goto error;
}
if (p->par.bps > 1 && p->par.le != SIO_LE_NATIVE) {
MP_ERR(ao, "swapped endian output not supported\n");
goto error;
}
if (p->par.bits == 8 && p->par.bps == 1) {
ao->format = p->par.sig ? AF_FORMAT_S8 : AF_FORMAT_U8;
} else if (p->par.bits == 16 && p->par.bps == 2) {
ao->format = p->par.sig ?
(p->par.le ? AF_FORMAT_S16_LE : AF_FORMAT_S16_BE) :
(p->par.le ? AF_FORMAT_U16_LE : AF_FORMAT_U16_BE);
ao->format = p->par.sig ? AF_FORMAT_S16 : AF_FORMAT_U16;
} else if ((p->par.bits == 24 || p->par.msb) && p->par.bps == 3) {
ao->format = p->par.sig ?
(p->par.le ? AF_FORMAT_S24_LE : AF_FORMAT_S24_BE) :
(p->par.le ? AF_FORMAT_U24_LE : AF_FORMAT_U24_BE);
ao->format = p->par.sig ? AF_FORMAT_S24 : AF_FORMAT_U24;
} else if ((p->par.bits == 32 || p->par.msb) && p->par.bps == 4) {
ao->format = p->par.sig ?
(p->par.le ? AF_FORMAT_S32_LE : AF_FORMAT_S32_BE) :
(p->par.le ? AF_FORMAT_U32_LE : AF_FORMAT_U32_BE);
ao->format = p->par.sig ? AF_FORMAT_S32 : AF_FORMAT_U32;
} else {
MP_ERR(ao, "couldn't set format\n");
goto error;
}
ao->bps = p->par.bps * p->par.pchan * p->par.rate;
ao->no_persistent_volume = true;
p->havevol = sio_onvol(p->hdl, volcb, p);
sio_onmove(p->hdl, movecb, p);
p->delay = 0;
if (!sio_start(p->hdl))
MP_ERR(ao, "init: couldn't start\n");
@@ -233,46 +225,56 @@ static void reset(struct ao *ao)
{
struct priv *p = ao->priv;
if (!sio_stop(p->hdl))
MP_ERR(ao, "reset: couldn't stop\n");
p->delay = 0;
if (!sio_start(p->hdl))
MP_ERR(ao, "reset: couldn't start\n");
if (p->playing) {
MP_WARN(ao, "Blocking until remaining audio is played... (sndio design bug).\n");
p->playing = false;
if (!sio_stop(p->hdl))
MP_ERR(ao, "reset: couldn't stop\n");
p->delay = 0;
if (!sio_start(p->hdl))
MP_ERR(ao, "reset: couldn't start\n");
}
}
/*
* play given number of bytes until sio_write() blocks
* play given number of samples until sio_write() blocks
*/
static int play(struct ao *ao, void **data, int samples, int flags)
{
struct priv *p = ao->priv;
int n;
n = sio_write(p->hdl, data[0], samples * ao->sstride);
n = sio_write(p->hdl, data[0], samples * ao->sstride) / ao->sstride;
p->delay += n;
if (flags & AOPLAY_FINAL_CHUNK)
reset(ao);
return n / ao->sstride;
p->playing = true;
/* on AOPLAY_FINAL_CHUNK, just let it underrun */
return n;
}
/*
* how many bytes can be played without blocking
* make libsndio call movecb()
*/
static void update(struct ao *ao)
{
struct priv *p = ao->priv;
int n = sio_pollfd(p->hdl, p->pfd, POLLOUT);
while (poll(p->pfd, n, 0) < 0 && errno == EINTR) {}
sio_revents(p->hdl, p->pfd);
}
/*
* how many samples can be played without blocking
*/
static int get_space(struct ao *ao)
{
struct priv *p = ao->priv;
int n;
/*
* call poll() and sio_revents(), so the
* delay counter is updated
*/
n = sio_pollfd(p->hdl, p->pfd, POLLOUT);
while (poll(p->pfd, n, 0) < 0 && errno == EINTR)
; /* nothing */
sio_revents(p->hdl, p->pfd);
update(ao);
return (p->par.bufsz * p->par.pchan * p->par.bps - p->delay) / ao->sstride;
int samples = p->par.bufsz - p->delay;
return samples / p->par.round * p->par.round;
}
/*
@@ -281,7 +283,10 @@ static int get_space(struct ao *ao)
static float get_delay(struct ao *ao)
{
struct priv *p = ao->priv;
return (float)p->delay / (p->par.bps * p->par.pchan * p->par.rate);
update(ao);
return p->delay / (double)p->par.rate;
}
/*
@@ -301,8 +306,8 @@ static void audio_resume(struct ao *ao)
int n, count, todo;
/*
* we want to start with buffers full, because mplayer uses
* get_space() pointer as clock, which would cause video to
* we want to start with buffers full, because mpv uses
* get_delay() as clock, which would cause video to
* accelerate while buffers are filled.
*/
todo = p->par.bufsz * p->par.pchan * p->par.bps;
+2 -1
View File
@@ -194,7 +194,6 @@ static int init(struct ao *ao)
wasapi_enumerate_devices(state->log);
}
ao->per_application_mixer = true;
if (state->opt_exclusive) {
state->share_mode = AUDCLNT_SHAREMODE_EXCLUSIVE;
} else {
@@ -284,6 +283,8 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
ISimpleAudioVolume_SetMute(state->pAudioVolumeProxy, mute, NULL);
return CONTROL_OK;
case AOCONTROL_HAS_PER_APP_VOLUME:
return CONTROL_TRUE;
case AOCONTROL_UPDATE_STREAM_TITLE: {
MP_VERBOSE(state, "Updating stream title to \"%s\"\n", (char*)arg);
wchar_t *title = mp_from_utf8(NULL, (char*)arg);
+1 -1
View File
@@ -28,7 +28,7 @@
#include <mmdeviceapi.h>
#include <avrt.h>
#include "compat/atomics.h"
#include "osdep/atomics.h"
typedef struct wasapi_state {
struct mp_log *log;
+22 -32
View File
@@ -142,47 +142,36 @@ static void set_format(WAVEFORMATEXTENSIBLE *wformat, WORD bytepersample,
wformat->dwChannelMask = chanmask;
}
static int format_set_bits(int old_format, int bits, int fp) {
int format = old_format;
format &= (~AF_FORMAT_BITS_MASK) & (~AF_FORMAT_POINT_MASK) & (~AF_FORMAT_SIGN_MASK);
format |= AF_FORMAT_SI;
switch (bits) {
case 32:
format |= AF_FORMAT_32BIT;
break;
case 24:
format |= AF_FORMAT_24BIT;
break;
case 16:
format |= AF_FORMAT_16BIT;
break;
default:
abort(); // (should be) unreachable
}
static int format_set_bits(int old_format, int bits, int fp)
{
if (fp) {
format |= AF_FORMAT_F;
} else {
format |= AF_FORMAT_I;
switch (bits) {
case 64: return AF_FORMAT_DOUBLE;
case 32: return AF_FORMAT_FLOAT;
default: return 0;
}
}
return format;
return af_fmt_change_bits(old_format, bits);
}
static int set_ao_format(struct wasapi_state *state,
struct ao *const ao,
WAVEFORMATEXTENSIBLE wformat) {
// .Data1 == 1 is PCM, .Data1 == 3 is IEEE_FLOAT
int format = format_set_bits(ao->format,
wformat.Format.wBitsPerSample, wformat.SubFormat.Data1 == 3);
WAVEFORMATEXTENSIBLE wformat)
{
if (wformat.SubFormat.Data1 != 1 && wformat.SubFormat.Data1 != 3) {
MP_ERR(ao, "unknown SubFormat %"PRIu32"\n",
(uint32_t)wformat.SubFormat.Data1);
return 0;
}
// .Data1 == 1 is PCM, .Data1 == 3 is IEEE_FLOAT
int format = format_set_bits(ao->format,
wformat.Format.wBitsPerSample, wformat.SubFormat.Data1 == 3);
if (!format)
return 0;
ao->samplerate = wformat.Format.nSamplesPerSec;
ao->bps = wformat.Format.nAvgBytesPerSec;
ao->format = format;
@@ -204,6 +193,8 @@ static int try_format(struct wasapi_state *state,
set_format(&wformat, bits / 8, samplerate, channels.num, mp_chmap_to_waveext(&channels));
int af_format = format_set_bits(ao->format, bits, bits == 32);
if (!af_format)
return 0;
MP_VERBOSE(ao, "trying %dch %s @ %dhz\n",
channels.num, af_fmt_to_str(af_format), samplerate);
@@ -292,14 +283,13 @@ static int try_passthrough(struct wasapi_state *state,
union WAVEFMT u;
u.extensible = &wformat;
MP_VERBOSE(ao, "trying passthrough for %s...\n",
af_fmt_to_str((ao->format&~AF_FORMAT_END_MASK) | AF_FORMAT_LE));
MP_VERBOSE(ao, "trying passthrough for %s...\n", af_fmt_to_str(ao->format));
HRESULT hr = IAudioClient_IsFormatSupported(state->pAudioClient,
state->share_mode,
u.ex, NULL);
if (!FAILED(hr)) {
ao->format = (ao->format&~AF_FORMAT_END_MASK) | AF_FORMAT_LE;
ao->format = ao->format;
state->format = wformat;
return 1;
}
@@ -310,7 +300,7 @@ static int find_formats(struct ao *const ao)
{
struct wasapi_state *state = (struct wasapi_state *)ao->priv;
if (AF_FORMAT_IS_IEC61937(ao->format) || ao->format == AF_FORMAT_MPEG2) {
if (AF_FORMAT_IS_IEC61937(ao->format)) {
if (try_passthrough(state, ao))
return 0;
+3 -11
View File
@@ -25,14 +25,6 @@
#include "audio/chmap.h"
#include "audio/chmap_sel.h"
// Minimum buffer size in seconds.
#define MIN_BUFFER 0.2
// If ao_get_delay() reaches this value after ao_play() was called with the
// AOPLAY_FINAL_CHUNK flag set, the playback core expects that the audio has
// all been played.
#define AO_EOF_DELAY 0.05
/* global data used by ao.c and ao drivers */
struct ao {
int samplerate;
@@ -44,8 +36,6 @@ struct ao {
int num_planes;
bool probing; // if true, don't fail loudly on init
bool untimed; // don't assume realtime playback
bool no_persistent_volume; // the AO does the equivalent of af_volume
bool per_application_mixer; // like above, but volume persists (per app)
int device_buffer; // device buffer in samples (guessed by
// common init code if not set by driver)
const struct ao_driver *api; // entrypoints to the wrapper (push.c/pull.c)
@@ -56,6 +46,7 @@ struct ao {
struct mp_log *log; // Using e.g. "[ao/coreaudio]" as prefix
int buffer;
double def_buffer;
void *api_priv;
};
@@ -134,6 +125,8 @@ struct ao_driver {
float (*get_delay)(struct ao *ao);
// push based: block until all queued audio is played (optional)
void (*drain)(struct ao *ao);
// Optional. Return true if audio has stopped in any way.
bool (*get_eof)(struct ao *ao);
// Wait until the audio buffer needs to be refilled. The lock is the
// internal mutex usually protecting the internal AO state (and used to
// protect driver calls), and must be temporarily unlocked while waiting.
@@ -158,7 +151,6 @@ struct ao_driver {
// These functions can be called by AOs.
int ao_play_silence(struct ao *ao, int samples);
void ao_wait_drain(struct ao *ao);
int ao_read_data(struct ao *ao, void **data, int samples, int64_t out_time_us);
struct pollfd;
int ao_wait_poll(struct ao *ao, struct pollfd *fds, int num_fds,
+19 -1
View File
@@ -30,7 +30,7 @@
#include "osdep/timer.h"
#include "osdep/threads.h"
#include "compat/atomics.h"
#include "osdep/atomics.h"
#include "misc/ring.h"
/*
@@ -193,6 +193,22 @@ static void resume(struct ao *ao)
ao->driver->resume(ao);
}
static void drain(struct ao *ao)
{
struct ao_pull_state *p = ao->api_priv;
if (atomic_load(&p->state) == AO_STATE_PLAY)
mp_sleep_us(get_delay(ao) * 1000000);
reset(ao);
}
static bool get_eof(struct ao *ao)
{
struct ao_pull_state *p = ao->api_priv;
// For simplicity, ignore the latency. Otherwise, we would have to run an
// extra thread to time it.
return mp_ring_buffered(p->buffers[0]) == 0;
}
static void uninit(struct ao *ao)
{
ao->driver->uninit(ao);
@@ -212,10 +228,12 @@ const struct ao_driver ao_api_pull = {
.init = init,
.control = control,
.uninit = uninit,
.drain = drain,
.reset = reset,
.get_space = get_space,
.play = play,
.get_delay = get_delay,
.get_eof = get_eof,
.pause = pause,
.resume = resume,
.priv_size = sizeof(struct ao_pull_state),
+131 -91
View File
@@ -35,7 +35,7 @@
#include "osdep/threads.h"
#include "osdep/timer.h"
#include "compat/atomics.h"
#include "osdep/atomics.h"
#include "audio/audio.h"
#include "audio/audio_buffer.h"
@@ -44,18 +44,15 @@ struct ao_push_state {
pthread_t thread;
pthread_mutex_t lock;
pthread_cond_t wakeup;
pthread_cond_t wakeup_drain;
// --- protected by lock
struct mp_audio_buffer *buffer;
bool terminate;
bool drain;
bool buffers_full;
bool avoid_ao_wait;
bool wait_on_ao;
bool still_playing;
bool need_wakeup;
bool requested_data;
bool paused;
// Whether the current buffer contains the complete audio.
@@ -87,22 +84,21 @@ static int control(struct ao *ao, enum aocontrol cmd, void *arg)
return r;
}
static double unlocked_get_delay(struct ao *ao)
{
struct ao_push_state *p = ao->api_priv;
double driver_delay = 0;
if (ao->driver->get_delay)
driver_delay = ao->driver->get_delay(ao);
return driver_delay + mp_audio_buffer_seconds(p->buffer);
}
static float get_delay(struct ao *ao)
{
struct ao_push_state *p = ao->api_priv;
pthread_mutex_lock(&p->lock);
double driver_delay = 0;
if (ao->driver->get_delay)
driver_delay = ao->driver->get_delay(ao);
double delay = driver_delay + mp_audio_buffer_seconds(p->buffer);
float delay = unlocked_get_delay(ao);
pthread_mutex_unlock(&p->lock);
if (delay >= AO_EOF_DELAY && p->expected_end_time) {
if (mp_time_sec() > p->expected_end_time) {
MP_ERR(ao, "Audio device EOF reporting is broken!\n");
MP_ERR(ao, "Please report this problem.\n");
delay = 0;
}
}
return delay;
}
@@ -114,7 +110,9 @@ static void reset(struct ao *ao)
ao->driver->reset(ao);
mp_audio_buffer_clear(p->buffer);
p->paused = false;
wakeup_playthread(ao);
if (p->still_playing)
wakeup_playthread(ao);
p->still_playing = false;
pthread_mutex_unlock(&p->lock);
}
@@ -145,16 +143,28 @@ static void drain(struct ao *ao)
{
struct ao_push_state *p = ao->api_priv;
MP_VERBOSE(ao, "draining...\n");
pthread_mutex_lock(&p->lock);
if (p->paused)
goto done;
p->final_chunk = true;
p->drain = true;
wakeup_playthread(ao);
while (p->drain)
pthread_cond_wait(&p->wakeup_drain, &p->lock);
while (p->still_playing && mp_audio_buffer_samples(p->buffer) > 0)
pthread_cond_wait(&p->wakeup, &p->lock);
if (ao->driver->drain) {
ao->driver->drain(ao);
} else {
double time = unlocked_get_delay(ao);
mp_sleep_us(MPMIN(time, ao->buffer / (double)ao->samplerate + 1) * 1e6);
}
done:
pthread_mutex_unlock(&p->lock);
if (!ao->driver->drain)
ao_wait_drain(ao);
reset(ao);
}
static int unlocked_get_space(struct ao *ao)
@@ -163,13 +173,17 @@ static int unlocked_get_space(struct ao *ao)
int space = mp_audio_buffer_get_write_available(p->buffer);
if (ao->driver->get_space) {
// The following code attempts to keep the total buffered audio to
// MIN_BUFFER/2+device_buffer in order to improve latency.
// ao->buffer in order to improve latency.
int device_space = ao->driver->get_space(ao);
int device_buffered = ao->device_buffer - device_space;
int soft_buffered = mp_audio_buffer_samples(p->buffer);
int min_buffer = MIN_BUFFER / 2 * ao->samplerate + ao->device_buffer;
int total_buffer = device_buffered + soft_buffered;
int missing = min_buffer - total_buffer;
// The extra margin helps avoiding too many wakeups if the AO is fully
// byte based and doesn't do proper chunked processing.
int min_buffer = ao->buffer + 64;
int missing = min_buffer - device_buffered - soft_buffered;
// But always keep the device's buffer filled as much as we can.
int device_missing = device_space - soft_buffered;
missing = MPMAX(missing, device_missing);
space = MPMIN(space, missing);
space = MPMAX(0, space);
}
@@ -185,6 +199,15 @@ static int get_space(struct ao *ao)
return space;
}
static bool get_eof(struct ao *ao)
{
struct ao_push_state *p = ao->api_priv;
pthread_mutex_lock(&p->lock);
bool eof = !p->still_playing;
pthread_mutex_unlock(&p->lock);
return eof;
}
static int play(struct ao *ao, void **data, int samples, int flags)
{
struct ao_push_state *p = ao->api_priv;
@@ -194,6 +217,8 @@ static int play(struct ao *ao, void **data, int samples, int flags)
int write_samples = mp_audio_buffer_get_write_available(p->buffer);
write_samples = MPMIN(write_samples, samples);
MP_TRACE(ao, "samples=%d flags=%d r=%d\n", samples, flags, write_samples);
if (write_samples < samples)
flags = flags & ~AOPLAY_FINAL_CHUNK;
bool is_final = flags & AOPLAY_FINAL_CHUNK;
@@ -207,16 +232,14 @@ static int play(struct ao *ao, void **data, int samples, int flags)
bool got_data = write_samples > 0 || p->paused || p->final_chunk != is_final;
p->expected_end_time = 0;
p->final_chunk = is_final;
p->paused = false;
p->still_playing |= write_samples > 0;
// If we don't have new data, the decoder thread basically promises it
// will send new data as soon as it's available.
if (got_data) {
p->requested_data = false;
if (got_data)
wakeup_playthread(ao);
}
pthread_mutex_unlock(&p->lock);
return write_samples;
}
@@ -246,37 +269,31 @@ static void ao_play_data(struct ao *ao)
}
r = MPMAX(r, 0);
// Probably can't copy the rest of the buffer due to period alignment.
bool stuck = r <= 0 && space >= max && data.samples > 0;
if ((flags & AOPLAY_FINAL_CHUNK) && stuck) {
bool stuck_eof = r <= 0 && space >= max && data.samples > 0;
if ((flags & AOPLAY_FINAL_CHUNK) && stuck_eof) {
MP_ERR(ao, "Audio output driver seems to ignore AOPLAY_FINAL_CHUNK.\n");
r = max;
}
mp_audio_buffer_skip(p->buffer, r);
if (p->final_chunk && mp_audio_buffer_samples(p->buffer) == 0) {
p->expected_end_time = mp_time_sec() + AO_EOF_DELAY + 0.25; // + margin
if (ao->driver->get_delay)
p->expected_end_time += ao->driver->get_delay(ao);
}
// In both cases, we have to account for space!=0, but the AO not accepting
// any new data (due to rounding to period boundaries).
p->buffers_full = max >= space && r <= 0;
p->avoid_ao_wait = (max == 0 && space > 0) || p->paused || stuck;
MP_TRACE(ao, "in=%d, space=%d r=%d flags=%d aw=%d full=%d f=%d\n", max,
space, r, flags, p->avoid_ao_wait, p->buffers_full, p->final_chunk);
}
// Estimate when the AO needs data again.
static double ao_estimate_timeout(struct ao *ao)
{
struct ao_push_state *p = ao->api_priv;
double timeout = 0;
if (p->buffers_full && ao->driver->get_delay) {
timeout = ao->driver->get_delay(ao) - 0.050;
// Keep extra safety margin if the buffers are large
if (timeout > 0.100)
timeout = MPMAX(timeout - 0.200, 0.100);
}
return MPMAX(timeout, ao->device_buffer * 0.75 / ao->samplerate);
if (r > 0)
p->expected_end_time = 0;
// Nothing written, but more input data than space - this must mean the
// AO's get_space() doesn't do period alignment correctly.
bool stuck = r == 0 && max >= space && space > 0;
if (stuck)
MP_ERR(ao, "Audio output is reporting incorrect buffer status.\n");
// Wait until space becomes available. Also wait if we actually wrote data,
// so the AO wakes us up properly if it needs more data.
p->wait_on_ao = space == 0 || r > 0 || stuck;
p->still_playing |= r > 0;
// If we just filled the AO completely (r == space), don't refill for a
// while. Prevents wakeup feedback with byte-granular AOs.
int needed = unlocked_get_space(ao);
bool more = needed >= (r == space ? ao->device_buffer / 4 : 1) && !stuck;
if (more)
mp_input_wakeup(ao->input_ctx); // request more data
MP_TRACE(ao, "in=%d flags=%d space=%d r=%d wa=%d needed=%d more=%d\n",
max, flags, space, r, p->wait_on_ao, needed, more);
}
static void *playthread(void *arg)
@@ -288,25 +305,9 @@ static void *playthread(void *arg)
if (!p->paused)
ao_play_data(ao);
// Request new data from decoder if buffer goes below "full".
// Allow a small margin of missing data for AOs that use timeouts.
double margin = ao->driver->wait ? 0 : ao->device_buffer / 8;
if (!p->buffers_full && unlocked_get_space(ao) > margin) {
if (!p->requested_data)
mp_input_wakeup(ao->input_ctx);
p->requested_data = true;
}
if (p->drain && (p->avoid_ao_wait || p->paused)) {
if (ao->driver->drain)
ao->driver->drain(ao);
p->drain = false;
pthread_cond_signal(&p->wakeup_drain);
}
if (!p->need_wakeup) {
MP_STATS(ao, "start audio wait");
if (p->avoid_ao_wait || p->paused) {
if (!p->wait_on_ao || p->paused) {
// Avoid busy waiting, because the audio API will still report
// that it needs new data, even if we're not ready yet, or if
// get_space() decides that the amount of audio buffered in the
@@ -314,12 +315,39 @@ static void *playthread(void *arg)
// The most important part is that the decoder is woken up, so
// that the decoder will wake up us in turn.
MP_TRACE(ao, "buffer inactive.\n");
mp_input_wakeup(ao->input_ctx);
pthread_cond_wait(&p->wakeup, &p->lock);
bool was_playing = p->still_playing;
double timeout = -1;
if (p->still_playing && !p->paused && p->final_chunk &&
!mp_audio_buffer_samples(p->buffer))
{
double now = mp_time_sec();
if (!p->expected_end_time)
p->expected_end_time = now + unlocked_get_delay(ao);
if (p->expected_end_time < now) {
p->still_playing = false;
} else {
timeout = p->expected_end_time - now;
}
}
if (was_playing && !p->still_playing)
mp_input_wakeup(ao->input_ctx);
pthread_cond_signal(&p->wakeup); // for draining
if (p->still_playing && timeout > 0) {
mpthread_cond_timedwait_rel(&p->wakeup, &p->lock, timeout);
} else {
pthread_cond_wait(&p->wakeup, &p->lock);
}
} else {
// Wait until the device wants us to write more data to it.
if (!ao->driver->wait || ao->driver->wait(ao, &p->lock) < 0) {
// Fallback to guessing.
double timeout = ao_estimate_timeout(ao);
double timeout = 0;
if (ao->driver->get_delay)
timeout = ao->driver->get_delay(ao);
timeout *= 0.25; // wake up if 25% played
mpthread_cond_timedwait_rel(&p->wakeup, &p->lock, timeout);
}
}
@@ -331,6 +359,19 @@ static void *playthread(void *arg)
return NULL;
}
static void destroy_no_thread(struct ao *ao)
{
struct ao_push_state *p = ao->api_priv;
ao->driver->uninit(ao);
for (int n = 0; n < 2; n++)
close(p->wakeup_pipe[n]);
pthread_cond_destroy(&p->wakeup);
pthread_mutex_destroy(&p->lock);
}
static void uninit(struct ao *ao)
{
struct ao_push_state *p = ao->api_priv;
@@ -342,14 +383,7 @@ static void uninit(struct ao *ao)
pthread_join(p->thread, NULL);
ao->driver->uninit(ao);
for (int n = 0; n < 2; n++)
close(p->wakeup_pipe[n]);
pthread_cond_destroy(&p->wakeup);
pthread_cond_destroy(&p->wakeup_drain);
pthread_mutex_destroy(&p->lock);
destroy_no_thread(ao);
}
static int init(struct ao *ao)
@@ -358,18 +392,23 @@ static int init(struct ao *ao)
pthread_mutex_init(&p->lock, NULL);
pthread_cond_init(&p->wakeup, NULL);
pthread_cond_init(&p->wakeup_drain, NULL);
mp_make_wakeup_pipe(p->wakeup_pipe);
if (ao->device_buffer <= 0) {
MP_FATAL(ao, "Couldn't probe device buffer size.\n");
goto err;
}
p->buffer = mp_audio_buffer_create(ao);
mp_audio_buffer_reinit_fmt(p->buffer, ao->format,
&ao->channels, ao->samplerate);
mp_audio_buffer_preallocate_min(p->buffer, ao->buffer);
if (pthread_create(&p->thread, NULL, playthread, ao)) {
ao->driver->uninit(ao);
return -1;
}
if (pthread_create(&p->thread, NULL, playthread, ao))
goto err;
return 0;
err:
destroy_no_thread(ao);
return -1;
}
const struct ao_driver ao_api_push = {
@@ -383,6 +422,7 @@ const struct ao_driver ao_api_push = {
.pause = audio_pause,
.resume = resume,
.drain = drain,
.get_eof = get_eof,
.priv_size = sizeof(struct ao_push_state),
};
+47 -1
View File
@@ -19,6 +19,9 @@
#include <libavutil/common.h>
#include <libavutil/log.h>
#include <libavutil/dict.h>
#include <libavutil/opt.h>
#include <libavutil/error.h>
#include <libavcodec/avcodec.h>
#include "common/common.h"
@@ -64,7 +67,6 @@ void mp_copy_lav_codec_headers(AVCodecContext *avctx, AVCodecContext *st)
avctx->channels = st->channels;
avctx->block_align = st->block_align;
avctx->channel_layout = st->channel_layout;
avctx->audio_service_type = st->audio_service_type;
avctx->bits_per_coded_sample = st->bits_per_coded_sample;
}
@@ -115,6 +117,8 @@ void mp_set_av_packet(AVPacket *dst, struct demux_packet *mpkt, AVRational *tb)
if (mpkt && mpkt->avpacket) {
dst->side_data = mpkt->avpacket->side_data;
dst->side_data_elems = mpkt->avpacket->side_data_elems;
if (dst->data == mpkt->avpacket->data)
dst->buf = mpkt->avpacket->buf;
}
if (mpkt && tb && tb->num > 0 && tb->den > 0)
dst->duration = mpkt->duration / av_q2d(*tb);
@@ -181,3 +185,45 @@ const char *mp_codec_from_av_codec_id(int codec_id)
}
return name;
}
// kv is in the format as by OPT_KEYVALUELIST(): kv[0]=key0, kv[1]=val0, ...
// Copy them to the dict.
void mp_set_avdict(AVDictionary **dict, char **kv)
{
for (int n = 0; kv && kv[n * 2]; n++)
av_dict_set(dict, kv[n * 2 + 0], kv[n * 2 + 1], 0);
}
// For use with libav* APIs that take AVDictionaries of options.
// Print options remaining in the dict as unset.
void mp_avdict_print_unset(struct mp_log *log, int msgl, AVDictionary *dict)
{
AVDictionaryEntry *t = NULL;
while ((t = av_dict_get(dict, "", t, AV_DICT_IGNORE_SUFFIX)))
mp_msg(log, msgl, "Could not set AVOption %s='%s'\n", t->key, t->value);
}
// kv is in the format as by OPT_KEYVALUELIST(): kv[0]=key0, kv[1]=val0, ...
// Set these options on given avobj (using av_opt_set..., meaning avobj must
// point to a struct that has AVClass as first member).
// Options which fail to set (error or not found) are printed to log.
// Returns: >=0 success, <0 failed to set an option
int mp_set_avopts(struct mp_log *log, void *avobj, char **kv)
{
int success = 0;
for (int n = 0; kv && kv[n * 2]; n++) {
char *k = kv[n * 2 + 0];
char *v = kv[n * 2 + 1];
int r = av_opt_set(avobj, k, v, AV_OPT_SEARCH_CHILDREN);
if (r == AVERROR_OPTION_NOT_FOUND) {
mp_err(log, "AVOption '%s' not found.\n", k);
success = -1;
} else if (r < 0) {
char errstr[80];
av_strerror(r, errstr, sizeof(errstr));
mp_err(log, "Could not set AVOption %s='%s' (%s)\n", k, v, errstr);
success = -1;
}
}
return success;
}
+5
View File
@@ -26,6 +26,8 @@
struct mp_decoder_list;
struct demux_packet;
struct AVDictionary;
struct mp_log;
int mp_lavc_set_extradata(AVCodecContext *avctx, void *ptr, int size);
void mp_copy_lav_codec_headers(AVCodecContext *avctx, AVCodecContext *st);
@@ -36,5 +38,8 @@ void mp_set_avcodec_threads(AVCodecContext *avctx, int threads);
void mp_add_lavc_decoders(struct mp_decoder_list *list, enum AVMediaType type);
int mp_codec_to_av_codec_id(const char *codec);
const char *mp_codec_from_av_codec_id(int codec_id);
void mp_set_avdict(struct AVDictionary **dict, char **kv);
void mp_avdict_print_unset(struct mp_log *log, int msgl, struct AVDictionary *d);
int mp_set_avopts(struct mp_log *log, void *avobj, char **kv);
#endif
-55
View File
@@ -1,55 +0,0 @@
/*
* AVOption parsing helper
* Copyright (C) 2008 Michael Niedermayer
*
* This file is part of MPlayer.
*
* MPlayer is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MPlayer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with MPlayer; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <stdlib.h>
#include <string.h>
#include <libavutil/opt.h>
#include "av_opts.h"
int parse_avopts(void *v, char *str){
char *start;
if (!str)
return 0;
start= str= strdup(str);
while(str && *str){
char *next_opt, *arg;
next_opt= strchr(str, ',');
if(next_opt) *next_opt++= 0;
arg = strchr(str, '=');
if(arg) *arg++= 0;
if (av_opt_set(v, str, arg, AV_OPT_SEARCH_CHILDREN) < 0) {
free(start);
return -1;
}
str= next_opt;
}
free(start);
return 0;
}
-30
View File
@@ -1,30 +0,0 @@
/*
* AVOption parsing helper
* Copyright (C) 2008 Michael Niedermayer
*
* This file is part of MPlayer.
*
* MPlayer is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* MPlayer is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with MPlayer; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#ifndef MPLAYER_AV_OPTS_H
#define MPLAYER_AV_OPTS_H
/**
* Parses str and sets AVOptions in v accordingly.
*/
int parse_avopts(void *v, char *str);
#endif /* MPLAYER_AV_OPTS_H */
+1 -1
View File
@@ -17,7 +17,7 @@
#include <assert.h>
#include "talloc.h"
#include "bstr/bstr.h"
#include "misc/bstr.h"
#include "common/msg.h"
#include "codecs.h"
+2 -2
View File
@@ -22,7 +22,7 @@
#include <libavutil/common.h>
#include "talloc.h"
#include "bstr/bstr.h"
#include "misc/bstr.h"
#include "common/common.h"
#define appendf(ptr, ...) \
@@ -171,7 +171,7 @@ static bool mp_parse_escape(void *talloc_ctx, bstr *dst, bstr *code)
if (code->start[0] == 'x' && code->len >= 3) {
bstr num = bstr_splice(*code, 1, 3);
char c = bstrtoll(num, &num, 16);
if (!num.len)
if (num.len)
return false;
bstr_xappend(talloc_ctx, dst, (bstr){&c, 1});
*code = bstr_cut(*code, 3);
+1 -1
View File
@@ -24,7 +24,7 @@
#include <stdbool.h>
#include <stdint.h>
#include "compat/compiler.h"
#include "osdep/compiler.h"
#include "talloc.h"
// double should be able to represent this exactly
+4 -5
View File
@@ -590,11 +590,8 @@ AVStream *encode_lavc_alloc_stream(struct encode_lavc_context *ctx,
}
avcodec_get_context_defaults3(stream->codec, ctx->vc);
// stream->time_base = ctx->timebase;
// doing this breaks mpeg2ts in ffmpeg
// which doesn't properly force the time base to be 90000
// furthermore, ffmpeg.c doesn't do this either and works
// Using codec->time_base is deprecated, but needed for older lavf.
stream->time_base = ctx->timebase;
stream->codec->time_base = ctx->timebase;
ctx->voptions = NULL;
@@ -626,6 +623,8 @@ AVStream *encode_lavc_alloc_stream(struct encode_lavc_context *ctx,
}
avcodec_get_context_defaults3(stream->codec, ctx->ac);
// Using codec->time_base is deprecated, but needed for older lavf.
stream->time_base = ctx->timebase;
stream->codec->time_base = ctx->timebase;
ctx->aoptions = NULL;
-3
View File
@@ -7,9 +7,6 @@
struct mpv_global {
struct MPOpts *opts;
struct mp_log *log;
int (*stream_interrupt_cb)(void *ctx);
void *stream_interrupt_cb_ctx;
};
#endif
+44 -31
View File
@@ -27,8 +27,8 @@
#include "talloc.h"
#include "bstr/bstr.h"
#include "compat/atomics.h"
#include "misc/bstr.h"
#include "osdep/atomics.h"
#include "common/common.h"
#include "common/global.h"
#include "misc/ring.h"
@@ -158,16 +158,10 @@ static void prepare_status_line(struct mp_log_root *root, char *new_status)
size_t clear_lines = MPMIN(MPMAX(new_lines, old_lines), root->blank_lines);
// clear the status line itself
if (terminal_erase_to_end_of_line[0]) {
fprintf(f, "\r%s", terminal_erase_to_end_of_line);
} else {
// This code is for MS windows (no ANSI control sequences)
get_screen_size();
fprintf(f, "\r%*s\r", screen_width - 1, "");
}
fprintf(f, "\r\033[K");
// and clear all previous old lines
for (size_t n = 1; n < clear_lines; n++)
fprintf(f, "%s\r%s", terminal_cursor_up, terminal_erase_to_end_of_line);
fprintf(f, "\033[A\r\033[K");
// skip "unused" blank lines, so that status is aligned to term bottom
for (size_t n = new_lines; n < clear_lines; n++)
fprintf(f, "\n");
@@ -200,10 +194,20 @@ bool mp_msg_has_status_line(struct mpv_global *global)
return r;
}
static void set_term_color(FILE *stream, int c)
{
if (c == -1) {
fprintf(stream, "\033[0m");
} else {
fprintf(stream, "\033[%d;3%dm", c >> 3, c & 7);
}
}
static void set_msg_color(FILE* stream, int lev)
{
static const int v_colors[] = {9, 1, 3, -1, -1, 2, 8, 8, 8, -1};
terminal_set_foreground_color(stream, v_colors[lev]);
set_term_color(stream, v_colors[lev]);
}
static void pretty_print_module(FILE* stream, const char *prefix, bool use_color, int lev)
@@ -214,12 +218,12 @@ static void pretty_print_module(FILE* stream, const char *prefix, bool use_color
unsigned int mod = 0;
for (int i = 0; i < prefix_len; ++i)
mod = mod * 33 + prefix[i];
terminal_set_foreground_color(stream, (mod + 1) % 15 + 1);
set_term_color(stream, (mod + 1) % 15 + 1);
}
fprintf(stream, "%10s", prefix);
if (use_color)
terminal_set_foreground_color(stream, -1);
set_term_color(stream, -1);
fprintf(stream, ": ");
if (use_color)
set_msg_color(stream, lev);
@@ -291,7 +295,7 @@ static void print_msg_on_terminal(struct mp_log *log, int lev, char *text)
fprintf(stream, "%s", terminate);
if (root->color)
terminal_set_foreground_color(stream, -1);
set_term_color(stream, -1);
fflush(stream);
}
@@ -363,34 +367,39 @@ void mp_msg_va(struct mp_log *log, int lev, const char *format, va_list va)
// parent's name. If the name starts with "/", the parent's name is not
// prefixed (except in verbose mode), and if it starts with "!", the name is
// not printed at all (except in verbose mode).
// If name is NULL, the parent's name/prefix is used.
// Thread-safety: fully thread-safe, but keep in mind that talloc is not (so
// talloc_ctx must be owned by the current thread).
struct mp_log *mp_log_new(void *talloc_ctx, struct mp_log *parent,
const char *name)
{
assert(parent);
assert(name);
struct mp_log *log = talloc_zero(talloc_ctx, struct mp_log);
if (!parent->root)
return log; // same as null_log
log->root = parent->root;
if (name[0] == '!') {
name = &name[1];
} else if (name[0] == '/') {
name = &name[1];
log->prefix = talloc_strdup(log, name);
} else {
log->prefix = parent->prefix
if (name) {
if (name[0] == '!') {
name = &name[1];
} else if (name[0] == '/') {
name = &name[1];
log->prefix = talloc_strdup(log, name);
} else {
log->prefix = parent->prefix
? talloc_asprintf(log, "%s/%s", parent->prefix, name)
: talloc_strdup(log, name);
}
log->verbose_prefix = parent->prefix
? talloc_asprintf(log, "%s/%s", parent->prefix, name)
: talloc_strdup(log, name);
if (log->prefix && !log->prefix[0])
log->prefix = NULL;
if (!log->verbose_prefix[0])
log->verbose_prefix = "global";
} else {
log->prefix = talloc_strdup(log, parent->prefix);
log->verbose_prefix = talloc_strdup(log, parent->verbose_prefix);
}
log->verbose_prefix = parent->prefix
? talloc_asprintf(log, "%s/%s", parent->prefix, name)
: talloc_strdup(log, name);
if (log->prefix && !log->prefix[0])
log->prefix = NULL;
if (!log->verbose_prefix[0])
log->verbose_prefix = "global";
return log;
}
@@ -428,8 +437,8 @@ void mp_msg_update_msglevels(struct mpv_global *global)
root->use_terminal = opts->use_terminal;
root->show_time = opts->msg_time;
if (root->use_terminal) {
root->color = opts->msg_color && isatty(fileno(stdout));
root->termosd = !opts->slave_mode && isatty(fileno(stderr));
root->color = opts->msg_color && isatty(STDOUT_FILENO);
root->termosd = isatty(STDERR_FILENO);
}
talloc_free(root->msglevels);
@@ -469,6 +478,10 @@ struct mp_log_buffer *mp_msg_log_buffer_new(struct mpv_global *global,
{
struct mp_log_root *root = global->log->root;
#if !HAVE_ATOMICS
return NULL;
#endif
pthread_mutex_lock(&mp_msg_lock);
struct mp_log_buffer *buffer = talloc_ptrtype(NULL, buffer);
+1 -1
View File
@@ -24,7 +24,7 @@
#include <stdlib.h>
#include <stdint.h>
#include "compat/compiler.h"
#include "osdep/compiler.h"
struct mp_log;
+20 -5
View File
@@ -30,7 +30,8 @@
struct playlist_entry *playlist_entry_new(const char *filename)
{
struct playlist_entry *e = talloc_zero(NULL, struct playlist_entry);
e->filename = talloc_strdup(e, filename);
char *local_filename = mp_file_url_to_filename(e, bstr0(filename));
e->filename = local_filename ? local_filename : talloc_strdup(e, filename);
return e;
}
@@ -105,10 +106,18 @@ static void playlist_unlink(struct playlist *pl, struct playlist_entry *entry)
entry->pl = NULL;
}
void playlist_entry_unref(struct playlist_entry *e)
{
e->reserved--;
if (e->reserved < 0)
talloc_free(e);
}
void playlist_remove(struct playlist *pl, struct playlist_entry *entry)
{
playlist_unlink(pl, entry);
talloc_free(entry);
entry->removed = true;
playlist_entry_unref(entry);
}
void playlist_clear(struct playlist *pl)
@@ -215,6 +224,15 @@ void playlist_transfer_entries(struct playlist *pl, struct playlist *source_pl)
}
}
void playlist_append_entries(struct playlist *pl, struct playlist *source_pl)
{
while (source_pl->first) {
struct playlist_entry *e = source_pl->first;
playlist_unlink(source_pl, e);
playlist_add(pl, e);
}
}
// Return number of entries between list start and e.
// Return -1 if e is not on the list, or if e is NULL.
int playlist_entry_to_index(struct playlist *pl, struct playlist_entry *e)
@@ -277,9 +295,6 @@ struct playlist *playlist_parse_file(const char *file, struct mpv_global *global
if (ret && !ret->first)
mp_warn(log, "Warning: empty playlist\n");
if (ret)
playlist_add_base_path(ret, mp_dirname(file));
talloc_free(log);
return ret;
}
+15 -1
View File
@@ -19,7 +19,7 @@
#define MPLAYER_PLAYLIST_H
#include <stdbool.h>
#include "bstr/bstr.h"
#include "misc/bstr.h"
struct playlist_param {
bstr name, value;
@@ -41,6 +41,17 @@ struct playlist_entry {
bool playback_short : 1;
// Set to true if not at least 1 frame (audio or video) could be played.
bool init_failed : 1;
// Entry was removed with playlist_remove (etc.), but not deallocated.
bool removed : 1;
// Additional refcount. Normally (reserved==0), the entry is owned by the
// playlist, and this can be used to keep the entry alive.
int reserved;
// Used to reject loading of unsafe entries from external playlists.
// Can have any of the following bit flags set:
// STREAM_SAFE_ONLY: only allow streams marked with is_safe
// STREAM_NETWORK_ONLY: only allow streams marked with is_network
// The value 0 allows everything.
int stream_flags;
};
struct playlist {
@@ -74,6 +85,7 @@ void playlist_shuffle(struct playlist *pl);
struct playlist_entry *playlist_get_next(struct playlist *pl, int direction);
void playlist_add_base_path(struct playlist *pl, bstr base_path);
void playlist_transfer_entries(struct playlist *pl, struct playlist *source_pl);
void playlist_append_entries(struct playlist *pl, struct playlist *source_pl);
int playlist_entry_to_index(struct playlist *pl, struct playlist_entry *e);
int playlist_entry_count(struct playlist *pl);
@@ -82,4 +94,6 @@ struct playlist_entry *playlist_entry_from_index(struct playlist *pl, int index)
struct mpv_global;
struct playlist *playlist_parse_file(const char *file, struct mpv_global *global);
void playlist_entry_unref(struct playlist_entry *e);
#endif
Loaded 100 of 340 files, more files were not shown because too many files have changed in this diff. Show more