mpd/src/output/OutputThread.cxx

713 lines
14 KiB
C++
Raw Normal View History

/*
2016-02-26 17:54:05 +01:00
* Copyright 2003-2016 The Music Player Daemon Project
* http://www.musicpd.org
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "config.h"
2014-01-28 11:42:54 +01:00
#include "Internal.hxx"
2013-07-30 08:34:10 +02:00
#include "OutputAPI.hxx"
2014-01-28 11:42:54 +01:00
#include "Domain.hxx"
2013-04-09 01:24:52 +02:00
#include "pcm/PcmMix.hxx"
#include "pcm/Domain.hxx"
2013-01-10 10:44:04 +01:00
#include "notify.hxx"
2014-01-24 16:31:52 +01:00
#include "filter/FilterInternal.hxx"
#include "filter/plugins/ConvertFilterPlugin.hxx"
#include "filter/plugins/ReplayGainFilterPlugin.hxx"
#include "mixer/MixerInternal.hxx"
#include "mixer/plugins/SoftwareMixerPlugin.hxx"
2015-08-15 15:55:46 +02:00
#include "player/Control.hxx"
2013-01-04 10:16:16 +01:00
#include "MusicPipe.hxx"
#include "MusicChunk.hxx"
2014-01-14 09:59:04 +01:00
#include "thread/Util.hxx"
#include "thread/Slack.hxx"
#include "thread/Name.hxx"
#include "util/Error.hxx"
#include "util/ConstBuffer.hxx"
#include "Log.hxx"
2013-10-15 09:21:13 +02:00
#include "Compiler.h"
2016-09-04 15:11:01 +02:00
#include <stdexcept>
#include <assert.h>
2013-07-30 20:11:57 +02:00
#include <string.h>
2009-02-25 19:53:38 +01:00
void
AudioOutput::CommandFinished()
{
assert(command != Command::NONE);
command = Command::NONE;
mutex.unlock();
2013-01-10 10:44:04 +01:00
audio_output_client_notify.Signal();
mutex.lock();
}
inline bool
AudioOutput::Enable()
{
if (really_enabled)
return true;
mutex.unlock();
Error error;
bool success = ao_plugin_enable(this, error);
mutex.lock();
if (!success) {
FormatError(error,
"Failed to enable \"%s\" [%s]",
name, plugin.name);
return false;
}
really_enabled = true;
return true;
}
inline void
AudioOutput::Disable()
{
if (open)
Close(false);
if (really_enabled) {
really_enabled = false;
mutex.unlock();
ao_plugin_disable(this);
mutex.lock();
}
}
inline AudioFormat
AudioOutput::OpenFilter(AudioFormat &format)
try {
2013-08-03 21:00:50 +02:00
assert(format.IsValid());
/* the replay_gain filter cannot fail here */
if (prepared_replay_gain_filter != nullptr)
replay_gain_filter_instance =
prepared_replay_gain_filter->Open(format);
if (prepared_other_replay_gain_filter != nullptr)
other_replay_gain_filter_instance =
prepared_other_replay_gain_filter->Open(format);
filter_instance = prepared_filter->Open(format);
if (mixer != nullptr && mixer->IsPlugin(software_mixer_plugin))
software_mixer_set_filter(*mixer, volume_filter.Get());
return filter_instance->GetOutAudioFormat();
} catch (...) {
CloseFilter();
throw;
}
void
AudioOutput::CloseFilter()
{
if (mixer != nullptr && mixer->IsPlugin(software_mixer_plugin))
software_mixer_set_filter(*mixer, nullptr);
delete replay_gain_filter_instance;
replay_gain_filter_instance = nullptr;
delete other_replay_gain_filter_instance;
other_replay_gain_filter_instance = nullptr;
delete filter_instance;
filter_instance = nullptr;
}
inline void
AudioOutput::Open()
{
bool success;
Error error;
struct audio_format_string af_string;
assert(!open);
assert(pipe != nullptr);
assert(current_chunk == nullptr);
assert(in_audio_format.IsValid());
fail_timer.Reset();
/* enable the device (just in case the last enable has failed) */
if (!Enable())
/* still no luck */
return;
/* open the filter */
AudioFormat filter_audio_format;
try {
filter_audio_format = OpenFilter(in_audio_format);
} catch (const std::runtime_error &e) {
FormatError(e, "Failed to open filter for \"%s\" [%s]",
name, plugin.name);
fail_timer.Update();
return;
}
2013-08-03 21:00:50 +02:00
assert(filter_audio_format.IsValid());
out_audio_format = filter_audio_format;
out_audio_format.ApplyMask(config_audio_format);
mutex.unlock();
const AudioFormat retry_audio_format = out_audio_format;
retry_without_dsd:
success = ao_plugin_open(this, out_audio_format, error);
mutex.lock();
assert(!open);
if (!success) {
FormatError(error, "Failed to open \"%s\" [%s]",
name, plugin.name);
mutex.unlock();
CloseFilter();
mutex.lock();
fail_timer.Update();
return;
}
try {
convert_filter_set(convert_filter.Get(), out_audio_format);
} catch (const std::runtime_error &e) {
FormatError(e, "Failed to convert for \"%s\" [%s]",
name, plugin.name);
mutex.unlock();
ao_plugin_close(this);
if (error.IsDomain(pcm_domain) &&
out_audio_format.format == SampleFormat::DSD) {
/* if the audio output supports DSD, but not
the given sample rate, it asks MPD to
resample; resampling DSD however is not
implemented; our last resort is to give up
DSD and fall back to PCM */
// TODO: clean up this workaround
FormatError(output_domain, "Retrying without DSD");
out_audio_format = retry_audio_format;
out_audio_format.format = SampleFormat::FLOAT;
/* clear the Error to allow reusing it */
error.Clear();
/* sorry for the "goto" - this is a workaround
for the stable branch that should be as
unintrusive as possible */
goto retry_without_dsd;
}
CloseFilter();
mutex.lock();
fail_timer.Update();
return;
}
open = true;
FormatDebug(output_domain,
"opened plugin=%s name=\"%s\" audio_format=%s",
plugin.name, name,
audio_format_to_string(out_audio_format, &af_string));
if (in_audio_format != out_audio_format)
FormatDebug(output_domain, "converting from %s",
audio_format_to_string(in_audio_format,
&af_string));
}
void
AudioOutput::Close(bool drain)
{
assert(open);
pipe = nullptr;
current_chunk = nullptr;
open = false;
mutex.unlock();
CloseOutput(drain);
CloseFilter();
mutex.lock();
FormatDebug(output_domain, "closed plugin=%s name=\"%s\"",
plugin.name, name);
}
inline void
AudioOutput::CloseOutput(bool drain)
{
if (drain)
ao_plugin_drain(this);
else
ao_plugin_cancel(this);
ao_plugin_close(this);
}
void
AudioOutput::ReopenFilter()
{
Error error;
mutex.unlock();
CloseFilter();
mutex.lock();
AudioFormat filter_audio_format;
try {
filter_audio_format = OpenFilter(in_audio_format);
convert_filter_set(convert_filter.Get(), out_audio_format);
} catch (const std::runtime_error &e) {
FormatError(e,
"Failed to open filter for \"%s\" [%s]",
name, plugin.name);
Close(false);
return;
}
}
void
AudioOutput::Reopen()
{
if (!config_audio_format.IsFullyDefined()) {
if (open) {
const MusicPipe *mp = pipe;
Close(true);
pipe = mp;
}
/* no audio format is configured: copy in->out, let
the output's open() method determine the effective
out_audio_format */
out_audio_format = in_audio_format;
out_audio_format.ApplyMask(config_audio_format);
}
if (open)
/* the audio format has changed, and all filters have
to be reconfigured */
ReopenFilter();
else
Open();
}
/**
* Wait until the output's delay reaches zero.
*
* @return true if playback should be continued, false if a command
* was issued
*/
inline bool
AudioOutput::WaitForDelay()
{
while (true) {
unsigned delay = ao_plugin_delay(this);
if (delay == 0)
return true;
(void)cond.timed_wait(mutex, delay);
if (command != Command::NONE)
return false;
}
}
static ConstBuffer<void>
ao_chunk_data(AudioOutput *ao, const MusicChunk *chunk,
Filter *replay_gain_filter,
unsigned *replay_gain_serial_p)
{
2013-10-19 18:19:03 +02:00
assert(chunk != nullptr);
2013-01-04 21:38:46 +01:00
assert(!chunk->IsEmpty());
assert(chunk->CheckFormat(ao->in_audio_format));
ConstBuffer<void> data(chunk->data, chunk->length);
(void)ao;
assert(data.size % ao->in_audio_format.GetFrameSize() == 0);
if (!data.IsEmpty() && replay_gain_filter != nullptr) {
replay_gain_filter_set_mode(replay_gain_filter,
ao->replay_gain_mode);
if (chunk->replay_gain_serial != *replay_gain_serial_p) {
replay_gain_filter_set_info(replay_gain_filter,
chunk->replay_gain_serial != 0
? &chunk->replay_gain_info
2013-10-19 18:19:03 +02:00
: nullptr);
*replay_gain_serial_p = chunk->replay_gain_serial;
}
try {
data = replay_gain_filter->FilterPCM(data);
} catch (const std::runtime_error &e) {
FormatError(e, "\"%s\" [%s] failed to filter",
2014-01-29 00:53:49 +01:00
ao->name, ao->plugin.name);
return nullptr;
}
}
return data;
}
static ConstBuffer<void>
ao_filter_chunk(AudioOutput *ao, const MusicChunk *chunk)
{
ConstBuffer<void> data =
ao_chunk_data(ao, chunk, ao->replay_gain_filter_instance,
&ao->replay_gain_serial);
if (data.IsEmpty())
return data;
/* cross-fade */
2013-10-19 18:19:03 +02:00
if (chunk->other != nullptr) {
ConstBuffer<void> other_data =
ao_chunk_data(ao, chunk->other,
ao->other_replay_gain_filter_instance,
&ao->other_replay_gain_serial);
if (other_data.IsNull())
2013-10-19 18:19:03 +02:00
return nullptr;
if (other_data.IsEmpty())
return data;
/* if the "other" chunk is longer, then that trailer
is used as-is, without mixing; it is part of the
"next" song being faded in, and if there's a rest,
it means cross-fading ends here */
if (data.size > other_data.size)
data.size = other_data.size;
2014-09-24 21:49:20 +02:00
float mix_ratio = chunk->mix_ratio;
if (mix_ratio >= 0)
/* reverse the mix ratio (because the
arguments to pcm_mix() are reversed), but
only if the mix ratio is non-negative; a
negative mix ratio is a MixRamp special
case */
mix_ratio = 1.0 - mix_ratio;
void *dest = ao->cross_fade_buffer.Get(other_data.size);
memcpy(dest, other_data.data, other_data.size);
if (!pcm_mix(ao->cross_fade_dither, dest, data.data, data.size,
2013-08-03 21:00:50 +02:00
ao->in_audio_format.format,
2014-09-24 21:49:20 +02:00
mix_ratio)) {
FormatError(output_domain,
"Cannot cross-fade format %s",
sample_format_to_string(ao->in_audio_format.format));
2013-10-19 18:19:03 +02:00
return nullptr;
}
data.data = dest;
data.size = other_data.size;
}
/* apply filter chain */
try {
return ao->filter_instance->FilterPCM(data);
} catch (const std::runtime_error &e) {
FormatError(e, "\"%s\" [%s] failed to filter",
2014-01-29 00:53:49 +01:00
ao->name, ao->plugin.name);
2013-10-19 18:19:03 +02:00
return nullptr;
}
}
inline bool
AudioOutput::PlayChunk(const MusicChunk *chunk)
{
assert(filter_instance != nullptr);
if (tags && gcc_unlikely(chunk->tag != nullptr)) {
mutex.unlock();
ao_plugin_send_tag(this, *chunk->tag);
mutex.lock();
}
auto data = ConstBuffer<char>::FromVoid(ao_filter_chunk(this, chunk));
if (data.IsNull()) {
Close(false);
/* don't automatically reopen this device for 10
seconds */
fail_timer.Update();
return false;
}
Error error;
while (!data.IsEmpty() && command == Command::NONE) {
if (!WaitForDelay())
break;
mutex.unlock();
size_t nbytes = ao_plugin_play(this, data.data, data.size,
error);
mutex.lock();
if (nbytes == 0) {
/* play()==0 means failure */
FormatError(error, "\"%s\" [%s] failed to play",
name, plugin.name);
Close(false);
/* don't automatically reopen this device for
10 seconds */
assert(!fail_timer.IsDefined());
fail_timer.Update();
return false;
}
assert(nbytes <= data.size);
assert(nbytes % out_audio_format.GetFrameSize() == 0);
data.data += nbytes;
data.size -= nbytes;
}
return true;
}
inline const MusicChunk *
AudioOutput::GetNextChunk() const
{
return current_chunk != nullptr
/* continue the previous play() call */
? current_chunk->next
/* get the first chunk from the pipe */
: pipe->Peek();
}
inline bool
AudioOutput::Play()
{
assert(pipe != nullptr);
const MusicChunk *chunk = GetNextChunk();
2013-10-19 18:19:03 +02:00
if (chunk == nullptr)
/* no chunk available */
return false;
current_chunk_finished = false;
assert(!in_playback_loop);
in_playback_loop = true;
while (chunk != nullptr && command == Command::NONE) {
assert(!current_chunk_finished);
current_chunk = chunk;
if (!PlayChunk(chunk)) {
assert(current_chunk == nullptr);
break;
}
assert(current_chunk == chunk);
chunk = chunk->next;
}
assert(in_playback_loop);
in_playback_loop = false;
current_chunk_finished = true;
mutex.unlock();
player_control->LockSignal();
mutex.lock();
return true;
}
inline void
AudioOutput::Pause()
{
mutex.unlock();
ao_plugin_cancel(this);
mutex.lock();
pause = true;
CommandFinished();
do {
if (!WaitForDelay())
break;
mutex.unlock();
bool success = ao_plugin_pause(this);
mutex.lock();
if (!success) {
Close(false);
break;
}
} while (command == Command::NONE);
pause = false;
}
inline void
AudioOutput::Task()
{
FormatThreadName("output:%s", name);
2016-09-04 15:11:01 +02:00
try {
SetThreadRealtime();
} catch (const std::runtime_error &e) {
LogError(e,
"OutputThread could not get realtime scheduling, continuing anyway");
}
2016-09-04 15:11:01 +02:00
SetThreadTimerSlackUS(100);
2014-01-14 09:59:04 +01:00
mutex.lock();
while (1) {
switch (command) {
case Command::NONE:
break;
case Command::ENABLE:
Enable();
CommandFinished();
break;
case Command::DISABLE:
Disable();
CommandFinished();
break;
case Command::OPEN:
Open();
CommandFinished();
break;
case Command::REOPEN:
Reopen();
CommandFinished();
break;
case Command::CLOSE:
assert(open);
assert(pipe != nullptr);
Close(false);
CommandFinished();
break;
case Command::PAUSE:
if (!open) {
/* the output has failed after
audio_output_all_pause() has
submitted the PAUSE command; bail
out */
CommandFinished();
break;
}
Pause();
/* don't "break" here: this might cause
Play() to be called when command==CLOSE
ends the paused state - "continue" checks
the new command first */
continue;
case Command::DRAIN:
if (open) {
assert(current_chunk == nullptr);
assert(pipe->Peek() == nullptr);
mutex.unlock();
ao_plugin_drain(this);
mutex.lock();
}
CommandFinished();
continue;
case Command::CANCEL:
current_chunk = nullptr;
if (open) {
mutex.unlock();
ao_plugin_cancel(this);
mutex.lock();
}
CommandFinished();
continue;
case Command::KILL:
current_chunk = nullptr;
CommandFinished();
mutex.unlock();
return;
}
if (open && allow_play && Play())
/* don't wait for an event if there are more
chunks in the pipe */
continue;
if (command == Command::NONE) {
woken_for_play = false;
cond.wait(mutex);
}
}
}
void
AudioOutput::Task(void *arg)
{
AudioOutput *ao = (AudioOutput *)arg;
ao->Task();
}
void
AudioOutput::StartThread()
{
assert(command == Command::NONE);
thread.Start(Task, this);
}