mpd/src/input/ThreadInputStream.cxx

155 lines
2.6 KiB
C++
Raw Normal View History

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright The Music Player Daemon Project
#include "ThreadInputStream.hxx"
#include "CondHandler.hxx"
#include "thread/Name.hxx"
#include <cassert>
#include <string.h>
ThreadInputStream::ThreadInputStream(const char *_plugin,
const char *_uri,
Mutex &_mutex,
2018-01-20 18:53:18 +01:00
size_t _buffer_size) noexcept
:InputStream(_uri, _mutex),
plugin(_plugin),
thread(BIND_THIS_METHOD(ThreadFunc)),
allocation(_buffer_size),
buffer(&allocation.front(), allocation.size())
{
allocation.SetName("InputStream");
allocation.ForkCow(false);
}
void
ThreadInputStream::Stop() noexcept
{
if (!thread.IsDefined())
return;
{
const std::scoped_lock<Mutex> lock(mutex);
close = true;
wake_cond.notify_one();
}
Cancel();
thread.Join();
buffer.Clear();
}
void
ThreadInputStream::Start()
{
2017-02-10 22:41:11 +01:00
thread.Start();
}
2018-01-20 18:53:18 +01:00
inline void
ThreadInputStream::ThreadFunc() noexcept
{
2014-05-11 18:25:55 +02:00
FormatThreadName("input:%s", plugin);
std::unique_lock<Mutex> lock(mutex);
try {
Open();
} catch (...) {
postponed_exception = std::current_exception();
SetReady();
return;
}
/* we're ready, tell it to our client */
SetReady();
while (!close) {
assert(!postponed_exception);
auto w = buffer.Write();
if (w.empty()) {
wake_cond.wait(lock);
} else {
size_t nbytes;
try {
const ScopeUnlock unlock(mutex);
2022-05-20 10:59:53 +02:00
nbytes = ThreadRead(w.data(), w.size());
} catch (...) {
postponed_exception = std::current_exception();
InvokeOnAvailable();
break;
}
InvokeOnAvailable();
if (nbytes == 0) {
eof = true;
break;
}
buffer.Append(nbytes);
}
}
Close();
}
void
ThreadInputStream::Check()
{
2014-10-11 21:57:31 +02:00
assert(!thread.IsInside());
if (postponed_exception)
std::rethrow_exception(postponed_exception);
}
bool
ThreadInputStream::IsAvailable() const noexcept
{
2014-10-11 21:57:31 +02:00
assert(!thread.IsInside());
return !buffer.empty() || eof || postponed_exception;
}
inline size_t
ThreadInputStream::Read(std::unique_lock<Mutex> &lock,
void *ptr, size_t read_size)
{
2014-10-11 21:57:31 +02:00
assert(!thread.IsInside());
CondInputStreamHandler cond_handler;
while (true) {
if (postponed_exception)
std::rethrow_exception(postponed_exception);
auto r = buffer.Read();
if (!r.empty()) {
2022-05-20 10:59:53 +02:00
size_t nbytes = std::min(read_size, r.size());
memcpy(ptr, r.data(), nbytes);
buffer.Consume(nbytes);
wake_cond.notify_all();
offset += nbytes;
return nbytes;
}
if (eof)
return 0;
const ScopeExchangeInputStreamHandler h(*this, &cond_handler);
cond_handler.cond.wait(lock);
}
}
bool
ThreadInputStream::IsEOF() const noexcept
{
2014-10-11 21:57:31 +02:00
assert(!thread.IsInside());
return eof;
}