1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 02:17:35 +00:00

Work on AudioServer

The center of this is now an ABuffer class in LibAudio.
ABuffer contains ASample, which has two channels (left/right) in
floating point for mixing purposes, in 44100hz.

This means that the loaders (AWavLoader in this case) needs to do some
manipulation to get things in the right format, but that we don't need
to care after format loading is done.

While we're at it, do some correctness fixes. PCM data is unsigned if
it's 8 bit, but 16 bit is signed. And /dev/audio also wants signed 16
bit audio, so give it what it wants.

On top of this, AudioServer now accepts requests to play a buffer.
The IPC mechanism here is pretty much a 1:1 copy-paste from
LibGUI/WindowServer. It can be generalized more in the future, but for
now I want to get AudioServer working decently first :)

Additionally, add a little "aplay" tool to load and play a WAV file. It
will break with large WAVs (run out of memory, heh...) but it's a start.

Future work needs to make AudioServer block buffer submission from
clients until it has played the buffer they are requesting to play.
This commit is contained in:
Robin Burchell 2019-07-15 12:54:52 +02:00 committed by Andreas Kling
parent 3db9706e57
commit 2df6f0e87f
19 changed files with 873 additions and 141 deletions

View file

@ -0,0 +1,68 @@
#pragma once
#include <AK/RefCounted.h>
#include <AK/ByteBuffer.h>
#include <AK/Types.h>
#include <AK/Vector.h>
// A single sample in an audio buffer.
// Values are floating point, and should range from -1.0 to +1.0
struct ASample {
ASample()
: left(0)
, right(0)
{}
// For mono
ASample(float left)
: left(left)
, right(left)
{}
// For stereo
ASample(float left, float right)
: left(left)
, right(right)
{}
void clamp()
{
if (left > 1)
left = 1;
else if (left < -1)
left = -1;
if (right > 1)
right = 1;
else if (right < -1)
right = -1;
}
ASample& operator+=(const ASample& other)
{
left += other.left;
right += other.right;
return *this;
}
float left;
float right;
};
// A buffer of audio samples, normalized to 44100hz.
class ABuffer : public RefCounted<ABuffer> {
public:
static RefPtr<ABuffer> from_pcm_data(ByteBuffer& data, int num_channels, int bits_per_sample, int source_rate);
ABuffer(Vector<ASample>& samples)
: m_samples(samples)
{}
const Vector<ASample>& samples() const { return m_samples; }
Vector<ASample>& samples() { return m_samples; }
const void* data() const { return m_samples.data(); }
int size_in_bytes() const { return m_samples.size() * sizeof(ASample); }
private:
Vector<ASample> m_samples;
};

View file

@ -1,13 +1,30 @@
#include "AClientConnection.h"
#include "ABuffer.h"
#include <SharedBuffer.h>
#include <LibCore/CEventLoop.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/uio.h>
AClientConnection::AClientConnection()
: m_notifier(CNotifier(m_connection.fd(), CNotifier::Read))
{
// We want to rate-limit our clients
m_connection.set_blocking(true);
m_notifier.on_ready_to_read = [this] {
drain_messages_from_server();
};
m_connection.on_connected = [this] {
m_notifier = make<CNotifier>(m_connection.fd(), CNotifier::Read);
m_notifier->on_ready_to_read = [this] { printf("AudioServer said something to us"); };
m_connection.write("Hello, friends");
ASAPI_ClientMessage request;
request.type = ASAPI_ClientMessage::Type::Greeting;
request.greeting.client_pid = getpid();
auto response = sync_request(request, ASAPI_ServerMessage::Type::Greeting);
m_server_pid = response.greeting.server_pid;
m_my_client_id = response.greeting.your_client_id;
dbg() << "**** C: Got greeting from AudioServer: client ID " << m_my_client_id << " PID " << m_server_pid;
};
int retries = 1000;
@ -17,10 +34,121 @@ AClientConnection::AClientConnection()
}
#ifdef ACLIENT_DEBUG
dbgprintf("AClientConnection: connect failed: %d, %s\n", errno, strerror(errno));
dbgprintf("**** C: AClientConnection: connect failed: %d, %s\n", errno, strerror(errno));
#endif
sleep(1);
--retries;
}
}
bool AClientConnection::drain_messages_from_server()
{
for (;;) {
ASAPI_ServerMessage message;
ssize_t nread = recv(m_connection.fd(), &message, sizeof(ASAPI_ServerMessage), MSG_DONTWAIT);
if (nread < 0) {
if (errno == EAGAIN) {
return true;
}
perror("read");
exit(1);
return false;
}
if (nread == 0) {
dbgprintf("EOF on IPC fd\n");
exit(1);
exit(-1);
return false;
}
ASSERT(nread == sizeof(message));
ByteBuffer extra_data;
if (message.extra_size) {
extra_data = ByteBuffer::create_uninitialized(message.extra_size);
int extra_nread = read(m_connection.fd(), extra_data.data(), extra_data.size());
if (extra_nread < 0) {
perror("read");
ASSERT_NOT_REACHED();
}
ASSERT((size_t)extra_nread == message.extra_size);
}
m_unprocessed_bundles.append({ move(message), move(extra_data) });
}
}
bool AClientConnection::wait_for_specific_event(ASAPI_ServerMessage::Type type, ASAPI_ServerMessage& event)
{
for (;;) {
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(m_connection.fd(), &rfds);
int rc = select(m_connection.fd() + 1, &rfds, nullptr, nullptr, nullptr);
if (rc < 0) {
perror("select");
}
ASSERT(rc > 0);
ASSERT(FD_ISSET(m_connection.fd(), &rfds));
bool success = drain_messages_from_server();
if (!success)
return false;
for (ssize_t i = 0; i < m_unprocessed_bundles.size(); ++i) {
if (m_unprocessed_bundles[i].message.type == type) {
event = move(m_unprocessed_bundles[i].message);
m_unprocessed_bundles.remove(i);
return true;
}
}
}
}
bool AClientConnection::post_message_to_server(const ASAPI_ClientMessage& message, const ByteBuffer& extra_data)
{
if (!extra_data.is_empty())
const_cast<ASAPI_ClientMessage&>(message).extra_size = extra_data.size();
struct iovec iov[2];
int iov_count = 1;
iov[0].iov_base = const_cast<ASAPI_ClientMessage*>(&message);
iov[0].iov_len = sizeof(message);
if (!extra_data.is_empty()) {
iov[1].iov_base = const_cast<u8*>(extra_data.data());
iov[1].iov_len = extra_data.size();
++iov_count;
}
int nwritten = writev(m_connection.fd(), iov, iov_count);
if (nwritten < 0) {
perror("writev");
ASSERT_NOT_REACHED();
}
ASSERT((size_t)nwritten == sizeof(message) + extra_data.size());
return true;
}
ASAPI_ServerMessage AClientConnection::sync_request(const ASAPI_ClientMessage& request, ASAPI_ServerMessage::Type response_type)
{
bool success = post_message_to_server(request);
ASSERT(success);
ASAPI_ServerMessage response;
success = wait_for_specific_event(response_type, response);
ASSERT(success);
return response;
}
void AClientConnection::play(const ABuffer& buffer)
{
auto shared_buf = SharedBuffer::create(m_server_pid, buffer.size_in_bytes());
if (!shared_buf) {
dbg() << "Failed to create a shared buffer!";
return;
}
memcpy(shared_buf->data(), buffer.data(), buffer.size_in_bytes());
shared_buf->seal();
ASAPI_ClientMessage request;
request.type = ASAPI_ClientMessage::Type::PlayBuffer;
request.play_buffer.buffer_id = shared_buf->shared_buffer_id();
sync_request(request, ASAPI_ServerMessage::Type::PlayingBuffer);
}

View file

@ -2,12 +2,29 @@
#include <LibCore/CLocalSocket.h>
#include <LibCore/CNotifier.h>
#include <LibAudio/ASAPI.h>
class ABuffer;
class AClientConnection {
public:
AClientConnection();
void play(const ABuffer& buffer);
private:
bool drain_messages_from_server();
bool wait_for_specific_event(ASAPI_ServerMessage::Type type, ASAPI_ServerMessage& event);
bool post_message_to_server(const ASAPI_ClientMessage& message, const ByteBuffer& extra_data = {});
ASAPI_ServerMessage sync_request(const ASAPI_ClientMessage& request, ASAPI_ServerMessage::Type response_type);
CLocalSocket m_connection;
OwnPtr<CNotifier> m_notifier;
CNotifier m_notifier;
struct IncomingASMessageBundle {
ASAPI_ServerMessage message;
ByteBuffer extra_data;
};
Vector<IncomingASMessageBundle> m_unprocessed_bundles;
int m_server_pid;
int m_my_client_id;
};

View file

@ -0,0 +1,42 @@
#pragma once
struct ASAPI_ServerMessage {
enum class Type {
Invalid,
Greeting,
PlayingBuffer,
};
Type type { Type::Invalid };
unsigned extra_size { 0 };
union {
struct {
int server_pid;
int your_client_id;
} greeting;
struct {
int buffer_id;
} playing_buffer;
};
};
struct ASAPI_ClientMessage {
enum class Type {
Invalid,
Greeting,
PlayBuffer,
};
Type type { Type::Invalid };
unsigned extra_size { 0 };
union {
struct {
int client_pid;
} greeting;
struct {
int buffer_id;
} play_buffer;
};
};

View file

@ -1,2 +0,0 @@
#include "AWavFile.h"

View file

@ -1,32 +0,0 @@
#pragma once
#include <AK/RefCounted.h>
#include <AK/ByteBuffer.h>
#include <AK/Types.h>
class AWavFile : public RefCounted<AWavFile> {
public:
enum class Format {
Invalid,
PCM,
};
Format format() const { return m_format; }
u16 channel_count() const { return m_channel_count; }
u32 sample_rate_per_second() const { return m_sample_rate; }
u32 average_byte_rate_per_second() const { return m_byte_rate; }
u16 block_align() const { return m_block_align; }
u16 bits_per_sample() const { return m_bits_per_sample; }
const ByteBuffer& sample_data() const { return m_sample_data; }
private:
Format m_format = Format::Invalid;
u16 m_channel_count = 0;
u32 m_sample_rate = 0;
u32 m_byte_rate = 0;
u16 m_block_align = 0;
u16 m_bits_per_sample = 0;
ByteBuffer m_sample_data;
friend class AWavLoader;
};

View file

@ -3,9 +3,9 @@
#include <limits>
#include "AWavLoader.h"
#include "AWavFile.h"
#include "ABuffer.h"
RefPtr<AWavFile> AWavLoader::load_wav(const StringView& path)
RefPtr<ABuffer> AWavLoader::load_wav(const StringView& path)
{
m_error_string = {};
@ -20,7 +20,7 @@ RefPtr<AWavFile> AWavLoader::load_wav(const StringView& path)
}
// TODO: A streaming parser might be better than forcing a ByteBuffer
RefPtr<AWavFile> AWavLoader::parse_wav(ByteBuffer& buffer)
RefPtr<ABuffer> AWavLoader::parse_wav(ByteBuffer& buffer)
{
BufferStream stream(buffer);
@ -62,36 +62,30 @@ RefPtr<AWavFile> AWavLoader::parse_wav(ByteBuffer& buffer)
CHECK_OK("FMT size");
ASSERT(fmt_size == 16);
auto ret = adopt(*new AWavFile);
u16 audio_format; stream >> audio_format;
CHECK_OK("Audio format"); // incomplete read check
ok = ok && audio_format == 1; // WAVE_FORMAT_PCM
ASSERT(audio_format == 1);
CHECK_OK("Audio format"); // value check
ret->m_format = AWavFile::Format::PCM;
u16 num_channels; stream >> num_channels;
ok = ok && (num_channels == 1 || num_channels == 2);
CHECK_OK("Channel count");
ret->m_channel_count = num_channels;
u32 sample_rate; stream >> sample_rate;
CHECK_OK("Sample rate");
ret->m_sample_rate = sample_rate;
u32 byte_rate; stream >> byte_rate;
CHECK_OK("Byte rate");
ret->m_byte_rate = byte_rate;
u16 block_align; stream >> block_align;
CHECK_OK("Block align");
ret->m_block_align = block_align;
u16 bits_per_sample; stream >> bits_per_sample;
CHECK_OK("Bits per sample"); // incomplete read check
ok = ok && (bits_per_sample == 8 || bits_per_sample == 16);
ASSERT(bits_per_sample == 8 || bits_per_sample == 16);
CHECK_OK("Bits per sample"); // value check
ret->m_bits_per_sample = bits_per_sample;
// Read chunks until we find DATA
bool found_data = false;
@ -118,10 +112,110 @@ RefPtr<AWavFile> AWavLoader::parse_wav(ByteBuffer& buffer)
ok = ok && int(data_sz) <= (buffer.size() - stream.offset());
CHECK_OK("Bad DATA (truncated)");
ret->m_sample_data = buffer.slice(stream.offset(), data_sz);
// At this point there should be no read failures!
// Just make sure we're good before we read the data...
ASSERT(!stream.handle_read_failure());
return ret;
auto sample_data = buffer.slice(stream.offset(), data_sz);
dbgprintf("Read WAV of format PCM with num_channels %d sample rate %d, bits per sample %d\n", num_channels, sample_rate, bits_per_sample);
return ABuffer::from_pcm_data(sample_data, num_channels, bits_per_sample, sample_rate);
}
// Small helper to resample from one playback rate to another
// This isn't really "smart", in that we just insert (or drop) samples.
// Should do better...
class AResampleHelper {
public:
AResampleHelper(float source, float target);
bool read_sample();
void prepare();
private:
const float m_ratio;
float m_current_ratio { 0 };
};
AResampleHelper::AResampleHelper(float source, float target)
: m_ratio(source / target)
{
}
void AResampleHelper::prepare()
{
m_current_ratio += m_ratio;
}
bool AResampleHelper::read_sample()
{
if (m_current_ratio > 1) {
m_current_ratio--;
return true;
}
return false;
}
template <typename T>
static void read_samples_from_stream(BufferStream& stream, Vector<ASample>& samples, int num_channels, int source_rate)
{
AResampleHelper resampler(source_rate, 44100);
T sample = 0;
float norm_l = 0;
float norm_r = 0;
switch (num_channels) {
case 1:
while (!stream.handle_read_failure()) {
resampler.prepare();
while (resampler.read_sample()) {
stream >> sample;
norm_l = float(sample) / std::numeric_limits<T>::max();
}
samples.append(ASample(norm_l));
}
break;
case 2:
while (!stream.handle_read_failure()) {
resampler.prepare();
while (resampler.read_sample()) {
stream >> sample;
norm_l = float(sample) / std::numeric_limits<T>::max();
stream >> sample;
norm_r = float(sample) / std::numeric_limits<T>::max();
}
samples.append(ASample(norm_l, norm_r));
}
break;
default:
ASSERT_NOT_REACHED();
}
}
// ### can't const this because BufferStream is non-const
// perhaps we need a reading class separate from the writing one, that can be
// entirely consted.
RefPtr<ABuffer> ABuffer::from_pcm_data(ByteBuffer& data, int num_channels, int bits_per_sample, int source_rate)
{
BufferStream stream(data);
Vector<ASample> fdata;
fdata.ensure_capacity(data.size() * 2);
dbg() << "Reading " << bits_per_sample << " bits and " << num_channels << " channels, total bytes: " << data.size();
switch (bits_per_sample) {
case 8:
read_samples_from_stream<u8>(stream, fdata, num_channels, source_rate);
break;
case 16:
read_samples_from_stream<i16>(stream, fdata, num_channels, source_rate);
break;
default:
ASSERT_NOT_REACHED();
}
// We should handle this in a better way above, but for now --
// just make sure we're good. Worst case we just write some 0s where they
// don't belong.
ASSERT(!stream.handle_read_failure());
return adopt(*new ABuffer(fdata));
}

View file

@ -1,14 +1,18 @@
#pragma once
#include <AK/RefPtr.h>
#include <AK/StringView.h>
#include <AK/AKString.h>
class AWavFile;
class ABuffer;
class ByteBuffer;
// Parses a WAV file and produces an ABuffer instance from it
class AWavLoader {
public:
RefPtr<AWavFile> load_wav(const StringView& path);
RefPtr<ABuffer> load_wav(const StringView& path);
const char* error_string() { return m_error_string.characters(); }
private:
RefPtr<AWavFile> parse_wav(ByteBuffer& buffer);
RefPtr<ABuffer> parse_wav(ByteBuffer& buffer);
String m_error_string;
};

View file

@ -2,7 +2,6 @@ include ../../Makefile.common
OBJS = \
AClientConnection.o \
AWavFile.o \
AWavLoader.o
LIBRARY = libaudio.a