Play sounds with SDL audio and stb_vorbis instead of SDL_mixer
Sounds decode once to 48 kHz stereo floats. Each play is a stream on one shared device, opened on the first play. A render's audio is mixed offline at 48 kHz, so command line renders get their sounds too. The About music is Ogg Vorbis now. Opus, libopus and libogg are gone.
This commit is contained in:
1 parent
7afdf709c3
commit
7e81ea4259
17 files changed
+250
-226
No files matched your search
@@ -11,9 +11,6 @@
|
||||
[submodule "external/lunasvg"]
|
||||
path = external/lunasvg
|
||||
url = https://github.com/sammycage/lunasvg
|
||||
[submodule "external/SDL_mixer"]
|
||||
path = external/SDL_mixer
|
||||
url = https://github.com/libsdl-org/SDL_mixer
|
||||
[submodule "external/simdjson"]
|
||||
path = external/simdjson
|
||||
url = https://github.com/simdjson/simdjson
|
||||
|
||||
+4
-12
@@ -25,6 +25,7 @@ if(MSVC)
|
||||
endif()
|
||||
|
||||
# SDL: static, with only video (OpenGL), audio, events, clipboard and file dialogs.
|
||||
# Its audio plays WAV and, through stb_vorbis, Ogg Vorbis.
|
||||
set(SDL_SHARED OFF CACHE BOOL "" FORCE)
|
||||
set(SDL_STATIC ON CACHE BOOL "" FORCE)
|
||||
foreach(OPTION TEST_LIBRARY EXAMPLES RENDER GPU VULKAN OPENGLES CAMERA HAPTIC JOYSTICK HIDAPI SENSOR POWER TRAY
|
||||
@@ -33,16 +34,6 @@ foreach(OPTION TEST_LIBRARY EXAMPLES RENDER GPU VULKAN OPENGLES CAMERA HAPTIC JO
|
||||
endforeach()
|
||||
add_subdirectory(external/SDL EXCLUDE_FROM_ALL)
|
||||
|
||||
# SDL_mixer: WAV, Vorbis and Opus only.
|
||||
foreach(OPTION DEPS_SHARED AIFF AU FLAC_LIBFLAC FLAC_DRFLAC GME MOD_XMP MP3_DRMP3 MP3_MPG123 MIDI_FLUIDSYNTH
|
||||
MIDI_TIMIDITY VOC VORBIS_VORBISFILE VORBIS_TREMOR WAVPACK TEST INSTALL)
|
||||
set(SDLMIXER_${OPTION} OFF CACHE BOOL "" FORCE)
|
||||
endforeach()
|
||||
foreach(OPTION OPUS VORBIS_STB WAVE)
|
||||
set(SDLMIXER_${OPTION} ON CACHE BOOL "" FORCE)
|
||||
endforeach()
|
||||
add_subdirectory(external/SDL_mixer EXCLUDE_FROM_ALL)
|
||||
|
||||
set(LUNASVG_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)
|
||||
add_subdirectory(external/lunasvg EXCLUDE_FROM_ALL)
|
||||
|
||||
@@ -77,7 +68,8 @@ target_compile_definitions(anm2ed_core PUBLIC IMGUI_DISABLE_OBSOLETE_FUNCTIONS
|
||||
# The editor: the core with its window, OpenGL and interface. The render tests link it too.
|
||||
file(GLOB_RECURSE APP_SOURCES CONFIGURE_DEPENDS src/*.cpp)
|
||||
list(REMOVE_ITEM APP_SOURCES ${CORE_SOURCES} ${CMAKE_SOURCE_DIR}/src/main.cpp)
|
||||
add_library(anm2ed_app STATIC ${APP_SOURCES} include/glad/glad.cpp external/imgui/backends/imgui_impl_sdl3.cpp
|
||||
set_source_files_properties(external/stb/stb_vorbis.c PROPERTIES COMPILE_OPTIONS -w)
|
||||
add_library(anm2ed_app STATIC ${APP_SOURCES} external/stb/stb_vorbis.c include/glad/glad.cpp external/imgui/backends/imgui_impl_sdl3.cpp
|
||||
external/imgui/backends/imgui_impl_opengl3.cpp)
|
||||
if(WIN32)
|
||||
set(PLATFORM_LIBRARIES opengl32 ws2_32 bcrypt imm32 version winmm shell32 ole32 advapi32 gdi32 user32 setupapi
|
||||
@@ -85,7 +77,7 @@ if(WIN32)
|
||||
else()
|
||||
set(PLATFORM_LIBRARIES GL)
|
||||
endif()
|
||||
target_link_libraries(anm2ed_app PUBLIC anm2ed_core SDL3::SDL3-static SDL3_mixer::SDL3_mixer ${PLATFORM_LIBRARIES})
|
||||
target_link_libraries(anm2ed_app PUBLIC anm2ed_core SDL3::SDL3-static ${PLATFORM_LIBRARIES})
|
||||
|
||||
add_executable(anm2ed src/main.cpp $<$<BOOL:${WIN32}>:anm2ed.rc>)
|
||||
target_link_libraries(anm2ed PRIVATE anm2ed_app)
|
||||
|
||||
Vendored
-1
Submodule external/SDL_mixer deleted from 4182794ea4.
Binary file not shown.
Binary file not shown.
+172
-79
@@ -1,120 +1,213 @@
|
||||
#include "audio.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <memory>
|
||||
#include <unordered_map>
|
||||
#include <vector>
|
||||
|
||||
struct AudioEntry
|
||||
#define STB_VORBIS_HEADER_ONLY
|
||||
#include <stb_vorbis.c>
|
||||
|
||||
constexpr SDL_AudioSpec AUDIO_SPEC = {SDL_AUDIO_F32, AUDIO_CHANNELS, AUDIO_FREQUENCY};
|
||||
constexpr int FRAME_SIZE = AUDIO_CHANNELS * sizeof(float);
|
||||
|
||||
// One play of a sound. The audio thread feeds its stream from `position`, wrapping around when it loops.
|
||||
struct AudioVoice
|
||||
{
|
||||
MIX_Audio* audio = nullptr;
|
||||
std::vector<MIX_Track*> tracks; // one per overlapping play, reused once finished
|
||||
std::atomic<float> squares[2]{};
|
||||
std::atomic<int> sampleCount = {};
|
||||
struct AudioSound* sound = nullptr;
|
||||
SDL_AudioStream* stream = nullptr;
|
||||
std::atomic<std::size_t> position = 0;
|
||||
std::atomic<bool> isLoop = false;
|
||||
};
|
||||
|
||||
// Sums the squares of the left/right samples the track plays, for its levels.
|
||||
static void SDLCALL levels_update(void* userdata, MIX_Track*, const SDL_AudioSpec* spec, float* pcm, int samples)
|
||||
// A decoded sound, its voices (one per overlapping play, reused once finished) and the loudness they played.
|
||||
struct AudioSound
|
||||
{
|
||||
auto entry = (AudioEntry*)userdata;
|
||||
auto channels = std::max(spec->channels, 1);
|
||||
float squares[2]{};
|
||||
for (int i = 0; i < samples; ++i)
|
||||
squares[std::min(i % channels, 1)] += pcm[i] * pcm[i];
|
||||
if (channels == 1)
|
||||
squares[1] = squares[0];
|
||||
for (int channel = 0; channel < 2; ++channel)
|
||||
entry->squares[channel] += squares[channel];
|
||||
entry->sampleCount += samples / channels;
|
||||
std::vector<float> samples;
|
||||
std::vector<std::unique_ptr<AudioVoice>> voices;
|
||||
std::atomic<float> squares[AUDIO_CHANNELS] = {};
|
||||
std::atomic<int> frameCount = 0;
|
||||
};
|
||||
|
||||
static std::unordered_map<std::uint64_t, AudioSound> sounds;
|
||||
|
||||
// Converts audio in `spec` to AUDIO_SPEC.
|
||||
static std::vector<float> samples_convert(const SDL_AudioSpec& spec, const void* data, int size)
|
||||
{
|
||||
Uint8* converted = nullptr;
|
||||
int convertedSize = 0;
|
||||
if (!SDL_ConvertAudioSamples(&spec, (const Uint8*)data, size, &AUDIO_SPEC, &converted, &convertedSize))
|
||||
return {};
|
||||
std::vector<float> samples(convertedSize / sizeof(float));
|
||||
std::memcpy(samples.data(), converted, samples.size() * sizeof(float));
|
||||
SDL_free(converted);
|
||||
return samples;
|
||||
}
|
||||
|
||||
static std::unordered_map<std::uint64_t, AudioEntry> entries;
|
||||
|
||||
static MIX_Mixer* audio_mixer_get()
|
||||
static std::vector<float> samples_decode(const AudioData& data)
|
||||
{
|
||||
static auto mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr);
|
||||
return mixer;
|
||||
if (data.bytes.size() >= 4 && std::memcmp(data.bytes.data(), "OggS", 4) == 0)
|
||||
{
|
||||
int channels = 0;
|
||||
int frequency = 0;
|
||||
short* decoded = nullptr;
|
||||
auto frames = stb_vorbis_decode_memory(data.bytes.data(), (int)data.bytes.size(), &channels, &frequency, &decoded);
|
||||
if (frames <= 0)
|
||||
return {};
|
||||
auto samples = samples_convert({SDL_AUDIO_S16, channels, frequency}, decoded, frames * channels * sizeof(short));
|
||||
free(decoded);
|
||||
return samples;
|
||||
}
|
||||
|
||||
static AudioEntry* entry_get(const AudioData& data)
|
||||
SDL_AudioSpec spec = {};
|
||||
Uint8* decoded = nullptr;
|
||||
Uint32 size = 0;
|
||||
if (!SDL_LoadWAV_IO(SDL_IOFromConstMem(data.bytes.data(), data.bytes.size()), true, &spec, &decoded, &size))
|
||||
return {};
|
||||
auto samples = samples_convert(spec, decoded, (int)size);
|
||||
SDL_free(decoded);
|
||||
return samples;
|
||||
}
|
||||
|
||||
static AudioSound* sound_get(const AudioData& data)
|
||||
{
|
||||
if (!data.is_valid())
|
||||
return nullptr;
|
||||
auto [it, isNew] = entries.try_emplace(data.uid);
|
||||
auto [it, isNew] = sounds.try_emplace(data.uid);
|
||||
if (isNew)
|
||||
if (auto io = SDL_IOFromConstMem(data.bytes.data(), data.bytes.size()))
|
||||
it->second.audio = MIX_LoadAudio_IO(audio_mixer_get(), io, true, true);
|
||||
return it->second.audio ? &it->second : nullptr;
|
||||
it->second.samples = samples_decode(data);
|
||||
return it->second.samples.empty() ? nullptr : &it->second;
|
||||
}
|
||||
|
||||
static bool is_on_mixer(MIX_Track* track, MIX_Mixer* mixer)
|
||||
static SDL_AudioDeviceID device_get()
|
||||
{
|
||||
return !mixer || MIX_GetTrackMixer(track) == mixer;
|
||||
static SDL_AudioDeviceID device = SDL_InitSubSystem(SDL_INIT_AUDIO)
|
||||
? SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &AUDIO_SPEC)
|
||||
: 0;
|
||||
return device;
|
||||
}
|
||||
|
||||
// A sound can play over itself: while a track is still playing it, another track takes the new play.
|
||||
void audio_play(const AudioData& data, bool isLoop, MIX_Mixer* mixer)
|
||||
// Runs on the audio thread: gives the stream what it asks for, and adds it to the sound's loudness.
|
||||
static void SDLCALL voice_feed(void* userdata, SDL_AudioStream* stream, int amount, int)
|
||||
{
|
||||
auto entry = entry_get(data);
|
||||
auto targetMixer = mixer ? mixer : audio_mixer_get();
|
||||
if (!entry || !targetMixer)
|
||||
auto voice = (AudioVoice*)userdata;
|
||||
auto& samples = voice->sound->samples;
|
||||
auto frames = (std::size_t)amount / FRAME_SIZE;
|
||||
auto position = voice->position.load();
|
||||
float squares[AUDIO_CHANNELS] = {};
|
||||
std::size_t fed = 0;
|
||||
while (fed < frames)
|
||||
{
|
||||
if (position * AUDIO_CHANNELS >= samples.size())
|
||||
{
|
||||
if (!voice->isLoop)
|
||||
break;
|
||||
position = 0;
|
||||
}
|
||||
auto count = std::min(frames - fed, samples.size() / AUDIO_CHANNELS - position);
|
||||
auto start = samples.data() + position * AUDIO_CHANNELS;
|
||||
for (std::size_t i = 0; i < count * AUDIO_CHANNELS; ++i)
|
||||
squares[i % AUDIO_CHANNELS] += start[i] * start[i];
|
||||
SDL_PutAudioStreamData(stream, start, (int)(count * FRAME_SIZE));
|
||||
position += count;
|
||||
fed += count;
|
||||
}
|
||||
voice->position = position;
|
||||
for (int channel = 0; channel < AUDIO_CHANNELS; ++channel)
|
||||
voice->sound->squares[channel] += squares[channel];
|
||||
voice->sound->frameCount += (int)fed;
|
||||
}
|
||||
|
||||
static bool is_voice_playing(AudioVoice& voice)
|
||||
{
|
||||
return voice.isLoop || voice.position * AUDIO_CHANNELS < voice.sound->samples.size() ||
|
||||
SDL_GetAudioStreamQueued(voice.stream) > 0;
|
||||
}
|
||||
|
||||
// A sound can play over itself: while a voice is still playing it, another voice takes the new play.
|
||||
void audio_play(const AudioData& data, AudioPlayMode mode)
|
||||
{
|
||||
auto sound = sound_get(data);
|
||||
if (!sound || !device_get())
|
||||
return;
|
||||
|
||||
auto free = std::ranges::find_if(
|
||||
entry->tracks, [&](MIX_Track* track) { return is_on_mixer(track, targetMixer) && !MIX_TrackPlaying(track); });
|
||||
auto track = free != entry->tracks.end() ? *free : MIX_CreateTrack(targetMixer);
|
||||
if (!track)
|
||||
auto free = std::ranges::find_if(sound->voices, [](auto& voice) { return !is_voice_playing(*voice); });
|
||||
AudioVoice* voice = nullptr;
|
||||
if (free != sound->voices.end())
|
||||
voice = free->get();
|
||||
else
|
||||
{
|
||||
voice = sound->voices.emplace_back(std::make_unique<AudioVoice>()).get();
|
||||
voice->sound = sound;
|
||||
voice->stream = SDL_CreateAudioStream(&AUDIO_SPEC, &AUDIO_SPEC);
|
||||
SDL_SetAudioStreamGetCallback(voice->stream, voice_feed, voice);
|
||||
SDL_BindAudioStream(device_get(), voice->stream);
|
||||
}
|
||||
|
||||
SDL_LockAudioStream(voice->stream);
|
||||
SDL_ClearAudioStream(voice->stream);
|
||||
voice->position = 0;
|
||||
voice->isLoop = mode == AUDIO_LOOP;
|
||||
SDL_UnlockAudioStream(voice->stream);
|
||||
}
|
||||
|
||||
void audio_stop(const AudioData& data)
|
||||
{
|
||||
auto it = sounds.find(data.uid);
|
||||
if (it == sounds.end())
|
||||
return;
|
||||
if (free == entry->tracks.end())
|
||||
for (auto& voice : it->second.voices)
|
||||
{
|
||||
entry->tracks.push_back(track);
|
||||
MIX_SetTrackCookedCallback(track, levels_update, entry);
|
||||
MIX_SetTrackAudio(track, entry->audio);
|
||||
SDL_LockAudioStream(voice->stream);
|
||||
voice->isLoop = false;
|
||||
voice->position = it->second.samples.size() / AUDIO_CHANNELS;
|
||||
SDL_ClearAudioStream(voice->stream);
|
||||
SDL_UnlockAudioStream(voice->stream);
|
||||
}
|
||||
|
||||
SDL_PropertiesID options = isLoop ? SDL_CreateProperties() : 0;
|
||||
if (options)
|
||||
SDL_SetNumberProperty(options, MIX_PROP_PLAY_LOOPS_NUMBER, -1);
|
||||
MIX_PlayTrack(track, options);
|
||||
if (options)
|
||||
SDL_DestroyProperties(options);
|
||||
}
|
||||
|
||||
void audio_stop(const AudioData& data, MIX_Mixer* mixer)
|
||||
{
|
||||
if (auto it = entries.find(data.uid); it != entries.end())
|
||||
for (auto track : it->second.tracks)
|
||||
if (is_on_mixer(track, mixer))
|
||||
MIX_StopTrack(track, 0);
|
||||
}
|
||||
|
||||
void audio_track_detach(const AudioData& data, MIX_Mixer* mixer)
|
||||
{
|
||||
auto it = entries.find(data.uid);
|
||||
if (it == entries.end())
|
||||
return;
|
||||
std::erase_if(it->second.tracks, [&](MIX_Track* track) {
|
||||
if (!is_on_mixer(track, mixer))
|
||||
return false;
|
||||
MIX_DestroyTrack(track);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
bool is_audio_playing(const AudioData& data)
|
||||
{
|
||||
auto it = entries.find(data.uid);
|
||||
return it != entries.end() && std::ranges::any_of(it->second.tracks, MIX_TrackPlaying);
|
||||
auto it = sounds.find(data.uid);
|
||||
return it != sounds.end() &&
|
||||
std::ranges::any_of(it->second.voices, [](auto& voice) { return is_voice_playing(*voice); });
|
||||
}
|
||||
|
||||
// The left/right loudness (RMS, 0-1) of what the track played since the last call.
|
||||
// The left/right loudness (RMS, 0-1) of what the sound played since the last call.
|
||||
glm::vec2 audio_levels_get(const AudioData& data)
|
||||
{
|
||||
auto it = entries.find(data.uid);
|
||||
if (it == entries.end())
|
||||
auto it = sounds.find(data.uid);
|
||||
if (it == sounds.end())
|
||||
return {};
|
||||
auto& entry = it->second;
|
||||
auto count = (float)std::max(entry.sampleCount.exchange(0), 1);
|
||||
return {std::sqrt(entry.squares[0].exchange(0.0f) / count), std::sqrt(entry.squares[1].exchange(0.0f) / count)};
|
||||
auto& sound = it->second;
|
||||
auto count = (float)std::max(sound.frameCount.exchange(0), 1);
|
||||
return {std::sqrt(sound.squares[0].exchange(0.0f) / count), std::sqrt(sound.squares[1].exchange(0.0f) / count)};
|
||||
}
|
||||
|
||||
std::vector<float> audio_mix(const std::vector<std::vector<const AudioData*>>& frameSounds, int fps)
|
||||
{
|
||||
std::vector<float> mix;
|
||||
if (fps <= 0)
|
||||
return mix;
|
||||
auto framesPerStep = (double)AUDIO_FREQUENCY / fps;
|
||||
for (std::size_t step = 0; step < frameSounds.size(); ++step)
|
||||
{
|
||||
auto start = (std::size_t)std::floor(step * framesPerStep) * AUDIO_CHANNELS;
|
||||
mix.resize(std::max(mix.size(), (std::size_t)std::floor((step + 1) * framesPerStep) * AUDIO_CHANNELS));
|
||||
for (auto data : frameSounds[step])
|
||||
{
|
||||
auto sound = sound_get(*data);
|
||||
if (!sound)
|
||||
continue;
|
||||
mix.resize(std::max(mix.size(), start + sound->samples.size()));
|
||||
for (std::size_t i = 0; i < sound->samples.size(); ++i)
|
||||
mix[start + i] += sound->samples[i];
|
||||
}
|
||||
}
|
||||
for (auto& sample : mix)
|
||||
sample = std::clamp(sample, -1.0f, 1.0f);
|
||||
return mix;
|
||||
}
|
||||
+17
-5
@@ -1,13 +1,25 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3_mixer/SDL_mixer.h>
|
||||
#include <glm/vec2.hpp>
|
||||
#include <vector>
|
||||
|
||||
#include "audio_data.h"
|
||||
|
||||
// Playback of AudioData. Decoded audio and tracks are cached per AudioData uid.
|
||||
void audio_play(const AudioData&, bool = false, MIX_Mixer* = nullptr);
|
||||
void audio_stop(const AudioData&, MIX_Mixer* = nullptr);
|
||||
void audio_track_detach(const AudioData&, MIX_Mixer* = nullptr);
|
||||
constexpr int AUDIO_CHANNELS = 2;
|
||||
constexpr int AUDIO_FREQUENCY = 48000;
|
||||
|
||||
enum AudioPlayMode
|
||||
{
|
||||
AUDIO_ONCE,
|
||||
AUDIO_LOOP
|
||||
};
|
||||
|
||||
// Sounds (WAV or Ogg Vorbis) are decoded on their first play to AUDIO_FREQUENCY stereo floats, cached by uid.
|
||||
// Each play is a stream on one shared device, opened on the first play, which mixes them.
|
||||
void audio_play(const AudioData&, AudioPlayMode = AUDIO_ONCE);
|
||||
void audio_stop(const AudioData&);
|
||||
bool is_audio_playing(const AudioData&);
|
||||
glm::vec2 audio_levels_get(const AudioData&);
|
||||
|
||||
// Each frame's sounds started on that frame and mixed at `fps`, as interleaved stereo floats.
|
||||
std::vector<float> audio_mix(const std::vector<std::vector<const AudioData*>>&, int fps);
|
||||
@@ -1,25 +0,0 @@
|
||||
#include "audio_stream.h"
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
#if defined(__clang__) || defined(__GNUC__)
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
#endif
|
||||
|
||||
void AudioStream::callback(void* userData, MIX_Mixer* mixer, const SDL_AudioSpec* spec, float* pcm, int samples)
|
||||
{
|
||||
auto self = (AudioStream*)userData;
|
||||
if (!self->isFirstCallbackCaptured)
|
||||
{
|
||||
self->firstCallbackCounter = SDL_GetPerformanceCounter();
|
||||
self->isFirstCallbackCaptured = true;
|
||||
}
|
||||
self->callbackSamples = samples;
|
||||
self->stream.insert(self->stream.end(), pcm, pcm + samples);
|
||||
}
|
||||
|
||||
AudioStream::AudioStream(MIX_Mixer* mixer)
|
||||
{
|
||||
MIX_GetMixerFormat(mixer, &spec);
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <SDL3_mixer/SDL_mixer.h>
|
||||
#include <vector>
|
||||
|
||||
class AudioStream
|
||||
{
|
||||
static void callback(void*, MIX_Mixer*, const SDL_AudioSpec*, float*, int);
|
||||
|
||||
public:
|
||||
std::vector<float> stream;
|
||||
SDL_AudioSpec spec = {};
|
||||
int callbackSamples = 0;
|
||||
Uint64 captureStartCounter = 0;
|
||||
Uint64 firstCallbackCounter = 0;
|
||||
bool isFirstCallbackCaptured = false;
|
||||
|
||||
AudioStream(MIX_Mixer*);
|
||||
};
|
||||
@@ -8,7 +8,6 @@
|
||||
#include <imgui/backends/imgui_impl_opengl3.h>
|
||||
#include <imgui/backends/imgui_impl_sdl3.h>
|
||||
|
||||
#include <SDL3_mixer/SDL_mixer.h>
|
||||
|
||||
#include "log.h"
|
||||
#include "sdl.h"
|
||||
@@ -177,10 +176,6 @@ Loader::Loader(int argc, const char** argv)
|
||||
logger.warning("Failed to detect primary display for UI scaling.");
|
||||
}
|
||||
|
||||
if (!MIX_Init())
|
||||
logger.warning(std::format("Could not initialize SDL_mixer! {}", SDL_GetError()));
|
||||
else
|
||||
logger.info("Initialized SDL_mixer");
|
||||
|
||||
SDL_SetStringProperty(windowProperties, SDL_PROP_WINDOW_CREATE_TITLE_STRING, "Anm2Ed");
|
||||
SDL_SetNumberProperty(windowProperties, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, settings.windowSize.x);
|
||||
@@ -335,7 +330,6 @@ Loader::~Loader()
|
||||
ImGui::DestroyContext();
|
||||
}
|
||||
|
||||
MIX_Quit();
|
||||
|
||||
if (SDL_WasInit(0))
|
||||
{
|
||||
|
||||
+11
-62
@@ -1,5 +1,7 @@
|
||||
#include "render.h"
|
||||
|
||||
#include <SDL3/SDL.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <cmath>
|
||||
@@ -29,7 +31,7 @@
|
||||
#include "ui/toast.h"
|
||||
|
||||
bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesystem::path& path,
|
||||
const std::vector<std::filesystem::path>& framePaths, AudioStream& audioStream, RenderType type,
|
||||
const std::vector<std::filesystem::path>& framePaths, const std::vector<float>& audio, RenderType type,
|
||||
int fps)
|
||||
{
|
||||
if (framePaths.empty() || ffmpegPath.empty() || path.empty())
|
||||
@@ -63,18 +65,16 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy
|
||||
}
|
||||
};
|
||||
|
||||
if (type != RENDER_GIF && !audioStream.stream.empty() && audioStream.spec.freq > 0 && audioStream.spec.channels > 0)
|
||||
if (type != RENDER_GIF && !audio.empty())
|
||||
{
|
||||
auto tempFilenameUtf8 =
|
||||
std::format("anm2ed_audio_{}_{}.f32", std::hash<std::string>{}(pathString), SDL_GetTicks());
|
||||
audioPath = temporaryDirectory / path_from_utf8(tempFilenameUtf8);
|
||||
|
||||
auto data = (const char*)audioStream.stream.data();
|
||||
auto byteCount = audioStream.stream.size() * sizeof(float);
|
||||
auto data = (const char*)audio.data();
|
||||
auto byteCount = audio.size() * sizeof(float);
|
||||
if (file_text_save(audioPath, std::string_view(data, byteCount), "wb"))
|
||||
{
|
||||
auto sampleRate = std::max(audioStream.spec.freq, 1);
|
||||
auto channels = std::max(audioStream.spec.channels, 1);
|
||||
auto audioDurationFilter = std::string{};
|
||||
auto frameCount = (double)std::max((int)framePaths.size(), 1);
|
||||
auto expectedDurationSeconds = frameCount / (double)fps;
|
||||
@@ -82,7 +82,7 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy
|
||||
audioDurationFilter += std::format("apad,atrim=duration={:.9f}", expectedDurationSeconds);
|
||||
|
||||
audioInputArguments =
|
||||
std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", sampleRate, channels, path_to_utf8(audioPath));
|
||||
std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", AUDIO_FREQUENCY, AUDIO_CHANNELS, path_to_utf8(audioPath));
|
||||
|
||||
switch (type)
|
||||
{
|
||||
@@ -248,50 +248,6 @@ void pixels_unpremultiply(std::vector<uint8_t>& pixels)
|
||||
}
|
||||
}
|
||||
|
||||
static void sounds_detach(const Document& document, MIX_Mixer* mixer)
|
||||
{
|
||||
for (auto sound : document.sounds_get())
|
||||
audio_track_detach(*sound, mixer);
|
||||
}
|
||||
|
||||
// Mixes each frame's trigger sounds into one stream at the render frame rate.
|
||||
static bool audio_stream_generate(AudioStream& audioStream, const Document& document,
|
||||
const std::vector<std::vector<const AudioData*>>& frameSounds, int fps)
|
||||
{
|
||||
audioStream.stream.clear();
|
||||
if (frameSounds.empty() || fps <= 0)
|
||||
return true;
|
||||
|
||||
SDL_AudioSpec mixSpec = audioStream.spec;
|
||||
mixSpec.format = SDL_AUDIO_F32;
|
||||
auto mixer = MIX_CreateMixer(&mixSpec);
|
||||
if (!mixer)
|
||||
return false;
|
||||
|
||||
auto channels = std::max(mixSpec.channels, 1);
|
||||
auto framesPerStep = (double)std::max(mixSpec.freq, 1) / (double)fps;
|
||||
auto accumulator = 0.0;
|
||||
std::vector<float> buffer;
|
||||
auto isGenerated = true;
|
||||
for (auto& sounds : frameSounds)
|
||||
{
|
||||
for (auto sound : sounds)
|
||||
audio_play(*sound, false, mixer);
|
||||
accumulator += framesPerStep;
|
||||
auto sampleFrames = std::max((int)std::floor(accumulator), 1);
|
||||
accumulator -= (double)sampleFrames;
|
||||
buffer.resize((std::size_t)sampleFrames * (std::size_t)channels);
|
||||
if (!(isGenerated = MIX_Generate(mixer, buffer.data(), (int)(buffer.size() * sizeof(float)))))
|
||||
break;
|
||||
audioStream.stream.insert(audioStream.stream.end(), buffer.begin(), buffer.end());
|
||||
}
|
||||
sounds_detach(document, mixer);
|
||||
MIX_DestroyMixer(mixer);
|
||||
if (!isGenerated)
|
||||
audioStream.stream.clear();
|
||||
return isGenerated;
|
||||
}
|
||||
|
||||
HeadlessGL::HeadlessGL()
|
||||
{
|
||||
if (!SDL_Init(SDL_INIT_VIDEO))
|
||||
@@ -397,7 +353,7 @@ bool Recorder::frame_capture(std::vector<uint8_t> pixels, glm::ivec2 size, std::
|
||||
return true;
|
||||
}
|
||||
|
||||
void Recorder::finish(const Document& document, AudioStream& audioStream)
|
||||
void Recorder::finish()
|
||||
{
|
||||
auto pathString = path_to_utf8(options.path);
|
||||
if (options.type == RENDER_PNGS)
|
||||
@@ -426,15 +382,9 @@ void Recorder::finish(const Document& document, AudioStream& audioStream)
|
||||
}
|
||||
else
|
||||
{
|
||||
audioStream.stream.clear();
|
||||
if (options.isSound && options.type != RENDER_GIF &&
|
||||
!audio_stream_generate(audioStream, document, sounds, options.fps))
|
||||
{
|
||||
toasts.push(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED));
|
||||
logger.error("Failed to generate deterministic render audio stream; exporting without audio.");
|
||||
}
|
||||
auto audio = options.isSound && options.type != RENDER_GIF ? audio_mix(sounds, options.fps) : std::vector<float>();
|
||||
auto isRendered =
|
||||
animation_render(options.ffmpegPath, options.path, frames, audioStream, options.type, options.fps);
|
||||
animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps);
|
||||
toast_log(isRendered ? Level::INFO : Level::ERROR,
|
||||
isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
|
||||
}
|
||||
@@ -471,8 +421,7 @@ bool animation_record(const RecorderOptions& recorderOptions, Canvas& canvas, Sh
|
||||
recorder.cancel();
|
||||
return false;
|
||||
}
|
||||
AudioStream audioStream(nullptr);
|
||||
recorder.finish(document, audioStream);
|
||||
recorder.finish();
|
||||
return is_path_exist(options.path);
|
||||
}
|
||||
|
||||
|
||||
+3
-3
@@ -6,7 +6,7 @@
|
||||
#include <vector>
|
||||
|
||||
#include "audio_data.h"
|
||||
#include "audio_stream.h"
|
||||
#include "audio.h"
|
||||
#include <glm/glm.hpp>
|
||||
|
||||
struct SDL_Window;
|
||||
@@ -170,7 +170,7 @@ public:
|
||||
float time_get() const;
|
||||
bool is_sound_frame() const;
|
||||
bool frame_capture(std::vector<uint8_t>, glm::ivec2, std::vector<const AudioData*> = {});
|
||||
void finish(const Document&, AudioStream&);
|
||||
void finish();
|
||||
void cancel();
|
||||
|
||||
private:
|
||||
@@ -187,4 +187,4 @@ bool animation_record(const RecorderOptions&, Canvas&, ShaderProgram&, Document&
|
||||
|
||||
std::filesystem::path ffmpeg_log_path();
|
||||
bool animation_render(const std::filesystem::path&, const std::filesystem::path&,
|
||||
const std::vector<std::filesystem::path>&, AudioStream&, RenderType, int);
|
||||
const std::vector<std::filesystem::path>&, const std::vector<float>&, RenderType, int);
|
||||
+1
-1
@@ -55,7 +55,7 @@ AudioData& Resources::music_track()
|
||||
{
|
||||
if (!isMusicLoaded)
|
||||
{
|
||||
music = AudioData(MUSIC_ABOUT_OPUS.data, MUSIC_ABOUT_OPUS.size);
|
||||
music = AudioData(MUSIC_ABOUT_OGG.data, MUSIC_ABOUT_OGG.size);
|
||||
isMusicLoaded = true;
|
||||
}
|
||||
return music;
|
||||
|
||||
+4
-4
@@ -105,9 +105,9 @@ static constexpr About::Credit CREDITS[] = {
|
||||
{"https://github.com/libsdl-org/SDL"},
|
||||
{"License: zlib"},
|
||||
{""},
|
||||
{"SDL_mixer"},
|
||||
{"https://github.com/libsdl-org/SDL_mixer"},
|
||||
{"License: zlib"},
|
||||
{"stb"},
|
||||
{"https://github.com/nothings/stb"},
|
||||
{"License: MIT or public domain"},
|
||||
{""},
|
||||
{"pugixml"},
|
||||
{"https://github.com/zeux/pugixml"},
|
||||
@@ -468,7 +468,7 @@ static void roll_draw(About& about, Resources& resources, ImVec2 min, ImVec2 siz
|
||||
|
||||
void About::reset(Resources& resources)
|
||||
{
|
||||
audio_play(resources.music_track(), true);
|
||||
audio_play(resources.music_track(), AUDIO_LOOP);
|
||||
roll = {};
|
||||
|
||||
for (int i = 0; i < FRIEND_COUNT; ++i)
|
||||
|
||||
@@ -134,14 +134,14 @@ void AnimationPreview::tick(Manager& manager, Settings& settings, float deltaSec
|
||||
|
||||
auto stop_all_sounds = [&]() {
|
||||
for (auto sound : document.sounds_get())
|
||||
audio_stop(*sound, mixer);
|
||||
audio_stop(*sound);
|
||||
};
|
||||
|
||||
if (manager.isRecording)
|
||||
{
|
||||
if (recorder.is_done())
|
||||
{
|
||||
recorder.finish(document, audioStream);
|
||||
recorder.finish();
|
||||
recording_stop(manager, document);
|
||||
}
|
||||
stop_all_sounds();
|
||||
@@ -177,7 +177,7 @@ void AnimationPreview::tick(Manager& manager, Settings& settings, float deltaSec
|
||||
if (manager.isRecording || !isSound)
|
||||
continue;
|
||||
for (auto sound : document.trigger_sounds_get(*animation, soundFrame))
|
||||
audio_play(*sound, false, mixer);
|
||||
audio_play(*sound);
|
||||
}
|
||||
|
||||
frameTime = playback.time;
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
#include <tuple>
|
||||
#include <vector>
|
||||
|
||||
#include "audio_stream.h"
|
||||
#include "ui/canvas_view.h"
|
||||
#include "manager.h"
|
||||
#include "model/draw.h"
|
||||
@@ -13,8 +12,6 @@
|
||||
|
||||
class AnimationPreview : public CanvasView
|
||||
{
|
||||
MIX_Mixer* mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr);
|
||||
AudioStream audioStream = AudioStream(mixer);
|
||||
bool wasPlaybackPlaying = false;
|
||||
int soundFrame = -1;
|
||||
bool isMoveDragging = false;
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
#include <format>
|
||||
#include <fstream>
|
||||
|
||||
#include "audio.h"
|
||||
#include "canvas.h"
|
||||
#include "embed.h"
|
||||
#include "document.h"
|
||||
#include "image.h"
|
||||
#include "render.h"
|
||||
@@ -329,3 +331,36 @@ TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the
|
||||
if (!std::getenv("ANM2ED_KEEP"))
|
||||
std::filesystem::remove_all(directory);
|
||||
}
|
||||
|
||||
// Sounds decode from WAV and Ogg Vorbis, and a render's audio starts each one on its frame.
|
||||
TEST_CASE("audio decodes and mixes")
|
||||
{
|
||||
AudioData music(MUSIC_ABOUT_OGG.data, MUSIC_ABOUT_OGG.size);
|
||||
auto musicMix = audio_mix({{&music}}, 30);
|
||||
CHECK(musicMix.size() > (std::size_t)AUDIO_FREQUENCY * AUDIO_CHANNELS);
|
||||
CHECK(std::ranges::any_of(musicMix, [](float sample) { return sample != 0.0f; }));
|
||||
|
||||
constexpr int FREQUENCY = 22050;
|
||||
constexpr int FRAMES = 100;
|
||||
std::vector<unsigned char> wav = {'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ', 16, 0, 0, 0,
|
||||
1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 16, 0, 'd', 'a', 't', 'a', 0, 0, 0, 0};
|
||||
auto put = [&](int offset, std::uint32_t value, int size) {
|
||||
for (int i = 0; i < size; ++i)
|
||||
wav[offset + i] = (unsigned char)(value >> (i * 8));
|
||||
};
|
||||
put(24, FREQUENCY, 4);
|
||||
put(28, FREQUENCY * 2, 4);
|
||||
put(40, FRAMES * 2, 4);
|
||||
for (int i = 0; i < FRAMES; ++i)
|
||||
{
|
||||
wav.push_back(0);
|
||||
wav.push_back(0x40);
|
||||
}
|
||||
put(4, (std::uint32_t)wav.size() - 8, 4);
|
||||
AudioData sound(wav.data(), wav.size());
|
||||
auto mix = audio_mix({{}, {&sound}}, 30);
|
||||
auto start = (std::size_t)(AUDIO_FREQUENCY / 30) * AUDIO_CHANNELS;
|
||||
REQUIRE(mix.size() > start + 2);
|
||||
CHECK(mix[start - 2] == 0.0f);
|
||||
CHECK(mix[start + 2] == doctest::Approx(0.5f).epsilon(0.05));
|
||||
}
|
||||
Reference in new issue
Block a user