#include "playback.h" #include "SDL_mixer.h" #include "playback_backend.hpp" #include #include extern "C" { #include #include #include } #include #include #include #include #include #ifdef __linux__ #include #endif #include "log.hpp" #include #include "dbus.hpp" #include #include "util.hpp" #include "file_backend.hpp" using namespace std::chrono; int NotSDL_ConvertAudioSamples(const SDL_AudioSpec *src_spec, const Uint8 *src_data, int src_len, const SDL_AudioSpec *dst_spec, Uint8 **dst_data, int *dst_len) { if (dst_data) { *dst_data = NULL; } if (dst_len) { *dst_len = 0; } if (!src_data) { return 0; } else if (src_len < 0) { return 0; } else if (!dst_data) { return 0; } else if (!dst_len) { return 0; } int retval = -1; Uint8 *dst = NULL; int dstlen = 0; SDL_AudioStream *stream = SDL_NewAudioStream(src_spec->format, src_spec->channels, src_spec->freq, dst_spec->format, dst_spec->channels, dst_spec->freq); if (stream) { if ((SDL_AudioStreamPut(stream, src_data, src_len) == 0) && (SDL_AudioStreamFlush(stream) == 0)) { dstlen = SDL_AudioStreamAvailable(stream); if (dstlen >= 0) { dst = (Uint8 *)SDL_malloc(dstlen); if (dst) { retval = (SDL_AudioStreamGet(stream, dst, dstlen) >= 0) ? 0 : -1; } } } } if (retval == -1) { SDL_free(dst); } else { *dst_data = dst; *dst_len = dstlen; } SDL_FreeAudioStream(stream); return retval; } size_t CalculateBufSize(SDL_AudioSpec *obtained, double seconds, double max_seconds, size_t samples_override = 0) { return ((((samples_override == 0) ? obtained->samples : samples_override) * std::min(seconds, max_seconds)) + 1) * sizeof(SAMPLETYPE) * obtained->channels; } void PlaybackInstance::SDLCallbackInner(Uint8 *stream, int len) { SDL_memset((void*)stream, 0, len); if (!playback_ready.load()) return; if (process == nullptr) return; if (st == nullptr) return; size_t unit = sizeof(SAMPLETYPE) * spec.channels; size_t bytes_per_iter = (bufsize / unit) * unit; while (st->numSamples() * unit <= (size_t)len) { if (process == nullptr) { return; } Uint8 *new_buf; int new_bufsize; new_buf = buf; bytes_per_iter = backend_spec.size; if (bytes_per_iter > bufsize) { bytes_per_iter = bufsize; } new_bufsize = bytes_per_iter; if (this->process != nullptr) { size_t new_bytes = this->process->render(buf, bytes_per_iter); if (SDL_AudioStreamPut(sdl_stream, buf, new_bytes) < 0) { ERROR.writefln("SDL_AudioStreamPut: %s", SDL_GetError()); DEBUG.writefln("Current audio backend: %s", process->get_backend_id().c_str()); DEBUG.writefln("SDL_AudioStream *sdl_stream = %0lx", (size_t)sdl_stream); return; } do { new_bufsize = SDL_AudioStreamGet(sdl_stream, buf, (bufsize / unit) * unit); if (new_bufsize < 0) { ERROR.writefln("SDL_AudioStreamGet: %s", SDL_GetError()); DEBUG.writefln("Current audio backend: %s", process->get_backend_id().c_str()); return; } SAMPLETYPE *sbuf = (SAMPLETYPE*)buf; for (size_t i = 0; i < (new_bufsize / unit) * spec.channels; i++) { sbuf[i] *= real_volume; } st->putSamples(sbuf, new_bufsize / unit); } while (new_bufsize > 0); } else { return; } } st->receiveSamples((SAMPLETYPE*)stream, len / unit); } #ifdef __ANDROID__ oboe::DataCallbackResult PlaybackInstance::onAudioReady( oboe::AudioStream *audioStream, void *audioData, int32_t numFrames) { SDLCallbackInner((Uint8*)audioData, numFrames * audioStream->getBytesPerFrame()); return oboe::DataCallbackResult::Continue; } #endif void PlaybackInstance::SDLCallback(void *userdata, Uint8 *stream, int len) { ((PlaybackInstance*)userdata)->SDLCallbackInner(stream, len); } void PlaybackInstance::Load(const char *file, int idx) { SDL_LockAudioDevice(device); playback_ready.store(false); if (process != nullptr) delete process; try { process = new PlaybackProcess(file, idx); } catch (std::exception e) { ERROR.writefln("Exception caught when creating process: %s", e.what()); process = nullptr; } length = 0.0; if (process != nullptr && process->process_running()) { length = process->get_length(); auto backend_spec_proxy = process->get_audio_spec(); memset(&backend_spec, 0, sizeof(backend_spec)); backend_spec.channels = backend_spec_proxy->channel_count(); audio_data_t sample_fmt; sample_fmt.size = backend_spec_proxy->bits() / 8; sample_fmt.endian = backend_spec_proxy->endian() == EndianID::BIG; sample_fmt.is_float = backend_spec_proxy->format_type() == FormatType::FLOAT; sample_fmt.is_signed = backend_spec_proxy->format_type() != FormatType::UNSIGNED; backend_spec.format = sample_spec_to_sdl(sample_fmt); backend_spec.freq = backend_spec_proxy->sample_rate(); backend_spec.samples = backend_spec_proxy->has_max_samples() ? backend_spec_proxy->max_samples() : backend_spec_proxy->has_min_samples() ? backend_spec_proxy->min_samples() : 0; if (backend_spec.samples == 0) backend_spec.samples = 100; DEBUG.writeln("Backend audio specification:"); DEBUG.writefln("\tFormat: %s", sdl_to_str(backend_spec.format).c_str()); DEBUG.writefln("\tChannels: %d", backend_spec.channels); DEBUG.writefln("\tSample rate: %d", backend_spec.freq); DEBUG.writefln("\tSamples: %d", backend_spec.samples); if (sdl_stream != nullptr) { SDL_FreeAudioStream(sdl_stream); } sdl_stream = SDL_NewAudioStream(backend_spec.format, backend_spec.channels, backend_spec.freq, spec.format, spec.channels, spec.freq); if (sdl_stream == nullptr) { ERROR.writefln("SDL_NewAudioStream: %s", SDL_GetError()); DEBUG.writefln("format: AUDIO_%s%d%s", sample_fmt.is_float ? "F" : sample_fmt.is_signed ? "S" : "U", sample_fmt.size * 8, sample_fmt.endian ? "MSB" : "LSB"); set_error("Failed to create SDL audio stream"); set_signal(PlaybackSignalErrorOccurred); } size_t required_size = sample_fmt.size * backend_spec.samples; st->setChannels(spec.channels); st->setRate(spec.freq); st->flush(); backend_spec.size = required_size; bufsize = backend_spec.size; buf = (Uint8*)malloc(bufsize); if (buf == nullptr) { ERROR.writeln("Failed to allocate memory for playback!"); set_error("Failed to allocate memory for playback!"); set_signal(PlaybackSignalErrorOccurred); bufsize = 0; } delete backend_spec_proxy; playback_ready.store(true); load_finished.store(true); this->process->set_position(0.0); } else { set_error("Failed to create playback backend."); set_signal(PlaybackSignalErrorOccurred); delete process; process = nullptr; } initial_render = true; SDL_UnlockAudioDevice(device); } void PlaybackInstance::Unload() { if (process == nullptr) return; SDL_LockAudioDevice(device); delete process; process = nullptr; SDL_FreeAudioStream(sdl_stream); sdl_stream = nullptr; free(buf); SDL_UnlockAudioDevice(device); } void PlaybackInstance::UpdateST() { bool any_changed = false; if (speed > 0.0f && speed_changed.exchange(false)) { any_changed = true; st->setRate(speed); set_signal(PlaybackSignalSpeedChanged); } if (tempo > 0.0f && tempo_changed.exchange(false)) { any_changed = true; st->setTempo(tempo); set_signal(PlaybackSignalTempoChanged); } if (pitch > 0.0f && pitch_changed.exchange(false)) { any_changed = true; st->setPitch(pitch); set_signal(PlaybackSignalPitchChanged); } if (any_changed && process != nullptr) { process->set_rate(st->getInputOutputSampleRatio()); } } double PlaybackInstance::GetMaxSeconds() { return std::max((double)(MaxSpeed * MaxTempo), st->getInputOutputSampleRatio()); } void PlaybackInstance::InitLoopFunction() { bool reload = false; init_audio_data(); speed_changed.store(true); tempo_changed.store(true); pitch_changed.store(true); playback_ready.store(false); if (!SDL_WasInit(SDL_INIT_AUDIO)) { if (SDL_InitSubSystem(SDL_INIT_AUDIO) < 0) { ERROR.writefln("Error initializing SDL: '%s'", SDL_GetError()); set_error("Failed to initialize SDL!"); return; } } SDL_AudioSpec obtained; SDL_AudioSpec desired; desired.format = #ifdef SOUNDTOUCH_INTEGER_SAMPLES AUDIO_S16SYS; #else AUDIO_F32SYS; #endif desired.freq = 48000; desired.samples = 200; desired.channels = 2; desired.callback = PlaybackInstance::SDLCallback; desired.userdata = this; st = new SoundTouch(); #ifndef __ANDROID__ if ((device = SDL_OpenAudioDevice(nullptr, 0, &desired, &obtained, SDL_AUDIO_ALLOW_CHANNELS_CHANGE|SDL_AUDIO_ALLOW_FREQUENCY_CHANGE|SDL_AUDIO_ALLOW_SAMPLES_CHANGE)) == 0) { ERROR.writefln("Error opening audio device: '%s'", SDL_GetError()); set_error("Failed to open audio device!"); running = false; loop_started = false; return; } #else oboe::AudioStreamBuilder builder; builder.setDirection(oboe::Direction::Output); builder.setSharingMode(oboe::SharingMode::Shared); builder.setPerformanceMode(oboe::PerformanceMode::None); builder.setFormat( #ifdef SOUNDTOUCH_INTEGER_SAMPLES oboe::AudioFormat::I16 #else oboe::AudioFormat::Float #endif ); builder.setDataCallback(this); auto res = builder.openStream(ostream); if (res != oboe::Result::OK) { ERROR.writefln("Error opening audio device."); set_error("Failed to open audio device!"); running = false; loop_started = false; return; } obtained = desired; obtained.channels = ostream->getChannelCount(); obtained.freq = ostream->getSampleRate(); auto bufferFrames = ostream->getBufferSizeInFrames(); auto bytesPerFrame = ostream->getBytesPerFrame(); auto bytesPerSample = ostream->getBytesPerSample(); obtained.size = bufferFrames * bytesPerFrame; obtained.samples = obtained.size / bytesPerSample; oboe::AudioFormat format = ostream->getFormat(); DEBUG.writefln("About to start audio stream.\n\ Format: %s\n\ Channel count: %u\n\ Sample rate: %u\n\ Buffer size (frames): %u\n\ Bytes per frame: %u\n\ Total bytes: %u\n\ Bytes per sample: %u\n\ Total samples: %u" , oboe::convertToText(format) , obtained.channels , obtained.freq , bufferFrames , bytesPerFrame , obtained.size , bytesPerSample , obtained.samples ); ostream->requestStart(); #endif spec = obtained; st->setSampleRate(spec.freq); st->setChannels(spec.channels); UpdateST(); SDL_PauseAudioDevice(device, 0); Load(filePath.c_str(), 0); reload = false; if (process && process->process_running()) { playback_ready.store(true); } else { playback_ready.store(false); } load_finished.store(true); set_signal(PlaybackSignalStarted); } void PlaybackInstance::LoopFunction() { if (file_changed.exchange(false) || load_requested.exchange(false)) { Unload(); Load(filePath.c_str(), 0); if (process && process->process_running()) { playback_ready.store(true); } else { playback_ready.store(false); } } if (stream_changed.exchange(false)) { current_file_mutex.lock(); if (current_file.has_value()) { std::string file = current_file.value(); if (current_stream >= streams.size() || current_stream < 0 || streams[current_stream].name == "" || streams[current_stream].length <= 0) { if (stream != nullptr) { current_stream = stream->stream_index; } else { current_stream = 0; } } else { SDL_LockAudioDevice(device); if (process && process->process_running()) process->set_stream_idx(current_stream); SDL_UnlockAudioDevice(device); } if (process && process->process_running()) { playback_ready.store(true); } else { playback_ready.store(false); } } current_file_mutex.unlock(); } if (flag_mutex.try_lock()) { if (seeking.exchange(false)) { if (process && process->process_running()) process->set_position(this->position); set_signal(PlaybackSignalSeeked); } if (pause_changed.exchange(false)) { SDL_PauseAudioDevice(device, paused ? 1 : 0); if (paused) { set_signal(PlaybackSignalPaused); } else { set_signal(PlaybackSignalResumed); } } if (update.exchange(false)) { SDL_LockAudioDevice(device); real_volume = volume / 100.0; UpdateST(); SDL_UnlockAudioDevice(device); } flag_mutex.unlock(); } if (process) { position = process->get_position(); } else { position = 0.0; } } void PlaybackInstance::DeinitLoopFunction() { playback_ready.store(false); // ==== Unload(); #ifndef __ANDROID__ SDL_CloseAudioDevice(device); #else if (ostream && ostream->getState() != oboe::StreamState::Closed) { ostream->stop(); ostream->close(); } ostream.reset(); #endif SDL_QuitSubSystem(SDL_INIT_AUDIO); delete st; free(buf); current_file_mutex.lock(); current_file = {}; current_file_mutex.unlock(); set_signal(PlaybackSignalStopped); } void PlaybackInstance::ThreadFunc() { #ifdef __linux__ pthread_setname_np(pthread_self(), "Playback control thread"); #endif start_loop(); while (running && loop_started) { LoopHook(); std::this_thread::sleep_for(20ms); } stop_loop(); } PlaybackInstance::PlaybackInstance() { running = false; paused = true; position = 0; length = 0; volume = 100.0; speed = 1.0; pitch = 1.0; tempo = 1.0; prev_speed = -1.0; prev_pitch = -1.0; prev_tempo = -1.0; tempo_changed.store(true); speed_changed.store(true); pitch_changed.store(true); current_file = {}; playback_ready = false; bufsize = 0; process = nullptr; } std::optional PlaybackInstance::get_current_file() { current_file_mutex.lock(); std::optional output = current_file; current_file_mutex.unlock(); return output; } std::optional PlaybackInstance::get_current_title() { current_file_mutex.lock(); std::optional output = current_title; current_file_mutex.unlock(); return output; } PlaybackInstance::~PlaybackInstance() { Stop(); } void PlaybackInstance::Load(std::string filePath) { this->filePath = filePath; INFO.writefln("Loading %s...", filePath.c_str()); if (running.exchange(true)) { load_requested.store(true); } else { #if defined(__EMSCRIPTEN__)||defined(__ANDROID__) start_loop(); #else thread = std::thread(&PlaybackInstance::ThreadFunc, this); loop_started = true; #endif } flag_mutex.lock(); this->position = 0.0; seeking.store(true); paused = true; Update(); flag_mutex.unlock(); } void PlaybackInstance::Start(std::string filePath, int streamIdx) { Load(filePath); while (loop_started && !load_finished.exchange(false)) { #if defined(__EMSCRIPTEN__)||defined(__ANDROID__) LoopHook(); #endif std::this_thread::sleep_for(20ms); } if (!loop_started) { return; } INFO.writefln("Playing %s...", filePath.c_str()); flag_mutex.lock(); this->position = 0.0; seeking.store(true); paused = false; current_stream = streamIdx; stream_changed.store(true); Update(); flag_mutex.unlock(); } void PlaybackInstance::play_stream(int idx) { flag_mutex.lock(); this->position = 0.0; seeking.store(true); paused = false; current_stream = idx; stream_changed.store(true); Update(); flag_mutex.unlock(); } double PlaybackInstance::GetPosition() { return position; } double PlaybackInstance::GetLength() { return length; } void PlaybackInstance::Seek(double position) { flag_mutex.lock(); this->position = position; seeking.store(true); flag_mutex.unlock(); } void PlaybackInstance::Pause() { flag_mutex.lock(); paused = !paused; pause_changed.store(true); flag_mutex.unlock(); } bool PlaybackInstance::IsPaused() { return paused; } void PlaybackInstance::Stop() { if (running.exchange(false)) { #if defined(__EMSCRIPTEN__)||defined(__ANDROID__) stop_loop(); #else thread.join(); #endif } } void PlaybackInstance::Update() { if (prev_pitch != pitch) { pitch_changed.store(true); } if (prev_speed != speed) { speed_changed.store(true); } if (prev_tempo != tempo) { tempo_changed.store(true); } update.store(true); } bool PlaybackInstance::IsStopped() { return !running; } void Playback::set_signal(uint16_t signal) { signal_mutex.lock(); for (auto &kv : signals_occurred) { kv.second |= signal; } signal_mutex.unlock(); } uint16_t Playback::handle_signals(uint16_t signals, void *handle) { if (signal_mutex.try_lock()) { if (!signals_occurred.contains(handle)) { signals_occurred[handle] = PlaybackSignalNone; } uint16_t output = signals_occurred[handle]; signals_occurred[handle] &= ~output; signal_mutex.unlock(); return output; } else { return PlaybackSignalNone; } } void Playback::register_handle(void *handle) { signal_mutex.lock(); if (!signals_occurred.contains(handle)) { signals_occurred[handle] = PlaybackSignalNone; } signal_mutex.unlock(); error_mutex.lock(); if (!errors_occurred.contains(handle)) { std::deque new_value; for (size_t i = 0; i < errors.size(); i++) { new_value.push_back(errors[i]); } errors_occurred[handle] = new_value; } error_mutex.unlock(); } void Playback::unregister_handle(void *handle) { signal_mutex.lock(); if (signals_occurred.contains(handle)) { signals_occurred.erase(handle); } signal_mutex.unlock(); error_mutex.lock(); if (errors_occurred.contains(handle)) { errors_occurred.erase(handle); } error_mutex.unlock(); } void PlaybackInstance::SetTempo(float tempo) { this->tempo = tempo; Update(); } void PlaybackInstance::SetPitch(float pitch) { this->pitch = pitch; Update(); } void PlaybackInstance::SetSpeed(float speed) { this->speed = speed; Update(); } void PlaybackInstance::SetVolume(float volume) { this->volume = volume; Update(); } float PlaybackInstance::GetTempo() { return tempo; } float PlaybackInstance::GetPitch() { return pitch; } float PlaybackInstance::GetSpeed() { return speed; } float PlaybackInstance::GetVolume() { return volume; } void Playback::set_error(std::string desc) { error_mutex.lock(); errors.push_back(desc); for (auto &kv : errors_occurred) { kv.second.push_front(desc); } error_mutex.unlock(); set_signal(PlaybackSignalErrorOccurred); } Playback *Playback::Create(bool *daemon_found, bool daemon) { #ifdef DBUS_ENABLED auto *dbus_proxy = DBusAPISender::Create(); if (dbus_proxy != nullptr) { if (daemon_found != nullptr) { *daemon_found = dbus_proxy->IsDaemon(); } DEBUG.writefln("DBus proxy daemon found: %s", *daemon_found ? "true" : "false"); if (daemon) { delete dbus_proxy; return nullptr; } else { return dbus_proxy; } } if (daemon_found != nullptr) { *daemon_found = false; } #endif DEBUG.writeln("Creating new playback instance."); return new PlaybackInstance(); } std::vector PlaybackInstance::get_streams() { std::vector output; for (auto stream : streams) { output.push_back(stream); } return output; } int PlaybackInstance::get_current_stream() { return current_stream; }