Files
anm2ed/src/resource/audio.cpp
T
shweetandClaude Opus 5.5 26ab394fe4 Stage 1: headless Image and AudioData; GPU and playback caches in the UI
- resource::Image (pixels, size, uid) replaces Texture in documents, undo and
  wizards; it lives in anm2ed_core with no GL. uid changes with the pixels.
- resource::texture::id_get uploads lazily and evicts textures not drawn in a frame
- resource::AudioData (bytes, uid) replaces Audio; resource::audio::play/stop/
  track_detach/is_playing cache decoded audio and tracks per uid
- Resources::icon_id_get shortens the icon call sites
- tests/assets.cpp covers Image png round trip, uid tracking, merge_append

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:52:34 -04:00

76 lines
2.2 KiB
C++

#include "audio.hpp"
#include <unordered_map>
namespace anm2ed::resource::audio
{
struct Entry
{
MIX_Audio* audio{};
MIX_Track* track{};
};
std::unordered_map<std::uint64_t, Entry> entries{};
MIX_Mixer* mixer_get()
{
static auto mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr);
return mixer;
}
Entry* entry_get(const AudioData& data)
{
if (!data.is_valid()) return nullptr;
auto [it, isNew] = entries.try_emplace(data.uid);
if (isNew)
if (auto io = SDL_IOFromConstMem(data.bytes.data(), data.bytes.size()))
it->second.audio = MIX_LoadAudio_IO(mixer_get(), io, true, true);
return it->second.audio ? &it->second : nullptr;
}
// The playing track, when it belongs to mixer (or any mixer, when none is given).
MIX_Track* track_get(const AudioData& data, MIX_Mixer* mixer)
{
auto it = entries.find(data.uid);
if (it == entries.end() || !it->second.track) return nullptr;
return !mixer || MIX_GetTrackMixer(it->second.track) == mixer ? it->second.track : nullptr;
}
void play(const AudioData& data, bool isLoop, MIX_Mixer* mixer)
{
auto entry = entry_get(data);
auto targetMixer = mixer ? mixer : mixer_get();
if (!entry || !targetMixer) return;
if (entry->track && MIX_GetTrackMixer(entry->track) != targetMixer) track_detach(data);
if (!entry->track) entry->track = MIX_CreateTrack(targetMixer);
if (!entry->track) return;
MIX_SetTrackAudio(entry->track, entry->audio);
SDL_PropertiesID options = isLoop ? SDL_CreateProperties() : 0;
if (options) SDL_SetNumberProperty(options, MIX_PROP_PLAY_LOOPS_NUMBER, -1);
MIX_PlayTrack(entry->track, options);
if (options) SDL_DestroyProperties(options);
}
void stop(const AudioData& data, MIX_Mixer* mixer)
{
if (auto track = track_get(data, mixer)) MIX_StopTrack(track, 0);
}
void track_detach(const AudioData& data, MIX_Mixer* mixer)
{
if (!track_get(data, mixer)) return;
auto& track = entries[data.uid].track;
MIX_DestroyTrack(track);
track = nullptr;
}
bool is_playing(const AudioData& data)
{
auto track = track_get(data, nullptr);
return track && MIX_TrackPlaying(track);
}
}