diff options
Diffstat (limited to 'audio/out')
-rw-r--r-- | audio/out/ao.c | 4 | ||||
-rw-r--r-- | audio/out/ao_coreaudio_chmap.c | 41 | ||||
-rw-r--r-- | audio/out/ao_coreaudio_chmap.h | 14 | ||||
-rw-r--r-- | audio/out/ao_openal.c | 1 | ||||
-rw-r--r-- | audio/out/ao_opensles.c | 250 | ||||
-rw-r--r-- | audio/out/ao_sdl.c | 14 | ||||
-rw-r--r-- | audio/out/ao_wasapi.c | 348 | ||||
-rw-r--r-- | audio/out/ao_wasapi.h | 33 | ||||
-rw-r--r-- | audio/out/ao_wasapi_changenotify.c | 20 | ||||
-rw-r--r-- | audio/out/ao_wasapi_utils.c | 157 | ||||
-rw-r--r-- | audio/out/pull.c | 14 | ||||
-rw-r--r-- | audio/out/push.c | 14 |
12 files changed, 553 insertions, 357 deletions
diff --git a/audio/out/ao.c b/audio/out/ao.c index ffcc43ab79..9c0f644c75 100644 --- a/audio/out/ao.c +++ b/audio/out/ao.c @@ -43,6 +43,7 @@ extern const struct ao_driver audio_out_sndio; extern const struct ao_driver audio_out_pulse; extern const struct ao_driver audio_out_jack; extern const struct ao_driver audio_out_openal; +extern const struct ao_driver audio_out_opensles; extern const struct ao_driver audio_out_null; extern const struct ao_driver audio_out_alsa; extern const struct ao_driver audio_out_wasapi; @@ -74,6 +75,9 @@ static const struct ao_driver * const audio_out_drivers[] = { #if HAVE_OPENAL &audio_out_openal, #endif +#if HAVE_OPENSLES + &audio_out_opensles, +#endif #if HAVE_SDL1 || HAVE_SDL2 &audio_out_sdl, #endif diff --git a/audio/out/ao_coreaudio_chmap.c b/audio/out/ao_coreaudio_chmap.c index bdd625ff53..3db2bdf3d5 100644 --- a/audio/out/ao_coreaudio_chmap.c +++ b/audio/out/ao_coreaudio_chmap.c @@ -1,18 +1,18 @@ /* * This file is part of mpv. * - * mpv is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * mpv is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. * * mpv is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * GNU Lesser General Public License for more details. * - * You should have received a copy of the GNU General Public License along - * with mpv. If not, see <http://www.gnu.org/licenses/>. + * You should have received a copy of the GNU Lesser General Public + * License along with mpv. If not, see <http://www.gnu.org/licenses/>. */ #include "common/common.h" @@ -133,6 +133,29 @@ coreaudio_error: return NULL; } + +#define CHMAP(n, ...) &(struct mp_chmap) MP_CONCAT(MP_CHMAP, n) (__VA_ARGS__) + +// Replace each channel in a with b (a->num == b->num) +static void replace_submap(struct mp_chmap *dst, struct mp_chmap *a, + struct mp_chmap *b) +{ + struct mp_chmap t = *dst; + if (!mp_chmap_is_valid(&t) || mp_chmap_diffn(a, &t) != 0) + return; + assert(a->num == b->num); + for (int n = 0; n < t.num; n++) { + for (int i = 0; i < a->num; i++) { + if (t.speaker[n] == a->speaker[i]) { + t.speaker[n] = b->speaker[i]; + break; + } + } + } + if (mp_chmap_is_valid(&t)) + *dst = t; +} + static bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout, struct mp_chmap *chmap) { @@ -163,6 +186,10 @@ static bool ca_layout_to_mp_chmap(struct ao *ao, AudioChannelLayout *layout, chmap->speaker[n] = speaker; } + // Remap weird 7.1(rear) layouts correctly. + replace_submap(chmap, CHMAP(6, FL, FR, BL, BR, SDL, SDR), + CHMAP(6, FL, FR, SL, SR, BL, BR)); + talloc_free(talloc_ctx); MP_VERBOSE(ao, "mp chmap: %s\n", mp_chmap_to_str(chmap)); return mp_chmap_is_valid(chmap) && !mp_chmap_is_unknown(chmap); diff --git a/audio/out/ao_coreaudio_chmap.h b/audio/out/ao_coreaudio_chmap.h index a67e1dc252..d58270fc47 100644 --- a/audio/out/ao_coreaudio_chmap.h +++ b/audio/out/ao_coreaudio_chmap.h @@ -1,18 +1,18 @@ /* * This file is part of mpv. * - * mpv is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * mpv is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. * * mpv is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * GNU Lesser General Public License for more details. * - * You should have received a copy of the GNU General Public License along - * with mpv. If not, see <http://www.gnu.org/licenses/>. + * You should have received a copy of the GNU Lesser General Public + * License along with mpv. If not, see <http://www.gnu.org/licenses/>. */ #ifndef MPV_COREAUDIO_CHMAP_H diff --git a/audio/out/ao_openal.c b/audio/out/ao_openal.c index c6c924b244..72e8799e00 100644 --- a/audio/out/ao_openal.c +++ b/audio/out/ao_openal.c @@ -236,6 +236,7 @@ static int init(struct ao *ao) return 0; err_out: + ao_data = NULL; return -1; } diff --git a/audio/out/ao_opensles.c b/audio/out/ao_opensles.c new file mode 100644 index 0000000000..0e80829557 --- /dev/null +++ b/audio/out/ao_opensles.c @@ -0,0 +1,250 @@ +/* + * OpenSL ES audio output driver. + * Copyright (C) 2016 Ilya Zhuravlev <whatever@xyz.is> + * + * This file is part of mpv. + * + * mpv is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * mpv is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with mpv. If not, see <http://www.gnu.org/licenses/>. + */ + +#include "ao.h" +#include "internal.h" +#include "common/msg.h" +#include "audio/format.h" +#include "options/m_option.h" +#include "osdep/timer.h" + +#include <SLES/OpenSLES.h> +#include <SLES/OpenSLES_Android.h> + +#include <pthread.h> + +struct priv { + SLObjectItf sl, output_mix, player; + SLBufferQueueItf buffer_queue; + SLEngineItf engine; + SLPlayItf play; + char *curbuf, *buf1, *buf2; + size_t buffer_size; + pthread_mutex_t buffer_lock; + + int cfg_frames_per_buffer; + int cfg_sample_rate; +}; + +static const int fmtmap[][2] = { + { AF_FORMAT_U8, SL_PCMSAMPLEFORMAT_FIXED_8 }, + { AF_FORMAT_S16, SL_PCMSAMPLEFORMAT_FIXED_16 }, + { AF_FORMAT_S32, SL_PCMSAMPLEFORMAT_FIXED_32 }, + { 0 } +}; + +#define DESTROY(thing) \ + if (p->thing) { \ + (*p->thing)->Destroy(p->thing); \ + p->thing = NULL; \ + } + +static void uninit(struct ao *ao) +{ + struct priv *p = ao->priv; + + DESTROY(player); + DESTROY(output_mix); + DESTROY(sl); + + p->buffer_queue = NULL; + p->engine = NULL; + p->play = NULL; + + pthread_mutex_destroy(&p->buffer_lock); + + free(p->buf1); + free(p->buf2); + p->curbuf = p->buf1 = p->buf2 = NULL; + p->buffer_size = 0; +} + +#undef DESTROY + +static void buffer_callback(SLBufferQueueItf buffer_queue, void *context) +{ + struct ao *ao = context; + struct priv *p = ao->priv; + SLresult res; + void *data[1]; + double delay; + + pthread_mutex_lock(&p->buffer_lock); + + data[0] = p->curbuf; + delay = 2 * p->buffer_size / (double)ao->bps; + ao_read_data(ao, data, p->buffer_size / ao->sstride, + mp_time_us() + 1000000LL * delay); + + res = (*buffer_queue)->Enqueue(buffer_queue, p->curbuf, p->buffer_size); + if (res != SL_RESULT_SUCCESS) + MP_ERR(ao, "Failed to Enqueue: %d\n", res); + else + p->curbuf = (p->curbuf == p->buf1) ? p->buf2 : p->buf1; + + pthread_mutex_unlock(&p->buffer_lock); +} + +#define DEFAULT_BUFFER_SIZE_MS 50 + +#define CHK(stmt) \ + { \ + SLresult res = stmt; \ + if (res != SL_RESULT_SUCCESS) { \ + MP_ERR(ao, "%s: %d\n", #stmt, res); \ + goto error; \ + } \ + } + +static int init(struct ao *ao) +{ + struct priv *p = ao->priv; + SLDataLocator_BufferQueue locator_buffer_queue; + SLDataLocator_OutputMix locator_output_mix; + SLDataFormat_PCM pcm; + SLDataSource audio_source; + SLDataSink audio_sink; + + // This AO only supports two channels at the moment + mp_chmap_from_channels(&ao->channels, 2); + + CHK(slCreateEngine(&p->sl, 0, NULL, 0, NULL, NULL)); + CHK((*p->sl)->Realize(p->sl, SL_BOOLEAN_FALSE)); + CHK((*p->sl)->GetInterface(p->sl, SL_IID_ENGINE, (void*)&p->engine)); + CHK((*p->engine)->CreateOutputMix(p->engine, &p->output_mix, 0, NULL, NULL)); + CHK((*p->output_mix)->Realize(p->output_mix, SL_BOOLEAN_FALSE)); + + locator_buffer_queue.locatorType = SL_DATALOCATOR_BUFFERQUEUE; + locator_buffer_queue.numBuffers = 2; + + pcm.formatType = SL_DATAFORMAT_PCM; + pcm.numChannels = 2; + + int compatible_formats[AF_FORMAT_COUNT]; + af_get_best_sample_formats(ao->format, compatible_formats); + pcm.bitsPerSample = 0; + for (int i = 0; compatible_formats[i] && !pcm.bitsPerSample; ++i) + for (int j = 0; fmtmap[j][0]; ++j) + if (compatible_formats[i] == fmtmap[j][0]) { + ao->format = fmtmap[j][0]; + pcm.bitsPerSample = fmtmap[j][1]; + break; + } + if (!pcm.bitsPerSample) { + MP_ERR(ao, "Cannot find compatible audio format\n"); + goto error; + } + pcm.containerSize = 8 * af_fmt_to_bytes(ao->format); + pcm.channelMask = SL_SPEAKER_FRONT_LEFT | SL_SPEAKER_FRONT_RIGHT; + pcm.endianness = SL_BYTEORDER_LITTLEENDIAN; + + if (p->cfg_sample_rate) + ao->samplerate = p->cfg_sample_rate; + + // samplesPerSec is misnamed, actually it's samples per ms + pcm.samplesPerSec = ao->samplerate * 1000; + + if (p->cfg_frames_per_buffer) + ao->device_buffer = p->cfg_frames_per_buffer; + else + ao->device_buffer = ao->samplerate * DEFAULT_BUFFER_SIZE_MS / 1000; + p->buffer_size = ao->device_buffer * ao->channels.num * + af_fmt_to_bytes(ao->format); + p->buf1 = calloc(1, p->buffer_size); + p->buf2 = calloc(1, p->buffer_size); + p->curbuf = p->buf1; + if (!p->buf1 || !p->buf2) { + MP_ERR(ao, "Failed to allocate device buffer\n"); + goto error; + } + int r = pthread_mutex_init(&p->buffer_lock, NULL); + if (r) { + MP_ERR(ao, "Failed to initialize the mutex: %d\n", r); + goto error; + } + + audio_source.pFormat = (void*)&pcm; + audio_source.pLocator = (void*)&locator_buffer_queue; + + locator_output_mix.locatorType = SL_DATALOCATOR_OUTPUTMIX; + locator_output_mix.outputMix = p->output_mix; + + audio_sink.pLocator = (void*)&locator_output_mix; + audio_sink.pFormat = NULL; + + SLboolean required[] = { SL_BOOLEAN_TRUE }; + SLInterfaceID iid_array[] = { SL_IID_BUFFERQUEUE }; + CHK((*p->engine)->CreateAudioPlayer(p->engine, &p->player, &audio_source, + &audio_sink, 1, iid_array, required)); + CHK((*p->player)->Realize(p->player, SL_BOOLEAN_FALSE)); + CHK((*p->player)->GetInterface(p->player, SL_IID_PLAY, (void*)&p->play)); + CHK((*p->player)->GetInterface(p->player, SL_IID_BUFFERQUEUE, + (void*)&p->buffer_queue)); + CHK((*p->buffer_queue)->RegisterCallback(p->buffer_queue, + buffer_callback, ao)); + + return 1; +error: + uninit(ao); + return -1; +} + +#undef CHK + +static void set_play_state(struct ao *ao, SLuint32 state) +{ + struct priv *p = ao->priv; + SLresult res = (*p->play)->SetPlayState(p->play, state); + if (res != SL_RESULT_SUCCESS) + MP_ERR(ao, "Failed to SetPlayState(%d): %d\n", state, res); +} + +static void reset(struct ao *ao) +{ + set_play_state(ao, SL_PLAYSTATE_STOPPED); +} + +static void resume(struct ao *ao) +{ + struct priv *p = ao->priv; + set_play_state(ao, SL_PLAYSTATE_PLAYING); + + // enqueue two buffers + buffer_callback(p->buffer_queue, ao); + buffer_callback(p->buffer_queue, ao); +} + +#define OPT_BASE_STRUCT struct priv + +const struct ao_driver audio_out_opensles = { + .description = "OpenSL ES audio output", + .name = "opensles", + .init = init, + .uninit = uninit, + .reset = reset, + .resume = resume, + + .priv_size = sizeof(struct priv), + .options = (const struct m_option[]) { + OPT_INTRANGE("frames-per-buffer", cfg_frames_per_buffer, 0, 1, 10000), + OPT_INTRANGE("sample-rate", cfg_sample_rate, 0, 1000, 100000), + {0} + }, +}; diff --git a/audio/out/ao_sdl.c b/audio/out/ao_sdl.c index 5e5bd25b96..627a1098cf 100644 --- a/audio/out/ao_sdl.c +++ b/audio/out/ao_sdl.c @@ -4,18 +4,18 @@ * * This file is part of mpv. * - * mpv is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * mpv is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. * * mpv is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * GNU Lesser General Public License for more details. * - * You should have received a copy of the GNU General Public License along - * with mpv. If not, see <http://www.gnu.org/licenses/>. + * You should have received a copy of the GNU Lesser General Public + * License along with mpv. If not, see <http://www.gnu.org/licenses/>. */ #include "config.h" diff --git a/audio/out/ao_wasapi.c b/audio/out/ao_wasapi.c index 1c0e85b7bb..eecfded9e1 100644 --- a/audio/out/ao_wasapi.c +++ b/audio/out/ao_wasapi.c @@ -3,18 +3,18 @@ * * Original author: Jonathan Yong <10walls@gmail.com> * - * mpv is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. + * mpv is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. * * mpv is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. + * GNU Lesser General Public License for more details. * - * You should have received a copy of the GNU General Public License along - * with mpv. If not, see <http://www.gnu.org/licenses/>. + * You should have received a copy of the GNU Lesser General Public + * License along with mpv. If not, see <http://www.gnu.org/licenses/>. */ #include <math.h> @@ -24,6 +24,7 @@ #include "options/m_option.h" #include "osdep/timer.h" #include "osdep/io.h" +#include "misc/dispatch.h" #include "ao_wasapi.h" // naive av_rescale for unsigned @@ -40,14 +41,12 @@ static HRESULT get_device_delay(struct wasapi_state *state, double *delay_us) { HRESULT hr; hr = IAudioClock_GetPosition(state->pAudioClock, &position, &qpc_position); + EXIT_ON_ERROR(hr); // GetPosition succeeded, but the result may be // inaccurate due to the length of the call // http://msdn.microsoft.com/en-us/library/windows/desktop/dd370889%28v=vs.85%29.aspx - if (hr == S_FALSE) { + if (hr == S_FALSE) MP_VERBOSE(state, "Possibly inaccurate device position.\n"); - hr = S_OK; - } - EXIT_ON_ERROR(hr); // convert position to number of samples careful to avoid overflow UINT64 sample_position = uint64_scale(position, @@ -62,7 +61,7 @@ static HRESULT get_device_delay(struct wasapi_state *state, double *delay_us) { QueryPerformanceCounter(&qpc); INT64 qpc_diff = av_rescale(qpc.QuadPart, 10000000, state->qpc_frequency.QuadPart) - qpc_position; - // ignore the above calculation if it yeilds more than 10 seconds (due to + // ignore the above calculation if it yields more than 10 seconds (due to // possible overflow inside IAudioClock_GetPosition) if (qpc_diff < 10 * 10000000) { *delay_us -= qpc_diff / 10.0; // convert to us @@ -71,7 +70,11 @@ static HRESULT get_device_delay(struct wasapi_state *state, double *delay_us) { "Ignoring it.\n", qpc_diff / 10000000.0); } - MP_TRACE(state, "Device delay: %g us\n", *delay_us); + if (sample_count > 0 && *delay_us <= 0) { + MP_WARN(state, "Under-run: Device delay: %g us\n", *delay_us); + } else { + MP_TRACE(state, "Device delay: %g us\n", *delay_us); + } return S_OK; exit_label: @@ -79,22 +82,39 @@ exit_label: return hr; } -static void thread_feed(struct ao *ao) +static bool thread_feed(struct ao *ao) { struct wasapi_state *state = ao->priv; HRESULT hr; UINT32 frame_count = state->bufferFrameCount; - + UINT32 padding; + hr = IAudioClient_GetCurrentPadding(state->pAudioClient, &padding); + EXIT_ON_ERROR(hr); + bool refill = false; if (state->share_mode == AUDCLNT_SHAREMODE_SHARED) { - UINT32 padding = 0; - hr = IAudioClient_GetCurrentPadding(state->pAudioClient, &padding); - EXIT_ON_ERROR(hr); - + // Return if there's nothing to do. + if (frame_count <= padding) + return false; + // In shared mode, there is only one buffer of size bufferFrameCount. + // We must therefore take care not to overwrite the samples that have + // yet to play. frame_count -= padding; - MP_TRACE(ao, "Frame to fill: %"PRIu32". Padding: %"PRIu32"\n", - frame_count, padding); + } else if (padding >= 2 * frame_count) { + // In exclusive mode, we exchange entire buffers of size + // bufferFrameCount with the device. If there are already two such + // full buffers waiting to play, there is no work to do. + return false; + } else if (padding < frame_count) { + // If there is not at least one full buffer of audio queued to play in + // exclusive mode, call this function again immediately to try and catch + // up and avoid a cascade of under-runs. WASAPI doesn't seem to be smart + // enough to send more feed events when it gets behind. + refill = true; } + MP_TRACE(ao, "Frame to fill: %"PRIu32". Padding: %"PRIu32"\n", + frame_count, padding); + double delay_us; hr = get_device_delay(state, &delay_us); EXIT_ON_ERROR(hr); @@ -119,67 +139,57 @@ static void thread_feed(struct ao *ao) atomic_fetch_add(&state->sample_count, frame_count); - return; + return refill; exit_label: MP_ERR(state, "Error feeding audio: %s\n", mp_HRESULT_to_str(hr)); MP_VERBOSE(ao, "Requesting ao reload\n"); ao_request_reload(ao); - return; + return false; } -static void thread_resume(struct ao *ao) +static void thread_reset(struct ao *ao) { struct wasapi_state *state = ao->priv; HRESULT hr; + MP_DBG(state, "Thread Reset\n"); + hr = IAudioClient_Stop(state->pAudioClient); + if (FAILED(hr)) + MP_ERR(state, "IAudioClient_Stop returned: %s\n", mp_HRESULT_to_str(hr)); + + hr = IAudioClient_Reset(state->pAudioClient); + if (FAILED(hr)) + MP_ERR(state, "IAudioClient_Reset returned: %s\n", mp_HRESULT_to_str(hr)); + atomic_store(&state->sample_count, 0); +} + +static void thread_resume(struct ao *ao) +{ + struct wasapi_state *state = ao->priv; MP_DBG(state, "Thread Resume\n"); - UINT32 padding = 0; - hr = IAudioClient_GetCurrentPadding(state->pAudioClient, &padding); - if (hr != S_OK) { - MP_ERR(state, "IAudioClient_GetCurrentPadding returned %s\n", - mp_HRESULT_to_str(hr)); - } + thread_reset(ao); + thread_feed(ao); - // Fill the buffer before starting, but only if there is no audio queued to - // play. This prevents overfilling the buffer, which leads to problems in - // exclusive mode - if (padding < (UINT32) state->bufferFrameCount) - thread_feed(ao); - - // start feeding next wakeup if something else hasn't been requested - int expected = WASAPI_THREAD_RESUME; - atomic_compare_exchange_strong(&state->thread_state, &expected, - WASAPI_THREAD_FEED); - hr = IAudioClient_Start(state->pAudioClient); - if (hr != S_OK) { + HRESULT hr = IAudioClient_Start(state->pAudioClient); + if (FAILED(hr)) { MP_ERR(state, "IAudioClient_Start returned %s\n", mp_HRESULT_to_str(hr)); } - - return; } -static void thread_reset(struct ao *ao) +static void thread_wakeup(void *ptr) { + struct ao *ao = ptr; struct wasapi_state *state = ao->priv; - HRESULT hr; - MP_DBG(state, "Thread Reset\n"); - hr = IAudioClient_Stop(state->pAudioClient); - // we may get S_FALSE if the stream is already stopped - if (hr != S_OK && hr != S_FALSE) - MP_ERR(state, "IAudioClient_Stop returned: %s\n", mp_HRESULT_to_str(hr)); - - // we may get S_FALSE if the stream is already reset - hr = IAudioClient_Reset(state->pAudioClient); - if (hr != S_OK && hr != S_FALSE) - MP_ERR(state, "IAudioClient_Reset returned: %s\n", mp_HRESULT_to_str(hr)); + SetEvent(state->hWake); +} - atomic_store(&state->sample_count, 0); - // start feeding next wakeup if something else hasn't been requested - int expected = WASAPI_THREAD_RESET; - atomic_compare_exchange_strong(&state->thread_state, &expected, - WASAPI_THREAD_FEED); - return; +static void set_thread_state(struct ao *ao, + enum wasapi_thread_state thread_state) +{ + struct wasapi_state *state = ao->priv; + atomic_store(&state->thread_state, thread_state); + thread_wakeup(ao); } static DWORD __stdcall AudioThread(void *lpParameter) @@ -190,44 +200,38 @@ static DWORD __stdcall AudioThread(void *lpParameter) state->init_ret = wasapi_thread_init(ao); SetEvent(state->hInitDone); - if (state->init_ret != S_OK) + if (FAILED(state->init_ret)) goto exit_label; MP_DBG(ao, "Entering dispatch loop\n"); - while (true) { // watch events - HANDLE events[] = {state->hWake}; - switch (MsgWaitForMultipleObjects(MP_ARRAY_SIZE(events), events, - FALSE, INFINITE, - QS_POSTMESSAGE | QS_SENDMESSAGE)) { - // AudioThread wakeup - case WAIT_OBJECT_0: - switch (atomic_load(&state->thread_state)) { - case WASAPI_THREAD_FEED: - thread_feed(ao); - break; - case WASAPI_THREAD_RESET: - thread_reset(ao); - break; - case WASAPI_THREAD_RESUME: - thread_reset(ao); - thread_resume(ao); - break; - case WASAPI_THREAD_SHUTDOWN: - thread_reset(ao); - goto exit_label; - default: - MP_ERR(ao, "Unhandled thread state\n"); - goto exit_label; - } + while (true) { + if (WaitForSingleObject(state->hWake, INFINITE) != WAIT_OBJECT_0) + MP_ERR(ao, "Unexpected return value from WaitForSingleObject\n"); + + mp_dispatch_queue_process(state->dispatch, 0); + + int thread_state = atomic_load(&state->thread_state); + switch (thread_state) { + case WASAPI_THREAD_FEED: + // fill twice on under-full buffer (see comment in thread_feed) + if (thread_feed(ao) && thread_feed(ao)) + MP_ERR(ao, "Unable to fill buffer fast enough\n"); break; - // messages to dispatch (COM marshalling) - case (WAIT_OBJECT_0 + MP_ARRAY_SIZE(events)): - wasapi_dispatch(ao); + case WASAPI_THREAD_RESET: + thread_reset(ao); break; - default: - MP_ERR(ao, "Unhandled thread event\n"); + case WASAPI_THREAD_RESUME: + thread_resume(ao); + break; + case WASAPI_THREAD_SHUTDOWN: + thread_reset(ao); goto exit_label; + default: + MP_ERR(ao, "Unhandled thread state: %d\n", thread_state); } + // the default is to feed unless something else is requested + atomic_compare_exchange_strong(&state->thread_state, &thread_state, + WASAPI_THREAD_FEED); } exit_label: wasapi_thread_uninit(ao); @@ -237,28 +241,18 @@ exit_label: return 0; } -static void set_thread_state(struct ao *ao, - enum wasapi_thread_state thread_state) -{ - struct wasapi_state *state = ao->priv; - atomic_store(&state->thread_state, thread_state); - SetEvent(state->hWake); -} - static void uninit(struct ao *ao) { MP_DBG(ao, "Uninit wasapi\n"); struct wasapi_state *state = ao->priv; - wasapi_release_proxies(state); if (state->hWake) set_thread_state(ao, WASAPI_THREAD_SHUTDOWN); - // wait up to 10 seconds if (state->hAudioThread && - WaitForSingleObject(state->hAudioThread, 10000) == WAIT_TIMEOUT) + WaitForSingleObject(state->hAudioThread, INFINITE) != WAIT_OBJECT_0) { - MP_ERR(ao, "Audio loop thread refuses to abort\n"); - return; + MP_ERR(ao, "Unexpected return value from WaitForSingleObject " + "while waiting for audio thread to terminate\n"); } SAFE_RELEASE(state->hInitDone, CloseHandle(state->hInitDone)); @@ -281,7 +275,7 @@ static int init(struct ao *ao) struct wasapi_state *state = ao->priv; state->log = ao->log; - state->deviceID = find_deviceID(ao); + state->deviceID = wasapi_find_deviceID(ao); if (!state->deviceID) { uninit(ao); return -1; @@ -292,102 +286,95 @@ static int init(struct ao *ao) state->hInitDone = CreateEventW(NULL, FALSE, FALSE, NULL); state->hWake = CreateEventW(NULL, FALSE, FALSE, NULL); if (!state->hInitDone || !state->hWake) { - MP_ERR(ao, "Error creating events\n"); + MP_FATAL(ao, "Error creating events\n"); uninit(ao); return -1; } + state->dispatch = mp_dispatch_create(state); + mp_dispatch_set_wakeup_fn(state->dispatch, thread_wakeup, ao); + state->init_ret = E_FAIL; state->hAudioThread = CreateThread(NULL, 0, &AudioThread, ao, 0, NULL); if (!state->hAudioThread) { - MP_ERR(ao, "Failed to create audio thread\n"); + MP_FATAL(ao, "Failed to create audio thread\n"); uninit(ao); return -1; } WaitForSingleObject(state->hInitDone, INFINITE); // wait on init complete SAFE_RELEASE(state->hInitDone,CloseHandle(state->hInitDone)); - if (state->init_ret != S_OK) { + if (FAILED(state->init_ret)) { if (!ao->probing) - MP_ERR(ao, "Received failure from audio thread\n"); + MP_FATAL(ao, "Received failure from audio thread\n"); uninit(ao); return -1; } - wasapi_receive_proxies(state); MP_DBG(ao, "Init wasapi done\n"); return 0; } -static int control_exclusive(struct ao *ao, enum aocontrol cmd, void *arg) +static int thread_control_exclusive(struct ao *ao, enum aocontrol cmd, void *arg) { struct wasapi_state *state = ao->priv; + if (!state->pEndpointVolume) + return CONTROL_UNKNOWN; switch (cmd) { case AOCONTROL_GET_VOLUME: case AOCONTROL_SET_VOLUME: - if (!state->pEndpointVolumeProxy || - !(state->vol_hw_support & ENDPOINT_HARDWARE_SUPPORT_VOLUME)) { + if (!(state->vol_hw_support & ENDPOINT_HARDWARE_SUPPORT_VOLUME)) return CONTROL_FALSE; - } - - float volume; - switch (cmd) { - case AOCONTROL_GET_VOLUME: - IAudioEndpointVolume_GetMasterVolumeLevelScalar( - state->pEndpointVolumeProxy, - &volume); - *(ao_control_vol_t *)arg = (ao_control_vol_t){ - .left = 100.0f * volume, - .right = 100.0f * volume, - }; - return CONTROL_OK; - case AOCONTROL_SET_VOLUME: - volume = ((ao_control_vol_t *)arg)->left / 100.f; - IAudioEndpointVolume_SetMasterVolumeLevelScalar( - state->pEndpointVolumeProxy, - volume, NULL); - return CONTROL_OK; - } + break; case AOCONTROL_GET_MUTE: case AOCONTROL_SET_MUTE: - if (!state->pEndpointVolumeProxy || - !(state->vol_hw_support & ENDPOINT_HARDWARE_SUPPORT_MUTE)) { + if (!(state->vol_hw_support & ENDPOINT_HARDWARE_SUPPORT_MUTE)) return CONTROL_FALSE; - } - - BOOL mute; - switch (cmd) { - case AOCONTROL_GET_MUTE: - IAudioEndpointVolume_GetMute(state->pEndpointVolumeProxy, - &mute); - *(bool *)arg = mute; - return CONTROL_OK; - case AOCONTROL_SET_MUTE: - mute = *(bool *)arg; - IAudioEndpointVolume_SetMute(state->pEndpointVolumeProxy, - mute, NULL); - return CONTROL_OK; - } + break; case AOCONTROL_HAS_PER_APP_VOLUME: return CONTROL_FALSE; - default: - return CONTROL_UNKNOWN; } + + float volume; + BOOL mute; + switch (cmd) { + case AOCONTROL_GET_VOLUME: + IAudioEndpointVolume_GetMasterVolumeLevelScalar( + state->pEndpointVolume, &volume); + *(ao_control_vol_t *)arg = (ao_control_vol_t){ + .left = 100.0f * volume, + .right = 100.0f * volume, + }; + return CONTROL_OK; + case AOCONTROL_SET_VOLUME: + volume = ((ao_control_vol_t *)arg)->left / 100.f; + IAudioEndpointVolume_SetMasterVolumeLevelScalar( + state->pEndpointVolume, volume, NULL); + return CONTROL_OK; + case AOCONTROL_GET_MUTE: + IAudioEndpointVolume_GetMute(state->pEndpointVolume, &mute); + *(bool *)arg = mute; + return CONTROL_OK; + case AOCONTROL_SET_MUTE: + mute = *(bool *)arg; + IAudioEndpointVolume_SetMute(state->pEndpointVolume, mute, NULL); + return CONTROL_OK; + } + return CONTROL_UNKNOWN; } -static int control_shared(struct ao *ao, enum aocontrol cmd, void * |