diff options
author | Robin Burchell <robin+git@viroteck.net> | 2019-07-15 12:54:52 +0200 |
---|---|---|
committer | Andreas Kling <awesomekling@gmail.com> | 2019-07-17 09:39:31 +0200 |
commit | 2df6f0e87f0312f6ee5c2b8abc11729487276bd1 (patch) | |
tree | 0a89021ff86a0daef01c128ad2d33b6a4a169331 /Libraries/LibAudio | |
parent | 3db9706e57d160077f2c1b4d98efb8f5558805e4 (diff) | |
download | serenity-2df6f0e87f0312f6ee5c2b8abc11729487276bd1.zip |
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.
Diffstat (limited to 'Libraries/LibAudio')
-rw-r--r-- | Libraries/LibAudio/ABuffer.h | 68 | ||||
-rw-r--r-- | Libraries/LibAudio/AClientConnection.cpp | 136 | ||||
-rw-r--r-- | Libraries/LibAudio/AClientConnection.h | 19 | ||||
-rw-r--r-- | Libraries/LibAudio/ASAPI.h | 42 | ||||
-rw-r--r-- | Libraries/LibAudio/AWavFile.cpp | 2 | ||||
-rw-r--r-- | Libraries/LibAudio/AWavFile.h | 32 | ||||
-rw-r--r-- | Libraries/LibAudio/AWavLoader.cpp | 122 | ||||
-rw-r--r-- | Libraries/LibAudio/AWavLoader.h | 10 | ||||
-rw-r--r-- | Libraries/LibAudio/Makefile | 1 |
9 files changed, 375 insertions, 57 deletions
diff --git a/Libraries/LibAudio/ABuffer.h b/Libraries/LibAudio/ABuffer.h new file mode 100644 index 0000000000..30a3742e7d --- /dev/null +++ b/Libraries/LibAudio/ABuffer.h @@ -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; +}; + diff --git a/Libraries/LibAudio/AClientConnection.cpp b/Libraries/LibAudio/AClientConnection.cpp index 002cc22fca..8cb3009564 100644 --- a/Libraries/LibAudio/AClientConnection.cpp +++ b/Libraries/LibAudio/AClientConnection.cpp @@ -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); +} diff --git a/Libraries/LibAudio/AClientConnection.h b/Libraries/LibAudio/AClientConnection.h index 7df832babc..5ef369d942 100644 --- a/Libraries/LibAudio/AClientConnection.h +++ b/Libraries/LibAudio/AClientConnection.h @@ -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; }; diff --git a/Libraries/LibAudio/ASAPI.h b/Libraries/LibAudio/ASAPI.h new file mode 100644 index 0000000000..e1c3c0b09a --- /dev/null +++ b/Libraries/LibAudio/ASAPI.h @@ -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; + }; +}; diff --git a/Libraries/LibAudio/AWavFile.cpp b/Libraries/LibAudio/AWavFile.cpp deleted file mode 100644 index ef9c77fa77..0000000000 --- a/Libraries/LibAudio/AWavFile.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "AWavFile.h" - diff --git a/Libraries/LibAudio/AWavFile.h b/Libraries/LibAudio/AWavFile.h deleted file mode 100644 index 6321179363..0000000000 --- a/Libraries/LibAudio/AWavFile.h +++ /dev/null @@ -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; -}; diff --git a/Libraries/LibAudio/AWavLoader.cpp b/Libraries/LibAudio/AWavLoader.cpp index ff1048f17b..1369d6fb1a 100644 --- a/Libraries/LibAudio/AWavLoader.cpp +++ b/Libraries/LibAudio/AWavLoader.cpp @@ -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)); +} diff --git a/Libraries/LibAudio/AWavLoader.h b/Libraries/LibAudio/AWavLoader.h index 72dee9f347..9e0c7ad2f6 100644 --- a/Libraries/LibAudio/AWavLoader.h +++ b/Libraries/LibAudio/AWavLoader.h @@ -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; }; diff --git a/Libraries/LibAudio/Makefile b/Libraries/LibAudio/Makefile index fa2c6507aa..33939c3fba 100644 --- a/Libraries/LibAudio/Makefile +++ b/Libraries/LibAudio/Makefile @@ -2,7 +2,6 @@ include ../../Makefile.common OBJS = \ AClientConnection.o \ - AWavFile.o \ AWavLoader.o LIBRARY = libaudio.a |