载入中...
搜索中...
未找到
Sound.cpp
浏览该文件的文档.
1#include "Sound.h"
2#include "Decoder.h"
3#include "SoundData.h"
4
5#include "common/Exception.h"
6#include "common/config.h"
7#include "common/Resource.h"
10
11#if defined(__EMSCRIPTEN__)
12#include <emscripten/emscripten.h>
13#else
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"
20#endif
21
22#include <simplesquirrel/simplesquirrel.hpp>
23
24#include <cctype>
25#include <chrono>
26#include <cstring>
27#include <fstream>
28#include <string>
29
30#if defined(_WIN32)
31#include <stdlib.h>
32#else
33#include <cstdlib>
34#endif
35
36namespace eve {
37namespace sound {
38
40
41namespace {
42
43#if defined(EVENGINE_MACOSX) || defined(EVENGINE_LINUX) || defined(EVENGINE_WINDOWS)
44
45bool fileExists(const std::string &path) {
46 std::ifstream in(path, std::ios::binary);
47 return in.good();
48}
49
50std::string parentPath(std::string path) {
51 while (!path.empty() && (path.back() == '/' || path.back() == '\\'))
52 path.pop_back();
53 auto slash = path.find_last_of("/\\");
54 if (slash == std::string::npos)
55 return {};
56 if (slash == 0)
57 return path.substr(0, 1);
58 return path.substr(0, slash);
59}
60
61std::string joinPath(const std::string &a, const std::string &b) {
62 if (a.empty())
63 return b;
64 if (a.back() == '/' || a.back() == '\\')
65 return a + b;
66 return a + "/" + b;
67}
68
69// Prefer installed / staged share/eve/timidity next to the executable.
70// Does not override an existing MMPAT_PATH_TO_CFG (user trim / custom banks).
71void ensureDesktopTimidityShare() {
72 if (const char *existing = std::getenv("MMPAT_PATH_TO_CFG")) {
73 if (existing[0] != '\0')
74 return;
75 }
76
77 auto *fs = filesystem::Filesystem::create();
78 std::string exe = fs->getExecutablePath();
79 if (exe.empty())
80 return;
81
82 std::string dir = parentPath(exe);
83 const char *relatives[] = {
84 "share/eve/timidity",
85 "../share/eve/timidity",
86 "../../share/eve/timidity",
87 "../../../share/eve/timidity",
88 };
89
90 std::string found;
91 for (const char *rel : relatives) {
92 std::string cand = joinPath(dir, rel);
93 if (fileExists(joinPath(cand, "timidity.cfg"))) {
94 found = cand;
95 break;
96 }
97 }
98 if (found.empty())
99 return;
100
101#if defined(_WIN32)
102 _putenv_s("MMPAT_PATH_TO_CFG", found.c_str());
103#else
104 setenv("MMPAT_PATH_TO_CFG", found.c_str(), 0);
105#endif
106}
107
108#endif // desktop
109
110} // namespace
111
113#if defined(EVENGINE_MACOSX) || defined(EVENGINE_LINUX) || defined(EVENGINE_WINDOWS)
114 ensureDesktopTimidityShare();
115#endif
116}
117
118Sound::~Sound() = default;
119
120namespace {
121
122#if defined(__EMSCRIPTEN__)
123// clang-format off
124EM_JS(int, startBrowserDecode, (const void* bytes, int size), {
125 try {
126 const encoded = HEAPU8.slice(bytes, bytes + size);
127 const store = globalThis.eveSoundDecode ||= { next: 1, requests: new Map(), context: null };
128 const id = store.next++;
129 const request = { status: 0, pcm: null, rate: 0, channels: 0 };
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) {
137 request.status = -1;
138 return;
139 }
140 const channels = buffer.numberOfChannels;
141 const pcm = new Uint8Array(buffer.length * channels * 2);
142 const view = new DataView(pcm.buffer);
143 const samples = Array.from({ length: channels }, (_, c) => buffer.getChannelData(c));
144 for (let frame = 0; frame < buffer.length; ++frame) {
145 for (let channel = 0; channel < channels; ++channel) {
146 const sample = Math.max(-1, Math.min(1, samples[channel][frame]));
147 view.setInt16((frame * channels + channel) * 2,
148 sample < 0 ? Math.round(sample * 32768) : Math.round(sample * 32767), true);
149 }
150 }
151 request.pcm = pcm;
152 request.rate = buffer.sampleRate;
153 request.channels = channels;
154 request.status = 1;
155 }).catch((error) => { console.error('[Sound] Browser decode failed', error); request.status = -1; });
156 return id;
157 } catch (error) {
158 console.error('[Sound] Browser decode could not start', error);
159 return -1;
160 }
161});
162EM_JS(int, browserDecodeStatus, (int id), {
163 const request = globalThis.eveSoundDecode?.requests.get(id);
164 return request ? request.status : -1;
165});
166EM_JS(int, browserDecodeSize, (int id), {
167 return globalThis.eveSoundDecode.requests.get(id).pcm.length;
168});
169EM_JS(int, browserDecodeRate, (int id), {
170 return globalThis.eveSoundDecode.requests.get(id).rate;
171});
172EM_JS(int, browserDecodeChannels, (int id), {
173 return globalThis.eveSoundDecode.requests.get(id).channels;
174});
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);
180});
181EM_JS(void, browserDecodeRelease, (int id), {
182 globalThis.eveSoundDecode?.requests.delete(id);
183});
184// clang-format on
185#else
186std::string lowerExt(std::string ext) {
187 for (char &c : ext)
188 c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
189 return ext;
190}
191
192template <typename T>
193std::unique_ptr<medialoader::Decoder> tryMake(const char *data, size_t size, int bufferSize) {
194 try {
195 return std::unique_ptr<medialoader::Decoder>(new T(data, size, bufferSize));
196 } catch (...) {
197 // Every decoder failure has the same fallback; one catch avoids a
198 // redundant typed exception handler in each decoder specialization.
199 return nullptr;
200 }
201}
202#endif
203
204} // namespace
205
206Decoder *Sound::newDecoder(Data *data, int bufferSize) {
207 if (data == nullptr || data->getData() == nullptr || data->getSize() == 0)
208 throw eve::Exception("Cannot decode empty sound data");
209
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) {
218 emscripten_sleep(1);
219 status = browserDecodeStatus(id);
220 }
221 if (status != 1) {
222 browserDecodeRelease(id);
223 throw eve::Exception("Could not decode browser audio data");
224 }
225 const int size = browserDecodeSize(id);
226 if (size <= 0) {
227 browserDecodeRelease(id);
228 throw eve::Exception("Browser audio decoded to an empty buffer");
229 }
230 try {
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,
236 bufferSize);
237 } catch (...) {
238 browserDecodeRelease(id);
239 throw;
240 }
241#else
242
243 std::vector<char> owned(static_cast<const char *>(data->getData()),
244 static_cast<const char *>(data->getData()) + data->getSize());
245
246 std::string ext;
247 if (auto *fd = dynamic_cast<filesystem::FileData *>(data)) ext = lowerExt(fd->getExtension());
248
249 const char *ptr = owned.data();
250 size_t size = owned.size();
251
252 auto tryByExt = [&](const std::string &e) -> std::unique_ptr<medialoader::Decoder> {
253 if (e.empty())
254 return nullptr;
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);
265 return nullptr;
266 };
267
268 auto impl = tryByExt(ext);
269 if (!impl) {
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);
275 }
276
277 if (!impl)
278 throw eve::Exception("Could not decode sound data: unsupported format");
279
280 return new Decoder(std::move(impl), std::move(owned));
281#endif
282}
283
285 if (decoder == nullptr)
286 throw eve::Exception("Decoder is null");
287
288 std::vector<uint8_t> pcm;
289 while (!decoder->isFinished()) {
290 int n = decoder->decode();
291 if (n <= 0)
292 break;
293 auto *buf = static_cast<const uint8_t *>(decoder->getBuffer());
294 pcm.insert(pcm.end(), buf, buf + n);
295 }
296
297 return new SoundData(std::move(pcm), decoder->getSampleRate(), decoder->getBitDepth(),
298 decoder->getChannelCount());
299}
300
302 Decoder *dec = newDecoder(data);
303 try {
305 delete dec;
306 return sd;
307 } catch (...) {
308 delete dec;
309 throw;
310 }
311}
312
314 if (path.empty())
315 throw eve::Exception("Sound::newSoundDataFromFile: empty path");
316
318 if (!resource)
319 throw eve::Exception("Could not load sound file: %s", path.c_str());
320 return static_cast<SoundData *>(resource);
321}
322
323SoundData *Sound::newSoundDataEmpty(int samples, int rate, int bitDepth, int channels) {
324 if (samples < 0)
325 throw eve::Exception("Invalid sample count");
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);
328 return new SoundData(std::move(pcm), rate, bitDepth, channels);
329}
330
331void Sound::expose(ssq::Table& table) {
332 auto cls = table.addClass(name, Sound::create, false);
333 expose(cls);
334
335 auto dec = table.addClass<Decoder>(
336 "Decoder", std::function<Decoder *()>([]() -> Decoder * { return nullptr; }), true);
337 dec.addFunc("decode", &Decoder::decode);
338 dec.addFunc("getSize", &Decoder::getSize);
339 dec.addFunc("seek", &Decoder::seek);
340 dec.addFunc("rewind", &Decoder::rewind);
341 dec.addFunc("isSeekable", &Decoder::isSeekable);
342 dec.addFunc("isFinished", &Decoder::isFinished);
343 dec.addFunc("getChannelCount", &Decoder::getChannelCount);
344 dec.addFunc("getBitDepth", &Decoder::getBitDepth);
345 dec.addFunc("getSampleRate", &Decoder::getSampleRate);
346 dec.addFunc("getDuration", &Decoder::getDuration);
347
348 auto sd = table.addClass<SoundData>(
349 "SoundData", std::function<SoundData *()>([]() -> SoundData * { return nullptr; }), true);
350 sd.addFunc("getSampleCount", &SoundData::getSampleCount);
351 sd.addFunc("getSampleRate", &SoundData::getSampleRate);
352 sd.addFunc("getBitDepth", &SoundData::getBitDepth);
353 sd.addFunc("getChannelCount", &SoundData::getChannelCount);
354 sd.addFunc("getDuration", &SoundData::getDuration);
355 sd.addFunc("getSize", &SoundData::getSize);
356}
357
358void Sound::expose(ssq::Class& cls) {
359 cls.addFunc("getName", &Sound::getName);
360 cls.addFunc("newDecoder", &Sound::newDecoder);
361 cls.addFunc("newSoundData", &Sound::newSoundData);
362 cls.addFunc("newSoundDataFromDecoder", &Sound::newSoundDataFromDecoder);
363 cls.addFunc("newSoundDataFromFile", &Sound::newSoundDataFromFile);
364 cls.addFunc("newSoundDataEmpty", &Sound::newSoundDataEmpty);
365}
366
367} // namespace sound
368} // namespace eve
std::map< std::string, std::vector< Key >, std::less<> > channels
ActiveSource owned
void * impl
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
const GltfImportRequest & request
wgpu::PopErrorScopeStatus status
glm::vec3 n
Definition Grass.cpp:63
std::int32_t c
void * ptr
float length
std::string id
std::chrono::steady_clock::time_point deadline
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
ssq::Object frame
OceanSprayView view
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
std::string error
Definition Package.cpp:174
std::string path
Definition PlayHost.cpp:111
bool found
std::string resource
float size
Definition TreeMesh.cpp:158
V3 dir
Definition TreeMesh.cpp:151
const VegetationPresetContext & context
Data public API.
Definition Data.h:8
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
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...
Definition Resource.cpp:141
static ResourceManager & getInstance()
Returns the instance.
Definition Resource.cpp:15
Resource is a game object that is managed by the ResourceManager. It can be loaded from a file or gen...
Definition Resource.h:52
Data buffer paired with a filename (used for type identification).
Definition FileData.h:14
Streaming audio decoder (medialoader-backed). Native builds own encoded bytes and decode incrementall...
Definition Decoder.h:23
void * getBuffer() const
Internal decoded buffer.
Definition Decoder.cpp:82
double getDuration()
Total duration in seconds.
Definition Decoder.cpp:90
bool isFinished()
True when the stream is fully decoded.
Definition Decoder.cpp:86
int getSampleRate() const
Returns the sample rate.
Definition Decoder.cpp:89
bool isSeekable()
True when seeking is supported.
Definition Decoder.cpp:85
int getChannelCount() const
Format metadata.
Definition Decoder.cpp:87
bool rewind()
Rewinds to the start; false when unsupported.
Definition Decoder.cpp:84
bool seek(double seconds)
Seeks to a time in seconds; false when unsupported.
Definition Decoder.cpp:83
int getSize() const
Bytes decoded so far into the internal buffer.
Definition Decoder.cpp:81
int getBitDepth() const
Returns the bit depth.
Definition Decoder.cpp:88
int decode()
Decodes the next chunk; returns bytes produced (0 = end/error).
Definition Decoder.cpp:80
Raw PCM audio buffer with format metadata (samples/rate/bit depth/channels).
Definition SoundData.h:15
double getDuration() const
Duration in seconds.
Definition SoundData.cpp:40
int getBitDepth() const
Returns the bit depth.
Definition SoundData.cpp:37
int getChannelCount() const
Returns the channel count.
Definition SoundData.cpp:38
int getSampleRate() const
Returns the sample rate.
Definition SoundData.cpp:36
int getSampleCount() const
Format metadata.
Definition SoundData.cpp:30
size_t getSize() const
Returns the size.
Definition SoundData.cpp:47
Sound module: decodes compressed audio and produces SoundData buffers. Script: sound <- eve....
Definition Sound.h:18
SoundData * newSoundDataFromDecoder(Decoder *decoder)
Fully decodes a Decoder into a SoundData buffer.
Definition Sound.cpp:284
SoundData * newSoundDataFromFile(std::string path)
Decodes a sound file from a VFS path through the unified resource cache. Repeated loads of one path s...
Definition Sound.cpp:313
SoundData * newSoundData(Data *data)
Fully decodes data into a SoundData buffer.
Definition Sound.cpp:301
~Sound() override
Sound.
SoundData * newSoundDataEmpty(int samples, int rate, int bitDepth, int channels)
Creates an empty PCM buffer (e.g. for synthesis).
Definition Sound.cpp:323
Decoder * newDecoder(Data *data, int bufferSize=16384)
Creates a streaming decoder over raw encoded data. @ownership Caller owns the returned decoder; its e...
Definition Sound.cpp:206
double sample(const Heightmap &map, double u, double v)
Sample.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
enum EVENGINE_API_FOUNDATION Array
OT_ARRAY (editable via Runtime array APIs / ReflectedPropertyModel).
Definition Runtime.h:120