6#include "common/config.h"
11#if defined(__EMSCRIPTEN__)
12#include <emscripten/emscripten.h>
14#include "medialoader/Exception.h"
15#include "medialoader/sound/WaveDecoder.h"
16#include "medialoader/sound/VorbisDecoder.h"
17#include "medialoader/sound/Mpg123Decoder.h"
18#include "medialoader/sound/FLACDecoder.h"
19#include "medialoader/sound/ModPlugDecoder.h"
22#include <simplesquirrel/simplesquirrel.hpp>
43#if defined(EVENGINE_MACOSX) || defined(EVENGINE_LINUX) || defined(EVENGINE_WINDOWS)
45bool fileExists(
const std::string &
path) {
46 std::ifstream in(
path, std::ios::binary);
50std::string parentPath(std::string
path) {
51 while (!
path.empty() && (
path.back() ==
'/' ||
path.back() ==
'\\'))
53 auto slash =
path.find_last_of(
"/\\");
54 if (slash == std::string::npos)
57 return path.substr(0, 1);
58 return path.substr(0, slash);
61std::string joinPath(
const std::string &
a,
const std::string &
b) {
64 if (
a.back() ==
'/' ||
a.back() ==
'\\')
71void ensureDesktopTimidityShare() {
72 if (
const char *existing = std::getenv(
"MMPAT_PATH_TO_CFG")) {
73 if (existing[0] !=
'\0')
77 auto *fs = filesystem::Filesystem::create();
78 std::string exe = fs->getExecutablePath();
82 std::string
dir = parentPath(exe);
83 const char *relatives[] = {
85 "../share/eve/timidity",
86 "../../share/eve/timidity",
87 "../../../share/eve/timidity",
91 for (
const char *rel : relatives) {
92 std::string cand = joinPath(
dir, rel);
93 if (fileExists(joinPath(cand,
"timidity.cfg"))) {
102 _putenv_s(
"MMPAT_PATH_TO_CFG",
found.c_str());
104 setenv(
"MMPAT_PATH_TO_CFG",
found.c_str(), 0);
113#if defined(EVENGINE_MACOSX) || defined(EVENGINE_LINUX) || defined(EVENGINE_WINDOWS)
114 ensureDesktopTimidityShare();
122#if defined(__EMSCRIPTEN__)
124EM_JS(
int, startBrowserDecode, (
const void*
bytes,
int size), {
127 const store = globalThis.eveSoundDecode ||= { next: 1, requests:
new Map(),
context: null };
128 const id = store.next++;
130 store.requests.set(
id,
request);
131 const Context = globalThis.AudioContext || globalThis.webkitAudioContext;
132 if (!Context)
throw new Error(
'Web Audio is unavailable');
133 store.context ||=
new Context();
134 store.context.decodeAudioData(encoded.buffer).then((
buffer) => {
135 if (
buffer.numberOfChannels < 1 ||
buffer.numberOfChannels > 2 ||
136 buffer.length *
buffer.numberOfChannels * 2 > 0x7fffffff) {
142 const view =
new DataView(pcm.buffer);
145 for (let channel = 0; channel <
channels; ++channel) {
146 const sample = Math.max(-1, Math.min(1, samples[channel][
frame]));
148 sample < 0 ? Math.round(sample * 32768) : Math.round(sample * 32767),
true);
155 }).
catch((
error) => { console.error(
'[Sound] Browser decode failed',
error);
request.status = -1; });
158 console.error(
'[Sound] Browser decode could not start',
error);
162EM_JS(
int, browserDecodeStatus, (
int id), {
163 const request = globalThis.eveSoundDecode?.requests.get(
id);
166EM_JS(
int, browserDecodeSize, (
int id), {
167 return globalThis.eveSoundDecode.requests.get(
id).pcm.length;
169EM_JS(
int, browserDecodeRate, (
int id), {
170 return globalThis.eveSoundDecode.requests.get(
id).
rate;
172EM_JS(
int, browserDecodeChannels, (
int id), {
173 return globalThis.eveSoundDecode.requests.get(
id).
channels;
175EM_JS(
void, browserDecodeCopyAndRelease, (
int id,
void* destination), {
176 const store = globalThis.eveSoundDecode;
177 const request = store.requests.get(
id);
178 HEAPU8.set(
request.pcm, destination);
179 store.requests.delete(
id);
181EM_JS(
void, browserDecodeRelease, (
int id), {
182 globalThis.eveSoundDecode?.requests.delete(
id);
186std::string lowerExt(std::string ext) {
188 c = static_cast<char>(
std::tolower(static_cast<unsigned char>(
c)));
193std::unique_ptr<medialoader::Decoder> tryMake(
const char *data,
size_t size,
int bufferSize) {
195 return std::unique_ptr<medialoader::Decoder>(
new T(data,
size, bufferSize));
207 if (data ==
nullptr || data->getData() ==
nullptr || data->getSize() == 0)
210#if defined(__EMSCRIPTEN__)
211 if (data->getSize() >
static_cast<std::size_t
>(0x7fffffff) || bufferSize <= 0)
212 throw eve::Exception(
"Browser audio data is too large or buffer size is invalid");
213 const int id = startBrowserDecode(data->getData(),
static_cast<int>(data->getSize()));
214 if (
id < 0)
throw eve::Exception(
"Could not start browser audio decode");
215 const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);
216 int status = browserDecodeStatus(
id);
217 while (
status == 0 && std::chrono::steady_clock::now() <
deadline) {
219 status = browserDecodeStatus(
id);
222 browserDecodeRelease(
id);
225 const int size = browserDecodeSize(
id);
227 browserDecodeRelease(
id);
231 std::vector<std::uint8_t> pcm(
static_cast<std::size_t
>(
size));
232 const int rate = browserDecodeRate(
id);
233 const int channels = browserDecodeChannels(
id);
234 browserDecodeCopyAndRelease(
id, pcm.data());
235 return new Decoder(std::make_shared<
const std::vector<std::uint8_t>>(std::move(pcm)),
rate,
channels,
238 browserDecodeRelease(
id);
243 std::vector<char>
owned(
static_cast<const char *
>(data->getData()),
244 static_cast<const char *
>(data->getData()) + data->getSize());
252 auto tryByExt = [&](
const std::string &e) -> std::unique_ptr<medialoader::Decoder> {
255 if (medialoader::WaveDecoder::accepts(e))
256 return tryMake<medialoader::WaveDecoder>(
ptr,
size, bufferSize);
257 if (medialoader::VorbisDecoder::accepts(e))
258 return tryMake<medialoader::VorbisDecoder>(
ptr,
size, bufferSize);
259 if (medialoader::Mpg123Decoder::accepts(e))
260 return tryMake<medialoader::Mpg123Decoder>(
ptr,
size, bufferSize);
261 if (medialoader::FLACDecoder::accepts(e))
262 return tryMake<medialoader::FLACDecoder>(
ptr,
size, bufferSize);
263 if (medialoader::ModPlugDecoder::accepts(e))
264 return tryMake<medialoader::ModPlugDecoder>(
ptr,
size, bufferSize);
268 auto impl = tryByExt(ext);
270 if (!
impl)
impl = tryMake<medialoader::WaveDecoder>(
ptr,
size, bufferSize);
271 if (!
impl)
impl = tryMake<medialoader::VorbisDecoder>(
ptr,
size, bufferSize);
272 if (!
impl)
impl = tryMake<medialoader::Mpg123Decoder>(
ptr,
size, bufferSize);
273 if (!
impl)
impl = tryMake<medialoader::FLACDecoder>(
ptr,
size, bufferSize);
274 if (!
impl)
impl = tryMake<medialoader::ModPlugDecoder>(
ptr,
size, bufferSize);
278 throw eve::Exception(
"Could not decode sound data: unsupported format");
285 if (decoder ==
nullptr)
288 std::vector<uint8_t> pcm;
293 auto *buf =
static_cast<const uint8_t *
>(decoder->
getBuffer());
294 pcm.insert(pcm.end(), buf, buf +
n);
326 size_t bytes =
static_cast<size_t>(samples) *
static_cast<size_t>(bitDepth / 8) *
static_cast<size_t>(
channels);
327 std::vector<uint8_t> pcm(
bytes, 0);
331void Sound::expose(ssq::Table& table) {
332 auto cls = table.addClass(
name, Sound::create,
false);
335 auto dec = table.addClass<
Decoder>(
336 "Decoder", std::function<Decoder *()>([]() ->
Decoder * {
return nullptr; }),
true);
348 auto sd = table.addClass<SoundData>(
349 "SoundData", std::function<SoundData *()>([]() -> SoundData * {
return nullptr; }),
true);
358void Sound::expose(ssq::Class&
cls) {
std::map< std::string, std::vector< Key >, std::less<> > channels
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
std::chrono::steady_clock::time_point deadline
#define Module_IMPL(ModuleName, newExpr)
std::unique_ptr< gpgpu::GpuBuffer > buffer
const VegetationPresetContext & context
EVENGINE_API_FOUNDATION public API.
virtual std::string getName() const =0
Returns the name.
Resource * get(std::string key)
Get the cached resource for key; on a miss, load it through the registered IAssetReloader providers a...
static ResourceManager & getInstance()
Returns the instance.
Resource is a game object that is managed by the ResourceManager. It can be loaded from a file or gen...
Data buffer paired with a filename (used for type identification).
Streaming audio decoder (medialoader-backed). Native builds own encoded bytes and decode incrementall...
void * getBuffer() const
Internal decoded buffer.
double getDuration()
Total duration in seconds.
bool isFinished()
True when the stream is fully decoded.
int getSampleRate() const
Returns the sample rate.
bool isSeekable()
True when seeking is supported.
int getChannelCount() const
Format metadata.
bool rewind()
Rewinds to the start; false when unsupported.
bool seek(double seconds)
Seeks to a time in seconds; false when unsupported.
int getSize() const
Bytes decoded so far into the internal buffer.
int getBitDepth() const
Returns the bit depth.
int decode()
Decodes the next chunk; returns bytes produced (0 = end/error).
Raw PCM audio buffer with format metadata (samples/rate/bit depth/channels).
double getDuration() const
Duration in seconds.
int getBitDepth() const
Returns the bit depth.
int getChannelCount() const
Returns the channel count.
int getSampleRate() const
Returns the sample rate.
int getSampleCount() const
Format metadata.
size_t getSize() const
Returns the size.
Sound module: decodes compressed audio and produces SoundData buffers. Script: sound <- eve....
SoundData * newSoundDataFromDecoder(Decoder *decoder)
Fully decodes a Decoder into a SoundData buffer.
SoundData * newSoundDataFromFile(std::string path)
Decodes a sound file from a VFS path through the unified resource cache. Repeated loads of one path s...
SoundData * newSoundData(Data *data)
Fully decodes data into a SoundData buffer.
SoundData * newSoundDataEmpty(int samples, int rate, int bitDepth, int channels)
Creates an empty PCM buffer (e.g. for synthesis).
Decoder * newDecoder(Data *data, int bufferSize=16384)
Creates a streaming decoder over raw encoded data. @ownership Caller owns the returned decoder; its e...
double sample(const Heightmap &map, double u, double v)
Sample.
Build metadata (engine git commit, build time, third-party version).
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).