refactor: JA_* a namespace Ja:: (estil aee_arcade)
This commit is contained in:
@@ -43,15 +43,15 @@ Audio::Audio() { initSDLAudio(); }
|
|||||||
|
|
||||||
// Destructor
|
// Destructor
|
||||||
Audio::~Audio() {
|
Audio::~Audio() {
|
||||||
JA_Quit();
|
Ja::quit();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Método principal
|
// Método principal
|
||||||
void Audio::update() {
|
void Audio::update() {
|
||||||
JA_Update();
|
Ja::update();
|
||||||
|
|
||||||
// Sincronizar estado: detectar cuando la música se para (ej. fade-out completado)
|
// Sincronizar estado: detectar cuando la música se para (ej. fade-out completado)
|
||||||
if (instance != nullptr && instance->music_.state == MusicState::PLAYING && JA_GetMusicState() != JA_MUSIC_PLAYING) {
|
if (instance != nullptr && instance->music_.state == MusicState::PLAYING && Ja::getMusicState() != Ja::MusicState::PLAYING) {
|
||||||
instance->music_.state = MusicState::STOPPED;
|
instance->music_.state = MusicState::STOPPED;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -71,12 +71,12 @@ void Audio::playMusic(const std::string& name, const int loop, const int crossfa
|
|||||||
if (resource == nullptr) { return; }
|
if (resource == nullptr) { return; }
|
||||||
|
|
||||||
if (crossfade_ms > 0 && music_.state == MusicState::PLAYING) {
|
if (crossfade_ms > 0 && music_.state == MusicState::PLAYING) {
|
||||||
JA_CrossfadeMusic(resource, crossfade_ms, loop);
|
Ja::crossfadeMusic(resource, crossfade_ms, loop);
|
||||||
} else {
|
} else {
|
||||||
if (music_.state == MusicState::PLAYING) {
|
if (music_.state == MusicState::PLAYING) {
|
||||||
JA_StopMusic();
|
Ja::stopMusic();
|
||||||
}
|
}
|
||||||
JA_PlayMusic(resource, loop);
|
Ja::playMusic(resource, loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
music_.name = name;
|
music_.name = name;
|
||||||
@@ -85,16 +85,16 @@ void Audio::playMusic(const std::string& name, const int loop, const int crossfa
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Reproduce la música por puntero (con crossfade opcional)
|
// Reproduce la música por puntero (con crossfade opcional)
|
||||||
void Audio::playMusic(JA_Music_t* music, const int loop, const int crossfade_ms) {
|
void Audio::playMusic(Ja::Music* music, const int loop, const int crossfade_ms) {
|
||||||
if (!music_enabled_ || music == nullptr) { return; }
|
if (!music_enabled_ || music == nullptr) { return; }
|
||||||
|
|
||||||
if (crossfade_ms > 0 && music_.state == MusicState::PLAYING) {
|
if (crossfade_ms > 0 && music_.state == MusicState::PLAYING) {
|
||||||
JA_CrossfadeMusic(music, crossfade_ms, loop);
|
Ja::crossfadeMusic(music, crossfade_ms, loop);
|
||||||
} else {
|
} else {
|
||||||
if (music_.state == MusicState::PLAYING) {
|
if (music_.state == MusicState::PLAYING) {
|
||||||
JA_StopMusic();
|
Ja::stopMusic();
|
||||||
}
|
}
|
||||||
JA_PlayMusic(music, loop);
|
Ja::playMusic(music, loop);
|
||||||
}
|
}
|
||||||
|
|
||||||
music_.name.clear(); // nom desconegut quan es passa per punter
|
music_.name.clear(); // nom desconegut quan es passa per punter
|
||||||
@@ -105,7 +105,7 @@ void Audio::playMusic(JA_Music_t* music, const int loop, const int crossfade_ms)
|
|||||||
// Pausa la música
|
// Pausa la música
|
||||||
void Audio::pauseMusic() {
|
void Audio::pauseMusic() {
|
||||||
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
if (music_enabled_ && music_.state == MusicState::PLAYING) {
|
||||||
JA_PauseMusic();
|
Ja::pauseMusic();
|
||||||
music_.state = MusicState::PAUSED;
|
music_.state = MusicState::PAUSED;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -113,7 +113,7 @@ void Audio::pauseMusic() {
|
|||||||
// Continua la música pausada
|
// Continua la música pausada
|
||||||
void Audio::resumeMusic() {
|
void Audio::resumeMusic() {
|
||||||
if (music_enabled_ && music_.state == MusicState::PAUSED) {
|
if (music_enabled_ && music_.state == MusicState::PAUSED) {
|
||||||
JA_ResumeMusic();
|
Ja::resumeMusic();
|
||||||
music_.state = MusicState::PLAYING;
|
music_.state = MusicState::PLAYING;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -121,7 +121,7 @@ void Audio::resumeMusic() {
|
|||||||
// Detiene la música
|
// Detiene la música
|
||||||
void Audio::stopMusic() {
|
void Audio::stopMusic() {
|
||||||
if (music_enabled_) {
|
if (music_enabled_) {
|
||||||
JA_StopMusic();
|
Ja::stopMusic();
|
||||||
music_.state = MusicState::STOPPED;
|
music_.state = MusicState::STOPPED;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,42 +129,42 @@ void Audio::stopMusic() {
|
|||||||
// Reproduce un sonido por nombre
|
// Reproduce un sonido por nombre
|
||||||
void Audio::playSound(const std::string& name, Group group) const {
|
void Audio::playSound(const std::string& name, Group group) const {
|
||||||
if (sound_enabled_) {
|
if (sound_enabled_) {
|
||||||
JA_PlaySound(AudioResource::getSound(name), 0, static_cast<int>(group));
|
Ja::playSound(AudioResource::getSound(name), 0, static_cast<int>(group));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reproduce un sonido por puntero directo
|
// Reproduce un sonido por puntero directo
|
||||||
void Audio::playSound(JA_Sound_t* sound, Group group) const {
|
void Audio::playSound(Ja::Sound* sound, Group group) const {
|
||||||
if (sound_enabled_ && sound != nullptr) {
|
if (sound_enabled_ && sound != nullptr) {
|
||||||
JA_PlaySound(sound, 0, static_cast<int>(group));
|
Ja::playSound(sound, 0, static_cast<int>(group));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Detiene todos los sonidos
|
// Detiene todos los sonidos
|
||||||
void Audio::stopAllSounds() const {
|
void Audio::stopAllSounds() const {
|
||||||
if (sound_enabled_) {
|
if (sound_enabled_) {
|
||||||
JA_StopChannel(-1);
|
Ja::stopChannel(-1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Realiza un fundido de salida de la música
|
// Realiza un fundido de salida de la música
|
||||||
void Audio::fadeOutMusic(int milliseconds) const {
|
void Audio::fadeOutMusic(int milliseconds) const {
|
||||||
if (music_enabled_ && getRealMusicState() == MusicState::PLAYING) {
|
if (music_enabled_ && getRealMusicState() == MusicState::PLAYING) {
|
||||||
JA_FadeOutMusic(milliseconds);
|
Ja::fadeOutMusic(milliseconds);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Consulta directamente el estado real de la música en jailaudio
|
// Consulta directamente el estado real de la música en jailaudio
|
||||||
auto Audio::getRealMusicState() -> MusicState {
|
auto Audio::getRealMusicState() -> MusicState {
|
||||||
JA_Music_state ja_state = JA_GetMusicState();
|
Ja::MusicState ja_state = Ja::getMusicState();
|
||||||
switch (ja_state) {
|
switch (ja_state) {
|
||||||
case JA_MUSIC_PLAYING:
|
case Ja::MusicState::PLAYING:
|
||||||
return MusicState::PLAYING;
|
return MusicState::PLAYING;
|
||||||
case JA_MUSIC_PAUSED:
|
case Ja::MusicState::PAUSED:
|
||||||
return MusicState::PAUSED;
|
return MusicState::PAUSED;
|
||||||
case JA_MUSIC_STOPPED:
|
case Ja::MusicState::STOPPED:
|
||||||
case JA_MUSIC_INVALID:
|
case Ja::MusicState::INVALID:
|
||||||
case JA_MUSIC_DISABLED:
|
case Ja::MusicState::DISABLED:
|
||||||
default:
|
default:
|
||||||
return MusicState::STOPPED;
|
return MusicState::STOPPED;
|
||||||
}
|
}
|
||||||
@@ -175,7 +175,7 @@ void Audio::setSoundVolume(float sound_volume, Group group) const {
|
|||||||
if (sound_enabled_) {
|
if (sound_enabled_) {
|
||||||
sound_volume = std::clamp(sound_volume, MIN_VOLUME, MAX_VOLUME);
|
sound_volume = std::clamp(sound_volume, MIN_VOLUME, MAX_VOLUME);
|
||||||
const float CONVERTED_VOLUME = sound_volume * Options::audio.volume;
|
const float CONVERTED_VOLUME = sound_volume * Options::audio.volume;
|
||||||
JA_SetSoundVolume(CONVERTED_VOLUME, static_cast<int>(group));
|
Ja::setSoundVolume(CONVERTED_VOLUME, static_cast<int>(group));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -184,7 +184,7 @@ void Audio::setMusicVolume(float music_volume) const {
|
|||||||
if (music_enabled_) {
|
if (music_enabled_) {
|
||||||
music_volume = std::clamp(music_volume, MIN_VOLUME, MAX_VOLUME);
|
music_volume = std::clamp(music_volume, MIN_VOLUME, MAX_VOLUME);
|
||||||
const float CONVERTED_VOLUME = music_volume * Options::audio.volume;
|
const float CONVERTED_VOLUME = music_volume * Options::audio.volume;
|
||||||
JA_SetMusicVolume(CONVERTED_VOLUME);
|
Ja::setMusicVolume(CONVERTED_VOLUME);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -206,7 +206,7 @@ void Audio::initSDLAudio() {
|
|||||||
if (!SDL_Init(SDL_INIT_AUDIO)) {
|
if (!SDL_Init(SDL_INIT_AUDIO)) {
|
||||||
std::cout << "SDL_AUDIO could not initialize! SDL Error: " << SDL_GetError() << '\n';
|
std::cout << "SDL_AUDIO could not initialize! SDL Error: " << SDL_GetError() << '\n';
|
||||||
} else {
|
} else {
|
||||||
JA_Init(FREQUENCY, SDL_AUDIO_S16LE, 2);
|
Ja::init(FREQUENCY, SDL_AUDIO_S16LE, 2);
|
||||||
enable(Options::audio.enabled);
|
enable(Options::audio.enabled);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,6 +4,11 @@
|
|||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
#include <utility> // Para move
|
#include <utility> // Para move
|
||||||
|
|
||||||
|
namespace Ja {
|
||||||
|
struct Music;
|
||||||
|
struct Sound;
|
||||||
|
} // namespace Ja
|
||||||
|
|
||||||
// --- Clase Audio: gestor de audio (singleton) ---
|
// --- Clase Audio: gestor de audio (singleton) ---
|
||||||
// Implementació canònica, byte-idèntica entre projectes.
|
// Implementació canònica, byte-idèntica entre projectes.
|
||||||
// Els volums es manegen internament com a float 0.0–1.0; la capa de
|
// Els volums es manegen internament com a float 0.0–1.0; la capa de
|
||||||
@@ -42,7 +47,7 @@ class Audio {
|
|||||||
|
|
||||||
// --- Control de música ---
|
// --- Control de música ---
|
||||||
void playMusic(const std::string& name, int loop = -1, int crossfade_ms = 0); // Reproducir música por nombre (con crossfade opcional)
|
void playMusic(const std::string& name, int loop = -1, int crossfade_ms = 0); // Reproducir música por nombre (con crossfade opcional)
|
||||||
void playMusic(struct JA_Music_t* music, int loop = -1, int crossfade_ms = 0); // Reproducir música por puntero (con crossfade opcional)
|
void playMusic(Ja::Music* music, int loop = -1, int crossfade_ms = 0); // Reproducir música por puntero (con crossfade opcional)
|
||||||
void pauseMusic(); // Pausar reproducción de música
|
void pauseMusic(); // Pausar reproducción de música
|
||||||
void resumeMusic(); // Continua la música pausada
|
void resumeMusic(); // Continua la música pausada
|
||||||
void stopMusic(); // Detener completamente la música
|
void stopMusic(); // Detener completamente la música
|
||||||
@@ -50,7 +55,7 @@ class Audio {
|
|||||||
|
|
||||||
// --- Control de sonidos ---
|
// --- Control de sonidos ---
|
||||||
void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual por nombre
|
void playSound(const std::string& name, Group group = Group::GAME) const; // Reproducir sonido puntual por nombre
|
||||||
void playSound(struct JA_Sound_t* sound, Group group = Group::GAME) const; // Reproducir sonido puntual por puntero
|
void playSound(Ja::Sound* sound, Group group = Group::GAME) const; // Reproducir sonido puntual por puntero
|
||||||
void stopAllSounds() const; // Detener todos los sonidos
|
void stopAllSounds() const; // Detener todos los sonidos
|
||||||
|
|
||||||
// --- Control de volumen (API interna: float 0.0..1.0) ---
|
// --- Control de volumen (API interna: float 0.0..1.0) ---
|
||||||
|
|||||||
@@ -3,11 +3,11 @@
|
|||||||
#include "core/resources/resource_cache.hpp"
|
#include "core/resources/resource_cache.hpp"
|
||||||
|
|
||||||
namespace AudioResource {
|
namespace AudioResource {
|
||||||
auto getMusic(const std::string& name) -> JA_Music_t* {
|
auto getMusic(const std::string& name) -> Ja::Music* {
|
||||||
return Resource::Cache::get()->getMusic(name);
|
return Resource::Cache::get()->getMusic(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
auto getSound(const std::string& name) -> JA_Sound_t* {
|
auto getSound(const std::string& name) -> Ja::Sound* {
|
||||||
return Resource::Cache::get()->getSound(name);
|
return Resource::Cache::get()->getSound(name);
|
||||||
}
|
}
|
||||||
} // namespace AudioResource
|
} // namespace AudioResource
|
||||||
|
|||||||
@@ -1,17 +1,19 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
// --- Audio Resource Adapter ---
|
// --- Audio Resource Adapter ---
|
||||||
// Aquest fitxer exposa una interfície comuna a Audio per obtenir JA_Music_t* /
|
// Aquest fitxer exposa una interfície comuna a Audio per obtenir Ja::Music* /
|
||||||
// JA_Sound_t* per nom. Cada projecte la implementa en audio_adapter.cpp
|
// Ja::Sound* per nom. Cada projecte la implementa en audio_adapter.cpp
|
||||||
// delegant al seu singleton de recursos (Resource::get(), Resource::Cache::get(),
|
// delegant al seu singleton de recursos (Resource::get(), Resource::Cache::get(),
|
||||||
// etc.). Això permet que audio.hpp/audio.cpp siguin idèntics entre projectes.
|
// etc.). Això permet que audio.hpp/audio.cpp siguin idèntics entre projectes.
|
||||||
|
|
||||||
#include <string> // Para string
|
#include <string> // Para string
|
||||||
|
|
||||||
struct JA_Music_t;
|
namespace Ja {
|
||||||
struct JA_Sound_t;
|
struct Music;
|
||||||
|
struct Sound;
|
||||||
|
} // namespace Ja
|
||||||
|
|
||||||
namespace AudioResource {
|
namespace AudioResource {
|
||||||
auto getMusic(const std::string& name) -> JA_Music_t*;
|
auto getMusic(const std::string& name) -> Ja::Music*;
|
||||||
auto getSound(const std::string& name) -> JA_Sound_t*;
|
auto getSound(const std::string& name) -> Ja::Sound*;
|
||||||
} // namespace AudioResource
|
} // namespace AudioResource
|
||||||
|
|||||||
@@ -3,160 +3,164 @@
|
|||||||
// --- Includes ---
|
// --- Includes ---
|
||||||
#include <SDL3/SDL.h>
|
#include <SDL3/SDL.h>
|
||||||
|
|
||||||
#include <cstdint> // Para uint32_t, uint8_t
|
#include <cstdint>
|
||||||
#include <cstdio> // Para NULL, fseek, fclose, fopen, fread, ftell, FILE, SEEK_END, SEEK_SET
|
#include <cstdio>
|
||||||
#include <cstdlib> // Para free, malloc
|
#include <cstdlib>
|
||||||
#include <iostream> // Para std::cout
|
#include <iostream>
|
||||||
#include <memory> // Para std::unique_ptr
|
#include <memory>
|
||||||
#include <string> // Para std::string
|
#include <string>
|
||||||
#include <vector> // Para std::vector
|
#include <vector>
|
||||||
|
|
||||||
#define STB_VORBIS_HEADER_ONLY
|
#define STB_VORBIS_HEADER_ONLY
|
||||||
|
// NOLINTNEXTLINE(bugprone-suspicious-include) — stb_vorbis és single-file: la macro de dalt limita a només-declaracions.
|
||||||
#include "external/stb_vorbis.c" // Para stb_vorbis_open_memory i streaming
|
#include "external/stb_vorbis.c" // Para stb_vorbis_open_memory i streaming
|
||||||
|
|
||||||
// Deleter stateless per a buffers reservats amb `SDL_malloc` / `SDL_LoadWAV*`.
|
// Deleter stateless per a buffers reservats amb `SDL_malloc` / `SDL_LoadWAV*`.
|
||||||
// Compatible amb `std::unique_ptr<Uint8[], SDLFreeDeleter>` — zero size
|
// Compatible amb `std::unique_ptr<Uint8[], SdlFreeDeleter>` — zero size
|
||||||
// overhead gràcies a EBO, igual que un unique_ptr amb default_delete.
|
// overhead gràcies a EBO, igual que un unique_ptr amb default_delete.
|
||||||
struct SDLFreeDeleter {
|
struct SdlFreeDeleter {
|
||||||
void operator()(Uint8* p) const noexcept {
|
void operator()(Uint8* p) const noexcept {
|
||||||
if (p) SDL_free(p);
|
if (p != nullptr) { SDL_free(p); }
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
namespace Ja {
|
||||||
|
|
||||||
// --- Public Enums ---
|
// --- Public Enums ---
|
||||||
enum JA_Channel_state : uint8_t {
|
enum class ChannelState : std::uint8_t {
|
||||||
JA_CHANNEL_INVALID,
|
INVALID,
|
||||||
JA_CHANNEL_FREE,
|
FREE,
|
||||||
JA_CHANNEL_PLAYING,
|
PLAYING,
|
||||||
JA_CHANNEL_PAUSED,
|
PAUSED,
|
||||||
JA_SOUND_DISABLED,
|
DISABLED,
|
||||||
};
|
};
|
||||||
enum JA_Music_state : uint8_t {
|
|
||||||
JA_MUSIC_INVALID,
|
enum class MusicState : std::uint8_t {
|
||||||
JA_MUSIC_PLAYING,
|
INVALID,
|
||||||
JA_MUSIC_PAUSED,
|
PLAYING,
|
||||||
JA_MUSIC_STOPPED,
|
PAUSED,
|
||||||
JA_MUSIC_DISABLED,
|
STOPPED,
|
||||||
|
DISABLED,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// --- Constants ---
|
||||||
|
inline constexpr int MAX_SIMULTANEOUS_CHANNELS = 20;
|
||||||
|
inline constexpr int MAX_GROUPS = 2;
|
||||||
|
inline constexpr SDL_AudioSpec DEFAULT_SPEC{.format = SDL_AUDIO_S16, .channels = 2, .freq = 48000};
|
||||||
|
|
||||||
// --- Struct Definitions ---
|
// --- Struct Definitions ---
|
||||||
#define JA_MAX_SIMULTANEOUS_CHANNELS 20
|
struct Sound {
|
||||||
#define JA_MAX_GROUPS 2
|
SDL_AudioSpec spec{DEFAULT_SPEC};
|
||||||
|
|
||||||
struct JA_Sound_t {
|
|
||||||
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
|
|
||||||
Uint32 length{0};
|
Uint32 length{0};
|
||||||
// Buffer descomprimit (PCM) propietat del sound. Reservat per SDL_LoadWAV
|
// Buffer descomprimit (PCM) propietat del sound. Reservat per SDL_LoadWAV
|
||||||
// via SDL_malloc; el deleter `SDLFreeDeleter` allibera amb SDL_free.
|
// via SDL_malloc; el deleter `SdlFreeDeleter` allibera amb SDL_free.
|
||||||
std::unique_ptr<Uint8[], SDLFreeDeleter> buffer;
|
std::unique_ptr<Uint8[], SdlFreeDeleter> buffer;
|
||||||
};
|
};
|
||||||
|
|
||||||
struct JA_Channel_t {
|
struct Channel {
|
||||||
JA_Sound_t* sound{nullptr};
|
Sound* sound{nullptr};
|
||||||
int pos{0};
|
int pos{0};
|
||||||
int times{0};
|
int times{0};
|
||||||
int group{0};
|
int group{0};
|
||||||
SDL_AudioStream* stream{nullptr};
|
SDL_AudioStream* stream{nullptr};
|
||||||
JA_Channel_state state{JA_CHANNEL_FREE};
|
ChannelState state{ChannelState::FREE};
|
||||||
};
|
};
|
||||||
|
|
||||||
struct JA_Music_t {
|
struct Music {
|
||||||
SDL_AudioSpec spec{SDL_AUDIO_S16, 2, 48000};
|
SDL_AudioSpec spec{DEFAULT_SPEC};
|
||||||
|
|
||||||
// OGG comprimit en memòria. Propietat nostra; es copia des del buffer
|
// OGG comprimit en memòria. Propietat nostra; es copia des del buffer
|
||||||
// d'entrada una sola vegada en JA_LoadMusic i es descomprimix en chunks
|
// d'entrada una sola vegada en loadMusic i es descomprimix en chunks
|
||||||
// per streaming. Com que stb_vorbis guarda un punter persistent al
|
// per streaming. Com que stb_vorbis guarda un punter persistent al
|
||||||
// `.data()` d'aquest vector, no el podem resize'jar un cop establert
|
// `.data()` d'aquest vector, no el podem resize'jar un cop establert
|
||||||
// (una reallocation invalidaria el punter que el decoder conserva).
|
// (una reallocation invalidaria el punter que el decoder conserva).
|
||||||
std::vector<Uint8> ogg_data;
|
std::vector<Uint8> ogg_data;
|
||||||
stb_vorbis* vorbis{nullptr}; // handle del decoder, viu tot el cicle del JA_Music_t
|
stb_vorbis* vorbis{nullptr}; // handle del decoder, viu tot el cicle del Music
|
||||||
|
|
||||||
std::string filename;
|
std::string filename;
|
||||||
|
|
||||||
int times{0}; // loops restants (-1 = infinit, 0 = un sol play)
|
int times{0}; // loops restants (-1 = infinit, 0 = un sol play)
|
||||||
SDL_AudioStream* stream{nullptr};
|
SDL_AudioStream* stream{nullptr};
|
||||||
JA_Music_state state{JA_MUSIC_INVALID};
|
MusicState state{MusicState::INVALID};
|
||||||
};
|
};
|
||||||
|
|
||||||
// --- Internal Global State (inline, C++17) ---
|
struct FadeState {
|
||||||
|
|
||||||
inline JA_Music_t* current_music{nullptr};
|
|
||||||
inline JA_Channel_t channels[JA_MAX_SIMULTANEOUS_CHANNELS];
|
|
||||||
|
|
||||||
inline SDL_AudioSpec JA_audioSpec{SDL_AUDIO_S16, 2, 48000};
|
|
||||||
inline float JA_musicVolume{1.0F};
|
|
||||||
inline float JA_soundVolume[JA_MAX_GROUPS];
|
|
||||||
inline bool JA_musicEnabled{true};
|
|
||||||
inline bool JA_soundEnabled{true};
|
|
||||||
inline SDL_AudioDeviceID sdlAudioDevice{0};
|
|
||||||
|
|
||||||
// --- Crossfade / Fade State ---
|
|
||||||
struct JA_FadeState {
|
|
||||||
bool active{false};
|
bool active{false};
|
||||||
Uint64 start_time{0};
|
Uint64 start_time{0};
|
||||||
int duration_ms{0};
|
int duration_ms{0};
|
||||||
float initial_volume{0.0F};
|
float initial_volume{0.0F};
|
||||||
};
|
};
|
||||||
|
|
||||||
struct JA_OutgoingMusic {
|
struct OutgoingMusic {
|
||||||
SDL_AudioStream* stream{nullptr};
|
SDL_AudioStream* stream{nullptr};
|
||||||
JA_FadeState fade;
|
FadeState fade;
|
||||||
};
|
};
|
||||||
|
|
||||||
inline JA_OutgoingMusic outgoing_music;
|
// --- Internal Global State (inline, C++17) ---
|
||||||
inline JA_FadeState incoming_fade;
|
inline Music* current_music{nullptr};
|
||||||
|
inline Channel channels[MAX_SIMULTANEOUS_CHANNELS];
|
||||||
|
|
||||||
|
inline SDL_AudioSpec audio_spec{DEFAULT_SPEC};
|
||||||
|
inline float music_volume{1.0F};
|
||||||
|
inline float sound_volume[MAX_GROUPS];
|
||||||
|
inline bool music_enabled{true};
|
||||||
|
inline bool sound_enabled{true};
|
||||||
|
inline SDL_AudioDeviceID sdl_audio_device{0};
|
||||||
|
|
||||||
|
inline OutgoingMusic outgoing_music;
|
||||||
|
inline FadeState incoming_fade;
|
||||||
|
|
||||||
// --- Forward Declarations ---
|
// --- Forward Declarations ---
|
||||||
inline void JA_StopMusic();
|
inline void stopMusic();
|
||||||
inline void JA_StopChannel(const int channel);
|
inline void stopChannel(int channel);
|
||||||
inline auto JA_PlaySoundOnChannel(JA_Sound_t* sound, const int channel, const int loop = 0, const int group = 0) -> int;
|
inline auto playSoundOnChannel(Sound* sound, int channel, int loop = 0, int group = 0) -> int;
|
||||||
inline void JA_CrossfadeMusic(JA_Music_t* music, int crossfade_ms, int loop = -1);
|
inline void crossfadeMusic(Music* music, int crossfade_ms, int loop = -1);
|
||||||
|
|
||||||
// --- Music streaming internals ---
|
// --- Music streaming internals ---
|
||||||
// Bytes-per-sample per canal (sempre s16)
|
// Bytes-per-sample per canal (sempre s16)
|
||||||
static constexpr int JA_MUSIC_BYTES_PER_SAMPLE = 2;
|
inline constexpr int MUSIC_BYTES_PER_SAMPLE = 2;
|
||||||
// Quants shorts decodifiquem per crida a get_samples_short_interleaved.
|
// Quants shorts decodifiquem per crida a get_samples_short_interleaved.
|
||||||
// 8192 shorts = 4096 samples/channel en estèreo ≈ 85ms de so a 48kHz.
|
// 8192 shorts = 4096 samples/channel en estèreo ≈ 85ms de so a 48kHz.
|
||||||
static constexpr int JA_MUSIC_CHUNK_SHORTS = 8192;
|
inline constexpr int MUSIC_CHUNK_SHORTS = 8192;
|
||||||
// Umbral d'audio per davant del cursor de reproducció. Mantenim ≥ 0.5 s a
|
// Umbral d'audio per davant del cursor de reproducció. Mantenim ≥ 0.5 s a
|
||||||
// l'SDL_AudioStream per absorbir jitter de frame i evitar underruns.
|
// l'SDL_AudioStream per absorbir jitter de frame i evitar underruns.
|
||||||
static constexpr float JA_MUSIC_LOW_WATER_SECONDS = 0.5F;
|
inline constexpr float MUSIC_LOW_WATER_SECONDS = 0.5F;
|
||||||
|
|
||||||
// Decodifica un chunk del vorbis i el volca a l'stream. Retorna samples
|
// Decodifica un chunk del vorbis i el volca a l'stream. Retorna samples
|
||||||
// decodificats per canal (0 = EOF de l'stream vorbis).
|
// decodificats per canal (0 = EOF de l'stream vorbis).
|
||||||
inline auto JA_FeedMusicChunk(JA_Music_t* music) -> int {
|
inline auto feedMusicChunk(Music* music) -> int {
|
||||||
if (!music || !music->vorbis || !music->stream) return 0;
|
if ((music == nullptr) || (music->vorbis == nullptr) || (music->stream == nullptr)) { return 0; }
|
||||||
|
|
||||||
short chunk[JA_MUSIC_CHUNK_SHORTS];
|
short chunk[MUSIC_CHUNK_SHORTS];
|
||||||
const int num_channels = music->spec.channels;
|
const int NUM_CHANNELS = music->spec.channels;
|
||||||
const int samples_per_channel = stb_vorbis_get_samples_short_interleaved(
|
const int SAMPLES_PER_CHANNEL = stb_vorbis_get_samples_short_interleaved(
|
||||||
music->vorbis,
|
music->vorbis,
|
||||||
num_channels,
|
NUM_CHANNELS,
|
||||||
chunk,
|
chunk,
|
||||||
JA_MUSIC_CHUNK_SHORTS);
|
MUSIC_CHUNK_SHORTS);
|
||||||
if (samples_per_channel <= 0) return 0;
|
if (SAMPLES_PER_CHANNEL <= 0) { return 0; }
|
||||||
|
|
||||||
const int bytes = samples_per_channel * num_channels * JA_MUSIC_BYTES_PER_SAMPLE;
|
const int BYTES = SAMPLES_PER_CHANNEL * NUM_CHANNELS * MUSIC_BYTES_PER_SAMPLE;
|
||||||
SDL_PutAudioStreamData(music->stream, chunk, bytes);
|
SDL_PutAudioStreamData(music->stream, chunk, BYTES);
|
||||||
return samples_per_channel;
|
return SAMPLES_PER_CHANNEL;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reompli l'stream fins que tinga ≥ JA_MUSIC_LOW_WATER_SECONDS bufferats.
|
// Reompli l'stream fins que tinga ≥ MUSIC_LOW_WATER_SECONDS bufferats.
|
||||||
// En arribar a EOF del vorbis, aplica el loop (times) o deixa drenar.
|
// En arribar a EOF del vorbis, aplica el loop (times) o deixa drenar.
|
||||||
inline void JA_PumpMusic(JA_Music_t* music) {
|
inline void pumpMusic(Music* music) {
|
||||||
if (!music || !music->vorbis || !music->stream) return;
|
if ((music == nullptr) || (music->vorbis == nullptr) || (music->stream == nullptr)) { return; }
|
||||||
|
|
||||||
const int bytes_per_second = music->spec.freq * music->spec.channels * JA_MUSIC_BYTES_PER_SAMPLE;
|
const int BYTES_PER_SECOND = music->spec.freq * music->spec.channels * MUSIC_BYTES_PER_SAMPLE;
|
||||||
const int low_water_bytes = static_cast<int>(JA_MUSIC_LOW_WATER_SECONDS * static_cast<float>(bytes_per_second));
|
const int LOW_WATER_BYTES = static_cast<int>(MUSIC_LOW_WATER_SECONDS * static_cast<float>(BYTES_PER_SECOND));
|
||||||
|
|
||||||
while (SDL_GetAudioStreamAvailable(music->stream) < low_water_bytes) {
|
while (SDL_GetAudioStreamAvailable(music->stream) < LOW_WATER_BYTES) {
|
||||||
const int decoded = JA_FeedMusicChunk(music);
|
const int DECODED = feedMusicChunk(music);
|
||||||
if (decoded > 0) continue;
|
if (DECODED > 0) { continue; }
|
||||||
|
|
||||||
// EOF: si queden loops, rebobinar; si no, tallar i deixar drenar.
|
// EOF: si queden loops, rebobinar; si no, tallar i deixar drenar.
|
||||||
if (music->times != 0) {
|
if (music->times != 0) {
|
||||||
stb_vorbis_seek_start(music->vorbis);
|
stb_vorbis_seek_start(music->vorbis);
|
||||||
if (music->times > 0) music->times--;
|
if (music->times > 0) { music->times--; }
|
||||||
} else {
|
} else {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
@@ -167,102 +171,112 @@ inline void JA_PumpMusic(JA_Music_t* music) {
|
|||||||
// siga robat per outgoing_music (crossfade o fade-out). Imprescindible amb
|
// siga robat per outgoing_music (crossfade o fade-out). Imprescindible amb
|
||||||
// streaming: l'stream robat no es pot re-alimentar perquè perd la referència
|
// streaming: l'stream robat no es pot re-alimentar perquè perd la referència
|
||||||
// al seu vorbis decoder. No aplica loop — si el vorbis s'esgota abans, parem.
|
// al seu vorbis decoder. No aplica loop — si el vorbis s'esgota abans, parem.
|
||||||
inline void JA_PreFillOutgoing(JA_Music_t* music, int duration_ms) {
|
inline void preFillOutgoing(Music* music, int duration_ms) {
|
||||||
if (!music || !music->vorbis || !music->stream) return;
|
if ((music == nullptr) || (music->vorbis == nullptr) || (music->stream == nullptr)) { return; }
|
||||||
|
|
||||||
const int bytes_per_second = music->spec.freq * music->spec.channels * JA_MUSIC_BYTES_PER_SAMPLE;
|
const int BYTES_PER_SECOND = music->spec.freq * music->spec.channels * MUSIC_BYTES_PER_SAMPLE;
|
||||||
const int needed_bytes = static_cast<int>((static_cast<int64_t>(duration_ms) * bytes_per_second) / 1000);
|
const int NEEDED_BYTES = static_cast<int>((static_cast<std::int64_t>(duration_ms) * BYTES_PER_SECOND) / 1000);
|
||||||
|
|
||||||
while (SDL_GetAudioStreamAvailable(music->stream) < needed_bytes) {
|
while (SDL_GetAudioStreamAvailable(music->stream) < NEEDED_BYTES) {
|
||||||
const int decoded = JA_FeedMusicChunk(music);
|
const int DECODED = feedMusicChunk(music);
|
||||||
if (decoded <= 0) break; // EOF: deixem drenar el que hi haja
|
if (DECODED <= 0) { break; } // EOF: deixem drenar el que hi haja
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Core Functions ---
|
// --- update() helpers ---
|
||||||
|
inline void updateOutgoingFade() {
|
||||||
|
if ((outgoing_music.stream == nullptr) || !outgoing_music.fade.active) { return; }
|
||||||
|
|
||||||
inline void JA_Update() {
|
const Uint64 NOW = SDL_GetTicks();
|
||||||
// --- Outgoing music fade-out (crossfade o fade-out a silencio) ---
|
const Uint64 ELAPSED = NOW - outgoing_music.fade.start_time;
|
||||||
if (outgoing_music.stream && outgoing_music.fade.active) {
|
if (ELAPSED >= static_cast<Uint64>(outgoing_music.fade.duration_ms)) {
|
||||||
Uint64 now = SDL_GetTicks();
|
|
||||||
Uint64 elapsed = now - outgoing_music.fade.start_time;
|
|
||||||
if (elapsed >= (Uint64)outgoing_music.fade.duration_ms) {
|
|
||||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||||
outgoing_music.stream = nullptr;
|
outgoing_music.stream = nullptr;
|
||||||
outgoing_music.fade.active = false;
|
outgoing_music.fade.active = false;
|
||||||
} else {
|
} else {
|
||||||
float percent = (float)elapsed / (float)outgoing_music.fade.duration_ms;
|
const float PERCENT = static_cast<float>(ELAPSED) / static_cast<float>(outgoing_music.fade.duration_ms);
|
||||||
SDL_SetAudioStreamGain(outgoing_music.stream, outgoing_music.fade.initial_volume * (1.0F - percent));
|
SDL_SetAudioStreamGain(outgoing_music.stream, outgoing_music.fade.initial_volume * (1.0F - PERCENT));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Current music ---
|
inline void updateIncomingFade() {
|
||||||
if (JA_musicEnabled && current_music && current_music->state == JA_MUSIC_PLAYING) {
|
if (!incoming_fade.active) { return; }
|
||||||
// Fade-in (parte de un crossfade)
|
|
||||||
if (incoming_fade.active) {
|
const Uint64 NOW = SDL_GetTicks();
|
||||||
Uint64 now = SDL_GetTicks();
|
const Uint64 ELAPSED = NOW - incoming_fade.start_time;
|
||||||
Uint64 elapsed = now - incoming_fade.start_time;
|
if (ELAPSED >= static_cast<Uint64>(incoming_fade.duration_ms)) {
|
||||||
if (elapsed >= (Uint64)incoming_fade.duration_ms) {
|
|
||||||
incoming_fade.active = false;
|
incoming_fade.active = false;
|
||||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
SDL_SetAudioStreamGain(current_music->stream, music_volume);
|
||||||
} else {
|
} else {
|
||||||
float percent = (float)elapsed / (float)incoming_fade.duration_ms;
|
const float PERCENT = static_cast<float>(ELAPSED) / static_cast<float>(incoming_fade.duration_ms);
|
||||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume * percent);
|
SDL_SetAudioStreamGain(current_music->stream, music_volume * PERCENT);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
inline void updateCurrentMusic() {
|
||||||
|
if (!music_enabled || (current_music == nullptr) || current_music->state != MusicState::PLAYING) { return; }
|
||||||
|
|
||||||
|
updateIncomingFade();
|
||||||
|
|
||||||
// Streaming: rellenem l'stream fins al low-water-mark i parem si el
|
// Streaming: rellenem l'stream fins al low-water-mark i parem si el
|
||||||
// vorbis s'ha esgotat i no queden loops.
|
// vorbis s'ha esgotat i no queden loops.
|
||||||
JA_PumpMusic(current_music);
|
pumpMusic(current_music);
|
||||||
if (current_music->times == 0 && SDL_GetAudioStreamAvailable(current_music->stream) == 0) {
|
if (current_music->times == 0 && SDL_GetAudioStreamAvailable(current_music->stream) == 0) {
|
||||||
JA_StopMusic();
|
stopMusic();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Sound channels ---
|
inline void updateSoundChannels() {
|
||||||
if (JA_soundEnabled) {
|
if (!sound_enabled) { return; }
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i)
|
|
||||||
if (channels[i].state == JA_CHANNEL_PLAYING) {
|
for (int i = 0; i < MAX_SIMULTANEOUS_CHANNELS; ++i) {
|
||||||
if (channels[i].times != 0) {
|
auto& ch = channels[i];
|
||||||
if ((Uint32)SDL_GetAudioStreamAvailable(channels[i].stream) < (channels[i].sound->length / 2)) {
|
if (ch.state != ChannelState::PLAYING) { continue; }
|
||||||
SDL_PutAudioStreamData(channels[i].stream, channels[i].sound->buffer.get(), channels[i].sound->length);
|
|
||||||
if (channels[i].times > 0) channels[i].times--;
|
if (ch.times != 0) {
|
||||||
|
if (static_cast<Uint32>(SDL_GetAudioStreamAvailable(ch.stream)) < (ch.sound->length / 2)) {
|
||||||
|
SDL_PutAudioStreamData(ch.stream, ch.sound->buffer.get(), ch.sound->length);
|
||||||
|
if (ch.times > 0) { ch.times--; }
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
if (SDL_GetAudioStreamAvailable(channels[i].stream) == 0) JA_StopChannel(i);
|
if (SDL_GetAudioStreamAvailable(ch.stream) == 0) { stopChannel(i); }
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_Init(const int freq, const SDL_AudioFormat format, const int num_channels) {
|
inline void update() {
|
||||||
JA_audioSpec = {format, num_channels, freq};
|
updateOutgoingFade();
|
||||||
if (sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice);
|
updateCurrentMusic();
|
||||||
sdlAudioDevice = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &JA_audioSpec);
|
updateSoundChannels();
|
||||||
if (sdlAudioDevice == 0) std::cout << "Failed to initialize SDL audio!" << '\n';
|
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; ++i) channels[i].state = JA_CHANNEL_FREE;
|
|
||||||
for (int i = 0; i < JA_MAX_GROUPS; ++i) JA_soundVolume[i] = 0.5F;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_Quit() {
|
inline void init(int freq, SDL_AudioFormat format, int num_channels) {
|
||||||
if (outgoing_music.stream) {
|
audio_spec = {.format = format, .channels = num_channels, .freq = freq};
|
||||||
|
if (sdl_audio_device != 0) { SDL_CloseAudioDevice(sdl_audio_device); }
|
||||||
|
sdl_audio_device = SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &audio_spec);
|
||||||
|
if (sdl_audio_device == 0) { std::cout << "Failed to initialize SDL audio!" << '\n'; }
|
||||||
|
for (auto& ch : channels) { ch.state = ChannelState::FREE; }
|
||||||
|
for (float& v : sound_volume) { v = 0.5F; }
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void quit() {
|
||||||
|
if (outgoing_music.stream != nullptr) {
|
||||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||||
outgoing_music.stream = nullptr;
|
outgoing_music.stream = nullptr;
|
||||||
}
|
}
|
||||||
if (sdlAudioDevice) SDL_CloseAudioDevice(sdlAudioDevice);
|
if (sdl_audio_device != 0) { SDL_CloseAudioDevice(sdl_audio_device); }
|
||||||
sdlAudioDevice = 0;
|
sdl_audio_device = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Music Functions ---
|
// --- Music Functions ---
|
||||||
|
inline auto loadMusic(const Uint8* buffer, Uint32 length) -> Music* {
|
||||||
|
if ((buffer == nullptr) || length == 0) { return nullptr; }
|
||||||
|
|
||||||
inline auto JA_LoadMusic(const Uint8* buffer, Uint32 length) -> JA_Music_t* {
|
// Allocem el Music primer per aprofitar el seu `std::vector<Uint8>`
|
||||||
if (!buffer || length == 0) return nullptr;
|
|
||||||
|
|
||||||
// Allocem el JA_Music_t primer per aprofitar el seu `std::vector<Uint8>`
|
|
||||||
// com a propietari del OGG comprimit. stb_vorbis guarda un punter
|
// com a propietari del OGG comprimit. stb_vorbis guarda un punter
|
||||||
// persistent al buffer; com que ací no el resize'jem, el .data() és
|
// persistent al buffer; com que ací no el resize'jem, el .data() és
|
||||||
// estable durant tot el cicle de vida del music.
|
// estable durant tot el cicle de vida del music.
|
||||||
auto* music = new JA_Music_t();
|
auto* music = new Music();
|
||||||
music->ogg_data.assign(buffer, buffer + length);
|
music->ogg_data.assign(buffer, buffer + length);
|
||||||
|
|
||||||
int vorbis_error = 0;
|
int vorbis_error = 0;
|
||||||
@@ -270,162 +284,160 @@ inline auto JA_LoadMusic(const Uint8* buffer, Uint32 length) -> JA_Music_t* {
|
|||||||
static_cast<int>(length),
|
static_cast<int>(length),
|
||||||
&vorbis_error,
|
&vorbis_error,
|
||||||
nullptr);
|
nullptr);
|
||||||
if (!music->vorbis) {
|
if (music->vorbis == nullptr) {
|
||||||
std::cout << "JA_LoadMusic: stb_vorbis_open_memory failed (error " << vorbis_error << ")" << '\n';
|
std::cout << "loadMusic: stb_vorbis_open_memory failed (error " << vorbis_error << ")" << '\n';
|
||||||
delete music;
|
delete music;
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
const stb_vorbis_info info = stb_vorbis_get_info(music->vorbis);
|
const stb_vorbis_info INFO = stb_vorbis_get_info(music->vorbis);
|
||||||
music->spec.channels = info.channels;
|
music->spec.channels = INFO.channels;
|
||||||
music->spec.freq = static_cast<int>(info.sample_rate);
|
music->spec.freq = static_cast<int>(INFO.sample_rate);
|
||||||
music->spec.format = SDL_AUDIO_S16;
|
music->spec.format = SDL_AUDIO_S16;
|
||||||
music->state = JA_MUSIC_STOPPED;
|
music->state = MusicState::STOPPED;
|
||||||
|
|
||||||
return music;
|
return music;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Overload amb filename — els callers l'usen per poder comparar la música
|
// Overload amb filename — els callers l'usen per poder comparar la música
|
||||||
// en curs amb JA_GetMusicFilename() i no rearrancar-la si ja és la mateixa.
|
// en curs amb getMusicFilename() i no rearrancar-la si ja és la mateixa.
|
||||||
inline auto JA_LoadMusic(Uint8* buffer, Uint32 length, const char* filename) -> JA_Music_t* {
|
inline auto loadMusic(Uint8* buffer, Uint32 length, const char* filename) -> Music* {
|
||||||
JA_Music_t* music = JA_LoadMusic(static_cast<const Uint8*>(buffer), length);
|
Music* music = loadMusic(static_cast<const Uint8*>(buffer), length);
|
||||||
if (music && filename) music->filename = filename;
|
if ((music != nullptr) && (filename != nullptr)) { music->filename = filename; }
|
||||||
return music;
|
return music;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_LoadMusic(const char* filename) -> JA_Music_t* {
|
inline auto loadMusic(const char* filename) -> Music* {
|
||||||
// Carreguem primer el arxiu en memòria i després el descomprimim.
|
// Carreguem primer el arxiu en memòria i després el descomprimim.
|
||||||
FILE* f = fopen(filename, "rb");
|
FILE* f = std::fopen(filename, "rb");
|
||||||
if (!f) return nullptr;
|
if (f == nullptr) { return nullptr; }
|
||||||
fseek(f, 0, SEEK_END);
|
std::fseek(f, 0, SEEK_END);
|
||||||
long fsize = ftell(f);
|
const long FSIZE = std::ftell(f);
|
||||||
fseek(f, 0, SEEK_SET);
|
std::fseek(f, 0, SEEK_SET);
|
||||||
auto* buffer = static_cast<Uint8*>(malloc(fsize + 1));
|
auto* buffer = static_cast<Uint8*>(std::malloc(FSIZE + 1));
|
||||||
if (!buffer) {
|
if (buffer == nullptr) {
|
||||||
fclose(f);
|
std::fclose(f);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
if (fread(buffer, fsize, 1, f) != 1) {
|
if (std::fread(buffer, FSIZE, 1, f) != 1) {
|
||||||
fclose(f);
|
std::fclose(f);
|
||||||
free(buffer);
|
std::free(buffer);
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
fclose(f);
|
std::fclose(f);
|
||||||
|
|
||||||
JA_Music_t* music = JA_LoadMusic(static_cast<const Uint8*>(buffer), static_cast<Uint32>(fsize));
|
Music* music = loadMusic(static_cast<const Uint8*>(buffer), static_cast<Uint32>(FSIZE));
|
||||||
if (music) {
|
if (music != nullptr) { music->filename = filename; }
|
||||||
music->filename = filename;
|
|
||||||
}
|
|
||||||
|
|
||||||
free(buffer);
|
std::free(buffer);
|
||||||
|
|
||||||
return music;
|
return music;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_PlayMusic(JA_Music_t* music, const int loop = -1) {
|
inline void playMusic(Music* music, int loop = -1) {
|
||||||
if (!JA_musicEnabled || !music || !music->vorbis) return;
|
if (!music_enabled || (music == nullptr) || (music->vorbis == nullptr)) { return; }
|
||||||
|
|
||||||
JA_StopMusic();
|
stopMusic();
|
||||||
|
|
||||||
current_music = music;
|
current_music = music;
|
||||||
current_music->state = JA_MUSIC_PLAYING;
|
current_music->state = MusicState::PLAYING;
|
||||||
current_music->times = loop;
|
current_music->times = loop;
|
||||||
|
|
||||||
// Rebobinem l'stream de vorbis al principi. Cobreix tant play-per-primera-
|
// Rebobinem l'stream de vorbis al principi. Cobreix tant play-per-primera-
|
||||||
// vegada com replays/canvis de track que tornen a la mateixa pista.
|
// vegada com replays/canvis de track que tornen a la mateixa pista.
|
||||||
stb_vorbis_seek_start(current_music->vorbis);
|
stb_vorbis_seek_start(current_music->vorbis);
|
||||||
|
|
||||||
current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &JA_audioSpec);
|
current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &audio_spec);
|
||||||
if (!current_music->stream) {
|
if (current_music->stream == nullptr) {
|
||||||
std::cout << "Failed to create audio stream!" << '\n';
|
std::cout << "Failed to create audio stream!" << '\n';
|
||||||
current_music->state = JA_MUSIC_STOPPED;
|
current_music->state = MusicState::STOPPED;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
SDL_SetAudioStreamGain(current_music->stream, music_volume);
|
||||||
|
|
||||||
// Pre-cargem el buffer abans de bindejar per evitar un underrun inicial.
|
// Pre-cargem el buffer abans de bindejar per evitar un underrun inicial.
|
||||||
JA_PumpMusic(current_music);
|
pumpMusic(current_music);
|
||||||
|
|
||||||
if (!SDL_BindAudioStream(sdlAudioDevice, current_music->stream)) {
|
if (!SDL_BindAudioStream(sdl_audio_device, current_music->stream)) {
|
||||||
std::cout << "[ERROR] SDL_BindAudioStream failed!" << '\n';
|
std::cout << "[ERROR] SDL_BindAudioStream failed!" << '\n';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_GetMusicFilename(const JA_Music_t* music = nullptr) -> const char* {
|
inline auto getMusicFilename(const Music* music = nullptr) -> const char* {
|
||||||
if (!music) music = current_music;
|
if (music == nullptr) { music = current_music; }
|
||||||
if (!music || music->filename.empty()) return nullptr;
|
if ((music == nullptr) || music->filename.empty()) { return nullptr; }
|
||||||
return music->filename.c_str();
|
return music->filename.c_str();
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_PauseMusic() {
|
inline void pauseMusic() {
|
||||||
if (!JA_musicEnabled) return;
|
if (!music_enabled) { return; }
|
||||||
if (!current_music || current_music->state != JA_MUSIC_PLAYING) return;
|
if ((current_music == nullptr) || current_music->state != MusicState::PLAYING) { return; }
|
||||||
|
|
||||||
current_music->state = JA_MUSIC_PAUSED;
|
current_music->state = MusicState::PAUSED;
|
||||||
SDL_UnbindAudioStream(current_music->stream);
|
SDL_UnbindAudioStream(current_music->stream);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_ResumeMusic() {
|
inline void resumeMusic() {
|
||||||
if (!JA_musicEnabled) return;
|
if (!music_enabled) { return; }
|
||||||
if (!current_music || current_music->state != JA_MUSIC_PAUSED) return;
|
if ((current_music == nullptr) || current_music->state != MusicState::PAUSED) { return; }
|
||||||
|
|
||||||
current_music->state = JA_MUSIC_PLAYING;
|
current_music->state = MusicState::PLAYING;
|
||||||
SDL_BindAudioStream(sdlAudioDevice, current_music->stream);
|
SDL_BindAudioStream(sdl_audio_device, current_music->stream);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_StopMusic() {
|
inline void stopMusic() {
|
||||||
// Limpiar outgoing crossfade si existe
|
// Limpiar outgoing crossfade si existe
|
||||||
if (outgoing_music.stream) {
|
if (outgoing_music.stream != nullptr) {
|
||||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||||
outgoing_music.stream = nullptr;
|
outgoing_music.stream = nullptr;
|
||||||
outgoing_music.fade.active = false;
|
outgoing_music.fade.active = false;
|
||||||
}
|
}
|
||||||
incoming_fade.active = false;
|
incoming_fade.active = false;
|
||||||
|
|
||||||
if (!current_music || current_music->state == JA_MUSIC_INVALID || current_music->state == JA_MUSIC_STOPPED) return;
|
if ((current_music == nullptr) || current_music->state == MusicState::INVALID || current_music->state == MusicState::STOPPED) { return; }
|
||||||
|
|
||||||
current_music->state = JA_MUSIC_STOPPED;
|
current_music->state = MusicState::STOPPED;
|
||||||
if (current_music->stream) {
|
if (current_music->stream != nullptr) {
|
||||||
SDL_DestroyAudioStream(current_music->stream);
|
SDL_DestroyAudioStream(current_music->stream);
|
||||||
current_music->stream = nullptr;
|
current_music->stream = nullptr;
|
||||||
}
|
}
|
||||||
// Deixem el handle de vorbis viu — es tanca en JA_DeleteMusic.
|
// Deixem el handle de vorbis viu — es tanca en deleteMusic.
|
||||||
// Rebobinem perquè un futur JA_PlayMusic comence des del principi.
|
// Rebobinem perquè un futur playMusic comence des del principi.
|
||||||
if (current_music->vorbis) {
|
if (current_music->vorbis != nullptr) {
|
||||||
stb_vorbis_seek_start(current_music->vorbis);
|
stb_vorbis_seek_start(current_music->vorbis);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_FadeOutMusic(const int milliseconds) {
|
inline void fadeOutMusic(int milliseconds) {
|
||||||
if (!JA_musicEnabled) return;
|
if (!music_enabled) { return; }
|
||||||
if (!current_music || current_music->state != JA_MUSIC_PLAYING) return;
|
if ((current_music == nullptr) || current_music->state != MusicState::PLAYING) { return; }
|
||||||
|
|
||||||
// Destruir outgoing anterior si existe
|
// Destruir outgoing anterior si existe
|
||||||
if (outgoing_music.stream) {
|
if (outgoing_music.stream != nullptr) {
|
||||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||||
outgoing_music.stream = nullptr;
|
outgoing_music.stream = nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Pre-omplim l'stream amb `milliseconds` de so: un cop robat, ja no
|
// Pre-omplim l'stream amb `milliseconds` de so: un cop robat, ja no
|
||||||
// tindrà accés al vorbis decoder i només podrà drenar el que tinga.
|
// tindrà accés al vorbis decoder i només podrà drenar el que tinga.
|
||||||
JA_PreFillOutgoing(current_music, milliseconds);
|
preFillOutgoing(current_music, milliseconds);
|
||||||
|
|
||||||
// Robar el stream del current_music al outgoing
|
// Robar el stream del current_music al outgoing
|
||||||
outgoing_music.stream = current_music->stream;
|
outgoing_music.stream = current_music->stream;
|
||||||
outgoing_music.fade = {true, SDL_GetTicks(), milliseconds, JA_musicVolume};
|
outgoing_music.fade = {.active = true, .start_time = SDL_GetTicks(), .duration_ms = milliseconds, .initial_volume = music_volume};
|
||||||
|
|
||||||
// Dejar current_music sin stream (ya lo tiene outgoing)
|
// Dejar current_music sin stream (ya lo tiene outgoing)
|
||||||
current_music->stream = nullptr;
|
current_music->stream = nullptr;
|
||||||
current_music->state = JA_MUSIC_STOPPED;
|
current_music->state = MusicState::STOPPED;
|
||||||
if (current_music->vorbis) stb_vorbis_seek_start(current_music->vorbis);
|
if (current_music->vorbis != nullptr) { stb_vorbis_seek_start(current_music->vorbis); }
|
||||||
incoming_fade.active = false;
|
incoming_fade.active = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_CrossfadeMusic(JA_Music_t* music, const int crossfade_ms, const int loop) {
|
inline void crossfadeMusic(Music* music, int crossfade_ms, int loop) {
|
||||||
if (!JA_musicEnabled || !music || !music->vorbis) return;
|
if (!music_enabled || (music == nullptr) || (music->vorbis == nullptr)) { return; }
|
||||||
|
|
||||||
// Destruir outgoing anterior si existe (crossfade durante crossfade)
|
// Destruir outgoing anterior si existe (crossfade durante crossfade)
|
||||||
if (outgoing_music.stream) {
|
if (outgoing_music.stream != nullptr) {
|
||||||
SDL_DestroyAudioStream(outgoing_music.stream);
|
SDL_DestroyAudioStream(outgoing_music.stream);
|
||||||
outgoing_music.stream = nullptr;
|
outgoing_music.stream = nullptr;
|
||||||
outgoing_music.fade.active = false;
|
outgoing_music.fade.active = false;
|
||||||
@@ -434,80 +446,79 @@ inline void JA_CrossfadeMusic(JA_Music_t* music, const int crossfade_ms, const i
|
|||||||
// Robar el stream de la musica actual al outgoing para el fade-out.
|
// Robar el stream de la musica actual al outgoing para el fade-out.
|
||||||
// Pre-omplim amb `crossfade_ms` de so perquè no es quede en silenci
|
// Pre-omplim amb `crossfade_ms` de so perquè no es quede en silenci
|
||||||
// abans d'acabar el fade (l'stream robat ja no pot alimentar-se).
|
// abans d'acabar el fade (l'stream robat ja no pot alimentar-se).
|
||||||
if (current_music && current_music->state == JA_MUSIC_PLAYING && current_music->stream) {
|
if ((current_music != nullptr) && current_music->state == MusicState::PLAYING && (current_music->stream != nullptr)) {
|
||||||
JA_PreFillOutgoing(current_music, crossfade_ms);
|
preFillOutgoing(current_music, crossfade_ms);
|
||||||
outgoing_music.stream = current_music->stream;
|
outgoing_music.stream = current_music->stream;
|
||||||
outgoing_music.fade = {true, SDL_GetTicks(), crossfade_ms, JA_musicVolume};
|
outgoing_music.fade = {.active = true, .start_time = SDL_GetTicks(), .duration_ms = crossfade_ms, .initial_volume = music_volume};
|
||||||
current_music->stream = nullptr;
|
current_music->stream = nullptr;
|
||||||
current_music->state = JA_MUSIC_STOPPED;
|
current_music->state = MusicState::STOPPED;
|
||||||
if (current_music->vorbis) stb_vorbis_seek_start(current_music->vorbis);
|
if (current_music->vorbis != nullptr) { stb_vorbis_seek_start(current_music->vorbis); }
|
||||||
}
|
}
|
||||||
|
|
||||||
// Iniciar la nueva pista con gain=0 (el fade-in la sube gradualmente)
|
// Iniciar la nueva pista con gain=0 (el fade-in la sube gradualmente)
|
||||||
current_music = music;
|
current_music = music;
|
||||||
current_music->state = JA_MUSIC_PLAYING;
|
current_music->state = MusicState::PLAYING;
|
||||||
current_music->times = loop;
|
current_music->times = loop;
|
||||||
|
|
||||||
stb_vorbis_seek_start(current_music->vorbis);
|
stb_vorbis_seek_start(current_music->vorbis);
|
||||||
current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &JA_audioSpec);
|
current_music->stream = SDL_CreateAudioStream(¤t_music->spec, &audio_spec);
|
||||||
if (!current_music->stream) {
|
if (current_music->stream == nullptr) {
|
||||||
std::cout << "Failed to create audio stream for crossfade!" << '\n';
|
std::cout << "Failed to create audio stream for crossfade!" << '\n';
|
||||||
current_music->state = JA_MUSIC_STOPPED;
|
current_music->state = MusicState::STOPPED;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
SDL_SetAudioStreamGain(current_music->stream, 0.0F);
|
SDL_SetAudioStreamGain(current_music->stream, 0.0F);
|
||||||
JA_PumpMusic(current_music); // pre-carrega abans de bindejar
|
pumpMusic(current_music); // pre-carrega abans de bindejar
|
||||||
SDL_BindAudioStream(sdlAudioDevice, current_music->stream);
|
SDL_BindAudioStream(sdl_audio_device, current_music->stream);
|
||||||
|
|
||||||
// Configurar fade-in
|
// Configurar fade-in
|
||||||
incoming_fade = {true, SDL_GetTicks(), crossfade_ms, 0.0F};
|
incoming_fade = {.active = true, .start_time = SDL_GetTicks(), .duration_ms = crossfade_ms, .initial_volume = 0.0F};
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_GetMusicState() -> JA_Music_state {
|
inline auto getMusicState() -> MusicState {
|
||||||
if (!JA_musicEnabled) return JA_MUSIC_DISABLED;
|
if (!music_enabled) { return MusicState::DISABLED; }
|
||||||
if (!current_music) return JA_MUSIC_INVALID;
|
if (current_music == nullptr) { return MusicState::INVALID; }
|
||||||
|
|
||||||
return current_music->state;
|
return current_music->state;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_DeleteMusic(JA_Music_t* music) {
|
inline void deleteMusic(Music* music) {
|
||||||
if (!music) return;
|
if (music == nullptr) { return; }
|
||||||
if (current_music == music) {
|
if (current_music == music) {
|
||||||
JA_StopMusic();
|
stopMusic();
|
||||||
current_music = nullptr;
|
current_music = nullptr;
|
||||||
}
|
}
|
||||||
if (music->stream) SDL_DestroyAudioStream(music->stream);
|
if (music->stream != nullptr) { SDL_DestroyAudioStream(music->stream); }
|
||||||
if (music->vorbis) stb_vorbis_close(music->vorbis);
|
if (music->vorbis != nullptr) { stb_vorbis_close(music->vorbis); }
|
||||||
// ogg_data (std::vector) i filename (std::string) s'alliberen sols
|
// ogg_data (std::vector) i filename (std::string) s'alliberen sols
|
||||||
// al destructor de JA_Music_t.
|
// al destructor de Music.
|
||||||
delete music;
|
delete music;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_SetMusicVolume(float volume) -> float {
|
inline auto setMusicVolume(float volume) -> float {
|
||||||
JA_musicVolume = SDL_clamp(volume, 0.0F, 1.0F);
|
music_volume = SDL_clamp(volume, 0.0F, 1.0F);
|
||||||
if (current_music && current_music->stream) {
|
if ((current_music != nullptr) && (current_music->stream != nullptr)) {
|
||||||
SDL_SetAudioStreamGain(current_music->stream, JA_musicVolume);
|
SDL_SetAudioStreamGain(current_music->stream, music_volume);
|
||||||
}
|
}
|
||||||
return JA_musicVolume;
|
return music_volume;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_SetMusicPosition(float /*value*/) {
|
inline void setMusicPosition(float /*value*/) {
|
||||||
// No implementat amb el backend de streaming.
|
// No implementat amb el backend de streaming.
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_GetMusicPosition() -> float {
|
inline auto getMusicPosition() -> float {
|
||||||
return 0.0F;
|
return 0.0F;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_EnableMusic(const bool value) {
|
inline void enableMusic(bool value) {
|
||||||
if (!value && current_music && (current_music->state == JA_MUSIC_PLAYING)) JA_StopMusic();
|
if (!value && (current_music != nullptr) && (current_music->state == MusicState::PLAYING)) { stopMusic(); }
|
||||||
JA_musicEnabled = value;
|
music_enabled = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- Sound Functions ---
|
// --- Sound Functions ---
|
||||||
|
inline auto loadSound(std::uint8_t* buffer, std::uint32_t size) -> Sound* {
|
||||||
inline auto JA_LoadSound(uint8_t* buffer, uint32_t size) -> JA_Sound_t* {
|
auto sound = std::make_unique<Sound>();
|
||||||
auto sound = std::make_unique<JA_Sound_t>();
|
|
||||||
Uint8* raw = nullptr;
|
Uint8* raw = nullptr;
|
||||||
if (!SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &raw, &sound->length)) {
|
if (!SDL_LoadWAV_IO(SDL_IOFromMem(buffer, size), 1, &sound->spec, &raw, &sound->length)) {
|
||||||
std::cout << "Failed to load WAV from memory: " << SDL_GetError() << '\n';
|
std::cout << "Failed to load WAV from memory: " << SDL_GetError() << '\n';
|
||||||
@@ -517,8 +528,8 @@ inline auto JA_LoadSound(uint8_t* buffer, uint32_t size) -> JA_Sound_t* {
|
|||||||
return sound.release();
|
return sound.release();
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_LoadSound(const char* filename) -> JA_Sound_t* {
|
inline auto loadSound(const char* filename) -> Sound* {
|
||||||
auto sound = std::make_unique<JA_Sound_t>();
|
auto sound = std::make_unique<Sound>();
|
||||||
Uint8* raw = nullptr;
|
Uint8* raw = nullptr;
|
||||||
if (!SDL_LoadWAV(filename, &sound->spec, &raw, &sound->length)) {
|
if (!SDL_LoadWAV(filename, &sound->spec, &raw, &sound->length)) {
|
||||||
std::cout << "Failed to load WAV file: " << SDL_GetError() << '\n';
|
std::cout << "Failed to load WAV file: " << SDL_GetError() << '\n';
|
||||||
@@ -528,152 +539,156 @@ inline auto JA_LoadSound(const char* filename) -> JA_Sound_t* {
|
|||||||
return sound.release();
|
return sound.release();
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_PlaySound(JA_Sound_t* sound, const int loop = 0, const int group = 0) -> int {
|
inline auto playSound(Sound* sound, int loop = 0, int group = 0) -> int {
|
||||||
if (!JA_soundEnabled || !sound) return -1;
|
if (!sound_enabled || (sound == nullptr)) { return -1; }
|
||||||
|
|
||||||
int channel = 0;
|
int channel = 0;
|
||||||
while (channel < JA_MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != JA_CHANNEL_FREE) { channel++; }
|
while (channel < MAX_SIMULTANEOUS_CHANNELS && channels[channel].state != ChannelState::FREE) { channel++; }
|
||||||
if (channel == JA_MAX_SIMULTANEOUS_CHANNELS) {
|
if (channel == MAX_SIMULTANEOUS_CHANNELS) {
|
||||||
// No hay canal libre, reemplazamos el primero
|
// No hi ha canal lliure, reemplacem el primer
|
||||||
channel = 0;
|
channel = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
return JA_PlaySoundOnChannel(sound, channel, loop, group);
|
return playSoundOnChannel(sound, channel, loop, group);
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_PlaySoundOnChannel(JA_Sound_t* sound, const int channel, const int loop, const int group) -> int {
|
inline auto playSoundOnChannel(Sound* sound, int channel, int loop, int group) -> int {
|
||||||
if (!JA_soundEnabled || !sound) return -1;
|
if (!sound_enabled || (sound == nullptr)) { return -1; }
|
||||||
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return -1;
|
if (channel < 0 || channel >= MAX_SIMULTANEOUS_CHANNELS) { return -1; }
|
||||||
|
|
||||||
JA_StopChannel(channel);
|
stopChannel(channel);
|
||||||
|
|
||||||
channels[channel].sound = sound;
|
channels[channel].sound = sound;
|
||||||
channels[channel].times = loop;
|
channels[channel].times = loop;
|
||||||
channels[channel].pos = 0;
|
channels[channel].pos = 0;
|
||||||
channels[channel].group = group;
|
channels[channel].group = group;
|
||||||
channels[channel].state = JA_CHANNEL_PLAYING;
|
channels[channel].state = ChannelState::PLAYING;
|
||||||
channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &JA_audioSpec);
|
channels[channel].stream = SDL_CreateAudioStream(&channels[channel].sound->spec, &audio_spec);
|
||||||
|
|
||||||
if (!channels[channel].stream) {
|
if (channels[channel].stream == nullptr) {
|
||||||
std::cout << "Failed to create audio stream for sound!" << '\n';
|
std::cout << "Failed to create audio stream for sound!" << '\n';
|
||||||
channels[channel].state = JA_CHANNEL_FREE;
|
channels[channel].state = ChannelState::FREE;
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer.get(), channels[channel].sound->length);
|
SDL_PutAudioStreamData(channels[channel].stream, channels[channel].sound->buffer.get(), channels[channel].sound->length);
|
||||||
SDL_SetAudioStreamGain(channels[channel].stream, JA_soundVolume[group]);
|
SDL_SetAudioStreamGain(channels[channel].stream, sound_volume[group]);
|
||||||
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
SDL_BindAudioStream(sdl_audio_device, channels[channel].stream);
|
||||||
|
|
||||||
return channel;
|
return channel;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_DeleteSound(JA_Sound_t* sound) {
|
inline void deleteSound(Sound* sound) {
|
||||||
if (!sound) return;
|
if (sound == nullptr) { return; }
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
for (int i = 0; i < MAX_SIMULTANEOUS_CHANNELS; i++) {
|
||||||
if (channels[i].sound == sound) JA_StopChannel(i);
|
if (channels[i].sound == sound) { stopChannel(i); }
|
||||||
}
|
}
|
||||||
// buffer es destrueix automàticament via RAII (SDLFreeDeleter).
|
// buffer es destrueix automàticament via RAII (SdlFreeDeleter).
|
||||||
delete sound;
|
delete sound;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_PauseChannel(const int channel) {
|
inline void pauseChannel(int channel) {
|
||||||
if (!JA_soundEnabled) return;
|
if (!sound_enabled) { return; }
|
||||||
|
|
||||||
if (channel == -1) {
|
if (channel == -1) {
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
for (auto& ch : channels) {
|
||||||
if (channels[i].state == JA_CHANNEL_PLAYING) {
|
if (ch.state == ChannelState::PLAYING) {
|
||||||
channels[i].state = JA_CHANNEL_PAUSED;
|
ch.state = ChannelState::PAUSED;
|
||||||
SDL_UnbindAudioStream(channels[i].stream);
|
SDL_UnbindAudioStream(ch.stream);
|
||||||
}
|
}
|
||||||
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
}
|
||||||
if (channels[channel].state == JA_CHANNEL_PLAYING) {
|
} else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
|
||||||
channels[channel].state = JA_CHANNEL_PAUSED;
|
if (channels[channel].state == ChannelState::PLAYING) {
|
||||||
|
channels[channel].state = ChannelState::PAUSED;
|
||||||
SDL_UnbindAudioStream(channels[channel].stream);
|
SDL_UnbindAudioStream(channels[channel].stream);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_ResumeChannel(const int channel) {
|
inline void resumeChannel(int channel) {
|
||||||
if (!JA_soundEnabled) return;
|
if (!sound_enabled) { return; }
|
||||||
|
|
||||||
if (channel == -1) {
|
if (channel == -1) {
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++)
|
for (auto& ch : channels) {
|
||||||
if (channels[i].state == JA_CHANNEL_PAUSED) {
|
if (ch.state == ChannelState::PAUSED) {
|
||||||
channels[i].state = JA_CHANNEL_PLAYING;
|
ch.state = ChannelState::PLAYING;
|
||||||
SDL_BindAudioStream(sdlAudioDevice, channels[i].stream);
|
SDL_BindAudioStream(sdl_audio_device, ch.stream);
|
||||||
}
|
}
|
||||||
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
}
|
||||||
if (channels[channel].state == JA_CHANNEL_PAUSED) {
|
} else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
|
||||||
channels[channel].state = JA_CHANNEL_PLAYING;
|
if (channels[channel].state == ChannelState::PAUSED) {
|
||||||
SDL_BindAudioStream(sdlAudioDevice, channels[channel].stream);
|
channels[channel].state = ChannelState::PLAYING;
|
||||||
|
SDL_BindAudioStream(sdl_audio_device, channels[channel].stream);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_StopChannel(const int channel) {
|
inline void stopChannel(int channel) {
|
||||||
if (channel == -1) {
|
if (channel == -1) {
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
for (auto& ch : channels) {
|
||||||
if (channels[i].state != JA_CHANNEL_FREE) {
|
if (ch.state != ChannelState::FREE) {
|
||||||
if (channels[i].stream) SDL_DestroyAudioStream(channels[i].stream);
|
if (ch.stream != nullptr) { SDL_DestroyAudioStream(ch.stream); }
|
||||||
channels[i].stream = nullptr;
|
ch.stream = nullptr;
|
||||||
channels[i].state = JA_CHANNEL_FREE;
|
ch.state = ChannelState::FREE;
|
||||||
channels[i].pos = 0;
|
ch.pos = 0;
|
||||||
channels[i].sound = nullptr;
|
ch.sound = nullptr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (channel >= 0 && channel < JA_MAX_SIMULTANEOUS_CHANNELS) {
|
} else if (channel >= 0 && channel < MAX_SIMULTANEOUS_CHANNELS) {
|
||||||
if (channels[channel].state != JA_CHANNEL_FREE) {
|
if (channels[channel].state != ChannelState::FREE) {
|
||||||
if (channels[channel].stream) SDL_DestroyAudioStream(channels[channel].stream);
|
if (channels[channel].stream != nullptr) { SDL_DestroyAudioStream(channels[channel].stream); }
|
||||||
channels[channel].stream = nullptr;
|
channels[channel].stream = nullptr;
|
||||||
channels[channel].state = JA_CHANNEL_FREE;
|
channels[channel].state = ChannelState::FREE;
|
||||||
channels[channel].pos = 0;
|
channels[channel].pos = 0;
|
||||||
channels[channel].sound = nullptr;
|
channels[channel].sound = nullptr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_GetChannelState(const int channel) -> JA_Channel_state {
|
inline auto getChannelState(int channel) -> ChannelState {
|
||||||
if (!JA_soundEnabled) return JA_SOUND_DISABLED;
|
if (!sound_enabled) { return ChannelState::DISABLED; }
|
||||||
if (channel < 0 || channel >= JA_MAX_SIMULTANEOUS_CHANNELS) return JA_CHANNEL_INVALID;
|
if (channel < 0 || channel >= MAX_SIMULTANEOUS_CHANNELS) { return ChannelState::INVALID; }
|
||||||
|
|
||||||
return channels[channel].state;
|
return channels[channel].state;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_SetSoundVolume(float volume, const int group = -1) -> float {
|
inline auto setSoundVolume(float volume, int group = -1) -> float {
|
||||||
const float v = SDL_clamp(volume, 0.0F, 1.0F);
|
const float V = SDL_clamp(volume, 0.0F, 1.0F);
|
||||||
|
|
||||||
if (group == -1) {
|
if (group == -1) {
|
||||||
for (int i = 0; i < JA_MAX_GROUPS; ++i) {
|
for (float& sv : sound_volume) {
|
||||||
JA_soundVolume[i] = v;
|
sv = V;
|
||||||
}
|
}
|
||||||
} else if (group >= 0 && group < JA_MAX_GROUPS) {
|
} else if (group >= 0 && group < MAX_GROUPS) {
|
||||||
JA_soundVolume[group] = v;
|
sound_volume[group] = V;
|
||||||
} else {
|
} else {
|
||||||
return v;
|
return V;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Aplicar volum als canals actius.
|
// Aplicar volum als canals actius.
|
||||||
for (int i = 0; i < JA_MAX_SIMULTANEOUS_CHANNELS; i++) {
|
for (auto& ch : channels) {
|
||||||
if ((channels[i].state == JA_CHANNEL_PLAYING) || (channels[i].state == JA_CHANNEL_PAUSED)) {
|
if ((ch.state == ChannelState::PLAYING) || (ch.state == ChannelState::PAUSED)) {
|
||||||
if (group == -1 || channels[i].group == group) {
|
if (group == -1 || ch.group == group) {
|
||||||
if (channels[i].stream) {
|
if (ch.stream != nullptr) {
|
||||||
SDL_SetAudioStreamGain(channels[i].stream, JA_soundVolume[channels[i].group]);
|
SDL_SetAudioStreamGain(ch.stream, sound_volume[ch.group]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return v;
|
return V;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline void JA_EnableSound(const bool value) {
|
inline void enableSound(bool value) {
|
||||||
if (!value) {
|
if (!value) {
|
||||||
JA_StopChannel(-1);
|
stopChannel(-1);
|
||||||
}
|
}
|
||||||
JA_soundEnabled = value;
|
sound_enabled = value;
|
||||||
}
|
}
|
||||||
|
|
||||||
inline auto JA_SetVolume(float volume) -> float {
|
inline auto setVolume(float volume) -> float {
|
||||||
float v = JA_SetMusicVolume(volume);
|
const float V = setMusicVolume(volume);
|
||||||
JA_SetSoundVolume(v, -1);
|
setSoundVolume(V, -1);
|
||||||
return v;
|
return V;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
} // namespace Ja
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
#include <stdexcept> // Para runtime_error
|
#include <stdexcept> // Para runtime_error
|
||||||
#include <utility>
|
#include <utility>
|
||||||
|
|
||||||
#include "core/audio/jail_audio.hpp" // Para JA_DeleteMusic, JA_DeleteSound, JA_Loa...
|
#include "core/audio/jail_audio.hpp" // Para Ja::deleteMusic, Ja::deleteSound, JA_Loa...
|
||||||
#include "core/rendering/screen.hpp" // Para Screen
|
#include "core/rendering/screen.hpp" // Para Screen
|
||||||
#include "core/rendering/text.hpp" // Para Text, loadTextFile
|
#include "core/rendering/text.hpp" // Para Text, loadTextFile
|
||||||
#include "core/resources/resource_helper.hpp" // Para Helper
|
#include "core/resources/resource_helper.hpp" // Para Helper
|
||||||
@@ -21,8 +21,10 @@
|
|||||||
#include "utils/defines.hpp" // Para WINDOW_CAPTION
|
#include "utils/defines.hpp" // Para WINDOW_CAPTION
|
||||||
#include "utils/utils.hpp" // Para getFileName, printWithDots, PaletteColor
|
#include "utils/utils.hpp" // Para getFileName, printWithDots, PaletteColor
|
||||||
#include "version.h" // Para Version::GIT_HASH
|
#include "version.h" // Para Version::GIT_HASH
|
||||||
struct JA_Music_t; // lines 17-17
|
namespace Ja {
|
||||||
struct JA_Sound_t; // lines 18-18
|
struct Music;
|
||||||
|
struct Sound;
|
||||||
|
} // namespace Ja
|
||||||
|
|
||||||
namespace Resource {
|
namespace Resource {
|
||||||
|
|
||||||
@@ -234,7 +236,7 @@ namespace Resource {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene el sonido a partir de un nombre
|
// Obtiene el sonido a partir de un nombre
|
||||||
auto Cache::getSound(const std::string& name) -> JA_Sound_t* { // NOLINT(readability-convert-member-functions-to-static)
|
auto Cache::getSound(const std::string& name) -> Ja::Sound* { // NOLINT(readability-convert-member-functions-to-static)
|
||||||
auto it = std::ranges::find_if(sounds_, [&name](const auto& s) -> bool { return s.name == name; });
|
auto it = std::ranges::find_if(sounds_, [&name](const auto& s) -> bool { return s.name == name; });
|
||||||
|
|
||||||
if (it != sounds_.end()) {
|
if (it != sounds_.end()) {
|
||||||
@@ -246,7 +248,7 @@ namespace Resource {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Obtiene la música a partir de un nombre
|
// Obtiene la música a partir de un nombre
|
||||||
auto Cache::getMusic(const std::string& name) -> JA_Music_t* { // NOLINT(readability-convert-member-functions-to-static)
|
auto Cache::getMusic(const std::string& name) -> Ja::Music* { // NOLINT(readability-convert-member-functions-to-static)
|
||||||
auto it = std::ranges::find_if(musics_, [&name](const auto& m) -> bool { return m.name == name; });
|
auto it = std::ranges::find_if(musics_, [&name](const auto& m) -> bool { return m.name == name; });
|
||||||
|
|
||||||
if (it != musics_.end()) {
|
if (it != musics_.end()) {
|
||||||
@@ -398,14 +400,14 @@ namespace Resource {
|
|||||||
try {
|
try {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
setCurrentLoading(name);
|
setCurrentLoading(name);
|
||||||
JA_Sound_t* sound = nullptr;
|
Ja::Sound* sound = nullptr;
|
||||||
|
|
||||||
auto audio_data = Helper::loadFile(l);
|
auto audio_data = Helper::loadFile(l);
|
||||||
if (!audio_data.empty()) {
|
if (!audio_data.empty()) {
|
||||||
sound = JA_LoadSound(audio_data.data(), static_cast<Uint32>(audio_data.size()));
|
sound = Ja::loadSound(audio_data.data(), static_cast<Uint32>(audio_data.size()));
|
||||||
}
|
}
|
||||||
if (sound == nullptr) {
|
if (sound == nullptr) {
|
||||||
sound = JA_LoadSound(l.c_str());
|
sound = Ja::loadSound(l.c_str());
|
||||||
}
|
}
|
||||||
if (sound == nullptr) {
|
if (sound == nullptr) {
|
||||||
throw std::runtime_error("Failed to decode audio file");
|
throw std::runtime_error("Failed to decode audio file");
|
||||||
@@ -426,14 +428,14 @@ namespace Resource {
|
|||||||
try {
|
try {
|
||||||
auto name = getFileName(l);
|
auto name = getFileName(l);
|
||||||
setCurrentLoading(name);
|
setCurrentLoading(name);
|
||||||
JA_Music_t* music = nullptr;
|
Ja::Music* music = nullptr;
|
||||||
|
|
||||||
auto audio_data = Helper::loadFile(l);
|
auto audio_data = Helper::loadFile(l);
|
||||||
if (!audio_data.empty()) {
|
if (!audio_data.empty()) {
|
||||||
music = JA_LoadMusic(audio_data.data(), static_cast<Uint32>(audio_data.size()));
|
music = Ja::loadMusic(audio_data.data(), static_cast<Uint32>(audio_data.size()));
|
||||||
}
|
}
|
||||||
if (music == nullptr) {
|
if (music == nullptr) {
|
||||||
music = JA_LoadMusic(l.c_str());
|
music = Ja::loadMusic(l.c_str());
|
||||||
}
|
}
|
||||||
if (music == nullptr) {
|
if (music == nullptr) {
|
||||||
throw std::runtime_error("Failed to decode music file");
|
throw std::runtime_error("Failed to decode music file");
|
||||||
@@ -608,10 +610,10 @@ namespace Resource {
|
|||||||
|
|
||||||
// Vacía el vector de sonidos
|
// Vacía el vector de sonidos
|
||||||
void Cache::clearSounds() {
|
void Cache::clearSounds() {
|
||||||
// Itera sobre el vector y libera los recursos asociados a cada JA_Sound_t
|
// Itera sobre el vector y libera los recursos asociados a cada Ja::Sound
|
||||||
for (auto& sound : sounds_) {
|
for (auto& sound : sounds_) {
|
||||||
if (sound.sound != nullptr) {
|
if (sound.sound != nullptr) {
|
||||||
JA_DeleteSound(sound.sound);
|
Ja::deleteSound(sound.sound);
|
||||||
sound.sound = nullptr;
|
sound.sound = nullptr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -620,10 +622,10 @@ namespace Resource {
|
|||||||
|
|
||||||
// Vacía el vector de musicas
|
// Vacía el vector de musicas
|
||||||
void Cache::clearMusics() {
|
void Cache::clearMusics() {
|
||||||
// Itera sobre el vector y libera los recursos asociados a cada JA_Music_t
|
// Itera sobre el vector y libera los recursos asociados a cada Ja::Music
|
||||||
for (auto& music : musics_) {
|
for (auto& music : musics_) {
|
||||||
if (music.music != nullptr) {
|
if (music.music != nullptr) {
|
||||||
JA_DeleteMusic(music.music);
|
Ja::deleteMusic(music.music);
|
||||||
music.music = nullptr;
|
music.music = nullptr;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,8 +16,8 @@ namespace Resource {
|
|||||||
static void destroy(); // Destrucción singleton
|
static void destroy(); // Destrucción singleton
|
||||||
static auto get() -> Cache*; // Acceso al singleton
|
static auto get() -> Cache*; // Acceso al singleton
|
||||||
|
|
||||||
auto getSound(const std::string& name) -> JA_Sound_t*; // Getters de recursos
|
auto getSound(const std::string& name) -> Ja::Sound*; // Getters de recursos
|
||||||
auto getMusic(const std::string& name) -> JA_Music_t*;
|
auto getMusic(const std::string& name) -> Ja::Music*;
|
||||||
auto getSurface(const std::string& name) -> std::shared_ptr<Surface>;
|
auto getSurface(const std::string& name) -> std::shared_ptr<Surface>;
|
||||||
auto getPalette(const std::string& name) -> Palette;
|
auto getPalette(const std::string& name) -> Palette;
|
||||||
auto getTextFile(const std::string& name) -> std::shared_ptr<Text::File>;
|
auto getTextFile(const std::string& name) -> std::shared_ptr<Text::File>;
|
||||||
|
|||||||
@@ -10,19 +10,21 @@
|
|||||||
#include "game/gameplay/room.hpp" // Para Room::Data
|
#include "game/gameplay/room.hpp" // Para Room::Data
|
||||||
|
|
||||||
// Forward declarations
|
// Forward declarations
|
||||||
struct JA_Music_t;
|
namespace Ja {
|
||||||
struct JA_Sound_t;
|
struct Music;
|
||||||
|
struct Sound;
|
||||||
|
} // namespace Ja
|
||||||
|
|
||||||
// Estructura para almacenar ficheros de sonido y su nombre
|
// Estructura para almacenar ficheros de sonido y su nombre
|
||||||
struct SoundResource {
|
struct SoundResource {
|
||||||
std::string name; // Nombre del sonido
|
std::string name; // Nombre del sonido
|
||||||
JA_Sound_t* sound{nullptr}; // Objeto con el sonido
|
Ja::Sound* sound{nullptr}; // Objeto con el sonido
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para almacenar ficheros musicales y su nombre
|
// Estructura para almacenar ficheros musicales y su nombre
|
||||||
struct MusicResource {
|
struct MusicResource {
|
||||||
std::string name; // Nombre de la musica
|
std::string name; // Nombre de la musica
|
||||||
JA_Music_t* music{nullptr}; // Objeto con la música
|
Ja::Music* music{nullptr}; // Objeto con la música
|
||||||
};
|
};
|
||||||
|
|
||||||
// Estructura para almacenar objetos Surface y su nombre
|
// Estructura para almacenar objetos Surface y su nombre
|
||||||
|
|||||||
@@ -14,7 +14,9 @@
|
|||||||
#include "game/options.hpp" // Para Cheat, Options, options
|
#include "game/options.hpp" // Para Cheat, Options, options
|
||||||
#include "utils/defines.hpp" // Para BORDER_TOP, BLOCK
|
#include "utils/defines.hpp" // Para BORDER_TOP, BLOCK
|
||||||
#include "utils/utils.hpp" // Para Color
|
#include "utils/utils.hpp" // Para Color
|
||||||
struct JA_Sound_t; // lines 13-13
|
namespace Ja {
|
||||||
|
struct Sound;
|
||||||
|
}
|
||||||
|
|
||||||
class Player {
|
class Player {
|
||||||
public:
|
public:
|
||||||
@@ -157,8 +159,8 @@ class Player {
|
|||||||
|
|
||||||
// --- Variables de renderizado y sonido ---
|
// --- Variables de renderizado y sonido ---
|
||||||
Uint8 color_ = 0; // Color del jugador
|
Uint8 color_ = 0; // Color del jugador
|
||||||
std::array<JA_Sound_t*, 24> jumping_sound_{}; // Array con todos los sonidos del salto
|
std::array<Ja::Sound*, 24> jumping_sound_{}; // Array con todos los sonidos del salto
|
||||||
std::array<JA_Sound_t*, 14> falling_sound_{}; // Array con todos los sonidos de la caída
|
std::array<Ja::Sound*, 14> falling_sound_{}; // Array con todos los sonidos de la caída
|
||||||
JumpSoundController jump_sound_ctrl_; // Controlador de sonidos de salto
|
JumpSoundController jump_sound_ctrl_; // Controlador de sonidos de salto
|
||||||
FallSoundController fall_sound_ctrl_; // Controlador de sonidos de caída
|
FallSoundController fall_sound_ctrl_; // Controlador de sonidos de caída
|
||||||
int fall_start_position_ = 0; // Posición Y al iniciar la caída
|
int fall_start_position_ = 0; // Posición Y al iniciar la caída
|
||||||
|
|||||||
Reference in New Issue
Block a user