Commit Graph

1949 Commits

Author SHA1 Message Date
Thomas Weißschuh 9add44b11a ao_pipewire: use mpv logging 2022-08-04 09:25:19 -07:00
Christoph Heinrich 490e263529 af_rubberband: add new engine option in rubberband 3.0.0 2022-08-03 15:29:02 +00:00
Thomas Weißschuh 0044c19f0d ao_pipewire: prevent deprecation warning for pw_stream_get_time() 2022-07-08 17:19:23 -07:00
Wim Taymans c7b17beaf1 ao_pipewire: pipewire uses linear volume
Don't use cube root volumes, pipewire uses linear volumes.
2022-07-08 07:45:09 -07:00
Wim Taymans c01bb44e36 ao_pipewire: don't access core after disconnect
pw_core_disconnect frees the core, so accessing it afterward to
destroy the context is not allowed.

Instead, just destroy the context, the first thing it does is disconnect
all cores for us.
2022-07-08 07:45:09 -07:00
Wim Taymans 60ed51008d ao_pipewire: zero listeners
The listeners need to be cleared because removing them might invoke the
removed handler, which could otherwise point to invalid memory.
2022-07-08 07:45:09 -07:00
Alex B d38ff1c958 ao_pipewire: support ao-volume on non-stereo channel layouts
mpv only remembers volume for two channels.
Always apply the same volume to all channels in case of
non-stereo layout similarly to ao_pulse.
Don't try to do anything smart when averaging volumes,
normally they are equal anyway.
2022-07-08 06:39:23 -07:00
Jan Ekström 8123adadbd audio/chmap: add mp_iterate_builtin_layouts
Mostly useful for unit tests in order to access the channel
layouts from chmap which have mapped channels.
2022-06-15 21:19:10 +03:00
Jan Ekström edfd17ab18 ad_lavc: switch to AVChannelLayout when available 2022-06-15 21:19:10 +03:00
Jan Ekström e7483ced5d af_lavcac3enc: switch to AVChannelLayout when available 2022-06-14 22:41:20 +03:00
Jan Ekström 42b58c5698 af_lavcac3enc: refactor chmap adding into its own function
This simplifies ifdeffery with AVChannelLayouts.
2022-06-14 22:19:45 +03:00
Jan Ekström 7a3f9af67f ao_lavc: switch to AVChannelLayout when available 2022-06-12 21:05:59 +03:00
Jan Ekström 302acb27c8 audio/aframe: switch to AVChannelLayout when available 2022-06-12 21:05:59 +03:00
Jan Ekström 1d15a5a059 audio: add AVChannelLayout helpers to convert from/to mp_chmap
This is the new FFmpeg channel layout structure, which now
combines channel count and layout into a single location.

Only unspecified (channel count only) and native (channel layout
mask based) layouts are currently supported for the initial move
towards non-deprecated APIs.
2022-06-12 21:05:59 +03:00
Guido Cella fe9e074752 various: remove trailing whitespace 2022-05-14 14:51:34 +00:00
Cœur bb5b4b1ba6 various: fix typos 2022-04-25 09:07:18 -04:00
Thomas Weißschuh deedc3d418 ao_pipewire: Do not hold thread lock during loop stop
Stopping the thread is done using pw_thread_loop_stop(),
*which must be called without the lock held.*

Fixes #10033
2022-03-31 14:40:21 -07:00
Thomas Weißschuh 84dc9b1a02 ao_pipewire: fix resource lifetimes
We have to destroy the core before destroying the loop.
Also we have to lock the mainloop for operations on its objects.

Fixes #10003
2022-03-30 13:06:33 -07:00
LaserEyess 7ac4b7dfe7 ao_sndio: fix parentheses warning
No change in logic, but wrap the LT operator and the && in parentheses
to silence the compiler warning.
2022-03-11 16:43:31 +01:00
Alex B bc9805c71a ao_pipewire: fix ao-volume handling
Pass channel volumes to `pw_stream_set_control` as array.
This is correct calling conventions and prevents
right channel muting every time ao-volume property is changed.

Terminate `pw_stream_set_control` calls with 0.
2022-02-11 11:27:57 -08:00
Thomas Weißschuh 09343bc86e ao_pipewire: validate pod creation
Our allocated buffers should be big enough, but add some errorhandling
just in case.
2022-02-06 22:44:40 -08:00
Thomas Weißschuh b7a71ea706 ao_pipewire: add support for device selection 2022-02-06 22:44:40 -08:00
Andrew Krasavin b01598510f ao_sndio: bugfix and small refactoring for #8314
Changes:
  * fixed hangups in the loop function and in some other cases
  * refactoring according to @michaelforney's recommendations in #8314
  * a few minor and/or cosmetic changes
  * ability to build ao_sndio using meson
2022-01-22 18:44:34 +00:00
rim adc32e25e0 ao_sndio: add this audio output again
Changes:
- rewrite to use new internal MPV API;
- code refactoring;
- fix buffers size calculations;
- buffer set to auto;
- reset() - clean/reinit device only after errors;
2022-01-22 18:44:34 +00:00
Philip Langdale 22b0bac28e ao/pipewire: Add copyright header
Sometimes the most obvious things can be missed.

Reflects authorship described in the original commit.

* https://github.com/mpv-player/mpv/pull/7902
* fddb143282
* https://github.com/mpv-player/mpv/pull/9587
2022-01-17 13:48:44 -08:00
Thomas Weißschuh 87aba146ed ao_pipewire: Add PipeWire audio backend
The AO provides a way for mpv to directly submit audio to the PipeWire
audio server.
Doing this directly instead of going through the various compatibility
layers provided by PipeWire has the following advantages:

* It reduces complexity of going through the compatibility layers
* It allows a richer integration between mpv and PipeWire
  (for example for metadata)
* Some users report issues with the compatibility layers that to not
  occur with the native AO

For now the AO is ordered after all the other relevant AOs, so it will
most probably not be picked up by default.
This is for the following reasons:

* Currently it is not possible to detect if the PipeWire daemon that mpv
  connects to is actually driving the system audio.
  (https://gitlab.freedesktop.org/pipewire/pipewire/-/issues/1835)
* It gives the AO time to stabilize before it is used by everyone.

Based-on-patch-by: Oschowa <oschowa@web.de>
Based-on-patch-by: Andreas Kempf <aakempf@gmail.com>
Helped-by: Ivan <etircopyhdot@gmail.com>
2022-01-17 11:43:02 -08:00
sfan5 429402cb08 af_lavcac3enc: fix some minor things
mark an array as static, a typo and a missing free
2022-01-10 22:56:52 +01:00
sfan5 d28a792c00 af_lavcac3enc: replace deprecated av_init_packet() 2022-01-10 22:56:52 +01:00
Niklas Haas 0bb15c7a13 af_lavcac3enc: fix memory leak on no-op
Simply returning out of this function leaks avpkt, need to always "goto
done".

Rewrite the logic a bit to make it more clear what's going on (IMO).

Fixes #9593
2021-12-14 21:25:02 +01:00
Ivan 87ce3b31a9 ao_openal: enable AL_SOFT_direct_channels_remix extension by default
Prevent audio distortions caused by OpenAL's 3D effects.
2021-11-29 11:27:39 +01:00
Aman Karmani ac3d567bd3 audio: stop corrupting audio on underreads
regression introduced in b74c09efbf

Signed-off-by: Aman Karmani <aman@tmm1.net>
2021-11-20 12:08:32 -08:00
Tom Yan d1e9f4a159 ao_opensles: add guards for sample rate to use
Upstream "Wilhelm" (the Android OpenSLES implementation) supports
only 8000 <= rate <= 192000. Make sure mpv resamples the audio
when necessary.
2021-11-19 14:27:52 +01:00
Emil Velikov 37619c4cf5 options: remove always true m_obj_list::allow_unknown_entries
Ever instance of m_obj_list is a constant and for all of them, the field
is true. Just remove the field all together.

Signed-off-by: Emil Velikov <emil.l.velikov@gmail.com>
2021-11-15 14:02:08 +00:00
Jan Ekström e6a75075b2 ao_oss: define PATH_DEV_MIXER as it is an internal define
This fixes a mismatch between configure working and build time
failing with Linux + OSSv4, enabling compilation on Debian based
Linux systems with the oss4-dev package.

Fixes #9378
2021-11-10 17:08:16 +01:00
sfan5 6996588254 audio: replace deprecated av_mallocz_array 2021-11-05 23:34:20 +01:00
Aman Karmani 06392e7ec1 ao_audiotrack: change buffer sizing logic
Previously number of channels was being ignored.

The buffer will now be between 75ms and 150ms

Signed-off-by: Aman Karmani <aman@tmm1.net>
2021-10-21 17:20:51 +02:00
Aman Karmani fa691e0f69 ao_audiotrack: allocate chunk buffer based on negotiated size
Signed-off-by: Aman Karmani <aman@tmm1.net>
2021-10-21 17:20:51 +02:00
Aman Karmani 6473711dce ao_audiotrack: support delay up to 2s as normal
Fixes issues streaming to echo speaker pair from firetv devices.

Signed-off-by: Aman Karmani <aman@tmm1.net>
2021-10-21 17:20:51 +02:00
Aman Karmani 432c0255bc ao_audiotrack: set device_buffer based on underlying buffer size when available
Signed-off-by: Aman Karmani <aman@tmm1.net>
2021-10-21 17:20:51 +02:00
Aman Karmani 7356ee5339 ao_audiotrack: use new style initializer for AudioTrack when available
Fixes deprecation warnings printed when using this driver.

Signed-off-by: Aman Karmani <aman@tmm1.net>
2021-10-21 17:20:51 +02:00
sfan5 d2a56227df Revert "audio: fix ao_reset() not clearing paused state leading to stuck AO"
In hindsight this is obviously broken.
This reverts commit fb5d976cb0.
2021-07-18 12:21:15 +02:00
sfan5 fb5d976cb0 audio: fix ao_reset() not clearing paused state leading to stuck AO
This would happen when switching from playback stuck in cache wait
(underrun) to another file.
2021-07-16 20:58:54 +02:00
Niklas Haas ec0006bfa1 af_scaletempo2: use gcc vectors to speed up inner loop
This brings my scaletempo2 benchmark down from ~22s to ~7s on my machine
(-march=native), and down to ~11s with a generic compile.

Guarded behind an appropriate #ifdef to avoid being ableist against
people who have the clinical need to run obscure platforms.

Closes #8848
2021-05-26 17:35:55 +02:00
sfan5 39630dc8b6 build: address AVCodec, AVInputFormat, AVOutputFormat const warnings
FFmpeg recently changed these to be const on their side.
2021-05-01 22:07:31 +02:00
sfan5 aa300f8023 ao/pulse: fix incorrect state reported after reset
fixes #8768
2021-04-29 17:06:29 +02:00
sfan5 3c34e6fec4 audio/aframe: reuse data buffer if less than 8 channels
This fixes audio encoding crashing under ASan.
When extended_data != data, FFmpeg copies more pointers from
extended_data (= the number of channels) than there really
are for non-planar formats (= exactly 1), but that's not our fault.
Regardless, this commit makes it work in all common cases.
2021-04-08 23:47:35 +03:00
rim 1b2e5137e0 ao_oss: add this audio output again
Changes:
- code refactored;
- mixer options removed;
- new mpv sound API used;
- add sound devices detect (mpv --audio-device=help will show all available devices);
- only OSSv4 supported now;

Tested on FreeBSD 12.2 amd64.
2021-03-15 12:42:35 +01:00
Thomas Weißschuh 63d71ba4ec ao/pulse: signal the mainloop when ops are done
Without the explicit signal the call to pa_threaded_mainloop_wait()
will not return as soon as possible.

Fixes 4f07607888
See #8633
2021-03-11 23:37:13 +02:00
Thomas Weißschuh 4f07607888 ao/pulse: wait for command completion when setting volume or mute
This makes the behavior of all control messages consistent,
fixing an inconsistency that has been with us since
4d8266c739 - which is the initial
rework of the polyaudio AO into the pulseaudio AO.

Muting the stream also directly triggers an update to the OSD.
When not waiting for the command completion this read of the mute
property may read the old state. A stale read.

Note that this somehow was not triggered on native Pulseaudio, but it is
an issue on Pipewire.

See https://gitlab.freedesktop.org/pipewire/pipewire/-/issues/868
2021-03-09 23:08:16 +02:00
Dorian Rudolph 2e45a3d336 af_scaletempo2: fix crash for speed >= 16
The input buffer size was fixed, but the required size depends on the
speed. Now the buffer will be resized dynamically.

Fixes #8081
2021-02-15 00:07:27 +02:00
Jan Ekström 8ddd4547fc ao_alsa: handle -EPIPE XRUNs from snd_pcm_status
Set pcm state to SND_PCM_STATE_XRUN in case -EPIPE is received,
and handle this state as per the usual logic.

This way snd_pcm_prepare gets called, and the loop continued.

Inspired by a patch posted by malc_ on #mpv.
2020-11-09 16:12:49 +01:00
Jan Ekström 976fcf57c1 ao_alsa: always initialize state if passed
Based on ao_play_data's assert, we are always expected to give
non-default values back from an AO's get_state.
2020-11-09 16:12:49 +01:00
sfan5 63ffa07b44 audio: take paused state into account in ao_start()
It makes no sense to instruct the AO to start the pull callbacks
when we know there's nothing to play (only affects pull AOs).
2020-09-20 18:52:54 +02:00
sfan5 c1db4630e6 audio: move start() calls outside of lock
Pull based AOs might want to call ao_read_data() inside start().
This fixes ao_opensles deadlocking.
2020-09-20 18:52:54 +02:00
wm4 cf19a0d3cc ao_alsa: make partial writes an error message
And I think "partial write" is easier to understand than "short write".
2020-09-03 22:40:20 +02:00
wm4 1643cb865f audio: fix stream-silence with push AOs (somewhat)
--audio-stream-silence is a shitty feature compensating for awful
consumer garbage, that mutes PCM at first to check whether it's
compressed audio, using formats advocated and owned by malicious patent
troll companies (who spend more money on their lawyers than paying any
technicians), wrapped in a wasteful way to make it constant bitrate
using a standard whose text is not freely available, and only rude users
want it. This feature has been carelessly broken, because it's
complicated and stupid. What would Jesus do? If not getting an aneurysm,
or pushing over tables with expensive A/V receivers on top of them, he'd
probably fix the feature. So let's take inspiration from Jesus Christ
himself, and do something as dumb as wasting some of our limited
lifetime on this incredibly stupid fucking shit.

This is tricky, because state changes like end-of-audio are supposed to
be driven by the AO driver, while playing silence precludes this. But it
seems code paths for "untimed" AOs can be reused.

But there are still problems. For example, underruns will just happen
normally (and stop audio streaming), because we don't have a separate
heuristic to check whether the buffer is "low enough" (as a consequence
of a network stall, but before the audio output itself underruns).
2020-09-03 22:39:23 +02:00
wm4 d3afe34c09 ao_lavc: slightly simplify filter use
Create a central function which pumps data through the filter. This also
might fix bogus use of the filter API on flushing. (The filter is just
used for convenience, but I guess the overall result is still simpler.)
2020-09-03 15:39:31 +02:00
wm4 5fc34cb4d6 ao_alsa: log more information on short writes 2020-09-02 22:22:45 +02:00
wm4 99cd22af01 audio: fix AVFrame allocation (crash with opus encoding)
AVFrame doesn't have public code for pool allocation, so mpv does it
manually. AVFrame allocation is very tricky, so we added a bug.

This crashed with libopus encoding, but not some other audio codecs,
because the libopus libavcodec wrapper accesses AVFrame.data. Most code
tries to avoid accessing AVFrame.data and uses AVFrame.extended_data,
because using the former would subtly corrupt memory on more than 8
channels. The fact that this problem manifested only now shows that most
AVFrame consuming FFmpeg code indeed uses extended_data for audio.
2020-09-01 21:28:13 +02:00
LAGonauta 0ac724f002 ao_openal: restore working condition with new push API 2020-08-31 20:24:14 +02:00
wm4 a805a152c1 ao: remove unused field 2020-08-31 20:23:44 +02:00
wm4 478d39c574 audio: fix inefficient behavior with ao_alsa, remove period_size field
It is now the AO's responsibility to handle period size alignment. The
ao->period_size alignment field is unused as of the recent audio
refactor commit. Remove it.

It turns out that ao_alsa shows extremely inefficient behavior as a
consequence of the removal of period size aligned writes in the
mentioned refactor commit. This is because it could get into a state
where it repeatedly wrote single samples (as small as 1 sample), and
starved the rest of the player as a consequence. Too bad. Explicitly
align the size in ao_alsa. Other AOs, which need this, should do the
same.

One reason why it broke so badly with ao_alsa was that it retried the
write() even if all reported space could be written. So stop doing that
too. Retry the write only if we somehow wrote less.

I'm not sure about ao_pulse.
2020-08-29 16:27:56 +02:00
wm4 40c2e71d33 audio_buffer: remove this
Unused, was terrible garbage. It was (or at least its implementation
was) always a make-shift solution, and just gross bullshit. It is unused
now, so delete it.
2020-08-29 13:12:32 +02:00
wm4 b74c09efbf audio: refactor how data is passed to AO
This replaces the two buffers (ao_chain.ao_buffer in the core, and
buffer_state.buffers in the AO) with a single queue. Instead of having a
byte based buffer, the queue is simply a list of audio frames, as output
by the decoder. This should make dataflow simpler and reduce copying.

It also attempts to simplify fill_audio_out_buffers(), the function I
always hated most, because it's full of subtle and buggy logic.

Unfortunately, I got assaulted by corner cases, dumb features (attempt
at seamless looping, really?), and other crap, so it got pretty
complicated again. fill_audio_out_buffers() is still full of subtle and
buggy logic. Maybe it got worse. On the other hand, maybe there really
is some progress. Who knows.

Originally, the data flow parts was meant to be in f_output_chain, but
due to tricky interactions with the playloop code, it's now in the dummy
filter in audio.c.

At least this improves the way the audio PTS is passed to the encoder in
encoding mode. Now it attempts to pass frames directly, along with the
pts, which should minimize timestamp problems. But to be honest, encoder
mode is one big kludge that shouldn't exist in this way.

This commit should be considered pre-alpha code. There are lots of bugs
still hiding.
2020-08-29 13:12:32 +02:00
wm4 a7413aff22 audio: clarify set_pause() documentation 2020-08-27 11:55:20 +02:00
wm4 b0fe01d55c audio: adjust frame clipping for spdif formats
Allow mp_aframe_clip_timestamps() to discard a spdif frame if it's
entirely out of the timestamp range. Just a minor thing that might make
handling these dumb formats easier.
2020-08-27 11:55:20 +02:00
wm4 6b13d71cdc audio: remove unused ring.h includes
From what I can tell, this has been copy-pasted from times when
ao_coreaudio still used its own ringbuffer, instead of the common code.
2020-08-27 11:55:20 +02:00
sfan5 fb736b49f1 ao/pulse: create the stream corked
Previously get_state() would keep setting the cork status
while paused, but it only does for that after underflows now.
Correct this oversight by creating the stream corked for start()
to uncork it at a later time.

fixes #8026
2020-08-26 16:14:29 +02:00
ekisu cdd8ba7224 ao/lavc: add channels and channel_layout to AVFrame
FFmpeg expects those fields to be set on the AVFrame when
encoding audio, not doing so will cause the avcodec_send_frame
call to return EINVAL (at least in recent builds).
2020-08-07 19:42:42 +02:00
Dorian Rudolph 6e3d4aa94b af_scaletempo2: fix bug where speed was not set
the --speed parameter did not work with
mpv --no-config whatever.mp3 --video=no --speed=2 --af=scaletempo2
(https://github.com/mpv-player/mpv/pull/7865#issuecomment-664243401)
2020-07-27 18:12:05 +02:00
wm4 1fe6def066 af_scaletempo2: M_PI is always defined
I forgot why/how (C99?), but other code also uses it.
2020-07-27 00:59:37 +02:00
Dorian Rudolph 785a2b1261 audio: add scaletempo2 filter based on chromium
scaletempo2 is a new audio filter for playing back
audio at modified speed and is based on chromium
commit 51ed77e3f37a9a9b80d6d0a8259e84a8ca635259.
It sounds subjectively better than the existing
implementions scaletempo and rubberband.
2020-07-27 00:57:22 +02:00
sfan5 7a7a0a78b5 ao/pulse: fix reporting of playing state
When get_state() corks the stream after an underrun happens
priv->playing is incorrectly reset to true, which can cause the
player to miss the underrun entirely. Stop resetting priv->playing
during corking (but not uncorking) to fix this.
2020-07-12 23:44:41 +02:00
sfan5 f3b29a680c ao/pulse: flush stream on underrun
The underflow callback introduced in d27ad96 can be called
when the buffer is still full, causing playback to never
resume afterwards since get_state() reports free_samples == 0.
Fix this by fully resetting on underrun, which flushes
the stream and ensures free buffer space.

fixes #7874
2020-07-12 23:34:08 +02:00
Kevin Mitchell 5e323333cf
audio: don't lock ao_control for pull mode drivers
The pull mode APIs were previously required to have thread-safe
ao_controls. However, locks were added in b83bdd1 for parity with push
mode. This introduced deadlocks in ao_wasapi.

Instead, only lock ao_control for the push mode APIs.

fixes #7787

See also #7832, #7811. We'll wait for feedback to see if those should
also be closed.
2020-06-17 02:22:51 -07:00
wm4 d5de79d10f audio: require certain AOs to set device_buffer
AOs which use the "push" API must set this field now. Actually, this was
sort of always required, but happened to work anyway. The future
intention is to use device_buffer as the pre-buffer amount, which has to
be available right before audio playback is started. "Pull" AOs really
need this too conceptually, just that the API is underspecified.

From what I can see, only ao_null did not do this yet.
2020-06-09 16:49:05 +02:00
Nicolas F 0fb02f181f ao/pulse: properly set device_buffer
Previously, device_buffer defaulted to 0 on pulse. This meant that
commit baa7b5c would always wait with a timeout of 0, leading to
high CPU usage for PulseAudio users.

By setting device_buffer to the number of samples per channel that
PulseAudio sets as its target, this commit fixes this behaviour.
2020-06-07 22:16:49 +03:00
wm4 c67f36dd18 audio: fix deadlock on draining
The playback thread may obviously still fill the AO'S entire audio
buffer, which means it unset p->draining, which makes no sense and broke
ao_drain(). So just don't unset it here.

Not sure if this really fixes this, it was hard to reproduce. Regression
due to the recent changes. There are probably many more bugs like this.
Stupid asynchronous nightmare state machine. Give me a language that
supports formal verification (in presence of concurrency) or something.
2020-06-04 12:42:36 +02:00
wm4 baa7b5c8dd audio: adjust wait duration
I feel like this makes slightly more sense. At least it doesn't include
the potentially arbitrary constant latency that is generally included in
the delay value. Also, the buffer status doesn't matter - either we've
filled the entire buffer (then we can wait this long), or there's not
enough data anyway (then the core will wake up the thread if new data is
available).

But ultimately, we have to guess, unless the AO does notify us with
ao_wakeup_playthread().

Draining may now wait for no reason up to 1/4th of the total buffer
time. Shouldn't be a disimprovement in practice.
2020-06-03 15:22:18 +02:00
wm4 68ade4e5a5 audio: avoid possible deadlock regression for some AOs
It's conceivable that ao->driver->reset() will make the audio API wait
for ao_read_data() (i.e. its audio callback) to return. Since we
recently moved the reset() call inside the same lock that ao_read_data()
acquires, this could deadlock. Whether this really happens depends on
how exactly the AO behaves. For example, ao_wasapi does not have this
problem. "Push" AOs are not affected either.

Fix by moving it outside of the lock. Assume ao->driver->start() will
not have this problem.

Could affect ao_sdl, ao_coreaudio (and similar rotten fruit AOs). I'm
unsure whether anyone experienced the problem in practice.
2020-06-02 20:43:49 +02:00
wm4 08b198aab4 audio: further simplify internal audio API somewhat
Instead of the relatively subtle underflow handling, simply signal
whether the stream is in a playing state. Should make it more robust.

Should affect ao_alsa and ao_pulse only (and ao_openal, but it's
broken).

For ao_pulse, I'm just guessing. How the hell do you query whether a
stream is playing? Who knows. Seems to work, judging from very
superficial testing.
2020-06-02 20:43:49 +02:00
wm4 0d3474c6c0 audio: slightly better condition for still_playing
Just a detail. If wrong (not unlikely because I'm just guessing my own
messy state machine), this will make the player freeze due to waiting
for something that never happens. Enjoy.
2020-06-02 20:43:49 +02:00
wm4 0edeb0899a af_scaletempo: handle obscure integer overflow
Saw it once, not really reproducible. This should fix it, and in any
case it's harmless.
2020-06-02 20:43:49 +02:00
wm4 c5158b057c audio: reduce extra wakeups caused by recent changes
The feeder thread basically woke up the core and itself too often, and
caused some CPU overhead. This was caused by the recent buffer.c
changes.

For one, do not let ao_read_data() wake up the core, and instead rely on
the feeder thread's own buffer management. This is a bit strange, since
the change intended to unify the buffer management, but being more
consequent about it is better deferred to later, when the buffer
management changes again anyway. And also, the "more" condition in the
feeder thread seems outdated, or at least what made it make sense has
been destroyed, so do something that may or may not be better. In any
case, I'm still not getting underruns with ao_alsa, but the wakeup
hammering is gone.
2020-06-01 15:48:45 +02:00
wm4 d27ad96542 audio: redo internal AO API
This affects "pull" AOs only: ao_alsa, ao_pulse, ao_openal, ao_pcm,
ao_lavc. There are changes to the other AOs too, but that's only about
renaming ao_driver.resume to ao_driver.start.

ao_openal is broken because I didn't manage to fix it, so it exits with
an error message. If you want it, why don't _you_ put effort into it? I
see no reason to waste my own precious lifetime over this (I realize the
irony).

ao_alsa loses the poll() mechanism, but it was mostly broken and didn't
really do what it was supposed to. There doesn't seem to be anything in
the ALSA API to watch the playback status without polling (unless you
want to use raw UNIX signals).

No idea if ao_pulse is correct, or whether it's subtly broken now. There
is no documentation, so I can't tell what is correct, without reverse
engineering the whole project. I recommend using ALSA.

This was supposed to be just a simple fix, but somehow it expanded scope
like a train wreck. Very high chance of regressions, but probably only
for the AOs listed above. The rest you can figure out from reading the
diff.
2020-06-01 01:08:16 +02:00
wm4 d448dd5bf2 audio: fix unpausing with some AOs
wasapi/coreaudio/sdl were affected, alsa/pusle were not.

The confusion here was that resume() has different meaning with pull and
push AOs.

Fixes: #7772
2020-05-31 14:43:13 +02:00
wm4 27e41c69aa ao_null: remove unreferenced function
Forgot in the previous commit to this file.
2020-05-27 21:29:43 +02:00
wm4 a4b7fcc183 audio: stop applying volume twice for some AOs
Regression since the recent refactor. How did nobody notice?

This happened because the push code now calls the function for the pull
code. Both the former and latter apply the volume, so oops.
2020-05-27 21:11:46 +02:00
wm4 9885952c2a audio: remove ao_driver.drain
The recent change to the common code removed all calls to ->drain. It's
currently emulated via a timed sleep and polling ao_eof_reached(). That
is actually fallback code for AOs which lacked draining. I could just
readd the drain call, but it was a bad idea anyway. My plan to handle
this better is to require the AO to signal a underrun, even if
AOPLAY_FINAL_CHUNK is not set. Also reinstate not possibly waiting for
ao_lavc.c. ao_pcm.c did not have anything to handle this; whatever.
2020-05-27 21:04:32 +02:00
wm4 b83bdd1d17 audio: merge pull/push ring buffer glue code
This is preparation to further cleanups (and eventually actual
improvements) of the audio output code.

AOs are split into two classes: pull and push. Pull AOs let an audio
callback of the native audio API read from a ring buffer. Push AOs
expose a function that works similar to write(), and for which we start
a "feeder" thread. It seems making this split was beneficial, because of
the different data flow, and emulating the one or other in the AOs
directly would have created code duplication (all the "pull" AOs had
their own ring buffer implementation before it was cleaned up).
Unfortunately, both types had completely separate implementations (in
pull.c and push.c). The idea was that little can be shared anyway. But
that's very annoying now, because I want to change the API between AO
and player.

This commit attempts to merge them. I've moved everything from push.c to
pull.c, the trivial entrypoints from ao.c to pull.c, and attempted to
reconcile the differences. It's a mess, but at least there's only one
ring buffer within the AO code now. Everything should work mostly the
same. Pull AOs now always copy the audio data under a lock; before this
commit, all ring buffer access was lock-free (except for the decoder
wakeup callback, which acquired a mutex). In theory, this is "bad", and
people obsessed with lock-free stuff will hate me, but in practice
probably won't matter. The planned change will probably remove this
copying-under-lock again, but who knows when this will happen.

One change for the push AOs now makes it drop audio, where before only a
warning was logged. This is only in case of AOs or drivers which exhibit
unexpected (and now unsupported) behavior.

This is a risky change. Although it's completely trivial conceptually,
there are too many special cases. In addition, I barely tested it, and
I've messed with it in a half-motivated state over a longer time, barely
making any progress, and finishing it under a rush when I already should
have been asleep. Most things seem to work, and I made superficial tests
with alsa, sdl, and encode mode. This should cover most things, but
there are a lot of tricky things that received no coverage. All this
text means you should be prepared to roll back to an older commit and
report your problem.
2020-05-25 01:54:37 +02:00
wm4 afb6f1c7e9 audio: add frame alloc function
Meh, why is this so roundabout?
2020-05-25 01:54:37 +02:00
wm4 ab4e0c42fb audio: redo video-sync=display-adrop
This mode drops or repeats audio data to adapt to video speed, instead
of resampling it or such. It was added to deal with SPDIF. The
implementation was part of fill_audio_out_buffers() - the entire
function is something whose complexity exploded in my face, and which I
want to clean up, and this is hopefully a first step.

Put it in a filter, and mess with the shitty glue code. It's all sort of
roundabout and illogical, but that can be rectified later. The important
part is that it works much like the resample or scaletempo filters.

For PCM audio, this does not work on samples anymore. This makes it much
worse. But for PCM you can use saner mechanisms that sound better. Also,
something about PTS tracking is wrong. But not wasting more time on
this.
2020-05-23 04:04:46 +02:00
wm4 43a67970b6 af_scaletempo: fix theoretical UB
Passing NULL to memset() is undefined behavior, even if the size
argument is 0. Could happen on init errors and such.
2020-05-23 03:49:46 +02:00
wm4 bc1a18ee24 options: cleanup .min use for OPT_CHANNELS
Replace use of .min==1 with a proper flag. This is a good idea, because
it has nothing to do with numeric limits (also see commit 9d32d62b61
for how this can go wrong).

With this, m_option.min/max are strictly used for numeric limits.
2020-04-09 11:27:38 +02:00
wm4 bca917f6d2 ao_oss: remove this audio output
Ancient Linux audio output. Apparently it survived until now, because
some BSDs (but not all) had use of this. But these should work with
ao_sdl or ao_openal too (that's why these AOs exist after all). ao_oss
itself has the problem that it's virtually unmaintainable from my point
of view due to all the subtle (or non-subtle) difference. Look at the
ifdef mess and the multiple code paths (that shouldn't exist) in the
removed source code.
2020-03-28 20:59:31 +01:00
wm4 4583bd8cc7 ao_rsound: remove this audio output
I wonder what this even is. I've never heard of anyone using it, and
can't find a corresponding library that actually builds with it. Good
enough to remove.
2020-03-28 20:59:00 +01:00
wm4 71d218eae4 ao_sndio: remove this audio output
It was always marked as "experimental", and had inherent problems that
were never fixed. It was disabled by default, and I don't think anyone
is using it.
2020-03-28 20:58:56 +01:00
wm4 6169fba796 encode: fix occasional init crash due to initialization order issues
Looks like the recent change to this actually made it crash whenever
audio happened to be initialized first, due to not setting the
mux_stream field before the on_ready callback. Mess a way around this.

Also remove a stray unused variable from ao_lavc.c.
2020-03-22 21:08:44 +01:00
wm4 63311762ed encode: add some shit that does some shit
?????????????

Makes no sense, can endless loop, but whatever.

Part of #7524.
2020-03-22 13:07:36 +01:00
wm4 de53155971 encode: restore audio muxer timebase use
Seems to crash hard if an error happens somewhere at init. Who cares.

Part of #7524.
2020-03-22 13:06:59 +01:00
Kevin Mitchell 3aad89829f ao_wasapi: try mix format except for chmap
In shared mode, we previously tried to feed the full native format to
IsFormatSupported in the hopes that the "closest match" returned was
actually that.

Turns out, IsFormatSupported will always return the mix format if we
don't use the mix format's sample rate. This will also clobber our
choice of channel map with the mix format channel map even if our
desired channel map is supported due to surround emulation.

The solution is to not bother trying to use anything other than the mix
format sample rate. While we're at it, we might as well use the mix
format PCM sample format (always float32) since this conversion will
happen anyway and may avoid unecessary dithering to intermediate
integer formats if we are already resampling or channel mixing.
2020-03-19 20:39:44 +02:00
Kevin Mitchell 609d0ef478 ao_wasapi: handle S_FALSE in mp_format_res_str
IsFormatSupported may return S_FALSE (considered SUCCESS) if the
requested format is not suppported, but is close to one that is.
2020-03-19 20:39:44 +02:00
wm4 26f4f18c06 options: change option macros and all option declarations
Change all OPT_* macros such that they don't define the entire m_option
initializer, and instead expand only to a part of it, which sets certain
fields. This requires changing almost every option declaration, because
they all use these macros. A declaration now always starts with

   {"name", ...

followed by designated initializers only (possibly wrapped in macros).
The OPT_* macros now initialize the .offset and .type fields only,
sometimes also .priv and others.

I think this change makes the option macros less tricky. The old code
had to stuff everything into macro arguments (and attempted to allow
setting arbitrary fields by letting the user pass designated
initializers in the vararg parts). Some of this was made messy due to
C99 and C11 not allowing 0-sized varargs with ',' removal. It's also
possible that this change is pointless, other than cosmetic preferences.

Not too happy about some things. For example, the OPT_CHOICE()
indentation I applied looks a bit ugly.

Much of this change was done with regex search&replace, but some places
required manual editing. In particular, code in "obscure" areas (which I
didn't include in compilation) might be broken now.

In wayland_common.c the author of some option declarations confused the
flags parameter with the default value (though the default value was
also properly set below). I fixed this with this change.
2020-03-18 19:52:01 +01:00
wm4 9d04e76f3f ao_pcm: fix double free on exit
This seems to be an older bug. It set priv->outputfilename to a new
talloc-allocated string, but the field is also managed as string option,
so talloc will free it first, then m_option_free() is called on the
dangling pointer. Possibly this is caused by the earlier ta destruction
order change.
2020-03-14 13:50:04 +01:00
wm4 8d965a1bfb options: change how option range min/max is handled
Before this commit, option declarations used M_OPT_MIN/M_OPT_MAX (and
some other identifiers based on these) to signal whether an option had
min/max values. Remove these flags, and make it use a range implicitly
on the condition if min<max is true.

This requires care in all cases when only M_OPT_MIN or M_OPT_MAX were
set (instead of both). Generally, the commit replaces all these
instances with using DBL_MAX/DBL_MIN for the "unset" part of the range.

This also happens to fix some cases where you could pass over-large
values to integer options, which were silently truncated, but now cause
an error.

This commit has some higher potential for regressions.
2020-03-13 17:34:46 +01:00
wm4 5d5a7e1953 ao_lavc: don't spam underrun warnings
Like ao_pcm, this is (conceptually) in perpetual underrun, as long as
dumping is fast enough.
2020-03-13 16:50:27 +01:00
wm4 eb381cbd4b options: split m_config.c/h
Move the "old" mostly command line parsing and option management related
code to m_config_frontend.c/h. Move the the code that enables other part
of the player to access options to m_config_core.c/h. "frontend" is out
of lack of creativity for a better name.

Unfortunately, the separation isn't quite clean yet. m_config_frontend.c
still references some m_config_core.c implementation details, and
m_config_new() is even left in m_config_core.c for now. There some odd
functions that should be removed as well (marked as "Bad functions").
Fixing these things requires more changes and will be done separately.

struct m_config is left with the current name to reduce diff noise.
Also, since there are a _lot_ source files that include m_config.h, add
a replacement m_config.h that "redirects" to m_config_core.h.
2020-03-13 16:50:27 +01:00
wm4 faf24a286f ad_lavc: disable decoder downmix by default
Let's see how much everyone hates this. Leaving it enabled seems
problematic, because libavcodec returns an unspecific error if it
doesn't like it.

Fixes: #6300
2020-02-29 22:08:38 +01:00
wm4 7d11eda72e Remove remains of Libav compatibility
Libav seems rather dead: no release for 2 years, no new git commits in
master for almost a year (with one exception ~6 months ago). From what I
can tell, some developers resigned themselves to the horrifying idea to
post patches to ffmpeg-devel instead, while the rest of the developers
went on to greener pastures.

Libav was a better project than FFmpeg. Unfortunately, FFmpeg won,
because it managed to keep the name and website. Libav was pushed more
and more into obscurity: while there was initially a big push for Libav,
FFmpeg just remained "in place" and visible for most people. FFmpeg was
slowly draining all manpower and energy from Libav. A big part of this
was that FFmpeg stole code from Libav (regular merges of the entire
Libav git tree), making it some sort of Frankenstein mirror of Libav,
think decaying zombie with additional legs ("features") nailed to it.
"Stealing" surely is the wrong word; I'm just aping the language that
some of the FFmpeg members used to use. All that is in the past now, I'm
probably the only person left who is annoyed by this, and with this
commit I'm putting this decade long problem finally to an end. I just
thought I'd express my annoyance about this fucking shitshow one last
time.

The most intrusive change in this commit is the resample filter, which
originally used libavresample. Since the FFmpeg developer refused to
enable libavresample by default for drama reasons, and the API was
slightly different, so the filter used some big preprocessor mess to
make it compatible to libswresample. All that falls away now. The
simplification to the build system is also significant.
2020-02-16 15:14:55 +01:00
wm4 cc52a03401 audio: slightly simplify pull underrun message printing
A previous commit moved the underrun reporting to report_underruns(),
and called it from get_space(). One reason was that I worried about
printing a log message from a "realtime" callback, so I tried to move it
out of the way. (Though there's little justification other than a bad
feeling. While an older version of the pull code tried to avoid any
mutexes at all in the callback to accommodate "requirements" from APIs
like jackaudio, we gave up on that. Nobody has complained yet.)

Simplify this and move underrun reporting back to the callback. But
instead of printing the message from there, move the message into the
playloop. Change the message slightly, because ao->log is inaccessible,
and without the log prefix (e.g. "[ao/alsa]"), some context is missing.
2020-02-13 18:02:16 +01:00
wm4 5bf433b16f player: consider audio buffer if AO driver does not report underruns
AOs can report audio underruns, but only ao_alsa and ao_sdl (???)
currently do so. If the AO was marked as not reporting it, the cache
state was used to determine whether playback was interrupted due to slow
input.

This caused problems in some cases, such as video with very low video
frame rate: when a new frame is displayed, a new frame has to be
decoded, and since there it's so much further into the file (long frame
durations), the cache gets into an underrun state for a short moment,
even though both audio and video are playing fine. Enlarging the audio
buffer didn't help.

Fix this by making all AOs report underruns. If the AO driver does not
report underruns, fall back to using the buffer state.

pull.c behavior is slightly changed. Pull AOs are normally intended to
be used by pseudo-realtime audio APIs that fetch an audio buffer from
the API user via callback. I think it makes no sense to consider a
buffer underflow not an underrun in any situation, since we return
silence to the reader. (OK, maybe the reader could check the return
value? But let's not go there as long as there's no implementation.)
Remove the flag from ao_sdl.c, since it just worked via the generic
mechanism. Make the redundant underrun message verbose only.

push.c seems to log a redundant underflow message when resuming (because
somehow ao_play_data() is called when there's still no new data in the
buffer). But since ao_alsa does its own underrun reporting, and I only
use ao_alsa, I don't really care.

Also in all my tests, there seemed to be a rather high delay until the
underflow was logged (with audio only). I have no idea why this happened
and didn't try to debug this, but there's probably something wrong
somewhere.

This commit may cause random regressions.

See: #7440
2020-02-13 01:32:58 +01:00
wm4 f3c498c7f1 ao: avoid unnecessary wakeups
If ao_add_events() is used, but all events flags are already set, then
we don't need to wakeup the core again.

Also, make the underrun message "exact" by avoiding the race condition
mentioned in the comment.

Avoiding redundant wakeups is not really worth the trouble, and it's
actually just a bonus in the change making the ao_underrun_event()
function return whether a new underrun was set, which is needed by the
following commit.
2020-02-13 01:28:14 +01:00
Rafael Rivera c40554295a ao_wasapi_utils: remove invalid audio session icon path (fixes #7269) 2020-01-31 23:08:47 +11:00
wm4 025e77eaf1 audio: react to --ao and --audio-buffer runtime changes
Before this commit, runtime changes were only applied if something else
caused audio to be reinitialized. Now setting them reinitializes audio
explicitly.
2019-12-27 17:56:22 +01:00
wm4 1cb085a82e options: get rid of GLOBAL_CONFIG hack
Just an implementation detail that can be cleaned up now. Internally,
m_config maintains a tree of m_sub_options structs, except for the root
it was not defined explicitly. GLOBAL_CONFIG was a hack to get access to
it anyway. Define it explicitly instead.
2019-11-29 12:14:43 +01:00
Aman Gupta 03fbb57bd9 audio: add ao_audiotrack for android 2019-11-19 12:10:26 -08:00
Aman Gupta f93faf26d8 audio: fix minor whitespace issue in out/internal.h 2019-11-19 12:10:26 -08:00
wm4 20c9538e32 audio: more alignment nonsense
It's hard to see what FFmpeg does or what its API requires. It looks
like the alignment in our own allocation code might be slightly too
lenient, but who knows. Even if this is not needed, upping the alignment
only wastes memory and doesn't do anything bad.

(Note that the only reason why we have our own code is because FFmpeg
doesn't even provide it as API. API users are forced to recreate this,
even if they have no need for custom allocation!)
2019-11-10 15:30:29 +01:00
wm4 4667b3a182 audio: work around ffmpeg being a piece of shit
The "amultiply" filter crashes in AVX mode on unaligned access if an
audio pointer is unaligned (on 32 or 64 bytes I assume).

A requirement that audio data needs to be aligned isn't documented
anywhere. In our case, the data is still sample- and channel-aligned,
which is completely sane. Sure, you can imagine optimizations which make
some algorithms even faster by requiring higher alignment. But, and this
is a big but, you shouldn't crash api users because you just invented a
new undocumented requirement. And even more importantly, your
user-crashing optimization won't matter because it's just a trivial
algorithm working on audio. You don't need to pretend to be an
optimization devil, and nobody will give you a prize for this. But no,
lets random make API users crash (and then probably blame them for it!)
for something that wouldn't matter at all.

Not to mention that they do "document" some requirements on _video_
data, yet their vf_crop probably can still produce unaligned video
pointers. Oh how hilarious that the same documentation also talks about
libswscale alignment requirements. (This is weird because libswscale is
just one of many, many things which consume video data. Also did you
know that zimg, written in C++ and using intrinsics, i.e. the antithesis
to FFmpeg development, is much faster than libswscale, easier to use,
and produces more correct results, even if you ignore that libswscale
flat out doesn't support some very important features?)

Fucking tired of this bullshit. Can't wait until someone comes up with a
better framework than this... (well let's not write this out).

Fix this by copying instead of adjusting the start pointer when skipping
samples. This makes general operations slower just to fix interoperating
with a single filter. Thank you for your "optimization", FFmpeg. Go die
in a fire.

Didn't check whether this is correct. It probably is? If the frame needs
to be copied (due to COW), and memory allocation fails, it just silently
(or audibly lol) doesn't skip samples, because a never-fail function can
suddenly fail. Well, who cares.

Fixes: #7141
2019-11-10 15:13:25 +01:00
wm4 6d92e55502 Replace uses of FFMIN/MAX with MPMIN/MAX
And remove libavutil includes where possible.
2019-10-31 11:24:20 +01:00
wm4 5d5fdb77e9 ad_lavc, vd_lavc: return full error codes to shared decoder loop
ad_lavc and vd_lavc use the lavc_process() helper to translate the
FFmpeg push/pull API to the internal filter API (which completely
mismatch, even though I'm responsible for both, just fucking kill me).

This interface was "slightly" too tight. It returned only a bool
indicating "progress", which was not enough to handle some cases (see
following commit).

While we're at it, move all state into a struct. This is only a single
bool, but we get the chance to add more if needed.

This fixes mpv falling asleep if decoding returns an error during
draining. If decoding fails when we already sent EOF, the state machine
stopped making progress. This left mpv just sitting around and doing
nothing.

A test case can be created with: echo $RANDOM >> image.png

This makes libavformat read a proper packet plus a packet of garbage.
libavcodec will decode a frame, and then return an error code. The
lavc_process() wrapper could not deal with this, because there was no
way to differentiate between "retry" and "send new packet". Normally, it
would send a new packet, so decoding would make progress anyway. If
there was "progress", we couldn't just retry, because it'd retry
forever.

This is made worse by the fact that it tries to decode at least two
frames before starting display, meaning it will "sit around and do
nothing" before the picture is displayed.

Change it so that on error return, "receiving" a frame is retried. This
will make it return the EOF, so everything works properly.

This is a high-risk change, because all these funny bullshit exceptions
for hardware decoding are in the way, and I didn't retest them. For
example, if hardware decoding is enabled, it keeps a list of packets,
that are fed into the decoder again if hardware decoding fails, and a
software fallback is performed. Another case of horrifying accidental
complexity.

Fixes: #6618
2019-10-24 18:50:28 +02:00
Stefano Pigozzi 899e0bd16b input: add gamepad support through SDL2
The code is very basic:

- only handles gamepads, could be extended for generic joysticks in the
  future.
- only has button mappings for controllers natively supported by SDL2.
  I heard more can be added through env vars, there's also ways to load
  mappings from text files, but I'd rather not go there yet. Common ones
  like Dualshock are supported natively.
- analog buttons (TRIGGER and AXIS) are mapped to discrete buttons using an
  activation threshold.
- only supports one gamepad at a time. the feature is intented to use
  gamepads as evolved remote controls, not play multiplayer games in mpv :)
2019-10-23 09:40:30 +02:00
wm4 cde94e83a9 audio/out: rip out old unused app/softvolume reporting
This was all dead code. Commit 995c47da9a (over 3 years ago) removed all
uses of the controls.

It would be nice if AOs could apply a linear gain volume, that only
affects the AO's audio stream for low-latency volume adjust and muting.
AOCONTROL_HAS_SOFT_VOLUME was supposed to signal this, but to use it,
we'd have to thoroughly check whether it really uses the expected
semantics, so there's really nothing useful left in this old code.
2019-10-11 21:05:11 +02:00
wm4 d908fbd584 audio/out/pull, ao_sdl: implement new underrun reporting
See previous commits. ao_sdl is worthless, but it might be a good test
for pull-based AOs.

This stops using the old underrun reporting if the new one is enabled.
Also, since the AO's behavior can in theory not be according to
expectations, this needs to be enabled for every single pull AO
separately.

For some reason, in certain cases I get multiple underrun warnings while
cache-pausing is active. It fills the cache, restarts the AO,
immediately underruns again, and then fills the cache again. I'm not
sure why this happens; maybe ao_sdl tries to catch up when it shouldn't.
Who knows.
2019-10-11 20:02:23 +02:00
wm4 89c717559b audio/out/pull: fix underflow reporting
I think this was _always_ wrong. Due to the line above the first changed
line, buffered_bytes==bytes always. I can only hope I broke this in a
less under-tested edit when I originally wrote this.

Fixes: c5a82f729b
2019-10-11 20:02:23 +02:00
wm4 1723b88cdd ao_alsa: use AO underrun reporting
This enables the change introduced in the previous commit for ao_alsa.
2019-10-11 20:02:23 +02:00
wm4 c84ec02128 ao: add API for underrun reporting
AOs can now call ao_underrun_event() (in any context) if an underrun has
happened. It will print a message.

This will be used in the following commits. But for now, audio.c only
clears the underrun bit, so that subsequent underruns still print the
warning message.

Since the underrun flag will be used in fragile ways by the playback
state machine, there is the "reports_underruns" field that signals
strong support for underrun reporting. (Otherwise, underrun events will
not be used by it.)
2019-10-11 19:25:45 +02:00
wm4 52f3dee16a ao_alsa: handle underruns in get_space() too
This is essentially optional. But it will give the higher level code a
better guarantee that underruns were tested.
2019-10-11 19:19:59 +02:00
wm4 c6c93499cb ao_alsa: mess with underrun handling again
This commit tries to prepare for better underrun reporting. The goal is
to report underruns relatively immediately. Until now, this happened
only when play() was called. Change this, and abuse that get_delay() is
called "relatively often" - this reports the underrun immediately in
practice.

Background:

In commit 81e51a15f7 (and also e38b0b245e), we were quite confused
about ALSA underrun handling. The commit message showed uncertainty how
case 3 happened, but it's blindingly obvious and simple.

Actually reading the code shows that ALSA does not have a concept of a
"final chunk" (or we don't use it). It's obvious we never pass the
AOPLAY_FINAL_CHUNK flag along to the ALSA API in any way. The only thing
we do is simply writing a partial fragment. Of course this will cause an
underrun. Doing a partial write saves us the trouble to pad the last
frame with silence, or so.

The main reason why the underrun message was avoided was that play() was
never called with a non-0 sample count again (except if reset() was
called before that). That was OK, at least the goal of avoiding the
unwanted message was reached. (And the original "bogus" message at end
of playback was perfectly correct, as far as ALSA goes.)

If network stalls, play() will called again only once new data is
available. Obviously, this could take a long time, thus it's too late.
2019-10-11 16:52:45 +02:00
wm4 e38b0b245e ao_alsa: don't silence legitimate underrun if final chunk underruns
It turns out that case 2) mentioned in the previous commit happened
quite often when playback ended normally.

There is probably a legitimate underrun with normal buffer sizes (100
ms, 4 fragments, gapless audio in "weak" mode). This is a result of the
player waiting for video to end, and/or the time needed to kill the
video window. The former case means that it depends on your test case
whether it happens (a file where video ends slightly before audio is
less likely to trigger it).

This in turn is due to how gapless playback works. Achieving not having
a "gap" requires queuing the audio of the next file without playing a
partial chunk (as AOPLAY_FINAL_CHUNK would do). The partial chunk is
then played as part of the first chunk played from the next file. But if
it detects "later" that there is no next file, it still needs to get rid
of the last fragment with AOPLAY_FINAL_CHUNK. At this point it's too
late, and an underrun may have actually happened. The way the player
uninits and reinits the entire playback engine for the next file in a
"serial" manner means it cannot know in advance whether this works.

This is the reason why the idiot who added the underrun exception for
the last chunk in play() was wrong (I wrote that btw., before you accuse
me of being rude). Yes, it's a real underrun, and you could probably
hear it.
2019-10-06 20:46:22 +02:00
wm4 81e51a15f7 ao_alsa: remove sometimes bogus XRUN message
This XRUN (aka underrun) message was printed in the following
situations:

1) legitimate underrun during playback
2) legitimate underrun when playing final chunk
3) bogus underrun when playing final chunk

The old underrun case (in play()) happens in cases 1) and 2) as well,
but 3) did not happen. It appears 3) is indeed something that happens,
although it's not known for sure. It's still pretty annoying, so remove
the new XRUN message.

When testing, care should be taken to play with buffer sizes, video
versus no video, and gapless enabled/disabled. Also, suspending the
player with Ctrl+Z in the terminal (SIGSTOP) and then resuming is a good
way to trigger a "normal" underrun.
2019-10-06 20:46:22 +02:00
Paul B Mahol 2b19a7c964 audio/filter: remove no longer used header 2019-10-05 12:36:38 +02:00
wm4 4fdd0940ed audio: fix copy&paste error
This wasn't used at all in my tests, because it simply passed the
frame directly to libswsresample. (And, by the way, will always do
that, because s64 is so obscure literally NOTHING uses it except
a sample specifically created to test this code. Screw FFmpeg.)
2019-09-27 21:31:04 +02:00
wm4 81c872efc0 ad_lavc: log on failure to read AVFrame
This can be due to unsupported sample formats (see previous commits),
minor allocation failures, and similar things. For identifying the exact
cause it's buried too deep in abstractions. But most time it doesn't
happen anyway, since it's extremely rare that new audio formats are
added.
2019-09-27 21:24:24 +02:00
wm4 53e3cb968a audio: add support for AV_SAMPLE_FMT_S64*
What an idiotic format. It makes no sense, and should have been
converted to S32 in the demuxer, rather than plague everyone with
another extremely obscure nonsense format. Why doesn't ffmpeg add S24
instead? That's an actually useful format.

May cause compilation failure with old FFmpeg or Libav libs, but I don't
care.
2019-09-27 21:21:34 +02:00
Philip Sequeira 21a5c416d5 options: add M_OPT_FILE to some more options that take files 2019-09-27 13:19:29 +02:00
Jan Ekström 69e4a5772a ao_pulse: add the newly added mappings for TrueHD/DTS-HD formats
Originally DTS-HD was mapped to PA_ENCODING_DTS_IEC61937 which I'm
actually not sure if it ever worked.
2019-09-27 00:23:36 +03:00
Leonardo Taccari 3d911d8ef0 ao_oss: Fallback to stereo when the device does not support >2 channels
ioctl(..., SNDCTL_DSP_CHANNELS, &nchannels) for not supported
nchannels does not return an error and instead set nchannels to
the default value.

Instead of failing with no audio, fallback to stereo.
2019-09-21 15:38:46 +02:00
Térence Clastres 41f4e8d73a ao_pulse: add --pulse-allow-suspended
This flag makes mpv continue using the PulseAudio driver even if the
sink is suspended.
This can be useful if JACK is running with PulseAudio in bridge mode and
the sink-input assigned to mpv is the one JACK controls, thus being
suspended.
By forcing mpv to still use PulseAudio in this case, the user can now
adjust the sink to an unsuspended one.
2019-09-21 12:54:36 +02:00
wm4 c8b8fe9981 audio: remove unreferenced af_lavrresample
This filter wasn't referenced anywhere and thus was dead code. It should
have been in the audio filter list in user_filters.c. This was intended
as compatibility wrapper (to avoid breaking old command lines and config
files), and has no real use. Apparently I forgot to add it to the filter
list (did I even test this shit?), and so it was rotting around for 1.5
years doing nothing (just like myself).

Note that users can just use the libavfilter provided filter to force
resampling, just that it has a different name and different options.
There's also af_format to force inserting auto conversion through the
internal f_swsresample filter.
2019-09-19 20:37:05 +02:00
wm4 4e4949b4dc audio_buffer: fix some more theoretical UB
This may call memmove() with size==0 and a NULL data pointer. In
addition to this being UB with memmove(), I think it's UB to do
arithmetic on a NULL pointer too. Of course, this doesn't matter in
practice at all, and is just stupidity to torture programmers.
2019-09-19 20:37:05 +02:00
wm4 32e3033666 ad_lavc: skip fully skipped frames
Fixes stupid messages with a opus/mkv test file that had an absurdly
huge codec delay.

This file fully skips several frames at the start. ad_lavc.c trimmed
these frames to 0 samples and returned them. The next layer
(f_decoder_wrapper.c) saw discontinuous PTS values, because the PTS
values increased by a frame, but amounted to 0 audio samples. This was
harmless, but logged PTS discontinuity errors.
2019-09-19 20:37:04 +02:00
wm4 b9d351f02a Implement backwards playback
See manpage additions. This is a huge hack. You can bet there are shit
tons of bugs. It's literally forcing square pegs into round holes.
Hopefully, the manpage wall of text makes it clear enough that the whole
shit can easily crash and burn. (Although it shouldn't literally crash.
That would be a bug. It possibly _could_ start a fire by entering some
sort of endless loop, not a literal one, just something where it tries
to do work without making progress.)

(Some obvious bugs I simply ignored for this initial version, but
there's a number of potential bugs I can't even imagine. Normal playback
should remain completely unaffected, though.)

How this works is also described in the manpage. Basically, we demux in
reverse, then we decode in reverse, then we render in reverse.

The decoding part is the simplest: just reorder the decoder output. This
weirdly integrates with the timeline/ordered chapter code, which also
has special requirements on feeding the packets to the decoder in a
non-straightforward way (it doesn't conflict, although a bugmessmass
breaks correct slicing of segments, so EDL/ordered chapter playback is
broken in backward direction).

Backward demuxing is pretty involved. In theory, it could be much
easier: simply iterating the usual demuxer output backward. But this
just doesn't fit into our code, so there's a cthulhu nightmare of shit.
To be specific, each stream (audio, video) is reversed separately. At
least this means we can do backward playback within cached content (for
example, you could play backwards in a live stream; on that note, it
disables prefetching, which would lead to losing new live video, but
this could be avoided).

The fuckmess also meant that I didn't bother trying to support
subtitles. Subtitles are a problem because they're "sparse" streams.
They need to be "passively" demuxed: you don't try to read a subtitle
packet, you demux audio and video, and then look whether there was a
subtitle packet. This means to get subtitles for a time range, you need
to know that you demuxed video and audio over this range, which becomes
pretty messy when you demux audio and video backwards separately.

Backward display is the most weird (and potentially buggy) part. To
avoid that we need to touch a LOT of timing code, we negate all
timestamps. The basic idea is that due to the navigation, all
comparisons and subtractions of timestamps keep working, and you don't
need to touch every single of them to "reverse" them.

E.g.:

    bool before = pts_a < pts_b;

would need to be:

    bool before = forward
        ? pts_a < pts_b
        : pts_a > pts_b;

or:

    bool before = pts_a * dir < pts_b * dir;

or if you, as it's implemented now, just do this after decoding:

    pts_a *= dir;
    pts_b *= dir;

and then in the normal timing/renderer code:

    bool before = pts_a < pts_b;

Consequently, we don't need many changes in the latter code. But some
assumptions inhererently true for forward playback may have been broken
anyway. What is mainly needed is fixing places where values are passed
between positive and negative "domains". For example, seeking and
timestamp user display always uses positive timestamps. The main mess is
that it's not obvious which domain a given variable should or does use.

Well, in my tests with a single file, it suddenly started to work when I
did this. I'm honestly surprised that it did, and that I didn't have to
change a single line in the timing code past decoder (just something
minor to make external/cached text subtitles display). I committed it
immediately while avoiding thinking about it. But there really likely
are subtle problems of all sorts.

As far as I'm aware, gstreamer also supports backward playback. When I
looked at this years ago, I couldn't find a way to actually try this,
and I didn't revisit it now. Back then I also read talk slides from the
person who implemented it, and I'm not sure if and which ideas I might
have taken from it. It's possible that the timestamp reversal is
inspired by it, but I didn't check. (I think it claimed that it could
avoid large changes by changing a sign?)

VapourSynth has some sort of reverse function, which provides a backward
view on a video. The function itself is trivial to implement, as
VapourSynth aims to provide random access to video by frame numbers (so
you just request decreasing frame numbers). From what I remember, it
wasn't exactly fluid, but it worked. It's implemented by creating an
index, and seeking to the target on demand, and a bunch of caching. mpv
could use it, but it would either require using VapourSynth as demuxer
and decoder for everything, or replacing the current file every time
something is supposed to be played backwards.

FFmpeg's libavfilter has reversal filters for audio and video. These
require buffering the entire media data of the file, and don't really
fit into mpv's architecture. It could be used by playing a libavfilter
graph that also demuxes, but that's like VapourSynth but worse.
2019-09-19 20:37:04 +02:00
sfan5 8f96169117 ao_opensles: fix delayed audio
This was forgotten in commit 5a8c48fde2
when the number of buffers was reduced to 1.
2019-09-02 00:38:05 +03:00
Aman Gupta 8b114e574a ao/audiounit: include AVAudioSession buffer in latency calc
Signed-off-by: Aman Gupta <aman@tmm1.net>
2019-04-05 10:29:44 +07:00
Aman Gupta e35aca3cb4 ao/audiounit: improve a/v sync
This more closely mimics ao_coreaudio, on which this driver was
originally based.

Signed-off-by: Aman Gupta <aman@tmm1.net>
2019-04-05 10:29:44 +07:00
Anton Kindestam 8b83c89966 Merge commit '559a400ac36e75a8d73ba263fd7fa6736df1c2da' into wm4-commits--merge-edition
This bumps libmpv version to 1.103
2018-12-05 19:19:24 +01:00
Jan Ekström 4056a9a420 ad_spdif: cosmetic alignment 2018-10-30 02:13:04 +02:00
Jan Ekström 25ee18d6e5 ad_spdif: fix DTS-HD HRA handling
Apparently, for bit streaming DTS-HD MA is specified to be handled as an
eight channel (7.1) bit stream, while DTS-HD HRA is specified to be
handled as a stereo bit stream.

Define a variable for this, and utilize it to set the correct values
for both the DTS-HD bit streaming rate, as well as the channel count
for the SPDIF encoder.

Fixes #6148
2018-10-30 02:13:04 +02:00
Josh Lehman 515c4163ea ao_audiounit: rename pause function to reset
AudioUnit output driver uses the pull based api so it should have
a reset function instead of a pause function.
2018-09-30 16:01:21 -07:00
Jan Ekström cea4ff3e5f ao_alsa: log the ALSA state if we get a non-XRUN error
The ALSA state generally can tell us more information in case we
get an unexpected error.
2018-09-29 20:02:46 +02:00
Jan Ekström fdc952486a ao_alsa: handle XRUNs separately from other errors
According to ALSA doxy, EPIPE is a synonym to SND_PCM_STATE_XRUN,
and that is a state that we should attempt to automatically recover
from. In case recovery fails, log an error and return zero.

A warning message will still be output for each XRUN since those
are not something we should generally be receiving.
2018-09-29 20:02:46 +02:00
Jan Ekström 3218a58082 ao_alsa: early exit get_space if paused or ALSA is not ready
This has been way too long coming, and for me to notice that a
whole lot of ao_alsa functions do an early return if the AO is
paused.

For the STATE_SETUP case, I had this reproduced once, and never
since. Still, seems like we can start calling this function before
the ALSA device has been fully initialized so we might as well
early exit in that case.
2018-09-29 20:02:46 +02:00
Niklas Haas fed0ea111b ao_jack: only auto-connect to audio ports
This prevents ao_jack from auto-connecting to MIDI ports (or other,
hypothetical future port types).
2018-09-26 22:44:48 +03:00
Tom Yan 9d6b15ab32 ao_pulse: fix tlength calculation
also remove the now unused non-sensical af_fmt_seconds_to_bytes.
2018-09-01 16:14:11 +02:00
Michael Hoang 91786fa99c Revert "ao_openal: enable building on OSX"
This reverts commit af6126adbe. Apple's
OpenAL support is ridiculously out of date, revert back to just using
OpenAL Soft on macOS (fixes #4645).
2018-08-26 15:49:22 +03:00
Hector Martin a10754f038 af_rubberband: reset delay to 0 on reset
This fixes A-V drift on seeking
2018-08-25 19:20:42 +03:00
Tom Yan 6c2d6a3046 ao_opensles: set numBuffers to 8
Apparently some Android builds/forks require this for Bluetooth
audio to work as they unexpectedly accept fast flag for it.

Shouldn't cause any side-effect (e.g. buffer requirement increased
when on wired audio). It's a hardcoded default in the upstream
AAudio implementation anyway.

Ref.:
https://android.googlesource.com/platform/frameworks/av/+/android-8.0.0_r1/media/libaaudio/src/legacy/AudioStreamTrack.cpp#109
https://android.googlesource.com/platform/frameworks/wilhelm/+/android-8.0.0_r1/src/android/AudioPlayer_to_android.cpp#1680
https://android.googlesource.com/platform/frameworks/av/+/android-8.0.0_r1/media/libaudioclient/AudioTrack.cpp#488
2018-08-13 19:10:10 +02:00
Tom Yan f2311ff514 audio/format: decouple af_fmt_is_planar from af_fmt_to_planar
so that af_fmt_to_planar (and hence af_fmt_from_planar) can just
return the input when it is not an interleaved (planar) format.
2018-08-11 11:56:27 +02:00
Tom Yan e1bd5288b7 ao_opensles: rework the heuristic of buffer/enqueue size setting
ao->device_buffer will only affect the enqueue size if the latter
is not specified. In other word, its intended purpose will solely
be setting/guarding the soft buffer size.

This guarantees that the soft buffer size will be consistent no
matter a specific enqueue size is set or not. (In the past it
would drop to the default of the generic audio-buffer option.)

opensles-frames-per-buffer has been renamed to opensles-frames-per
-enqueue, as it was never purposed to set the soft buffer size. It
will only make sure the size is never smaller than itself, just as
before.

opensles-buffer-size-in-ms is introduced to allow easy tuning of
the relative (i.e. in time) soft buffer size (and enqueue size,
unless the aforementioned option is set). As "device buffer" never
really made sense in this AO, this option OVERRIDES audio-buffer
whenever its value (including the default) is larger than 0.

Setting opensl-buffer-size-in-ms to 1 allows you to equate the soft
buffer size to the absolute enqueue size set with opensl-frames-per
-enqueue conveniently (unless it is less than 1ms).

When both are set to 0, audio-buffer will be the ultimate fallback.
If audio-buffer is also 0, the AO errors out.
2018-08-05 17:52:01 +02:00
Tom Yan 8baad91e7b ao_opensles: allow s32 and float output
OpenSLES (and its AudioTrack backend) in Android can take 32-bit
fixed and floating point input since Android L (API 21).
2018-08-05 17:51:45 +02:00
Tom Yan 4e91cb72ef audio/format: minor fix for af_fmt_from_planar
See af_fmt_to_planar.
2018-08-05 17:51:45 +02:00
Jan Ekström 36cc33ff5a ao_alsa: simplify get_space() 2018-06-04 00:03:11 +03:00
Muhammad Faiz 945303a92e ao_alsa: replace snd_pcm_status() with snd_pcm_avail() in get_space()
Fixes a bug with alsa dmix on Fedora 29. After several minutes,
audio suddenly becomes bad and muted.

Actually, I don't know what causes this. Probably this is a bug in alsa.
In any case, as snd_pcm_status() returns not only 'avail', but also other
fields such as tstamp, htstamp, etc, this could be considered a good
simplification, as only avail is required for this function.
2018-06-04 00:00:57 +03:00
wm4 f8ab59eacd player: get rid of mpv_global.opts
This was always a legacy thing. Remove it by applying an orgy of
mp_get_config_group() calls, and sometimes m_config_cache_alloc() or
mp_read_option_raw().

win32 changes untested.
2018-05-24 19:56:35 +02:00
wm4 fb22bf2317 ao: use a local option struct
Instead of accessing MPOpts.
2018-05-24 19:56:35 +02:00
wm4 e02c9b9902 build: make encoding mode non-optional
Makes it easier to not break the build by confusing the ifdeffery.
2018-05-03 01:08:44 +03:00
wm4 0ab3184526 encode: get rid of the output packet queue
Until recently, ao_lavc and vo_lavc started encoding whenever the core
happened to send them data. Since audio and video are not initialized at
the same time, and the muxer was not necessarily opened when the first
encoder started to produce data, the resulting packets were put into a
queue. As soon as the muxer was opened, the queue was flushed.

Change this to make the core wait with sending data until all encoders
are initialized. This has the advantage that we don't need to queue up
the packets.
2018-05-03 01:08:44 +03:00
wm4 f18c4175ad encode: remove old timestamp handling
This effectively makes --ocopyts the default. The --ocopyts option
itself is also removed, because it's redundant.
2018-05-03 01:08:44 +03:00
wm4 6c8362ef54 encode: rewrite half of it
The main change is that we wait with opening the muxer ("writing
headers") until we have data from all streams. This fixes race
conditions at init due to broken assumptions in the old code.

This also changes a lot of other stuff. I found and fixed a few API
violations (often things for which better mechanisms were invented, and
the old ones are not valid anymore). I try to get away from the public
mutex and shared fields in encode_lavc_context. For now it's still
needed for some timestamp-related fields, but most are gone. It also
removes some bad code duplication between audio and video paths.
2018-04-29 02:21:32 +03:00
wm4 20a1f250c6 encode: cosmetics
Mostly whitespace changes; some semantic preserving transformations.
2018-04-20 12:37:34 +02:00
wm4 9ee9313465 ao_alsa: actually report underruns to user
Print them as a warning.

Note that there may be some cases where it underruns, without being a
bad condition. This could possibly happen e.g. if the last chunk is
written, and then it resumes playback some time after that. Eventually I
want to add more code to avoid such spurious warnings.
2018-04-15 23:11:33 +03:00
wm4 66810c1550 ao_pulse: reduce requested device buffer size
Same deal as with the previous commit for ALSA.

Untested.
2018-04-15 23:11:33 +03:00
wm4 17f58455b0 ao_alsa: reduce requested buffer size
There is a dedicated thread for feeding audio to the ALSA API from a
buffer with a larger size. There is little reason to have such a large
device buffer.
2018-04-15 23:11:33 +03:00
wm4 401bd57d44 ao_alsa: add options for controlling period/buffer size 2018-04-15 23:11:33 +03:00
Jan Ekström 9de51b6032 ao_openal: document the muted↔gain conversion
This struck me as odd for a moment, so adding a comment.
2018-04-15 01:18:53 +03:00
LAGonauta 614ad62f89 ao/openal: Add option to set buffering characteristics
One can now set the number of buffers and the buffer size.
This can reduce the CPU usage and the total latency stays mostly the same.
As there are sync mechanisms the A/V sync continue intact and working.

It also modifies 6.1 channel order, as per OpenAL spec
and add AOPLAY_FINAL_CHUNK support
2018-04-15 00:57:01 +03:00
LAGonauta 567df04012 ao/openal: Add better sample format and channel layout selection
Also re-added floating-point support.
2018-04-15 00:57:01 +03:00
LAGonauta 8f82dc92aa ao/openal: Add OpenAL Soft extension to get the correct latency
OpenAL Soft's AL_SOFT_source_latency extension allows one to correctly
get the device output latency, facilitating the syncronization with
video.
Also added a simpler generic fallback that does not take into account
latency of the device.
2018-04-15 00:57:01 +03:00
LAGonauta dd357a7d53 ao/openal: Add support for direct channels output
Uses OpenAL Soft's AL_DIRECT_CHANNELS_SOFT extension and can be controlled through
a new CLI option, --openal-direct-channels.
This allows one to send the audio data direrctly to the desired channel without
effects applied.
2018-04-15 00:57:01 +03:00
LAGonauta abaab930f0 ao/openal: Add hardware mute support
While the volume is set on the listener, mute is set on the sound source.
Seemed easier that way.
2018-04-15 00:57:01 +03:00
LAGonauta c59ebbe399 ao/openal: Use only one source for audio output
Floating point audio not supported on this commit.
2018-04-15 00:57:01 +03:00
Tom Yan b0951d71f8 ao_opensles: let cfg_frames_per_buffer accept buffer size up to 0.5s at 192kHz 2018-04-05 04:35:49 +03:00
Tom Yan e3b3e28deb ao_opensles: remove useless cfg_sample_rate
We should always use the ao-neutral --audio-samplerate option.
2018-04-05 04:35:49 +03:00
Tom Yan 14b429de8d ao_opensles: bump device buffer size to 250ms
Although half (non-fast track on sink rate) or one-third (non-fast track not on sink rate) of the buffer size of the created AudioTrack instance as the SL Enqueue buffer size is basically enough for dropout-free playback, only using the full size can avoid stutter upon (re)start of playback.

Here are the various buffer sizes on different track/sink rate when on Bluetooth audio on Android O:

aptX @ 48kHz:
Sink rate: 48000 Hz
44100 Hz: 10632 frames (241.09 ms)
48000 Hz: 11544 frames (240.50 ms)
88200 Hz: 21216 frames (240.54 ms)
96000 Hz: 23088 frames (240.50 ms)
176400 Hz: 42384 frames (240.27 ms)
192000 Hz: 46128 frames (240.25 ms)

SBC/AAC/aptX @ 44.1kHz:
Sink rate: 44100 Hz
44100 Hz: 10776 frames (244.35 ms)
48000 Hz: 11748 frames (244.75 ms)
88200 Hz: 21552 frames (244.35 ms)
96000 Hz: 23448 frames (244.25 ms)
176400 Hz: 43056 frames (244.08 ms)
192000 Hz: 46848 frames (244.00 ms)

The above results were produced with the following code:

import android.media.AudioAttributes;
import android.media.AudioFormat;
import android.media.AudioTrack;

class AudioInfo {
    public static void main(String[] args) {
	int nosr = AudioTrack.getNativeOutputSampleRate(3);
	System.out.printf("Sink rate: %d Hz\n", nosr);

	int[] rates = {44100,48000,88200,96000,176400,192000};
	for (int rate: rates) {
	    AudioAttributes aa = new AudioAttributes.Builder().setFlags(256).build();
	    AudioFormat af = new AudioFormat.Builder().setSampleRate(rate).build();
	    AudioTrack at = new AudioTrack(aa, af, 4, 1, 0);
	    int sr = at.getSampleRate();
	    int bs = at.getBufferSizeInFrames();
	    float ms = bs * (float) 1000 / sr;
	    at.release();
	    System.out.printf("%d Hz: %d frames (%.2f ms)\n", sr, bs, ms);
	}
    }
}

Therefore bumping the device buffer size to 250ms.
2018-04-05 04:35:49 +03:00
Tom Yan 5a8c48fde2 ao_opensles: do one buffer only
Doing two buffers causes stutters upon (re)start of playback on Android O for all kinds of sinks.
2018-04-05 04:35:49 +03:00
Jan Ekström 59a04562b1 ao_opensles: re-flow interface/configuration retrieval
This manages to make the code more readable. Thanks to
MakeGho@IRCnet for the snippet on which this was based.
2018-03-24 03:43:57 +02:00
Aman Gupta aaa076b631 ao_opensles: fix audio sync using device latency extension 2018-03-23 01:00:01 +02:00
wm4 2f20168b0b ao_sdl: fix default buffer size
If you set desired.samples to 0, SDL will return a default buffer size
on obtained.samples. This was broken, because ceil_power_of_two(0)
returns 1. Since 0 is usually not considered a power of two, this is
probably correct, but we still want to set desired.samples to 0 in this
case.
2018-03-08 17:12:32 -08:00
wm4 f40e0cb0f2 ao: do not allow actual buffer size of 0
You can use --audio-buffer=0 to minimize the audio buffer size. But if
the AO reports no device buffer size (like e.g. ao_jack does), then the
buffer size is actually 0, and playback can never work properly.

Make it fallback to a size of 1, which is unlikely to work properly, but
you get what you asked for, instead of a freeze.
2018-03-08 17:12:32 -08:00
tomty89 013a8f75f3 ao_opensles: bump device buffer size to 200ms
While the soft buffer size is already by default 200ms, it is not enough to guarantee dropout-free playback on Bluetooth audio. Bumping the device buffer size to the same value seems to suffice.
2018-03-07 01:40:05 +02:00
tomty89 0a9ab1b076 ao_opensles: remove set_play_state()
Set play state to playing in init() instead. We no longer touch the play state afterwards.
2018-03-07 01:40:05 +02:00
tomty89 ba68e570de ao_opensles: clear buffer queue in reset()
Avoid resume() from causing SL_RESULT_BUFFER_INSUFFICIENT ("Failed to Enqueue: 7" when seek or resume from pause).
2018-03-07 01:40:05 +02:00
wm4 0ec0c147ed audio: don't touch spdif frames in mp_aframe_clip_timestamps()
It can't work for this type of format.
2018-02-13 17:45:29 -08:00
wm4 1dcf511376 build: drop support for SDL1
For some reason it was supported for ao_sdl because we've only used SDL1
API.
2018-02-13 17:45:29 -08:00
wm4 171ec0a7e4
af_scaletempo: output minimally sized audio frame
This helps the filter to adapt much faster to speed changes. Before this
commit, the filter just converted and output the full input frame, which
could cause problems with large input frames. This was made worse by
certain filters like dynaudnorm or loudnorm outputting pretty large
frames.

This commit changes the filter from trying to convert all input at once
to only outputting a single internally filtered frame. Internally, this
filter already output data in units of 60ms by default (controlled by
the "stride" sub-option), and concatenated as many output frames as
necessary to consume all input.

Behavior is still kind of bad when inserting the filter. This is because
the large frames can be buffered up after the insertion point, so the
speed change will be performed with a larger latency. The scaletempo
filter can't do anything against this, although it can be fixed by
inserting scaletempo as user filter as part of --af.
2018-02-03 05:01:29 -08:00
wm4 8b3306924d codecs: remove unused family field
MPlayer used this to distinguish multiple decoder wrappers (such as
libavcodec vs. binary codec loader vs. builtin decoders). It lost
meaning in mpv as non-libavcodec things were dropped. Now it doesn't
serve any purpose anymore.

Parsing was removed quite a while ago, and the recent filter change
removed any use of the internal family field. Get rid of it.
2018-02-01 10:21:55 +01:00
wm4 76e7e78ce9 audio: move to decoder wrapper
Use the decoder wrapper that was introduced for video. This removes all
code duplication the old audio decoder wrapper had with the video code.

(The audio wrapper was copy pasted from the video one over a decade ago,
and has been kept in sync ever since by the power of copy&paste. Since
the original copy&paste was possibly done by someone who did not answer
to the LGPL relicensing, this should also remove all doubts about
whether any of this code is left, since we now completely remove any
code that could possibly have been based on it.)

There is some complication with spdif handling, and a minor behavior
change (it will restrict the list of codecs to spdif if spdif is to be
used), but there should not be any difference in practice.
2018-01-30 03:10:27 -08:00
wm4 054c02ad64 ao_null: add --ao-null-format option for debugging
Helpful especially to test spdif fallback and so on.
2018-01-30 03:10:27 -08:00
wm4 b9f804b566 audio: rewrite filtering glue code
Use the new filtering code for audio too.
2018-01-30 03:10:27 -08:00
wm4 bd25fc5307 ao_alsa: reduce verbosity at -v
Always make the hw params dump function use MSGL_DEBUG, and remove the
MSGL_V use. That means you need -v -v to see them. The detailed
information is usually not very interesting, so this reduces the log
noise.
2018-01-25 20:18:32 -08:00
wm4 d36ff64b29 audio: fix annyoing af_get_best_sample_formats() definition
The af_get_best_sample_formats() function had an argument of
int[AF_FORMAT_COUNT], which is slightly incorrect, because it's 0
terminated and should in theory have AF_FORMAT_COUNT+1 entries. It won't
actually write this many formats (since some formats are fundamentally
incompatible), but it still feels annoying and incorrect. So fix it, and
require that callers pass an AF_FORMAT_COUNT+1 array.

Note that the array size has no meaning in C function arguments (just
another issue with C static arrays being weird and stupid), so get rid
of it completely.

Not changing the af_lavcac3enc use, since that is rewritten in another
branch anyway.
2018-01-25 20:18:32 -08:00
wm4 da662ef182 Fix undefined preprocessor behavior
This commit eliminates the following clang warning:

  warning: macro expansion producing 'defined' has undefined behavior [-Wexpansion-to-defined]

Going by the clang commit message, this seems to be explicitly specified
as UB by the standard, and they added this warning because MSVC
apparently results in different behavior. Whatever, we can just avoid
the warning with some small changes.
2018-01-18 00:25:00 -08:00
Vobe e7ea893c2f af_rubberband: add af-command to multiply current pitch
This commit introduces the multiply-pitch af-command. Users may bind
keys to this command in order to incrementally adjust the pitch of a
track. This will probably mostly be useful for musicians trying to
transpose up and down by semi tones without having to calculate
the correct ratio beforehand.

As an example, here is an input.conf to test this feature:

    { af-command all multiply-pitch 0.9438743126816935
    } af-command all multiply-pitch 1.059463094352953
2018-01-15 23:14:01 -08:00
wm4 a5f53da229 af_lavrresample: deprecate this filter
The future direction might be not having such a user-visible filter at
all, similar to how vf_scale went away (or actually, redirects to
libavfilter's vf_scale).
2018-01-13 03:26:45 -08:00
wm4 6d4b4c0de3 audio: add global options for resampler defaults
This is part of trying to get rid of --af-defaults, and the af
resample filter.

It requires a complicated mechanism to set the defaults on the resample
filter for backwards compatibility.
2018-01-13 03:26:45 -08:00
wm4 23edaf4412 audio/aframe: add missing include statements
Otherwise it doesn't compile if they are not indirectly included before.
2018-01-13 03:26:45 -08:00
wm4 0a406f97e0 video, audio: don't actively wait for demuxer input
If feed_packet() ended with DATA_WAIT, the player should have gone to
sleep, until the demuxer wakes it up again when there is new data. But
the call to read_frame() unconditionally overwrote this status code, so
it never waited. The consequence was that the core burned CPU by
effectively polling the demuxer status, which was noticeable especially
when seeking in network streams (since seeking is async, decoders will
start out with having to wait for network).

Regression since commit 33e5755c.
2018-01-09 09:19:56 +01:00
wm4 33e5755c23 video, audio: always read all frames before getting next packet
The old code tried to make sure at all times to try to read a new
packet. Only once that was read, it tried to retrieve new video or audio
frames the decoder might already have decoded.

Change this to strictly read frames from the decoder until it signals
that it wants a new packet, and only then read and feed a new packet.
This is in theory nicer, follows the libavcodec recommended data flow,
and and reduces the minimum latency by 1 frame.

This merely requires switching the order in which those calls are done.
Normally, the decoder will return only 1 frame until a new packet is
required. If we would just feed it 1 packet, return DATA_AGAIN, and wait
until the next frame is decoded, we would run the playloop 1 time too
often for no reason (which is fine but might have some overhead). To
avoid this, try to read a frame again after possibly feeding a packet.
For this reason, move the feed/read code to its own functions each,
instead of merely moving the code.

The audio and video code for this particular thing is basically
duplicated. The idea is to unify them one day, so make the change to
both. (Doing this for video is the real motivation for this change, see
below.)

The video code change is slightly more complicated, because we have to
care about the framedrop counting (which is just a heuristic, but for
now considered better than nothing, and possibly considered required to
warn the user of framedrops happening - maybe).

Apparently this change helps with stalling streams on Android with the
mediacodec wrapper and mpeg2 decoder implementations which deinterlace on
decoding (and return 2 frames per packet).

Based on an idea and observations by tmm1.
2018-01-01 23:17:56 -08:00
wm4 69ae23fdd1 options: drop some previously deprecated options
A release has been made, so drop options deprecated for that release.
Also drop some options which have been deprecated a much longer time
before.

Also fix a typo in client-api-changes.rst.
2017-12-25 04:06:17 -07:00
Nicolas F 744b67d9e5 Fix various typos in log messages 2017-12-03 21:24:18 +01:00
wm4 b56f109219 ao: minor simplification to gain processing code
Cosmetic move of a variable, and consider an adjustment below 1/256 or
so not worth applying (even in the float case).
2017-11-30 01:31:37 +01:00
wm4 6f8cf73f54 ao: simplify hack for float atomics
stdatomic.h defines no atomic_float typedef. We can't just use _Atomic
unconditionally, because we support compilers without C11 atomics. So
just create a custom atomic_float typedef in the wrapper, which uses
_Atomic in the C11 code path.
2017-11-30 01:20:03 +01:00
wm4 d725630b5f audio: add audio softvol processing to AO
This does what af_volume used to do. Since we couldn't relicense it,
just rewrite it. Since we don't have a new filter mechanism yet, and the
libavfilter is too inconvenient, do applying the volume gain in ao.c
directly. This is done before handling the audio data to the driver.

Since push.c runs a separate thread, and pull.c is called asynchronously
from the audio driver's thread, the volume value needs to be
synchronized. There's no existing central mutex, so do some shit with
atomics. Since there's no atomic_float type predefined (which is at
least needed when using the legacy wrapper), do some nonsense about
reinterpret casting the float value to an int for the purpose of atomic
access. Not sure if using memcpy() is undefined behavior, but for now I
don't care.

The advantage of not using a filter is lower complexity (no filter auto
insertion), and lower latency (gain processing is done after our
internal audio buffer of at least 200ms).

Disavdantages include inability to use native volume control _before_
other filters with custom filter chains, and the need to add new
processing for each new sample type.

Since this doesn't reuse any of the old GPL code, nor does indirectly
rely on it, volume and replaygain handling now works in LGPL mode.

How to process the gain is inspired by libavfilter's af_volume (LGPL).
In particular, we use exactly the same rounding, and we quantize
processing for integer sample types by 256 steps. Some of libavfilter's
copyright may or may not apply, but I think not, and it's the same
license anyway.
2017-11-29 21:30:51 +01:00
wm4 3d27a0792b af: remove deprecated audio filters
These couldn't be relicensed, and won't survive the LGPL transition. The
other existing filters are mostly LGPL (except libaf glue code).

This remove the deprecated pan option. I guess it could be restored by
inserting a libavfilter filter (if there's one), but for now let it be
gone.

This temporarily breaks volume control (and things related to it, like
replaygain).
2017-11-29 21:30:51 +01:00
wm4 274cc06aaf ao_alsa: change license to LGPL
Looks like this is covered by LGPL relicensing agreements now.

Notes about contributors who could not be reached or who didn't agree:

Commit 7fccb6486e has tons of mp_msg changes look like they are not
copyrightable (even if they were, all mp_msg calls were rewritten in
mpv times again). The additional play() change looks suspicious, but
the function was rewritten several times anyway (first time after that
commit in 4f40ec312).

Commit 89ed1748ae was rewritten in commit 325311af3 and then again
several times after that. Basically all this code is unnecessary in
modern mpv and has been removed.

No code survived from the following commits: 4d31c3c53, 61ecf838f2,
d38968bd, 4deb67c3f. At least two cosmetic typo fixes are not
considered as well.

Commit 22bb046ad is reverted (this wasn't a valid warning anyway, just
a C++-ism icc applied to C). Using the constants is nicer, but at least
I don't have to decide whether that change was copyrightable.
2017-11-23 16:43:59 +01:00
wm4 b2a08db71a ao_alsa: don't convert twice on retry
Obscure corner case.
2017-11-23 16:43:59 +01:00
wm4 a7a1ae0b3d build: make it easier to force FFmpeg upstream
Apparently some people want this. Actually making it compile is still
their problem, though, and I expect that build with FFmpeg upstream will
occasionally be broken (as it is right now). This is because mpv also
relies on API provided by Libav, and if FFmpeg hasn't merged that yet,
it's not our problem - we provide a version of FFmpeg upstream with
those changes merged, and it's called ffmpeg-mpv.

Also adjust the README which still talked about FFmpeg releases.
2017-11-01 16:50:18 +01:00
wm4 a7f4ecb012 Bump libav* API use
(Not tested on Windows and OSX.)
2017-10-30 20:55:42 +01:00
wm4 d6ebb2df47 Get rid of deprecated AVFrame accessors
Fist we were required to use them for ABI compat. reasons (and other
BS), now they're deprecated and we're supposed to access them directly
again.
2017-10-30 13:36:44 +01:00
wm4 6a9f457102 audio/out: initialize an array to avoid confusing static analyzer
I _think_ this confuses Coverity and it thinks there is uninitialized
data to be read. Initialize the array to change/remove the warning, or
if there's a real problem, to make it easier to detect. (Basically apply
defensive coding.)
2017-10-27 14:11:33 +02:00
wm4 c54673b86f af_lavfi: fix small memory leak
Plus restructure the error path to make this simpler.
2017-10-27 13:54:40 +02:00
wm4 a5b51f75dc demux: get rid of demux_packet.new_segment field
The new_segment field was used to track the decoder data flow handler of
timeline boundaries, which are used for ordered chapters etc. (anything
that sets demuxer_desc.load_timeline). This broke seeking with the
demuxer cache enabled. The demuxer is expected to set the new_segment
field after every seek or segment boundary switch, so the cached packets
basically contained incorrect values for this, and the decoders were not
initialized correctly.

Fix this by getting rid of the flag completely. Let the decoders instead
compare the segment information by content, which is hopefully enough.
(In theory, two segments with same information could perhaps appear in
broken-ish corner cases, or in an attempt to simulate looping, and such.
I preferred the simple solution over others, such as generating unique
and stable segment IDs.)

We still add a "segmented" field to make it explicit whether segments
are used, instead of doing something silly like testing arbitrary other
segment fields for validity.

Cached seeking with timeline stuff is still slightly broken even with
this commit: the seek logic is not aware of the overlap that segments
can have, and the timestamp clamping that needs to be performed in
theory to account for the fact that a packet might contain a frame that
is always clipped off by segment handling. This can be fixed later.
2017-10-24 19:35:55 +02:00
wm4 14f01bd398 aframe: fix logically dead code
Detected by a well known static analyzer.
2017-10-18 12:11:37 +02:00
wm4 14541ae258 Add checks for HAVE_GPL to various GPL-only source files
This should actually cover all of them, if you take into account that
some unchanged GPL source files include header files with such checks.
Also this was done already for the libaf derived code.

This is only for "safety" and to avoid misunderstandings.
2017-10-10 15:51:16 +02:00
wm4 b6af3db568 command: drop "audio-out-detected-device" property
Coreaudio stopped setting it a few releases ago (66a958bb4f). There is
not much of a user- or API-visible change, so remove it without
deprecation.
2017-10-09 15:48:47 +02:00
wm4 4582b8993d audio: fix channel conversion with NA channels
The case at hand was 5.1 -> fl-fr-fc-lfe-na-na (apparently triggered by
ALSA). That means only the NA channels have to be cleared, but the
result was actually that fc and lfe were cleared. This is due to a
simple regression in the reorder code, which quite obviously got the
index of the first NA channel wrong.
2017-09-27 16:22:06 +02:00
wm4 20f958c977 audio: fix resampling
Let's blame FFmpeg for just overwriting the samplerate in
av_frame_copy_props(). Can't fully hide my own brain damage though,
since mp_aframe_config_copy() expected that the rate is copied (that
function also copies format and channel layout).
2017-09-21 14:34:50 +02:00
wm4 bfa9b62858 build: add preliminary LGPL mode
See "Copyright" file for caveats.

This changes the remaining "almost LGPL" files to LGPL, because we think
that the conditions the author set for these was finally fulfilled.
2017-09-21 13:56:27 +02:00
wm4 fdb300b983 audio: make libaf derived code optional
This code could not be relicensed. The intention was to write new filter
code (which could handle both audio and video), but that's a bit of
work. Write some code that can do audio conversion (resampling,
downmixing, etc.) without the old audio filter chain code in order to
speed up the LGPL relicensing.

If you build with --disable-libaf, nothing in audio/filter/* is compiled
in. It breaks a few features, such as --volume, --af, pitch correction
on speed changes, replaygain.

Most likely this adds some bugs, even if --disable-libaf is not used.
(How the fuck does EOF notification work again anyway?)
2017-09-21 12:48:30 +02:00
wm4 3a2d5e68ac audio: move libswresample wrapper out of audio filter code
Move it from af_lavrresample.c to a new aconverter.c file, which is
independent from the filter chain code. It also doesn't use mp_audio,
and thus has no GPL dependencies.

Preparation for later commits. Not particularly well tested, so have
fun.
2017-09-21 12:42:09 +02:00
wm4 caaa1189ba audio_buffer: remove dependency on mp_audio
Just reimplement it in some way, as mp_audio is GPL-only.

Actually I wanted to get rid of audio_buffer.c completely (and instead
have a list of mp_aframes), but to do so would require rewriting some
more player core audio code. So to get this LGPL relicensing over
quickly, just do some extra work.
2017-09-21 04:10:19 +02:00
wm4 997e1fb621 audio: fix spdif mode
Not sure how this was not caught before. It crashed when trying to use
spdif mode.
2017-08-23 12:14:11 +02:00
wm4 b21e0746f6 ao_rsound: allow setting the host
Completely untested (rsound dev libs unavailable on my system). Trivial
enough that it's very likely that it'll just work. No port selection,
but could be added by parsing it as part of the device name.

Should fix #4714.
2017-08-21 15:46:00 +02:00
wm4 1f7fe1597d audio: fix uninitialized data access
dst was not supposed to be initialized, the mp_audio_ setters (which
initialize dst's fields) assume it is -> shit happens. Regression from
recent changes. Was probably harmless.
2017-08-18 17:53:38 +02:00
wm4 158768513c audio: fix build on Libav
Sigh...
2017-08-16 21:26:16 +02:00
wm4 1f593beeb4 audio: introduce a new type to hold audio frames
This is pretty pointless, but I believe it allows us to claim that the
new code is not affected by the copyright of the old code. This is
needed, because the original mp_audio struct was written by someone who
has disagreed with LGPL relicensing (it was called af_data at the time,
and was defined in af.h).

The "GPL'ed" struct contents that surive are pretty trivial: just the
data pointer, and some metadata like the format, samplerate, etc. - but
at least in this case, any new code would be extremely similar anyway,
and I'm not really sure whether it's OK to claim different copyright. So
what we do is we just use AVFrame (which of course is LGPL with 100%
certainty), and add some accessors around it to adapt it to mpv
conventions.

Also, this gets rid of some annoying conventions of mp_audio, like the
struct fields that require using an accessor to write to them anyway.

For the most part, this change is only dumb replacements of mp_audio
related functions and fields. One minor actual change is that you can't
allocate the new type on the stack anymore.

Some code still uses mp_audio. All audio filter code will be deleted, so
it makes no sense to convert this code. (Audio filters which are LGPL
and which we keep will have to be ported to a new filter infrastructure
anyway.) player/audio.c uses it because it interacts with the old filter
code. push.c has some complex use of mp_audio and mp_audio_buffer, but
this and pull.c will most likely be rewritten to do something else.
2017-08-16 21:10:54 +02:00
wm4 baead23ea0 af_lavrresample: don't call swr_set_compensation() unless necessary
This was _always_ called, even if the resampling was static, or the
filter was inserted for format conversion only. This should have been
fine, as I expected the function not to enable resampling when the
compensation is unset, and the source/target rates are the same. But
this is not the case, and it always enables resampling.

So explicitly avoid the call. If we have already called it successfully,
it's better not do avoid it (to overwrite the previous compensation
value), but it will also be cheap/no-op then.

Probably fixes #4716.
2017-08-12 12:12:52 +02:00
Kevin Mitchell 12cafdc868 ao_wasapi: remove old comment 2017-08-07 16:33:29 -07:00
Kevin Mitchell 6f40c211a5 ao_wasapi: reorganize wasapi.h
Remove dead declarations. Move macro only used in wasapi_utils.c closer to use.
Rearrange declaration order.
2017-08-07 14:33:03 -07:00
Kevin Mitchell 434d3d4976 ao_wasapi: deduplicate wasapi sample format selection 2017-08-07 14:33:03 -07:00
Kevin Mitchell 15eb1e1ad3 ao_wasapi: clean up find_formats logic
There were too many functions within functions, too much going on in if
clauses and duplicated code. Fix it.
2017-08-07 14:33:03 -07:00
Kevin Mitchell bee602da82 ao_wasapi: return bool instead of HRESULT from thread_init
Any bad HRESULTs should have been printed already and lots of failure modes
don't have an HRESULT leading to awkward hr = E_FAIL business.

This also checks the exit status of GetBufferSize in the align hack. A final
fatal message is added if either of the retry hacks fail.
2017-08-07 14:33:03 -07:00
wm4 8c82555e41 ao_oss: fix a dumb calculation
period_size used the wrong unit, and even if the unit had been correct,
was assigned the wrong value.

Probably fixes #4642.
2017-07-21 19:45:59 +02:00
wm4 ddd068491c Replace remaining avcodec_close() calls
This API isn't deprecated (yet?), but it's still inferior and harder to
use than avcodec_free_context().

Leave the call only in 1 case in af_lavcac3enc.c, where we apparently
seriously close and reopen the encoder for whatever reason.
2017-07-16 12:51:48 +02:00
Kevin Mitchell c5dfd66e14 ao_wasapi: remove redundant / outdated comment
Where this was moved from, it made slightly more sense. Here what the comment is
trying to say is already pretty obvious from the code.
2017-07-10 21:01:39 -07:00
Kevin Mitchell 63b6aa3f57 ao_waspi: use switch for handling fix_format errors 2017-07-10 21:01:39 -07:00
Kevin Mitchell 4389ddcc34 ao_wasapi: don't repeat format negotiation on align hack
Even if it did return a different result, the bufferFrameCount from the align
hack would be wrong anyway.
2017-07-10 21:01:39 -07:00
Kevin Mitchell 71cc28b804 ao_wasapi: fix leak on align hack 2017-07-10 21:01:39 -07:00
wm4 b016760a28 ad_spdif: minor cleanups
Use avcodec_free_context() unstead of random other calls. Actually it
was already used in the second case, but calling avcodec_close() is
redundant.

Don't crash if allocating a codec context fails.
2017-07-10 16:40:52 +02:00