added ADPCM, added encode/decode functions for vorbis/wav, automatically convert audio to ADPCM for Dreamcast playback, (theoretically working) spatial audio for AICA-audio backend, non-streamed (SFX) maybe working?

This commit is contained in:
ecker 2026-07-28 00:57:52 -05:00
parent d3d33383ec
commit 44e0caca5b
27 changed files with 1259 additions and 222 deletions

1
.gitignore vendored
View File

@ -63,6 +63,7 @@ default/
*.vmt
*.vtf
*.ztmp
*.adp
maps/
models/

View File

@ -23,7 +23,7 @@ CLIENT_SRC_DIR += ./client
# Base Flags
OPTIMIZATIONS = -O3 -fstrict-aliasing -DUF_NO_EXCEPTIONS
WARNINGS = -Wall -Wno-unknown-pragmas -Wno-unused-function -Wno-unused-variable -Wno-switch -Wno-reorder -Wno-sign-compare -Wno-unused-but-set-variable -Wno-ignored-attributes -Wno-narrowing -Wno-misleading-indentation
FLAGS += -std=c++2b $(OPTIMIZATIONS) $(WARNINGS) -fdiagnostics-color=always -DUF_DEV_ENV
FLAGS += -std=c++2b $(OPTIMIZATIONS) $(WARNINGS) -fdiagnostics-color=always
# Base Library Definitions
LIB_NAME += uf

View File

@ -137,4 +137,7 @@ typedef void ALvoid;
#define AL_STREAM_HANDLE 0x10001
#define AL_STREAM_FILL_CALLBACK 0x10002
#define AL_STREAM_USER_DATA 0x10003
#define AL_STREAM_USER_DATA 0x10003
#define AL_FORMAT_MONO_ADPCM_SEGA 0x2015
#define AL_FORMAT_STEREO_ADPCM_SEGA 0x2016

View File

@ -0,0 +1,23 @@
#pragma once
#if !UF_USE_ADP
#define UF_USE_adp 0
#else
#define UF_USE_adp 1
#include <uf/config.h>
#include <uf/utils/audio/audio.h>
namespace ext {
namespace adp {
void UF_API load( pod::AudioClip& );
void UF_API open( pod::AudioSource& );
void UF_API update( pod::AudioSource& );
void UF_API close( pod::AudioClip& );
void UF_API close( pod::AudioSource& );
bool UF_API decode( const uf::stl::string& filename, pod::PCM& pcm );
uf::stl::vector<uint8_t> UF_API encode( const pod::PCM& pcm );
}
}
#endif

View File

@ -1,7 +1,9 @@
#pragma once
#if !UF_USE_PCM
#define UF_USE_pcm 0
#else
#define UF_USE_pcm 1
#include <uf/config.h>
#include <uf/utils/audio/audio.h>
namespace ext {
@ -15,4 +17,5 @@ namespace ext {
uf::stl::vector<int16_t> UF_API convertTo16bit( const uf::stl::vector<float>& );
uf::stl::vector<int16_t> UF_API convertTo16bit( const float*, size_t );
}
}
}
#endif

View File

@ -1,8 +1,10 @@
#pragma once
#if !UF_USE_VORBIS
#define UF_USE_ogg 0
#else
#define UF_USE_ogg 1
#include <uf/config.h>
#if UF_USE_VORBIS
#if UF_USE_TREMOR
#include <tremor/ivorbisfile.h>
#else
@ -18,6 +20,11 @@ namespace ext {
void UF_API update( pod::AudioSource& );
void UF_API close( pod::AudioClip& );
void UF_API close( pod::AudioSource& );
bool UF_API decode( const uf::stl::string& filename, pod::PCM& pcm );
uf::stl::vector<uint8_t> UF_API encode( const pod::PCM& pcm );
}
// alias
namespace ogg = vorbis;
}
#endif

View File

@ -1,8 +1,10 @@
#pragma once
#if !UF_USE_WAV
#define UF_USE_wav 0
#else
#define UF_USE_wav 1
#include <uf/config.h>
#if UF_USE_WAV
#include <uf/utils/audio/audio.h>
namespace ext {
@ -12,6 +14,9 @@ namespace ext {
void UF_API update( pod::AudioSource& );
void UF_API close( pod::AudioClip& );
void UF_API close( pod::AudioSource& );
bool UF_API decode( const uf::stl::string& filename, pod::PCM& pcm );
uf::stl::vector<uint8_t> UF_API encode( const pod::PCM& pcm );
}
}
#endif

View File

@ -109,12 +109,12 @@
#if UF_CTTI
#if 0
#include <ctti/ctti.hpp>
#define TYPE_INDEX_T decltype(ctti::type_id_of<void>())
#define TYPE_HASH_T decltype(ctti::type_id_of<void>().hash())
#define TYPE(T) ctti::type_id_of<TYPE_SANITIZE(T)>()
#define TYPE_HASH(T) TYPE(T).hash()
#define TYPE_NAME(T) ctti::name_of<TYPE_SANITIZE(T)>()
#include <ctti/ctti.hpp>
#define TYPE_INDEX_T decltype(ctti::type_id_of<void>())
#define TYPE_HASH_T decltype(ctti::type_id_of<void>().hash())
#define TYPE(T) ctti::type_id_of<TYPE_SANITIZE(T)>()
#define TYPE_HASH(T) TYPE(T).hash()
#define TYPE_NAME(T) ctti::name_of<TYPE_SANITIZE(T)>()
#else
#include <ctti/type_id.hpp>
#define TYPE_INDEX_T ctti::type_id_t

View File

@ -57,6 +57,8 @@ namespace uf {
void UF_API update( pod::AudioSource& source, const pod::Vector3f& position, const pod::Quaternion<>& orientation );
void UF_API destroy( pod::AudioSource& source );
void UF_API destroy( pod::AudioClip& clip );
bool UF_API decode( const uf::stl::string& filename, pod::PCM& pcm );
uf::stl::vector<uint8_t> UF_API encode( const uf::stl::string& extension, pod::PCM& pcm );
void UF_API listener( const pod::Transform<>& transform );
void UF_API loop( pod::AudioSource& source, bool state );
void UF_API position( pod::AudioSource& source, const pod::Vector3f& v );

View File

@ -10,6 +10,25 @@
#include <uf/ext/openal/buffer.h>
#include <uf/utils/time/time.h>
#define UF_AUDIO_CALL_1(str, fmt, fun, ...) if ( (str) == #fmt ) ext::fmt::fun(__VA_ARGS__);
#define UF_AUDIO_CALL_0(str, fmt, fun, ...)
#define UF_AUDIO_DISPATCH_EVAL(use_val, str, fmt, fun, ...) \
TOKEN_PASTE(UF_AUDIO_CALL_, use_val)(str, fmt, fun, __VA_ARGS__)
#define UF_AUDIO_DISPATCH(str, fmt, fun, ...) \
UF_AUDIO_DISPATCH_EVAL(TOKEN_PASTE(UF_USE_, fmt), str, fmt, fun, __VA_ARGS__)
#define UF_AUDIO_CALL_SET_1(str, fmt, val, fun, ...) if ( (str) == #fmt ) val = ext::fmt::fun(__VA_ARGS__);
#define UF_AUDIO_CALL_SET_0(str, fmt, val, fun, ...)
#define UF_AUDIO_DISPATCH_SET_EVAL(use_val, str, fmt, val, fun, ...) \
TOKEN_PASTE(UF_AUDIO_CALL_SET_, use_val)(str, fmt, val, fun, __VA_ARGS__)
#define UF_AUDIO_DISPATCH_SET(str, fmt, val, fun, ...) \
UF_AUDIO_DISPATCH_SET_EVAL(TOKEN_PASTE(UF_USE_, fmt), str, fmt, val, fun, __VA_ARGS__)
// shoved here because dependencies
namespace pod {
// this technically could either be a template or have the samples buffer be uint8_t and store the bit depth / an enum for the format but I only really care about supporting 16-bit PCMs

View File

@ -26,6 +26,8 @@ namespace uf {
uf::stl::string UF_API basename( const uf::stl::string& );
uf::stl::string UF_API extension( const uf::stl::string& );
uf::stl::string UF_API extension( const uf::stl::string&, int32_t );
uf::stl::string UF_API remove_extension( const uf::stl::string& str );
uf::stl::string UF_API replace_extension( const uf::stl::string& str, const uf::stl::string& new_ext );
uf::stl::string UF_API directory( const uf::stl::string& );
uf::stl::string UF_API normalize( const uf::stl::string& );
size_t UF_API size( const uf::stl::string& );

View File

@ -76,6 +76,7 @@ namespace uf {
pod::Mount UF_API createDiskMount( const uf::stl::string& uri, int priority = 0 );
uf::stl::string UF_API resolveBase( const uf::stl::string& path );
bool UF_API isPhysical( const uf::stl::string& path );
}
}

View File

@ -249,6 +249,7 @@ uf::asset::Payload uf::asset::resolveToPayload( const uf::stl::string& uri, cons
{ "ogg", uf::asset::Type::AUDIO },
{ "wav", uf::asset::Type::AUDIO },
{ "adp", uf::asset::Type::AUDIO },
{ "json", uf::asset::Type::JSON },
{ "bson", uf::asset::Type::JSON },
@ -362,14 +363,18 @@ uf::stl::string uf::asset::load( uf::asset::Payload& payload ) {
asset.open(filename);
#if UF_USE_DC_TEXCONV
uf::stl::string output = uf::io::directory( filename ) + "/" + uf::io::basename( filename );
if ( extension != "dtex" && !uf::io::exists( output + ".dtex" ) ) {
uf::stl::string target = "dtex";
uf::stl::string output = uf::io::replace_extension( filename, target );
bool exists = uf::io::exists( output );
bool physical = uf::vfs::isPhysical( filename );
bool stale = exists ? uf::io::mtime( filename ) > uf::io::mtime( output ) : true;
if ( extension != target && !exists && physical && stale ) {
pod::Vector2ui size = { 32, 32 };
uf::stl::string filter = "linear";
uf::stl::string dtexFormat = "auto";
uf::stl::string format = "auto";
auto img = asset.scale( size, filter);
auto dtex = ext::texconv::convert( img, dtexFormat );
auto dtex = ext::texconv::convert( img, format );
ext::texconv::save( dtex, output );
UF_MSG_DEBUG("Converting image: {} => {}", filename, output );
}
@ -379,6 +384,25 @@ uf::stl::string uf::asset::load( uf::asset::Payload& payload ) {
UF_ASSET_REGISTER(pod::AudioClip)
asset.streamed = payload.metadata["streamed"].as<bool>( asset.streamed );
uf::audio::load(asset, filename);
#if UF_USE_ADP_ENCODER
uf::stl::string target = "adp";
uf::stl::string output = uf::io::replace_extension( filename, target );
bool exists = uf::io::exists( output );
bool physical = uf::vfs::isPhysical( filename );
bool stale = exists ? uf::io::mtime( filename ) > uf::io::mtime( output ) : true;
if ( extension != target && !exists && physical && stale ) {
pod::PCM pcm;
uf::stl::vector<uint8_t> encoded;
if ( uf::audio::decode( filename, pcm ) ) {
encoded = uf::audio::encode( target, pcm );
}
if ( !encoded.empty() ) {
UF_MSG_DEBUG("Converting audio: {} => {}", filename, output);
uf::io::write( output, encoded.data(), encoded.size() );
}
}
#endif
} break;
case uf::asset::Type::JSON: {
UF_ASSET_REGISTER(uf::Serializer)

View File

@ -59,6 +59,7 @@ void ext::AudioEmitterBehavior::initialize( uf::Object& self ) {
if ( !uf::asset::has( filename ) ) {
auto payload = uf::asset::resolveToPayload(filename, "");
payload.type = uf::asset::Type::AUDIO;
payload.metadata["streamed"] = false; // json["streamed"];
uf::asset::load( payload );
}

View File

@ -11,27 +11,47 @@
#include <math.h>
#include <kos/mutex.h>
#include <dc/cache.h>
#include <dc/sound/aica_comm.h>
typedef struct snd_effect {
uint32_t locl, locr;
uint32_t len;
uint32_t rate;
uint32_t used;
uint32_t fmt;
uint16_t stereo;
LIST_ENTRY(snd_effect) list;
} snd_effect_t;
#define UF_AICA_THREADED 0
namespace impl {
typedef int (*fill_callback_t)(void* user_data, uint8_t* buffer, int req_bytes);
constexpr int STREAM_BUFFER_SIZE = 16384;
constexpr int STREAM_BUFFER_SIZE = 65536; // 16384;
constexpr int DRIVER_BUFFER_SIZE = 65536;
constexpr size_t MAX_VIRTUAL_SOURCES = 256;
constexpr size_t MAX_VIRTUAL_BUFFERS = 1024;
constexpr size_t MAX_QUEUE_SIZE = 16;
struct Source {
bool active = false;
pod::Vector3f position = {0, 0, 0};
float gain = 1;
float pitch = 1;
float max_distance = 100;
float gain = 1.0f;
float pitch = 1.0f;
float max_distance = 100.0f;
bool looping = false;
int state = AL_STOPPED;
ALuint buffer_id = 0;
int hw_channel = -1;
ALuint queue[MAX_QUEUE_SIZE];
size_t queue_head = 0;
size_t queue_tail = 0;
size_t queue_count = 0;
};
struct Buffer {
@ -39,6 +59,8 @@ namespace impl {
uint32_t aica_addr = 0;
snd_stream_hnd_t stream_hnd = SND_STREAM_INVALID;
snd_effect_t* sfx_effect = nullptr;
void* user_data = nullptr;
uint8_t* stream_buffer = nullptr;
impl::fill_callback_t fill_callback = nullptr;
@ -47,7 +69,7 @@ namespace impl {
ALsizei size = 0;
ALsizei frequency = 0;
};
struct Listener {
pod::Vector3f position = {0, 0, 0};
pod::Vector3f right = {1, 0, 0};
@ -85,41 +107,160 @@ namespace impl {
uint32_t getSourceIndex() {
for ( size_t i = 1; i < impl::MAX_VIRTUAL_SOURCES; ++i ) {
if ( !impl::sources[i].active ) {
impl::sources[i].active = true;
impl::sources[i].state = AL_STOPPED;
UF_MSG_DEBUG("Assigning index: {}", i);
return i;
}
}
return 0;
}
uint32_t getBufferIndex() {
for ( size_t i = 1; i < impl::MAX_VIRTUAL_BUFFERS; ++i ) {
if ( !impl::buffers[i].active ) {
impl::buffers[i].active = true;
UF_MSG_DEBUG("Assigning index: {}", i);
impl::sources[i] = {
.active = true,
};
UF_MSG_DEBUG("Assigning Source index: {}", i);
return i;
}
}
return 0;
}
uint32_t getBufferIndex() {
for ( size_t i = 1; i < impl::MAX_VIRTUAL_BUFFERS; ++i ) {
if ( !impl::buffers[i].active ) {
impl::buffers[i] = {
.active = true,
};
UF_MSG_DEBUG("Assigning Buffer index: {}", i);
return i;
}
}
return 0;
}
pod::Vector3f spatial( impl::Source& source, impl::Listener& listener ) {
if ( !uf::vector::isValid( source.position ) || !uf::vector::isValid( listener.position ) ) {
return { 0, 0, 0 };
}
pod::Vector3f d = source.position - listener.position;
float dist = uf::vector::norm( d );
if ( dist > EPS ) d /= dist;
float pan_factor = 0.0f;
if ( dist > 0.001f ) {
pan_factor = uf::vector::dot( listener.right, d );
}
int pan = (int)((pan_factor + 1.0f) * 127.5f);
if ( pan < 0 ) pan = 0;
if ( pan > 255 ) pan = 255;
return pod::Vector3f{ dist, (float)pan, 0.0f };
}
snd_stream_hnd_t allocateStreamSlot() {
snd_stream_hnd_t hnd = snd_stream_alloc( impl::kos_stream_callback, impl::DRIVER_BUFFER_SIZE );
if ( hnd != SND_STREAM_INVALID ) return hnd;
impl::Source* victim_src = nullptr;
impl::Buffer* victim_buf = nullptr;
for ( size_t i = 1; i < impl::MAX_VIRTUAL_SOURCES; ++i ) {
impl::Source& src = impl::sources[i];
if ( src.active && src.state == AL_PLAYING && src.buffer_id > 0 ) {
impl::Buffer& buf = impl::buffers[src.buffer_id];
if ( buf.stream_hnd != SND_STREAM_INVALID ) {
victim_src = &src;
victim_buf = &buf;
break;
}
}
}
if ( victim_buf && victim_src ) {
UF_MSG_DEBUG("[AICA] Evicting active stream handle {} to release hardware slot", victim_buf->stream_hnd);
snd_stream_stop( victim_buf->stream_hnd );
mutex_lock(&impl::g_streamMutex);
impl::g_activeStreams.erase(victim_buf->stream_hnd);
mutex_unlock(&impl::g_streamMutex);
snd_stream_destroy( victim_buf->stream_hnd );
victim_buf->stream_hnd = SND_STREAM_INVALID;
victim_src->state = AL_STOPPED;
hnd = snd_stream_alloc( impl::kos_stream_callback, impl::DRIVER_BUFFER_SIZE );
}
return hnd;
}
void update() {
for ( size_t i = 1; i < impl::MAX_VIRTUAL_SOURCES; ++i ) {
impl::Source& src = impl::sources[i];
if ( !src.active ) continue;
if ( src.state != AL_PLAYING ) continue;
pod::Vector3f spatial_data = impl::spatial(src, impl::listener);
float dist = spatial_data[0];
int left_pan = (int)spatial_data[1];
int right_pan = (int)spatial_data[2];
float base_gain = src.gain;
float gain_factor = 1.0f;
if ( dist > 0.0f && src.max_distance > 0.0f ) {
gain_factor = 1.0f - (dist / src.max_distance);
if ( gain_factor < 0.0f ) gain_factor = 0.0f;
}
int vol = (int)(255.0f * base_gain * gain_factor);
if ( vol < 0 ) vol = 0;
if ( vol > 255 ) vol = 255;
if ( 0 < src.buffer_id && src.buffer_id < impl::MAX_VIRTUAL_BUFFERS ) {
impl::Buffer& buffer = impl::buffers[src.buffer_id];
if ( buffer.stream_hnd != SND_STREAM_INVALID ) {
snd_stream_volume(buffer.stream_hnd, vol);
snd_stream_pan(buffer.stream_hnd, left_pan, right_pan);
int poll_result = snd_stream_poll(buffer.stream_hnd);
if ( poll_result < 0 ) {
src.state = AL_STOPPED;
snd_stream_stop(buffer.stream_hnd);
}
} else if ( src.hw_channel != -1 ) {
bool playing = snd_is_playing(src.hw_channel);
if ( !playing ) {
src.state = AL_STOPPED;
snd_sfx_chn_free(src.hw_channel);
if ( buffer.sfx_effect && buffer.sfx_effect->stereo ) {
snd_sfx_chn_free(src.hw_channel + 1);
}
src.hw_channel = -1;
} else {
AICA_CMDSTR_CHANNEL(tmp, cmd, chan);
cmd->cmd = AICA_CMD_CHAN;
cmd->timestamp = 0;
cmd->size = AICA_CMDSTR_CHANNEL_SIZE;
cmd->cmd_id = src.hw_channel;
chan->cmd = AICA_CH_CMD_UPDATE | AICA_CH_UPDATE_SET_VOL | AICA_CH_UPDATE_SET_PAN;
chan->vol = vol;
chan->pan = (buffer.sfx_effect && buffer.sfx_effect->stereo) ? 0 : left_pan;
snd_sh4_to_aica(tmp, cmd->size);
if ( buffer.sfx_effect && buffer.sfx_effect->stereo ) {
cmd->cmd_id = src.hw_channel + 1;
chan->pan = 255;
snd_sh4_to_aica(tmp, cmd->size);
}
}
}
}
}
}
#if UF_AICA_THREADED
kthread_t* thread_handle = nullptr;
// to-do: pipe into uf::thread instead?
void* audio_thread( void* param ) {
while ( true ) {
mutex_lock( &impl::g_streamMutex );
for ( auto& pair : impl::g_activeStreams ) {
// to-do: check if playing
int status = snd_stream_poll(pair.first);
if ( status < 0 ) {
// to-do: set source to stopped
}
}
impl::update();
mutex_unlock( &impl::g_streamMutex );
thd_sleep(50);
thd_sleep(20);
}
return NULL;
}
@ -226,9 +367,7 @@ void ext::al::Source::get( ALenum name, ALint* f ) const {
if ( f ) this->get( name, f[0] );
}
void ext::al::Source::set( ALenum name, ALint x, ALint y, ALint z ) {
// ...
}
void ext::al::Source::set( ALenum name, ALint x, ALint y, ALint z ) {}
void ext::al::Source::set( const uf::stl::string& string, ALfloat x, ALfloat y, ALfloat z ) {
if ( string == "POSITION" ) this->set( AL_POSITION, x, y, z );
@ -252,27 +391,47 @@ void ext::al::Source::play() {
if ( 0 < src.buffer_id && src.buffer_id < impl::MAX_VIRTUAL_BUFFERS ) {
impl::Buffer& buffer = impl::buffers[src.buffer_id];
int vol = 255; // (int)(255.0f * src.gain);
int pan = 128;
if ( buffer.aica_addr != 0 ) {
// snd_sfx_play(buffer.aica_addr, vol, pan); // earrape
pod::Vector3f spatial_data = impl::spatial(src, impl::listener);
float dist = spatial_data[0];
int left_pan = (int)spatial_data[1];
float gain_factor = 1.0f;
if ( dist > 0.0f && src.max_distance > 0.0f ) {
gain_factor = 1.0f - (dist / src.max_distance);
if ( gain_factor < 0.0f ) gain_factor = 0.0f;
}
int vol = (int)(255.0f * src.gain * gain_factor);
if ( vol < 0 ) vol = 0;
if ( vol > 255 ) vol = 255;
if ( buffer.aica_addr != 0 && buffer.sfx_effect ) {
sfx_play_data_t play_data = {0};
play_data.chn = -1;
play_data.idx = (sfxhnd_t)buffer.sfx_effect;
play_data.vol = vol;
play_data.pan = buffer.sfx_effect->stereo ? 0 : left_pan;
play_data.loop = src.looping ? 1 : 0;
play_data.loopstart = 0;
play_data.loopend = buffer.sfx_effect->len;
play_data.freq = buffer.sfx_effect->rate;
src.hw_channel = snd_sfx_play_ex(&play_data);
} else if ( buffer.stream_hnd != SND_STREAM_INVALID ) {
int channels = (buffer.format == AL_FORMAT_STEREO16 || buffer.format == AL_FORMAT_STEREO8) ? 1 : 0;
bool is_stereo = (buffer.format == AL_FORMAT_STEREO16 || buffer.format == AL_FORMAT_STEREO8 || buffer.format == AL_FORMAT_STEREO_ADPCM_SEGA);
int st = is_stereo ? 1 : 0;
mutex_lock(&impl::g_streamMutex);
snd_stream_reinit(buffer.stream_hnd, impl::kos_stream_callback);
snd_stream_start(buffer.stream_hnd, buffer.frequency, channels);
snd_stream_volume(buffer.stream_hnd, vol);
/*
snd_stream_reinit(buffer.stream_hnd, impl::kos_stream_callback);
snd_stream_queue_enable(buffer.stream_hnd);
snd_stream_start(buffer.stream_hnd, buffer.frequency, channels);
snd_stream_queue_go(buffer.stream_hnd);
snd_stream_volume(buffer.stream_hnd, vol);
*/
if ( buffer.format == AL_FORMAT_MONO_ADPCM_SEGA || buffer.format == AL_FORMAT_STEREO_ADPCM_SEGA ) {
snd_stream_start_adpcm(buffer.stream_hnd, buffer.frequency, st);
} else if ( buffer.format == AL_FORMAT_MONO8 || buffer.format == AL_FORMAT_STEREO8 ) {
snd_stream_start_pcm8(buffer.stream_hnd, buffer.frequency, st);
} else {
snd_stream_start(buffer.stream_hnd, buffer.frequency, st);
}
snd_stream_volume(buffer.stream_hnd, vol);
mutex_unlock(&impl::g_streamMutex);
}
}
@ -286,8 +445,11 @@ void ext::al::Source::pause() {
if ( 0 < src.buffer_id && src.buffer_id < impl::MAX_VIRTUAL_BUFFERS ) {
impl::Buffer& buffer = impl::buffers[src.buffer_id];
if ( buffer.aica_addr != 0 ) {
// ...
if ( buffer.aica_addr != 0 && src.hw_channel != -1 ) {
snd_sfx_stop(src.hw_channel);
if ( buffer.sfx_effect && buffer.sfx_effect->stereo ) {
snd_sfx_stop(src.hw_channel + 1);
}
} else if ( buffer.stream_hnd != SND_STREAM_INVALID ) {
snd_stream_stop(buffer.stream_hnd);
}
@ -302,8 +464,14 @@ void ext::al::Source::stop() {
if ( 0 < src.buffer_id && src.buffer_id < impl::MAX_VIRTUAL_BUFFERS ) {
impl::Buffer& buffer = impl::buffers[src.buffer_id];
if ( buffer.aica_addr != 0 ) {
// ...
if ( buffer.aica_addr != 0 && src.hw_channel != -1 ) {
snd_sfx_stop(src.hw_channel);
snd_sfx_chn_free(src.hw_channel);
if ( buffer.sfx_effect && buffer.sfx_effect->stereo ) {
snd_sfx_stop(src.hw_channel + 1);
snd_sfx_chn_free(src.hw_channel + 1);
}
src.hw_channel = -1;
} else if ( buffer.stream_hnd != SND_STREAM_INVALID ) {
snd_stream_stop(buffer.stream_hnd);
}
@ -315,12 +483,31 @@ bool ext::al::Source::playing() const {
return impl::sources[this->m_index].state == AL_PLAYING;
}
// to-do: implement queueing
void ext::al::Source::queue( ALsizei n, ALuint* indices ) {
//AL_CHECK_RESULT(alSourceQueueBuffers(this->m_index, n, indices));
if ( !this->m_index ) return;
impl::Source& src = impl::sources[this->m_index];
for ( ALsizei i = 0; i < n; ++i ) {
if ( src.queue_count < impl::MAX_QUEUE_SIZE ) {
src.queue[src.queue_tail] = indices[i];
src.queue_tail = (src.queue_tail + 1) % impl::MAX_QUEUE_SIZE;
src.queue_count++;
}
}
if ( src.state == AL_STOPPED && src.queue_count > 0 ) {
src.buffer_id = src.queue[src.queue_head];
}
}
void ext::al::Source::unqueue( ALsizei n, ALuint* indices ) {
//AL_CHECK_RESULT(alSourceUnqueueBuffers(this->m_index, n, indices));
if ( !this->m_index ) return;
impl::Source& src = impl::sources[this->m_index];
for ( ALsizei i = 0; i < n; ++i ) {
if ( src.queue_count > 0 ) {
indices[i] = src.queue[src.queue_head];
src.queue_head = (src.queue_head + 1) % impl::MAX_QUEUE_SIZE;
src.queue_count--;
}
}
}
bool ext::al::Buffer::initialized() const {
@ -330,7 +517,7 @@ bool ext::al::Buffer::initialized() const {
void ext::al::Buffer::initialize( size_t size ) {
if ( this->initialized() ) this->destroy();
this->m_indices.resize(size, 0);
for ( auto i = 0; i < size; ++i ) {
for ( size_t i = 0; i < size; ++i ) {
this->m_indices[i] = impl::getBufferIndex();
}
}
@ -342,6 +529,11 @@ void ext::al::Buffer::destroy() {
if ( 0 < index && index < impl::MAX_VIRTUAL_BUFFERS ) {
impl::Buffer& buffer = impl::buffers[index];
if ( buffer.sfx_effect ) {
free(buffer.sfx_effect);
buffer.sfx_effect = nullptr;
}
if ( buffer.aica_addr ) {
snd_mem_free( buffer.aica_addr );
} else if ( buffer.stream_hnd != SND_STREAM_INVALID ) {
@ -374,16 +566,9 @@ ALuint ext::al::Buffer::getIndex( size_t i ) const { return this->m_indices[i];
void ext::al::Buffer::poll( size_t i ) {
#if !UF_AICA_THREADED
if ( !this->initialized() ) return;
ALuint index = this->m_indices[i];
if ( 0 < index && index < impl::MAX_VIRTUAL_BUFFERS ) {
impl::Buffer& buffer = impl::buffers[index];
if ( buffer.stream_hnd == SND_STREAM_INVALID ) return;
// to-do: adjust volume based on distance / pan based on orientation
int poll_result = snd_stream_poll( buffer.stream_hnd );
if ( poll_result < 0 ) UF_MSG_ERROR("[AICA] snd_stream_poll({}) failed with code: {}", buffer.stream_hnd, poll_result);
}
mutex_lock( &impl::g_streamMutex );
impl::update();
mutex_unlock( &impl::g_streamMutex );
#endif
}
@ -409,8 +594,6 @@ void ext::al::Buffer::get( ALenum name, ALint& value, size_t i ) const {
}
void ext::al::Buffer::set( ALenum name, ALint* iv, size_t i ) {
//AL_CHECK_RESULT(alBufferiv( this->m_indices[i], name, iv ));
if ( !this->initialized() ) this->initialize(1);
ALuint index = this->m_indices[i];
@ -420,11 +603,12 @@ void ext::al::Buffer::set( ALenum name, ALint* iv, size_t i ) {
else if ( name == AL_STREAM_USER_DATA ) buffer.user_data = (void*)(iv);
}
}
void ext::al::Buffer::buffer( ALenum format, const ALvoid* data, ALsizei size, ALsizei frequency, size_t i ) {
if ( !this->initialized() ) this->initialize();
ext::al::Buffer::buffer( this->m_indices[i], format, data, size, frequency );
}
// to-do: pick between snd_sfx_* backend (non-streamed) or snd_stream_* (streamed)
#if 1
void ext::al::Buffer::buffer( ALuint index, ALenum format, const ALvoid* data, ALsizei size, ALsizei frequency ) {
impl::Buffer& buffer = impl::buffers[index];
@ -446,9 +630,9 @@ void ext::al::Buffer::buffer( ALuint index, ALenum format, const ALvoid* data, A
UF_MSG_ERROR("[AICA] Failed to allocate {} bytes", impl::STREAM_BUFFER_SIZE);
return;
}
buffer.stream_hnd = snd_stream_alloc( impl::kos_stream_callback, impl::DRIVER_BUFFER_SIZE );
buffer.stream_hnd = impl::allocateStreamSlot();
if ( buffer.stream_hnd == SND_STREAM_INVALID ) {
UF_MSG_ERROR("[AICA] Failed to allocate {} bytes", impl::STREAM_BUFFER_SIZE);
UF_MSG_ERROR("[AICA] Failed to allocate streaming slot context");
return;
}
mutex_lock(&impl::g_streamMutex);
@ -460,13 +644,109 @@ void ext::al::Buffer::buffer( ALuint index, ALenum format, const ALvoid* data, A
UF_MSG_ERROR("[AICA] Failed to allocate {} bytes", size);
return;
}
spu_memload(aica_addr, (void*)(data), size);
if ( format == AL_FORMAT_STEREO_ADPCM_SEGA && buffer.sfx_effect && buffer.sfx_effect->stereo ) {
uint32_t* left_temp = (uint32_t*)memalign(32, size / 2);
uint32_t* right_temp = (uint32_t*)memalign(32, size / 2);
if ( left_temp && right_temp ) {
snd_adpcm_split((uint32_t*)data, left_temp, right_temp, size);
spu_memload(aica_addr, left_temp, size / 2);
spu_memload(aica_addr + (size / 2), right_temp, size / 2);
UF_MSG_DEBUG("[AICA] Stereo ADPCM Split Success: locl=0x{:X}, locr=0x{:X}", aica_addr, aica_addr + (size / 2));
} else {
UF_MSG_ERROR("[AICA] Failed to allocate aligned splitting memory");
spu_memload(aica_addr, (void*)(data), size);
}
if ( left_temp ) free(left_temp);
if ( right_temp ) free(right_temp);
} else {
spu_memload(aica_addr, (void*)(data), size);
}
buffer.aica_addr = aica_addr;
UF_MSG_DEBUG("[AICA] Buffer ID {} allocated {} bytes at SPU addr 0x{:X}", index, size, aica_addr);
} else {
UF_EXCEPTION("[AICA] invalid invocation");
}
}
#else
void ext::al::Buffer::buffer( ALuint index, ALenum format, const ALvoid* data, ALsizei size, ALsizei frequency ) {
impl::Buffer& buffer = impl::buffers[index];
if ( buffer.sfx_effect ) {
free(buffer.sfx_effect);
buffer.sfx_effect = nullptr;
}
if ( buffer.aica_addr ) {
snd_mem_free(buffer.aica_addr);
buffer.aica_addr = 0;
}
if ( buffer.stream_hnd != SND_STREAM_INVALID ) {
snd_stream_destroy(buffer.stream_hnd);
}
buffer.format = format;
buffer.frequency = frequency;
buffer.size = size;
if ( buffer.fill_callback ) {
if ( !buffer.stream_buffer ) buffer.stream_buffer = (uint8_t*)(memalign(32, impl::STREAM_BUFFER_SIZE));
if ( !buffer.stream_buffer ) {
UF_MSG_ERROR("[AICA] Failed to allocate {} bytes", impl::STREAM_BUFFER_SIZE);
return;
}
buffer.stream_hnd = impl::allocateStreamSlot();
if ( buffer.stream_hnd == SND_STREAM_INVALID ) {
UF_MSG_ERROR("[AICA] Failed to allocate streaming slot context");
return;
}
mutex_lock(&impl::g_streamMutex);
impl::g_activeStreams[buffer.stream_hnd] = &buffer;
mutex_unlock(&impl::g_streamMutex);
} else if ( data && size ) {
uint16_t channels = (format == AL_FORMAT_STEREO8 || format == AL_FORMAT_STEREO16) ? 2 : 1;
uint16_t bitsize = (format == AL_FORMAT_MONO8 || format == AL_FORMAT_STEREO8) ? 8 : 16;
uint32_t aica_fmt = (bitsize == 8) ? AICA_SM_8BIT : AICA_SM_16BIT;
buffer.sfx_effect = (snd_effect_t*)malloc(sizeof(snd_effect_t));
if ( !buffer.sfx_effect ) {
UF_MSG_ERROR("[AICA] Out of host memory for static sound descriptor");
return;
}
memset(buffer.sfx_effect, 0, sizeof(snd_effect_t));
buffer.sfx_effect->rate = frequency;
buffer.sfx_effect->stereo = (channels > 1);
buffer.sfx_effect->fmt = aica_fmt;
buffer.sfx_effect->len = (bitsize == 16) ? (size / 2) / channels : size / channels;
uint32_t aica_addr = snd_mem_malloc(size);
if ( !aica_addr ) {
free(buffer.sfx_effect);
buffer.sfx_effect = nullptr;
UF_MSG_ERROR("[AICA] Failed to allocate SPU RAM ({} bytes)", size);
return;
}
spu_memload(aica_addr, (void*)(data), size);
buffer.aica_addr = aica_addr;
buffer.sfx_effect->locl = aica_addr;
if ( channels > 1 ) {
buffer.sfx_effect->locr = aica_addr + (size / 2);
}
UF_MSG_DEBUG("[AICA] Static Buffer ID {} allocated {} bytes at SPU addr 0x{:X}", index, size, aica_addr);
} else {
UF_EXCEPTION("[AICA] invalid invocation");
}
}
#endif
// stubbed
void ext::al::Filter::initialize() {}

View File

@ -0,0 +1,392 @@
#if UF_USE_ADP
#include <uf/config.h>
#include <uf/ext/audio/adp.h>
#include <uf/utils/io/vfs.h>
#if UF_USE_OPENAL
#include <uf/ext/openal/openal.h>
#endif
#if UF_USE_AICA
#include <uf/ext/aica/aica.h>
#endif
namespace {
struct AdpHeader {
char magic[4]; // "ADPF"
uint32_t channels;
uint32_t sampleRate;
uint32_t totalSamples;
uint32_t dataSize;
};
struct AdpState {
int32_t predictor = 0;
int32_t step = 127;
};
struct AdpVfsContext {
AdpHeader header;
pod::File file;
size_t dataOffset = 0;
AdpState state[2];
~AdpVfsContext() {
if ( file ) file.close( file.handle );
}
};
static const int32_t YAMAHA_SCALE[8] = { 230, 230, 230, 230, 307, 409, 512, 614 };
inline int16_t decode_sample(uint8_t nibble, AdpState& state) {
int32_t d = nibble & 7;
int32_t diff = state.step >> 3;
if ( d & 1 ) diff += state.step >> 2;
if ( d & 2 ) diff += state.step >> 1;
if ( d & 4 ) diff += state.step;
if ( nibble & 8 ) {
state.predictor -= diff;
} else {
state.predictor += diff;
}
if ( state.predictor > 32767 ) state.predictor = 32767;
else if ( state.predictor < -32768 ) state.predictor = -32768;
state.step = (state.step * YAMAHA_SCALE[d]) >> 8;
if ( state.step < 127 ) state.step = 127;
if ( state.step > 24576 ) state.step = 24576;
return (int16_t)state.predictor;
}
int fill_buffer( void* user_data, uint8_t* buffer, int req_bytes ) {
pod::AudioSource* source = (pod::AudioSource*)user_data;
pod::AudioClip* clip = source->clip;
AdpVfsContext* ctx = (AdpVfsContext*)source->streamState.handle;
#if UF_USE_AICA
size_t bytesRead = ctx->file.read(ctx->file.handle, buffer, req_bytes);
if ( bytesRead == 0 && source->settings.loop ) {
ctx->file.seek(ctx->file.handle, ctx->dataOffset, SEEK_SET);
bytesRead = ctx->file.read(ctx->file.handle, buffer, req_bytes);
}
return (int)bytesRead;
#else
int16_t* pcmOut = (int16_t*)buffer;
int totalPcmSamplesNeeded = req_bytes / sizeof(int16_t);
int totalSamplesRead = 0;
int channels = ctx->header.channels;
uint8_t adpByte;
while ( totalSamplesRead < totalPcmSamplesNeeded ) {
if ( ctx->file.read(ctx->file.handle, &adpByte, 1) != 1 ) {
if ( source->settings.loop ) {
ctx->file.seek(ctx->file.handle, ctx->dataOffset, SEEK_SET);
ctx->state[0] = {0, 127}; ctx->state[1] = {0, 127};
continue;
}
break;
}
if ( channels == 1 ) {
pcmOut[totalSamplesRead++] = decode_sample(adpByte & 0x0F, ctx->state[0]);
if ( totalSamplesRead < totalPcmSamplesNeeded ) {
pcmOut[totalSamplesRead++] = decode_sample((adpByte >> 4) & 0x0F, ctx->state[0]);
}
} else if ( channels == 2 ) {
pcmOut[totalSamplesRead++] = decode_sample(adpByte & 0x0F, ctx->state[0]); // Left
pcmOut[totalSamplesRead++] = decode_sample((adpByte >> 4) & 0x0F, ctx->state[1]); // Right
}
}
return totalSamplesRead * sizeof(int16_t);
#endif
}
bool decode( const AdpHeader& header, const uint8_t* rawAdp, pod::PCM& pcm ) {
pcm.channels = header.channels;
pcm.sampleRate = header.sampleRate;
pcm.samples.resize(header.totalSamples * header.channels);
AdpState decState[2] = { {0, 127}, {0, 127} };
size_t sampleIdx = 0;
if ( header.channels == 1 ) {
for ( size_t i = 0; i < header.dataSize; ++i ) {
pcm.samples[sampleIdx++] = decode_sample(rawAdp[i] & 0x0F, decState[0]);
if ( sampleIdx < pcm.samples.size() ) {
pcm.samples[sampleIdx++] = decode_sample((rawAdp[i] >> 4) & 0x0F, decState[0]);
}
}
} else if ( header.channels == 2 ) {
for ( size_t i = 0; i < header.dataSize; ++i ) {
pcm.samples[sampleIdx++] = decode_sample(rawAdp[i] & 0x0F, decState[0]); // Left
pcm.samples[sampleIdx++] = decode_sample((rawAdp[i] >> 4) & 0x0F, decState[1]); // Right
}
}
return true;
}
}
void ext::adp::load( pod::AudioClip& clip ) {
AdpVfsContext* ctx = new AdpVfsContext();
ctx->file = uf::vfs::open(clip.filename);
if ( !ctx->file ) {
UF_MSG_ERROR("ADP: Failed to open file: {}", clip.filename);
delete ctx; return;
}
ctx->file.read(ctx->file.handle, &ctx->header, sizeof(AdpHeader));
clip.info.channels = ctx->header.channels;
clip.info.bitDepth = 4;
clip.info.frequency = ctx->header.sampleRate;
clip.info.size = ctx->header.dataSize;
clip.info.duration = (double)ctx->header.totalSamples / ctx->header.sampleRate;
#if UF_USE_AICA
clip.info.format = (ctx->header.channels == 2) ? AL_FORMAT_STEREO_ADPCM_SEGA : AL_FORMAT_MONO_ADPCM_SEGA;
#else
clip.info.format = (ctx->header.channels == 2) ? AL_FORMAT_STEREO16 : AL_FORMAT_MONO16;
#endif
UF_MSG_DEBUG("filename={}, streamed={}", clip.filename, clip.streamed);
if ( !clip.streamed ) {
std::vector<uint8_t> rawAdp(ctx->header.dataSize);
ctx->file.read(ctx->file.handle, rawAdp.data(), ctx->header.dataSize);
#if UF_USE_AICA
clip.alBuffer.buffer(clip.info.format, rawAdp.data(), (ALsizei)rawAdp.size(), clip.info.frequency);
#else
pod::PCM pcm;
if ( ::decode(ctx->header, rawAdp.data(), pcm) ) {
clip.alBuffer.buffer(clip.info.format, pcm.samples.data(), (ALsizei)(pcm.samples.size() * sizeof(int16_t)), clip.info.frequency);
}
#endif
}
delete ctx;
}
void ext::adp::open( pod::AudioSource& source ) {
pod::AudioClip* clip = source.clip;
if ( !clip || !clip->streamed ) return;
source.streamBuffers.initialize(source.settings.buffers);
AdpVfsContext* ctx = new AdpVfsContext();
ctx->file = uf::vfs::open(clip->filename);
if ( !ctx->file ) {
UF_MSG_ERROR("ADP: Failed to open streaming file: {}", clip->filename);
delete ctx; return;
}
ctx->file.read(ctx->file.handle, &ctx->header, sizeof(AdpHeader));
ctx->dataOffset = sizeof(AdpHeader);
ctx->state[0] = {0, 127}; ctx->state[1] = {0, 127};
source.streamState.handle = (void*)ctx;
#if UF_USE_AICA
source.streamBuffers.set( AL_STREAM_FILL_CALLBACK, (ALint*)(::fill_buffer) );
source.streamBuffers.set( AL_STREAM_USER_DATA, (ALint*)(&source) );
source.alSource.set(AL_BUFFER, (ALint)(source.streamBuffers.getIndex(0)));
source.streamBuffers.buffer( clip->info.format, NULL, 0, clip->info.frequency );
#else
uint8_t buffer[uf::audio::bufferSize];
uint8_t queuedBuffers = 0;
for ( ; queuedBuffers < source.settings.buffers; ++queuedBuffers ) {
int totalRead = ::fill_buffer(&source, buffer, uf::audio::bufferSize);
if ( totalRead == 0 ) break;
ext::al::Buffer::buffer( source.streamBuffers.getIndex(queuedBuffers), clip->info.format, buffer, totalRead, clip->info.frequency);
}
source.alSource.queue( queuedBuffers, &source.streamBuffers.getIndex(0) );
#endif
}
void ext::adp::update( pod::AudioSource& source ) {
pod::AudioClip* clip = source.clip;
if ( !clip || !clip->streamed || !source.streamState.handle ) return;
#if UF_USE_AICA
source.streamBuffers.poll();
#else
AdpVfsContext* ctx = (AdpVfsContext*)source.streamState.handle;
ALint state, processed, queued;
source.alSource.get(AL_SOURCE_STATE, state);
source.alSource.get(AL_BUFFERS_PROCESSED, processed);
source.alSource.get(AL_BUFFERS_QUEUED, queued);
bool hasData = (ctx->file.tell(ctx->file.handle) < (long)clip->info.size) || !source.info.pending.empty() || source.settings.loop;
auto fillAndQueueBuffer = [&](ALuint index) -> bool {
uint8_t buffer[uf::audio::bufferSize];
int totalRead = ::fill_buffer(&source, buffer, uf::audio::bufferSize);
if ( totalRead > 0 ) {
ext::al::Buffer::buffer(index, clip->info.format, buffer, totalRead, clip->info.frequency);
source.alSource.queue( 1, &index );
return true;
}
return false;
};
if ( queued == 0 ) {
if ( hasData ) {
for ( int i = 0; i < source.settings.buffers; ++i ) {
if ( !fillAndQueueBuffer(source.streamBuffers.getIndex(i)) ) break;
}
}
} else {
while ( processed > 0 ) {
ALuint index;
source.alSource.unqueue( 1, &index );
processed--;
if ( hasData ) fillAndQueueBuffer(index);
}
}
if ( state != AL_PLAYING && queued > 0 ) {
source.alSource.play();
}
#endif
}
void ext::adp::close( pod::AudioClip& clip ) {}
void ext::adp::close( pod::AudioSource& source ) {
if ( !source.clip || !source.clip->streamed ) return;
#if !UF_USE_AICA
ALint queued;
source.alSource.get(AL_BUFFERS_QUEUED, queued);
while ( queued-- ) {
ALuint buffer;
source.alSource.unqueue( 1, &buffer );
}
#endif
source.streamBuffers.destroy();
if ( source.streamState.handle ) {
AdpVfsContext* ctx = (AdpVfsContext*)source.streamState.handle;
delete ctx;
source.streamState.handle = nullptr;
}
}
bool ext::adp::decode( const uf::stl::string& filename, pod::PCM& pcm ) {
pod::File file = uf::vfs::open(filename);
if ( !file ) {
UF_MSG_ERROR("ADP Decoder: Failed to open file: {}", filename);
return false;
}
AdpHeader header;
file.read(file.handle, &header, sizeof(AdpHeader));
if ( std::strncmp(header.magic, "ADPF", 4) != 0 ) {
UF_MSG_ERROR("ADP Decoder: Invalid file format magic in: {}", filename);
file.close(file.handle);
return false;
}
std::vector<uint8_t> rawAdp(header.dataSize);
file.read(file.handle, rawAdp.data(), header.dataSize);
file.close(file.handle);
return ::decode(header, rawAdp.data(), pcm);
}
#if UF_USE_ADP_ENCODER
namespace {
uint8_t adp_encode_sample(int16_t sample, AdpState& state) {
int32_t diff = sample - state.predictor;
uint8_t nibble = 0;
if (diff < 0) {
nibble = 8;
diff = -diff;
}
int32_t d = 0;
int32_t temp_step = state.step;
if (diff >= temp_step) {
d |= 4;
diff -= temp_step;
}
temp_step >>= 1;
if (diff >= temp_step) {
d |= 2;
diff -= temp_step;
}
temp_step >>= 1;
if (diff >= temp_step) {
d |= 1;
}
nibble |= d;
int32_t reconstructed_diff = state.step >> 3;
if ( d & 1 ) reconstructed_diff += state.step >> 2;
if ( d & 2 ) reconstructed_diff += state.step >> 1;
if ( d & 4 ) reconstructed_diff += state.step;
if (nibble & 8) {
state.predictor -= reconstructed_diff;
} else {
state.predictor += reconstructed_diff;
}
if (state.predictor > 32767) state.predictor = 32767;
else if (state.predictor < -32768) state.predictor = -32768;
state.step = (state.step * YAMAHA_SCALE[d]) >> 8;
if (state.step < 127) state.step = 127;
if (state.step > 24576) state.step = 24576;
return nibble;
}
}
uf::stl::vector<uint8_t> ext::adp::encode( const pod::PCM& pcm ) {
uf::stl::vector<uint8_t> output;
AdpHeader header;
header.channels = pcm.channels;
header.sampleRate = pcm.sampleRate;
uint32_t totalFrames = (uint32_t)(pcm.samples.size() / pcm.channels);
header.totalSamples = totalFrames;
header.dataSize = (totalFrames * pcm.channels + 1) / 2;
output.resize(sizeof(AdpHeader) + header.dataSize);
std::memcpy(output.data(), &header, sizeof(AdpHeader));
uint8_t* adpData = output.data() + sizeof(AdpHeader);
AdpState state[2] = { {0, 127}, {0, 127} };
if ( pcm.channels == 1 ) {
for ( size_t i = 0; i < pcm.samples.size(); i += 2 ) {
uint8_t n0 = ::adp_encode_sample(pcm.samples[i], state[0]);
uint8_t n1 = (i + 1 < pcm.samples.size()) ? ::adp_encode_sample(pcm.samples[i + 1], state[0]) : 0;
adpData[i / 2] = n0 | (n1 << 4);
}
} else if ( pcm.channels == 2 ) {
for ( size_t i = 0; i < pcm.samples.size(); i += 2 ) {
uint8_t left = ::adp_encode_sample(pcm.samples[i], state[0]);
uint8_t right = ::adp_encode_sample(pcm.samples[i + 1], state[1]);
adpData[i / 2] = left | (right << 4);
}
}
return output;
}
#endif
#endif

View File

@ -4,7 +4,6 @@
#if UF_USE_OPENAL
#include <uf/ext/openal/openal.h>
#endif
#if UF_USE_AICA
#include <uf/ext/aica/aica.h>
#endif
@ -65,60 +64,80 @@ namespace {
return (long)ctx->file.tell(ctx->file.handle);
}
int fill_buffer( pod::AudioSource* source, uint8_t* buffer, int req_bytes ) {
pod::AudioClip* clip = source->clip;
VorbisVfsContext* ctx = (VorbisVfsContext*)source->streamState.context;
OggVorbis_File* vorbisFile = (OggVorbis_File*)source->streamState.handle;
bool decode( OggVorbis_File* vorbisFile, pod::PCM& pcm ) {
vorbis_info* info = ov_info(vorbisFile, -1);
pcm.channels = info->channels;
pcm.sampleRate = info->rate;
int totalRead = 0;
while ( totalRead < req_bytes ) {
int result = OV_READ(vorbisFile, (char*)buffer + totalRead, req_bytes - totalRead, 0, 2, 1, &source->streamState.bitStream);
if ( result <= 0 ) {
if ( result == 0 ) {
if ( !source->info.pending.empty() ) {
ogg_int64_t totalSamples = ov_pcm_total(vorbisFile, -1);
pcm.samples.resize(totalSamples * info->channels);
uf::stl::string nextFile = source->info.pending.front();
source->info.pending.erase(source->info.pending.begin());
char* bufferPtr = (char*)pcm.samples.data();
int totalBytesNeeded = totalSamples * info->channels * sizeof(int16_t);
int totalBytesRead = 0;
int bitStream = 0;
ov_clear(vorbisFile);
VorbisVfsContext* nextCtx = new VorbisVfsContext();
nextCtx->file = uf::vfs::open(nextFile);
ov_callbacks callbacks = { funs::read, funs::seek, funs::close, funs::tell };
if ( ov_open_callbacks((void*) nextCtx, vorbisFile, NULL, -1, callbacks) < 0 ) {
UF_MSG_ERROR("Gapless Vorbis transition failed! Could not open: {}", nextFile);
delete nextCtx;
break;
}
clip->filename = nextFile;
nextCtx->file.seek(nextCtx->file.handle, 0, SEEK_END);
clip->info.size = nextCtx->file.tell(nextCtx->file.handle);
nextCtx->file.seek(nextCtx->file.handle, 0, SEEK_SET);
clip->info.duration = ov_time_total(vorbisFile, -1);
source->info.elapsed = 0.0f;
source->info.timer.reset();
source->info.timer.start();
ctx = nextCtx;
source->streamState.context = (void*) ctx;
continue;
}
else if ( source->settings.loop ) {
uint32_t seekTarget = clip->info.loop.has ? clip->info.loop.start : 0;
ov_pcm_seek(vorbisFile, seekTarget);
continue;
}
}
break;
while ( totalBytesRead < totalBytesNeeded ) {
int readCount = OV_READ(vorbisFile, bufferPtr + totalBytesRead, totalBytesNeeded - totalBytesRead, endian, 2, 1, &bitStream);
if ( readCount <= 0 ) break;
totalBytesRead += readCount;
}
totalRead += result;
return true;
}
int fill_buffer( pod::AudioSource* source, uint8_t* buffer, int req_bytes ) {
pod::AudioClip* clip = source->clip;
VorbisVfsContext* ctx = (VorbisVfsContext*)source->streamState.context;
OggVorbis_File* vorbisFile = (OggVorbis_File*)source->streamState.handle;
int totalRead = 0;
while ( totalRead < req_bytes ) {
int result = OV_READ(vorbisFile, (char*)buffer + totalRead, req_bytes - totalRead, 0, 2, 1, &source->streamState.bitStream);
if ( result <= 0 ) {
if ( result == 0 ) {
if ( !source->info.pending.empty() ) {
uf::stl::string nextFile = source->info.pending.front();
source->info.pending.erase(source->info.pending.begin());
ov_clear(vorbisFile);
VorbisVfsContext* nextCtx = new VorbisVfsContext();
nextCtx->file = uf::vfs::open(nextFile);
ov_callbacks callbacks = { funs::read, funs::seek, funs::close, funs::tell };
if ( ov_open_callbacks((void*) nextCtx, vorbisFile, NULL, -1, callbacks) < 0 ) {
UF_MSG_ERROR("Gapless Vorbis transition failed! Could not open: {}", nextFile);
delete nextCtx;
break;
}
clip->filename = nextFile;
nextCtx->file.seek(nextCtx->file.handle, 0, SEEK_END);
clip->info.size = nextCtx->file.tell(nextCtx->file.handle);
nextCtx->file.seek(nextCtx->file.handle, 0, SEEK_SET);
clip->info.duration = ov_time_total(vorbisFile, -1);
source->info.elapsed = 0.0f;
source->info.timer.reset();
source->info.timer.start();
ctx = nextCtx;
source->streamState.context = (void*) ctx;
continue;
}
else if ( source->settings.loop ) {
uint32_t seekTarget = clip->info.loop.has ? clip->info.loop.start : 0;
ov_pcm_seek(vorbisFile, seekTarget);
continue;
}
}
break;
}
totalRead += result;
}
return totalRead;
}
return totalRead;
}
}
inline bool format( pod::AudioClip& clip, int channels, int bitDepth) {
@ -142,7 +161,6 @@ void ext::vorbis::open( pod::AudioSource& source ) {
source.streamState.consumed = 0;
source.streamState.bitStream = 0;
VorbisVfsContext* ctx = new VorbisVfsContext();
ctx->file = uf::vfs::open(clip->filename);
if ( !ctx->file ) {
@ -164,13 +182,9 @@ void ext::vorbis::open( pod::AudioSource& source ) {
source.streamState.handle = (void*) vorbisFile;
#if UF_USE_AICA
UF_MSG_DEBUG("Setting callback");
source.streamBuffers.set( AL_STREAM_FILL_CALLBACK, (ALint*)(funs::fill_buffer) );
UF_MSG_DEBUG("Setting userdata");
source.streamBuffers.set( AL_STREAM_USER_DATA, (ALint*)(&source) );
UF_MSG_DEBUG("Setting buffer");
source.alSource.set(AL_BUFFER, (ALint)(source.streamBuffers.getIndex(0)));
UF_MSG_DEBUG("Initializing buffer");
source.alSource.set( AL_BUFFER, (ALint)(source.streamBuffers.getIndex(0)) );
source.streamBuffers.buffer( clip->info.format, NULL, 0, clip->info.frequency );
#else
char buffer[uf::audio::bufferSize];
@ -255,19 +269,13 @@ void ext::vorbis::load( pod::AudioClip& clip ) {
}
if ( !clip.streamed ) {
uf::stl::vector<uint8_t> bytes;
char buffer[uf::audio::bufferSize];
int bitStream = 0;
int readCount = 0;
do {
readCount = OV_READ(vorbisFile, buffer, uf::audio::bufferSize, endian, 2, 1, &bitStream);
if ( readCount > 0 ) bytes.insert(bytes.end(), buffer, buffer + readCount);
} while ( readCount > 0 );
clip.alBuffer.buffer(clip.info.format, bytes.data(), (ALsizei) bytes.size(), clip.info.frequency);
if ( clip.info.loop.has ) {
ALint loopPoints[2] = { (ALint) clip.info.loop.start, (ALint) clip.info.loop.end };
clip.alBuffer.set( 0x2015 /* AL_LOOP_POINTS_SOFT */, loopPoints );
pod::PCM pcm;
if ( funs::decode( vorbisFile, pcm ) ) {
clip.alBuffer.buffer(clip.info.format, pcm.samples.data(), (ALsizei)(pcm.samples.size() * sizeof(int16_t)), clip.info.frequency);
if ( clip.info.loop.has ) {
ALint loopPoints[2] = { (ALint) clip.info.loop.start, (ALint) clip.info.loop.end };
clip.alBuffer.set( 0x2015 /* AL_LOOP_POINTS_SOFT */, loopPoints );
}
}
}
@ -280,11 +288,7 @@ void ext::vorbis::update( pod::AudioSource& source ) {
if ( !clip || !clip->streamed || !source.streamState.handle ) return;
#if UF_USE_AICA
ALint state;
source.alSource.get(AL_SOURCE_STATE, state);
if ( state == AL_PLAYING ) {
source.streamBuffers.poll();
}
source.streamBuffers.poll();
#else
OggVorbis_File* vorbisFile = (OggVorbis_File*) source.streamState.handle;
VorbisVfsContext* ctx = (VorbisVfsContext*) source.streamState.context;
@ -295,13 +299,6 @@ void ext::vorbis::update( pod::AudioSource& source ) {
source.alSource.get(AL_BUFFERS_QUEUED, queued);
bool hasData = (ctx->file.tell(ctx->file.handle) < clip->info.size) || !source.info.pending.empty() || source.settings.loop;
#if !NO_FUN
if ( source.settings.loopMode == 1 ) {
source.alSource.set(AL_LOOPING, AL_FALSE);
}
#else
// source.alSource.set(AL_LOOPING, hasData ? AL_TRUE : AL_FALSE);
#endif
auto fillAndQueueBuffer = [&](ALuint index) -> bool {
uint8_t buffer[uf::audio::bufferSize];
@ -330,8 +327,6 @@ void ext::vorbis::update( pod::AudioSource& source ) {
if ( hasData ) {
fillAndQueueBuffer(index);
} else {
// ensure AL_LOOPING is off
}
}
}
@ -342,25 +337,25 @@ void ext::vorbis::update( pod::AudioSource& source ) {
if ( state != AL_PLAYING && queued > 0 ) {
source.alSource.play();
}
#if !NO_FUN
if ( source.settings.loopMode == 1 ) {
source.alSource.set(AL_LOOPING, AL_FALSE);
}
#endif
#endif
}
void ext::vorbis::close( pod::AudioClip& clip ) {
// ...
}
void ext::vorbis::close( pod::AudioSource& source ) {
if ( !source.clip || !source.clip->streamed ) return;
#if !UF_USE_AICA
ALint queued;
source.alSource.get(AL_BUFFERS_QUEUED, queued);
while ( queued-- ) {
ALuint buffer;
source.alSource.unqueue( 1, &buffer );
}
#endif
source.streamBuffers.destroy();
if ( source.streamState.handle ) {
@ -372,4 +367,138 @@ void ext::vorbis::close( pod::AudioSource& source ) {
}
}
bool ext::vorbis::decode( const uf::stl::string& filename, pod::PCM& outPcm ) {
VorbisVfsContext* ctx = new VorbisVfsContext();
ctx->file = uf::vfs::open(filename);
if ( !ctx->file ) {
delete ctx; return false;
}
OggVorbis_File* vorbisFile = new OggVorbis_File;
ov_callbacks callbacks = { funs::read, funs::seek, funs::close, funs::tell };
if ( ov_open_callbacks((void*) ctx, vorbisFile, NULL, 0, callbacks) < 0 ) {
delete ctx; delete vorbisFile; return false;
}
bool result = funs::decode( vorbisFile, outPcm );
ov_clear(vorbisFile);
delete vorbisFile;
return result;
}
#if UF_USE_VORBIS_ENCODER
#include <vorbis/vorbisenc.h>
uf::stl::vector<uint8_t> ext::vorbis::encode( const pod::PCM& pcm ) {
uf::stl::vector<uint8_t> output;
if ( pcm.samples.empty() ) return output;
vorbis_info vi;
vorbis_info_init(&vi);
int ret = vorbis_encode_init_vbr(&vi, pcm.channels, pcm.sampleRate, 0.4f);
if ( ret < 0 ) {
UF_MSG_ERROR("Vorbis Encoder: Initialization failed.");
vorbis_info_clear(&vi);
return output;
}
vorbis_dsp_state vd;
vorbis_block vb;
vorbis_analysis_init(&vd, &vi);
vorbis_block_init(&vd, &vb);
ogg_stream_state os;
ogg_stream_init(&os, std::rand());
vorbis_comment vc;
vorbis_comment_init(&vc);
vorbis_comment_add_tag(&vc, "ENCODER", "uf::audio pipeline");
ogg_packet header_packet;
ogg_packet header_comm;
ogg_packet header_code;
vorbis_analysis_headerout(&vd, &vc, &header_packet, &header_comm, &header_code);
ogg_stream_packetin(&os, &header_packet);
ogg_stream_packetin(&os, &header_comm);
ogg_stream_packetin(&os, &header_code);
auto flush_ogg_pages = [&](bool force) {
ogg_page og;
if ( force ) {
while ( ogg_stream_flush(&os, &og) != 0 ) {
output.insert(output.end(), og.header, og.header + og.header_len);
output.insert(output.end(), og.body, og.body + og.body_len);
}
} else {
while ( ogg_stream_pageout(&os, &og) != 0 ) {
output.insert(output.end(), og.header, og.header + og.header_len);
output.insert(output.end(), og.body, og.body + og.body_len);
}
}
};
flush_ogg_pages(true);
size_t samplesProcessed = 0;
size_t totalSamples = pcm.samples.size() / pcm.channels;
constexpr int block_size = 1024;
while ( samplesProcessed < totalSamples ) {
int toWrite = (totalSamples - samplesProcessed > block_size) ? block_size : (totalSamples - samplesProcessed);
float** buffer = vorbis_analysis_buffer(&vd, toWrite);
for ( int i = 0; i < toWrite; ++i ) {
for ( int c = 0; c < pcm.channels; ++c ) {
size_t srcIdx = (samplesProcessed + i) * pcm.channels + c;
buffer[c][i] = pcm.samples[srcIdx] / 32768.f;
}
}
vorbis_analysis_wrote(&vd, toWrite);
while ( vorbis_analysis_blockout(&vd, &vb) == 1 ) {
vorbis_analysis(&vb, nullptr);
vorbis_bitrate_addblock(&vb);
ogg_packet op;
while ( vorbis_bitrate_flushpacket(&vd, &op) == 1 ) {
ogg_stream_packetin(&os, &op);
flush_ogg_pages(false);
}
}
samplesProcessed += toWrite;
}
vorbis_analysis_wrote(&vd, 0);
while ( vorbis_analysis_blockout(&vd, &vb) == 1 ) {
vorbis_analysis(&vb, nullptr);
vorbis_bitrate_addblock(&vb);
ogg_packet op;
while ( vorbis_bitrate_flushpacket(&vd, &op) == 1 ) {
ogg_stream_packetin(&os, &op);
flush_ogg_pages(false);
}
}
flush_ogg_pages(true);
ogg_stream_clear(&os);
vorbis_block_clear(&vb);
vorbis_dsp_clear(&vd);
vorbis_comment_clear(&vc);
vorbis_info_clear(&vi);
return output;
}
#endif
#endif

View File

@ -103,6 +103,15 @@ namespace {
return (int)(totalFramesRead * frameSize);
}
bool decode( drwav* wav, pod::PCM& pcm ) {
pcm.channels = wav->channels;
pcm.sampleRate = wav->sampleRate;
pcm.samples.resize(wav->totalPCMFrameCount * wav->channels);
drwav_read_pcm_frames_s16(wav, wav->totalPCMFrameCount, pcm.samples.data());
return true;
}
}
// default to 16-bit audio
@ -160,19 +169,22 @@ void ext::wav::load( pod::AudioClip& clip ) {
return;
}
UF_MSG_DEBUG("filename={}, streamed={}", clip.filename, clip.streamed);
if ( !clip.streamed ) {
uf::stl::vector<int16_t> pcm(wav->totalPCMFrameCount * wav->channels);
drwav_read_pcm_frames_s16(wav, wav->totalPCMFrameCount, pcm.data());
clip.alBuffer.buffer(clip.info.format, pcm.data(), (ALsizei)(pcm.size() * sizeof(int16_t)), clip.info.frequency);
if ( clip.info.loop.has ) {
ALint loopPoints[2] = { (ALint) clip.info.loop.start, (ALint) clip.info.loop.end };
clip.alBuffer.set( 0x2015 /* AL_LOOP_POINTS_SOFT */, loopPoints );
pod::PCM pcm;
if ( funs::decode( &ctx->wav, pcm ) ) {
clip.alBuffer.buffer(clip.info.format, pcm.samples.data(), (ALsizei)(pcm.samples.size() * sizeof(int16_t)), clip.info.frequency);
if ( clip.info.loop.has ) {
ALint loopPoints[2] = { (ALint) clip.info.loop.start, (ALint) clip.info.loop.end };
clip.alBuffer.set( 0x2015 /* AL_LOOP_POINTS_SOFT */, loopPoints );
}
}
}
drwav_uninit(wav);
delete ctx;
}
void ext::wav::open( pod::AudioSource& source ) {
pod::AudioClip* clip = source.clip;
if ( !clip || !clip->streamed ) return;
@ -223,11 +235,7 @@ void ext::wav::update( pod::AudioSource& source ) {
if ( !clip || !clip->streamed || !source.streamState.handle ) return;
#if UF_USE_AICA
ALint state;
source.alSource.get(AL_SOURCE_STATE, state);
if ( state == AL_PLAYING ) {
source.streamBuffers.poll();
}
source.streamBuffers.poll();
#else
DrWavVfsContext* ctx = (DrWavVfsContext*) source.streamState.handle;
ALint state, processed, queued;
@ -237,11 +245,6 @@ void ext::wav::update( pod::AudioSource& source ) {
source.alSource.get(AL_BUFFERS_QUEUED, queued);
bool hasData = (ctx->file.tell(ctx->file.handle) < clip->info.size) || !source.info.pending.empty() || source.settings.loop;
#if !NO_FUN
if ( source.settings.loopMode == 1 ) {
source.alSource.set(AL_LOOPING, AL_FALSE);
}
#endif
auto fillAndQueueBuffer = [&](ALuint index) -> bool {
uint8_t buffer[uf::audio::bufferSize];
@ -279,25 +282,24 @@ void ext::wav::update( pod::AudioSource& source ) {
if ( state != AL_PLAYING && queued > 0 ) {
source.alSource.play();
}
#if !NO_FUN
if ( source.settings.loopMode == 1 ) source.alSource.set(AL_LOOPING, AL_FALSE);
#endif
#endif
}
void ext::wav::close( pod::AudioClip& clip ) {
// ...
}
void ext::wav::close(pod::AudioSource& source) {
if ( !source.clip || !source.clip->streamed ) return;
#if !UF_USE_AICA
ALint queued;
source.alSource.get(AL_BUFFERS_QUEUED, queued);
while ( queued-- ) {
ALuint buffer;
source.alSource.unqueue( 1, &buffer );
}
#endif
source.streamBuffers.destroy();
@ -309,4 +311,58 @@ void ext::wav::close(pod::AudioSource& source) {
}
}
bool ext::wav::decode( const uf::stl::string& filename, pod::PCM& outPcm ) {
DrWavVfsContext ctx;
ctx.file = uf::vfs::open(filename);
if ( !ctx.file ) {
UF_MSG_ERROR("WAV Decoder: Failed to open file: {}", filename);
return false;
}
if ( !drwav_init(&ctx.wav, funs::read, funs::seek, funs::tell, &ctx, nullptr) ) {
UF_MSG_ERROR("WAV Decoder: Failed to initialize decoder on: {}", filename);
return false;
}
bool result = funs::decode(&ctx.wav, outPcm);
drwav_uninit(&ctx.wav);
return result;
}
#if UF_USE_WAV_ENCODER
uf::stl::vector<uint8_t> ext::wav::encode( const pod::PCM& pcm ) {
uf::stl::vector<uint8_t> output;
struct WAVHeader {
char riff[4] = {'R', 'I', 'F', 'F'};
uint32_t overallSize;
char wave[4] = {'W', 'A', 'V', 'E'};
char fmt_chunk_marker[4] = {'f', 'm', 't', ' '};
uint32_t length_of_fmt = 16;
uint16_t format_type = 1;
uint16_t channels;
uint32_t sample_rate;
uint32_t byterate;
uint16_t block_align;
uint16_t bits_per_sample = 16;
char data_chunk_header[4] = {'d', 'a', 't', 'a'};
uint32_t data_size;
};
WAVHeader header;
header.channels = pcm.channels;
header.sample_rate = pcm.sampleRate;
header.byterate = pcm.sampleRate * pcm.channels * sizeof(int16_t);
header.block_align = pcm.channels * sizeof(int16_t);
header.data_size = (uint32_t)(pcm.samples.size() * sizeof(int16_t));
header.overallSize = sizeof(WAVHeader) - 8 + header.data_size;
output.resize(sizeof(WAVHeader) + header.data_size);
std::memcpy(output.data(), &header, sizeof(WAVHeader));
std::memcpy(output.data() + sizeof(WAVHeader), pcm.samples.data(), header.data_size);
return output;
}
#endif
#endif

View File

@ -378,7 +378,7 @@ void ext::opengl::CommandBuffer::drawIndexed( const ext::opengl::CommandBuffer::
::shadowState.projectionDirty = false;
}
#if 0 && UF_ENV_DREAMCAST
#if UF_ENV_DREAMCAST
// washingtondc ~~has~~ had a regression where non-alpha-tested polys do not render
// more convenient to just work around the regression since later builds have working opengl backends
GL_ERROR_CHECK(glEnable(GL_ALPHA_TEST));
@ -386,6 +386,8 @@ void ext::opengl::CommandBuffer::drawIndexed( const ext::opengl::CommandBuffer::
GL_ERROR_CHECK(glEnable(GL_BLEND));
GL_ERROR_CHECK(glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA));
GL_ERROR_CHECK(glDisable(GL_DEPTH_TEST));
#else
if ( drawInfo.blend.modeAlpha > 0 ) {
if ( !::shadowState.alphaTestEnabled ) {
@ -448,10 +450,12 @@ void ext::opengl::CommandBuffer::drawIndexed( const ext::opengl::CommandBuffer::
}
pod::Vector4f color = {1,1,1,1};
/*
if ( drawInfo.color.enabled ) {
color = drawInfo.color.pointer ? *drawInfo.color.pointer : drawInfo.color.value;
color = uf::vector::clamp( color, pod::Vector4f{0,0,0,0}, pod::Vector4f{1, 1, 1, 1} );
}
*/
if ( color != ::shadowState.color ) {
GL_ERROR_CHECK(glColor4f( color[0], color[1], color[2], color[3] ));
::shadowState.color = color;
@ -570,7 +574,7 @@ void ext::opengl::CommandBuffer::drawIndexed( const ext::opengl::CommandBuffer::
}
GLenum colorType = GL_FLOAT;
if ( drawInfo.attributes.color.descriptor.type == uf::renderer::enums::Type::UBYTE || drawInfo.attributes.color.descriptor.size == sizeof(uint8_t)) {
colorType = GL_UNSIGNED_BYTE;
colorType = GL_UNSIGNED_BYTE;
}
GL_ERROR_CHECK(glColorPointer(drawInfo.attributes.color.descriptor.components, colorType, drawInfo.attributes.color.stride, colorPtr));
} else if ( ::shadowState.colorArrayEnabled ) {

View File

@ -127,7 +127,8 @@ pod::Dtex ext::texconv::convert( const uf::Image& _image, const uf::stl::string
return dtex;
}
bool UF_API ext::texconv::save( const pod::Dtex& dtex, const uf::stl::string& filename, bool preview ) {
bool UF_API ext::texconv::save( const pod::Dtex& dtex, const uf::stl::string& _filename, bool preview ) {
uf::stl::string filename = uf::io::remove_extension( _filename );
uf::stl::string outputFilename = filename + ".dtex";
uf::stl::string paletteFilename = filename + ".pal";
uf::stl::string previewFilename = filename + ".preview.png";

View File

@ -6,10 +6,14 @@
#if UF_USE_OPENAL
#include <uf/ext/openal/openal.h>
#endif
#if UF_USE_AICA
#include <uf/ext/aica/aica.h>
#endif
#include <uf/ext/audio/vorbis.h>
#include <uf/ext/audio/wav.h>
#include <uf/ext/audio/pcm.h>
#include <uf/ext/audio/adp.h>
bool uf::audio::muted = false;
@ -56,9 +60,10 @@ bool uf::audio::load( pod::AudioClip& clip, const uf::stl::string& filename ) {
if ( !clip.streamed ) uf::audio::initialize( clip, 1 );
if ( clip.extension == "ogg" ) ext::vorbis::load( clip );
else if ( clip.extension == "wav" ) ext::wav::load( clip );
// else UF_MSG_ERROR ...
UF_AUDIO_DISPATCH( clip.extension, ogg, load, clip );
UF_AUDIO_DISPATCH( clip.extension, wav, load, clip );
UF_AUDIO_DISPATCH( clip.extension, adp, load, clip );
UF_AUDIO_DISPATCH( clip.extension, pcm, load, clip );
return true;
}
@ -77,9 +82,11 @@ void uf::audio::bind( pod::AudioSource& source, pod::AudioClip* clip ) {
source.alSource.set( AL_BUFFER, (ALint)clip->alBuffer.getIndex(0) );
} else {
source.streamState.consumed = 0;
if ( clip->extension == "ogg" ) ext::vorbis::open( source );
else if ( clip->extension == "wav" ) ext::wav::open( source );
//else if ( clip->extension == "pcm" ) ext::pcm::open( source );
UF_AUDIO_DISPATCH( clip->extension, ogg, open, source );
UF_AUDIO_DISPATCH( clip->extension, wav, open, source );
UF_AUDIO_DISPATCH( clip->extension, adp, open, source );
UF_AUDIO_DISPATCH( clip->extension, pcm, open, source );
}
}
@ -118,9 +125,10 @@ void uf::audio::update( pod::AudioSource& source ) {
if ( !source.clip || !source.clip->streamed ) return;
auto update = [&]{
if ( source.clip->extension == "ogg" ) ext::vorbis::update( source );
else if ( source.clip->extension == "wav" ) ext::wav::update( source );
//else if ( source.clip->extension == "pcm" ) ext::pcm::update( source );
UF_AUDIO_DISPATCH( source.clip->extension, ogg, update, source );
UF_AUDIO_DISPATCH( source.clip->extension, wav, update, source );
UF_AUDIO_DISPATCH( source.clip->extension, adp, update, source );
UF_AUDIO_DISPATCH( source.clip->extension, pcm, update, source );
};
if ( uf::audio::asyncUpdate ) uf::thread::queue( uf::thread::fetchWorker(), update );
@ -140,9 +148,10 @@ void uf::audio::destroy( pod::AudioSource& source ) {
source.alSource.set( AL_BUFFER, 0 );
if ( source.clip && source.clip->streamed ) {
if ( source.clip->extension == "ogg" ) ext::vorbis::close( source );
else if ( source.clip->extension == "wav" ) ext::wav::close( source );
//else if ( source.clip->extension == "pcm" ) ext::pcm::close( source );
UF_AUDIO_DISPATCH( source.clip->extension, ogg, close, source );
UF_AUDIO_DISPATCH( source.clip->extension, wav, close, source );
UF_AUDIO_DISPATCH( source.clip->extension, adp, close, source );
UF_AUDIO_DISPATCH( source.clip->extension, pcm, close, source );
}
source.clip = nullptr;
@ -152,11 +161,31 @@ void uf::audio::destroy( pod::AudioSource& source ) {
#endif
}
bool uf::audio::decode( const uf::stl::string& filename, pod::PCM& pcm ) {
bool success = false;
auto extension = uf::io::extension( filename );
UF_AUDIO_DISPATCH_SET( extension, adp, success, decode, filename, pcm );
UF_AUDIO_DISPATCH_SET( extension, ogg, success, decode, filename, pcm );
UF_AUDIO_DISPATCH_SET( extension, wav, success, decode, filename, pcm );
return success;
}
uf::stl::vector<uint8_t> uf::audio::encode( const uf::stl::string& extension, pod::PCM& pcm ) {
uf::stl::vector<uint8_t> buffer;
#if UF_USE_AUDIO_ENCODER
UF_AUDIO_DISPATCH_SET( extension, adp, buffer, encode, pcm );
UF_AUDIO_DISPATCH_SET( extension, ogg, buffer, encode, pcm );
UF_AUDIO_DISPATCH_SET( extension, wav, buffer, encode, pcm );
#endif
return buffer;
}
void uf::audio::destroy( pod::AudioClip& clip ) {
clip.alBuffer.destroy();
if ( clip.extension == "ogg" ) ext::vorbis::close( clip );
else if ( clip.extension == "wav" ) ext::wav::close( clip );
//else if ( clip.extension == "pcm" ) ext::pcm::close( clip );
UF_AUDIO_DISPATCH( clip.extension, ogg, close, clip );
UF_AUDIO_DISPATCH( clip.extension, wav, close, clip );
UF_AUDIO_DISPATCH( clip.extension, adp, close, clip );
UF_AUDIO_DISPATCH( clip.extension, pcm, close, clip );
}
void uf::audio::listener( const pod::Transform<>& transform ) {

View File

@ -54,6 +54,20 @@ uf::stl::string uf::io::extension( const uf::stl::string& str, int32_t count ) {
}
return extension;
}
uf::stl::string uf::io::remove_extension( const uf::stl::string& str ) {
size_t last_dot = str.find_last_of('.');
size_t last_slash = str.find_last_of('/');
if ( last_dot != uf::stl::string::npos && (last_slash == uf::stl::string::npos || last_dot > last_slash) ) {
return str.substr( 0, last_dot );
}
return str;
}
uf::stl::string uf::io::replace_extension( const uf::stl::string& str, const uf::stl::string& new_ext ) {
uf::stl::string base = uf::io::remove_extension( str );
if ( new_ext.empty() ) return base;
if ( new_ext[0] == '.' ) return base + new_ext;
return base + "." + new_ext;
}
uf::stl::string uf::io::directory( const uf::stl::string& str ) {
return str.substr( 0, str.find_last_of('/') ) + "/";
}
@ -291,7 +305,7 @@ uf::stl::string uf::io::assetScheme( const uf::stl::string& _filename ) {
if ( extension == "json" ) return "ent://";
if ( extension == "png" || extension == "dtex" ) return "tex://";
if ( extension == "glb" || extension == "gltf" || extension == "graph" ) return "mdl://";
if ( extension == "ogg" || extension == "wav" ) return "snd://";
if ( extension == "ogg" || extension == "wav" || extension == "adp" ) return "snd://";
if ( extension == "spv" ) return "spv://";
if ( extension == "lua" ) return "lua://";
@ -381,7 +395,7 @@ uf::stl::string uf::io::preferred( const uf::stl::string& filename ) {
// to-do: make this config.json defineable
#if UF_ENV_DREAMCAST
if ( assetType == "texture" ) preferredExtension = ".dtex";
else if ( assetType == "audio" ) preferredExtension = ".wav";
else if ( assetType == "audio" ) preferredExtension = ".adp";
#else
if ( assetType == "texture" ) preferredExtension = ".png";
else if ( assetType == "audio" ) preferredExtension = ".ogg";
@ -392,5 +406,11 @@ uf::stl::string uf::io::preferred( const uf::stl::string& filename ) {
// create preferred path
uf::stl::string preferredPath = uf::string::replace( filename, extension, preferredExtension );
// pick it if exists
return uf::io::exists( preferredPath ) ? preferredPath : filename;
if ( uf::io::exists( preferredPath ) ) return preferredPath;
// create cached path (for virtual sources)
uf::stl::string cachePath = "cache/" + preferredPath;
// pick it if it exists
if ( uf::io::exists( cachePath ) ) return cachePath;
return filename;
}

View File

@ -605,6 +605,19 @@ uf::stl::string uf::vfs::resolveBase( const uf::stl::string& path ) {
return path;
}
bool uf::vfs::isPhysical( const uf::stl::string& path ) {
uf::stl::string prefix, relative;
uf::io::splitUri(path, prefix, relative);
for ( const auto& mount : mounts ) {
if ( prefix.empty() && mount.priority < 0 ) continue;
if ( prefix.empty() || mount.prefix == prefix ) {
return mount.exists == ::vfs_exists;
}
}
return false;
}
#if UF_ENV_DREAMCAST
#define VFS_BASE "/cd/"
#else

View File

@ -1,5 +1,9 @@
INCS += -I./dep/include/stb/ -I./dep/include/nlohmann/
ifneq (,$(findstring UF_DEV_ENV,$(FLAGS)))
FLAGS += -DUF_USE_AUDIO_ENCODER
endif
ifneq (,$(findstring ffx:sdk,$(REQ_DEPS)))
ifneq (,$(findstring vulkan,$(REQ_DEPS)))
ifneq (,$(findstring gcc,$(REQ_DEPS)))
@ -74,10 +78,24 @@ ifneq (,$(findstring ogg,$(REQ_DEPS)))
ifeq (,$(findstring dreamcast,$(ARCH)))
DEPS += -lvorbis -lvorbisfile -logg
endif
ifneq (,$(findstring UF_DEV_ENV,$(FLAGS)))
FLAGS += -DUF_USE_VORBIS_ENCODER
DEPS += -lvorbisenc
endif
endif
ifneq (,$(findstring wav,$(REQ_DEPS)))
FLAGS += -DUF_USE_WAV
ifneq (,$(findstring UF_DEV_ENV,$(FLAGS)))
FLAGS += -DUF_USE_WAV_ENCODER
endif
endif
ifneq (,$(findstring adp,$(REQ_DEPS)))
FLAGS += -DUF_USE_ADP
ifneq (,$(findstring UF_DEV_ENV,$(FLAGS)))
FLAGS += -DUF_USE_ADP_ENCODER
endif
endif
ifneq (,$(findstring zlib,$(REQ_DEPS)))

View File

@ -1,5 +1,5 @@
FLAGS += -DUF_ENV_DREAMCAST
REQ_DEPS += opengl gldc json:nlohmann zlib lz4 lua simd ctti fmt ttf ogg wav aica # openal aldc
REQ_DEPS += opengl gldc json:nlohmann zlib lz4 lua simd ctti fmt ttf ogg wav adp aica # openal aldc
INCS := -I./dep/dreamcast/include $(INCS)

View File

@ -1,3 +1,5 @@
FLAGS += -DUF_DEV_ENV
ifneq (,$(findstring -DUF_DEV_ENV,$(FLAGS)))
REQ_DEPS += toml xatlas curl dc:texconv valve lgs # meshoptimizer ffx:fsr cpptrace vall_e # ncurses openvr draco discord bullet ultralight-ux
FLAGS += -march=native -g # -flto # -g

View File

@ -1,9 +1,11 @@
ifneq (,$(findstring -DUF_DEV_ENV,$(FLAGS)))
FLAGS += -DUF_DEV_ENV
ifneq (,$(findstring UF_DEV_ENV,$(FLAGS)))
REQ_DEPS += meshoptimizer toml xatlas curl dc:texconv ffx:sdk openvr valve lgs # vall_e cpptrace # ncurses draco discord ultralight-ux
FLAGS += -march=native -g # -flto # -g
endif
REQ_DEPS += $(RENDERER) json:nlohmann zlib lz4 luajit simd ctti gltf imgui fmt ttf openal ogg wav
REQ_DEPS += $(RENDERER) json:nlohmann zlib lz4 luajit simd ctti gltf imgui fmt ttf openal ogg wav adp
FLAGS += -DUF_ENV_WINDOWS -DUF_ENV_WIN64 -DWIN32_LEAN_AND_MEAN
DEPS += -lgdi32 -ldwmapi
LINKS += #-Wl,-subsystem,windows