载入中...
搜索中...
未找到
AudioCapabilities.cpp
浏览该文件的文档.
8#include "audio/Audio.h"
9#include "audio/Source.h"
10#include "common/AudioQuery.h"
11#include "common/Capability.h"
13#include "sound/Sound.h"
14#include "sound/SoundData.h"
15
16#include <algorithm>
17#include <cstdint>
18#include <cmath>
19#include <cstring>
20#include <list>
21#include <limits>
22#include <map>
23#include <memory>
24#include <optional>
25#include <set>
26#include <string>
27#include <utility>
28#include <vector>
29
30namespace eve::audio {
31namespace {
32
33std::uint64_t stableAudioSeed(eve::action::ActionExecutionId executionId,
34 const eve::LogicalId& itemId, std::uint64_t salt = 0) {
35 std::uint64_t hash = 1469598103934665603ULL ^ executionId.value() ^ salt;
36 for (const unsigned char value : itemId.format()) {
37 hash ^= value;
38 hash *= 1099511628211ULL;
39 }
40 return hash;
41}
42
43const std::string& selectAudioUri(const eve::action::ActionAudioBinding& binding, std::uint64_t seed) {
44 if (binding.randomUris.empty()) return binding.uri;
45 return binding.randomUris[static_cast<std::size_t>(seed % binding.randomUris.size())];
46}
47
48double selectAudioPitch(const eve::action::ActionAudioBinding& binding, std::uint64_t seed) {
49 if (binding.randomPitchOffset <= 0.0) return binding.pitch;
50 constexpr double divisor = static_cast<double>(std::numeric_limits<std::uint64_t>::max());
51 const double unit = static_cast<double>(seed) / divisor;
52 return std::clamp(binding.pitch + (unit * 2.0 - 1.0) * binding.randomPitchOffset, 0.1, 3.0);
53}
54
55Result<void> configureAudioSource(Source& source, const eve::action::ActionAudioBinding& binding, double pitch) {
56 source.setVolume(static_cast<float>(binding.volume));
57 source.setPitch(static_cast<float>(pitch));
58 source.setLooping(binding.looping);
59 auto blend = source.setSpatialBlend(static_cast<float>(binding.spatialBlend));
60 if (!blend.ok()) return blend;
61 source.setAttenuationDistances(static_cast<float>(binding.minDistance),
62 static_cast<float>(binding.maxDistance));
63 return Result<void>::success();
64}
65
66// One module-owned binding invalidates retained clients before the OpenAL context closes.
67// Main-thread only: clients remove themselves before destruction; shutdown uses a snapshot.
68class AudioClient;
69struct AudioBinding {
70 Audio* audio;
71 std::vector<AudioClient*> clients;
72 void close() noexcept;
73};
74class AudioClient {
75public:
76 explicit AudioClient(std::shared_ptr<AudioBinding> binding) : binding_(std::move(binding)) {
77 binding_->clients.push_back(this);
78 }
79 virtual ~AudioClient() { std::erase(binding_->clients, this); }
80 virtual void closeAudio() noexcept {}
81
82protected:
83 std::shared_ptr<AudioBinding> binding_;
84};
85void AudioBinding::close() noexcept {
86 // These private final clients release sources only; they cannot add/remove clients.
87 // Keep shutdown allocation-free while the OpenAL context is still current.
88 for (auto* client : clients) client->closeAudio();
89 audio = nullptr;
90}
91
92class AudioQueryImpl final : public eve::IAudioQuery, private AudioClient {
93public:
94 explicit AudioQueryImpl(std::shared_ptr<AudioBinding> binding) : AudioClient(std::move(binding)) {}
95 float volume() const override {
96 auto* a = binding_->audio;
97 return a ? a->getVolume() : 1.f;
98 }
99
100 void setVolume(float v) override {
101 if (auto* a = binding_->audio) a->setVolume(v);
102 }
103
104 void stopAll() override {
105 if (auto* a = binding_->audio) a->stopAll();
106 }
107};
108
109class ActionAudioWaveformProvider final : public eve::action::IActionAudioWaveformProvider {
110public:
113 if (request.bucketCount == 0 || request.bucketCount > kMaximumBuckets)
115 "Audio waveform bucket count is outside the bounded range", "bucketCount");
116 if (request.blockDuration <= eve::Duration::zero())
118 "Audio waveform block duration must be positive", "blockDuration");
119 if (request.binding.uri.empty())
121 "Audio waveform URI must be non-empty", "uri");
122 if (!std::isfinite(request.binding.pitch) || request.binding.pitch <= 0.0)
124 "Audio waveform pitch must be positive and finite", "pitch");
125 try {
126 auto* data = eve::sound::Sound::create()->newSoundDataFromFile(request.binding.uri);
127 if (!data || data->getSampleRate() <= 0 || data->getSampleCount() <= 0 ||
128 (data->getBitDepth() != 8 && data->getBitDepth() != 16) ||
129 (data->getChannelCount() != 1 && data->getChannelCount() != 2))
131 "Audio waveform requires bounded PCM8 or PCM16 data", "uri");
132 // The provider returns a cache-owned SoundData; pin it so a concurrent
133 // unload cannot destroy the payload while this request samples it.
134 auto retained = eve::ResourceManager::getInstance().pin(data);
135 if (!retained.ok())
136 return failure(eve::DiagnosticCode::NotFound, "audio waveform resource is no longer cached", "uri");
137 eve::ResourcePin keepAlive = std::move(retained).takeValue();
138 // The pin is the authority from here on; the borrowed pointer may have gone
139 // stale before the pin was taken.
140 data = static_cast<eve::sound::SoundData*>(keepAlive.get());
142 result.clipDurationSeconds = data->getDuration();
143 result.buckets.resize(request.bucketCount);
144 const double blockSeconds = request.blockDuration.seconds();
145 const auto frameCount = static_cast<std::size_t>(data->getSampleCount());
146 for (std::size_t bucket = 0; bucket < request.bucketCount; ++bucket) {
147 const double localStart = blockSeconds * static_cast<double>(bucket) /
148 static_cast<double>(request.bucketCount);
149 const double localEnd = blockSeconds * static_cast<double>(bucket + 1) /
150 static_cast<double>(request.bucketCount);
151 result.buckets[bucket] = sampleBucket(*data, request.binding, localStart, localEnd, frameCount);
152 }
154 } catch (const std::exception& error) {
155 return failure(eve::DiagnosticCode::Failed, error.what(), "uri");
156 }
157 }
158
159private:
160 static constexpr std::size_t kMaximumBuckets = 4096;
161 static constexpr std::size_t kMaximumSamplesPerBucket = 8192;
162
163 static float sampleAt(const eve::sound::SoundData& data, std::size_t frame, int channel) noexcept {
164 const auto channels = static_cast<std::size_t>(data.getChannelCount());
165 const auto index = frame * channels + static_cast<std::size_t>(channel);
166 const auto* bytes = static_cast<const std::uint8_t*>(data.getData());
167 if (data.getBitDepth() == 8)
168 return (static_cast<float>(bytes[index]) - 128.0f) / 128.0f;
169 std::int16_t sample = 0;
170 std::memcpy(&sample, bytes + index * sizeof(sample), sizeof(sample));
171 return static_cast<float>(sample) / 32768.0f;
172 }
173
174 static eve::action::ActionAudioWaveformBucket sampleBucket(
176 double localStart, double localEnd, std::size_t frameCount) noexcept {
178 result.minimum = 1.0f;
179 result.maximum = -1.0f;
180 const double duration = data.getDuration();
181 if (duration <= 0.0) return {};
182 double mediaStart = localStart * binding.pitch;
183 double mediaEnd = localEnd * binding.pitch;
184 if (!binding.looping && mediaStart >= duration) return {};
185 if (binding.looping) {
186 const double span = std::max(0.0, mediaEnd - mediaStart);
187 mediaStart = span >= duration ? 0.0 : std::fmod(mediaStart, duration);
188 mediaEnd = mediaStart + std::min(span, duration);
189 } else {
190 mediaStart = std::min(mediaStart, duration);
191 mediaEnd = std::min(mediaEnd, duration);
192 }
193 const double mediaSpan = std::max(0.0, mediaEnd - mediaStart);
194 const auto estimatedFrames = static_cast<std::size_t>(
195 std::ceil(mediaSpan * static_cast<double>(data.getSampleRate())));
196 const std::size_t stride = std::max<std::size_t>(
197 1, (estimatedFrames + kMaximumSamplesPerBucket - 1) / kMaximumSamplesPerBucket);
198 const std::size_t samples = std::max<std::size_t>(
199 1, std::min(estimatedFrames + 1, kMaximumSamplesPerBucket));
200 for (std::size_t offset = 0; offset < samples; ++offset) {
201 double media = mediaStart + static_cast<double>(offset * stride) /
202 static_cast<double>(data.getSampleRate());
203 if (binding.looping)
204 media = std::fmod(media, duration);
205 else
206 media = std::min(media, duration);
207 const auto frame = std::min(frameCount - 1, static_cast<std::size_t>(media * data.getSampleRate()));
208 for (int channel = 0; channel < data.getChannelCount(); ++channel) {
209 const float value = sampleAt(data, frame, channel);
210 result.minimum = std::min(result.minimum, value);
211 result.maximum = std::max(result.maximum, value);
212 }
213 }
214 if (result.minimum > result.maximum) return {};
215 return result;
216 }
217
219 eve::DiagnosticCode code, std::string message, std::string path) {
221 eve::Diagnostic::error(code, std::move(message), std::move(path)));
222 }
223};
224
225class AudioActionParameterSink final : public eve::action::IActionParameterSink, private AudioClient {
226public:
227 explicit AudioActionParameterSink(std::shared_ptr<AudioBinding> binding) : AudioClient(std::move(binding)) {}
228 bool supports(const eve::LogicalId& target) const noexcept override {
229 return target.format() == "audio:master-volume";
230 }
231
232 eve::Result<void> apply(const eve::action::ActionParameterSample& sample) override {
233 auto* audio = binding_->audio;
234 if (!audio)
235 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "Audio parameter target is unavailable", "audio"));
236 const ActiveKey key{sample.executionId, sample.itemId.format()};
237 auto candidate = active_;
239 if (candidate.contains(key))
240 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "Audio parameter curve is already active", "itemId"));
241 if (candidate.empty()) baseline_ = audio->getVolume();
242 candidate.emplace(key, ActiveValue{sample.operation, sample.value});
244 const auto found = candidate.find(key);
245 if (found == candidate.end())
246 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "Audio parameter curve has no active state", "itemId"));
247 found->second = ActiveValue{sample.operation, sample.value};
248 } else {
249 if (!candidate.erase(key))
251 }
252 const double value = compose(candidate);
253 if (!std::isfinite(value) || value < 0.0 || value > static_cast<double>(std::numeric_limits<float>::max()))
254 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "Audio parameter curves produced an invalid master volume", "value"));
255 active_ = std::move(candidate);
256 audio->setVolume(static_cast<float>(value));
258 }
259
260private:
261 using ActiveKey = std::pair<eve::action::ActionExecutionId, std::string>;
262 struct ActiveValue {
264 double value = 0.0;
265 };
266
267 double compose(const std::map<ActiveKey, ActiveValue>& values) const noexcept {
268 double result = baseline_;
269 for (const auto& [key, active] : values) {
270 (void)key;
271 switch (active.operation) {
275 }
276 }
277 return result;
278 }
279
280
281 std::map<ActiveKey, ActiveValue> active_;
282 double baseline_ = 1.0;
283};
284
285using ActiveKey = std::pair<eve::action::ActionExecutionId, std::string>;
286
287class AudioActionHandler final : public eve::action::IActionNotifyHandler, private AudioClient {
288public:
289 explicit AudioActionHandler(std::shared_ptr<AudioBinding> binding) : AudioClient(std::move(binding)) {}
292 if (!binding_->audio)
294 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "Audio module is unavailable", "audio"));
295 const ActiveKey key{context.executionId, event.itemId.format()};
297 const auto found = active_.find(key);
298 if (found == active_.end())
300 if (!context.interrupted && found->second.fadeOutOnExit && found->second.fadeOutDuration > 0.0) {
301 const float now = static_cast<float>(context.time.seconds());
302 auto fade =
303 found->second.source->fadeOutAndStop(static_cast<float>(found->second.fadeOutDuration), now);
304 if (!fade.ok()) return eve::Result<void>::failure(fade.status());
305 fading_.push_back({context.executionId, std::move(found->second)});
306 } else {
307 found->second.source->stop();
308 }
309 active_.erase(found);
311 }
312 const bool instant = event.kind == eve::action::ActionTimelineEventKind::Notify;
314 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "audio state requires enter or exit", "event.kind"));
315 if (!instant && active_.contains(key))
316 return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::Conflict, "audio state is already active", "itemId"));
319 if (!binding) return eve::Result<void>::failure(binding.status());
320 auto pose = resolvePose(binding.value().spatial, context);
321 if (!pose) return eve::Result<void>::failure(pose.status());
322 auto* audio = binding_->audio;
323 if (!audio) return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "Audio module is unavailable", "audio"));
324 try {
325 const auto seed = stableAudioSeed(context.executionId, event.itemId);
326 auto* data = eve::sound::Sound::create()->newSoundDataFromFile(selectAudioUri(binding.value(), seed));
327 auto dataPin = eve::ResourceManager::getInstance().pin(data);
328 if (!dataPin.ok()) return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "audio resource is no longer cached", "uri"));
329 eve::ResourcePin keepAlive = std::move(dataPin).takeValue();
330 auto* live = static_cast<eve::sound::SoundData*>(keepAlive.get());
331 std::unique_ptr<Source> source(audio->newSource(live));
332 auto configured = configureAudioSource(*source, binding.value(),
333 selectAudioPitch(binding.value(), seed ^ 0x9e3779b97f4a7c15ULL));
334 if (!configured.ok()) return eve::Result<void>::failure(configured.status());
335 applyPosition(*source, binding.value().spatial, pose.value());
336 source->play();
337 ActiveSource owned{std::move(keepAlive), std::move(source), binding.value().spatial,
338 std::move(pose).takeValue(), binding.value().volume, binding.value().fadeOutOnExit,
339 binding.value().fadeOutDuration};
340 if (instant) {
341 auto duration = eve::Duration::fromSeconds(owned.source->getDuration() / owned.source->getPitch());
342 if (!duration) return eve::Result<void>::failure(duration.status());
343 auto end = context.time.tryAdd(duration.value());
344 if (!end) return eve::Result<void>::failure(end.status());
345 transients_.push_back({context.executionId, std::move(end).takeValue(), std::move(owned)});
346 } else {
347 active_.emplace(key, std::move(owned));
348 }
349 } catch (const std::exception& error) {
351 }
353 }
354
357 const auto found = active_.find({context.executionId, block.itemId.format()});
358 if (found == active_.end()) return eve::Result<void>::failure(eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "active audio has no source", "itemId"));
360 auto pose = resolvePose(found->second.spatial, context);
361 if (!pose) return eve::Result<void>::failure(pose.status());
362 found->second.pose.positionX = pose.value().positionX;
363 found->second.pose.positionY = pose.value().positionY;
364 found->second.pose.positionZ = pose.value().positionZ;
366 found->second.pose = std::move(pose).takeValue();
367 }
368 applyPosition(*found->second.source, found->second.spatial, found->second.pose);
370 }
371
373 const eve::action::ActionNotifyContext&) const override {
376 if (!binding) return eve::Result<void>::failure(binding.status());
378 }
379
381 const auto before = transients_.size();
382 std::erase_if(transients_, [&](TransientSource& transient) {
383 if (transient.executionId != context.executionId || context.time < transient.endTime) return false;
384 transient.owned.source->stop();
385 return true;
386 });
387 const auto fadingBefore = fading_.size();
388 bool fadingAdvanced = false;
389 const float now = static_cast<float>(context.time.seconds());
390 std::erase_if(fading_, [&](FadingSource& fading) {
391 if (fading.executionId != context.executionId) return false;
392 fadingAdvanced = true;
393 if (!fading.owned.source->advanceFade(now).ok()) return true;
394 return !fading.owned.source->isFading();
395 });
397 before == transients_.size() && fadingBefore == fading_.size() && !fadingAdvanced
399 : eve::StatusCode::Applied));
400 }
401
402 void closeAudio() noexcept override {
403 active_.clear();
404 transients_.clear();
405 fading_.clear();
406 }
407
408private:
409 struct ActiveSource {
410 // Source borrows this data; the pin keeps it alive across cache unload.
412 std::unique_ptr<Source> source;
415 double volume = 1.0;
416 bool fadeOutOnExit = true;
417 double fadeOutDuration = 0.1;
418 };
419 struct TransientSource {
422 ActiveSource owned;
423 };
424 struct FadingSource {
426 ActiveSource owned;
427 };
428
429 static eve::Result<eve::EntitySpatialPose> resolvePose(
431 std::optional<ecs::EntityHandle> handle;
434 handle = context.source;
435 attachments = context.sourceAttachment;
436 } else {
437 if (spatial.targetIndex >= context.targets.size())
440 "audio target index is unavailable", "targetIndex"));
442 if (spatial.targetIndex < context.targetAttachments.size())
443 attachments = context.targetAttachments[spatial.targetIndex];
444 }
446 if (handle) {
448 if (!root) return root;
449 pose = std::move(root).takeValue();
450 }
451 if (spatial.bone.empty()) return eve::Result<eve::EntitySpatialPose>::success(std::move(pose));
452 if (!attachments)
455 "audio bone requires an attachment source", "bone"));
456 auto point = attachments->get().sampleAttachmentPoint(
457 spatial.bone, {static_cast<float>(spatial.positionOffset.x),
458 static_cast<float>(spatial.positionOffset.y),
459 static_cast<float>(spatial.positionOffset.z)});
461 pose.positionX = point.value().x;
462 pose.positionY = point.value().y;
463 pose.positionZ = point.value().z;
465 }
466
467 static void applyPosition(Source& source, const eve::action::ActionSpatialBinding& spatial,
469 const double offsetX = spatial.bone.empty() ? spatial.positionOffset.x : 0.0;
470 const double offsetY = spatial.bone.empty() ? spatial.positionOffset.y : 0.0;
471 const double offsetZ = spatial.bone.empty() ? spatial.positionOffset.z : 0.0;
472 source.setPosition(static_cast<float>(pose.positionX + offsetX),
473 static_cast<float>(pose.positionY + offsetY),
474 static_cast<float>(pose.positionZ + offsetZ));
475 }
476
477
478 std::map<ActiveKey, ActiveSource> active_;
479 std::vector<TransientSource> transients_;
480 std::vector<FadingSource> fading_;
481};
482
483class AudioActionPreviewSink final : public eve::action::IActionPreviewSink, private AudioClient {
484public:
485 explicit AudioActionPreviewSink(std::shared_ptr<AudioBinding> binding) : AudioClient(std::move(binding)) {}
486 ~AudioActionPreviewSink() override {
487 discardPrepared();
488 stopAll(current_);
489 stopAll(transients_);
490 }
491
493 if (!binding_->audio)
495 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "Audio module is unavailable", "audio"));
496 discardPrepared();
497 const bool retainContinuous = frame.reason == eve::action::ActionPreviewReason::Advance;
498 for (const auto& block : frame.activeBlocks) {
499 if (block.type.format() != "presentation:audio-state") continue;
500 const std::string key = block.itemId.format();
503 if (!binding) return failPrepared(binding.status());
504 const auto current = current_.find(key);
505 if (retainContinuous && current != current_.end() && current->second.payload == block.payload) {
506 preparedRetained_.insert(key);
507 continue;
508 }
509 auto audio = makeAudio(binding.value(), block.localTime,
510 stableAudioSeed(eve::action::ActionExecutionId::zero(), block.itemId));
511 if (!audio) return failPrepared(audio.status());
512 if (audio.value())
513 preparedStates_.emplace(key, PreviewAudio{block.payload, std::move(*audio.value())});
514 }
515 for (const auto& cue : frame.cues) {
517 cue.type.format() != "presentation:audio")
518 continue;
521 if (!binding) return failPrepared(binding.status());
522 auto audio = makeAudio(binding.value(), eve::Duration::zero(),
523 stableAudioSeed(eve::action::ActionExecutionId::zero(), cue.itemId));
524 if (!audio) return failPrepared(audio.status());
525 if (audio.value()) preparedInstants_.push_back(std::move(*audio.value()));
526 }
528 }
529
530 void present(const eve::action::ActionPreviewFrame&) noexcept override {
531 for (auto it = current_.begin(); it != current_.end();) {
532 if (preparedRetained_.contains(it->first)) {
533 ++it;
534 continue;
535 }
536 it->second.audio.source->stop();
537 it = current_.erase(it);
538 }
539 current_.merge(preparedStates_);
540 for (auto& [key, state] : current_) {
541 if (preparedRetained_.contains(key)) continue;
542 state.audio.source->play();
543 }
544 preparedRetained_.clear();
545
546 std::erase_if(transients_, [](const OwnedAudio& audio) { return !audio.source->isPlaying(); });
547 for (auto& audio : preparedInstants_) audio.source->play();
548 transients_.splice(transients_.end(), preparedInstants_);
549 }
550
551 void discardPrepared() noexcept override {
552 preparedStates_.clear();
553 preparedInstants_.clear();
554 preparedRetained_.clear();
555 }
556
557 void closeAudio() noexcept override {
558 discardPrepared();
559 stopAll(current_);
560 stopAll(transients_);
561 }
562
563private:
564 struct OwnedAudio {
565 OwnedAudio(eve::ResourcePin data, std::unique_ptr<Source> source)
566 : data(std::move(data)), source(std::move(source)) {}
567
568 // Source borrows this data; the pin keeps it alive across cache unload.
569 eve::ResourcePin data;
570 std::unique_ptr<Source> source;
571 };
572 struct PreviewAudio {
574 OwnedAudio audio;
575 };
576
577 eve::Result<void> failPrepared(const eve::Status& status) {
578 discardPrepared();
580 }
581
583 eve::Duration localTime, std::uint64_t seed) {
584 auto* audio = binding_->audio;
585 if (!audio)
587 eve::DiagnosticCode::NotFound, "Audio preview requires the Audio module", "audio"));
588 try {
589 auto* data = eve::sound::Sound::create()->newSoundDataFromFile(selectAudioUri(binding, seed));
590 auto dataPin = eve::ResourceManager::getInstance().pin(data);
591 if (!dataPin.ok()) return eve::Result<std::optional<OwnedAudio>>::failure(dataPin.status());
592 eve::ResourcePin keepAlive = std::move(dataPin).takeValue();
593 auto* live = static_cast<eve::sound::SoundData*>(keepAlive.get());
594 std::unique_ptr<Source> source(audio->newSource(live));
595 OwnedAudio owned(std::move(keepAlive), std::move(source));
596 auto configured =
597 configureAudioSource(*owned.source, binding, selectAudioPitch(binding, seed ^ 0x9e3779b97f4a7c15ULL));
598 if (!configured.ok()) return eve::Result<std::optional<OwnedAudio>>::failure(configured.status());
599 owned.source->setPosition(static_cast<float>(binding.spatial.positionOffset.x),
600 static_cast<float>(binding.spatial.positionOffset.y),
601 static_cast<float>(binding.spatial.positionOffset.z));
602 const double duration = owned.source->getDuration();
603 double mediaTime = localTime.seconds() * owned.source->getPitch();
604 if (duration > 0.0) {
605 if (binding.looping)
606 mediaTime = std::fmod(mediaTime, duration);
607 else if (mediaTime >= duration)
608 return eve::Result<std::optional<OwnedAudio>>::success(std::nullopt);
609 }
610 if (mediaTime > 0.0 && !owned.source->seek(mediaTime))
612 eve::DiagnosticCode::Unsupported, "Audio preview source does not support seeking", "uri"));
614 std::optional<OwnedAudio>(std::move(owned)));
615 } catch (const std::exception& error) {
618 }
619 }
620
621 static void stopAll(std::map<std::string, PreviewAudio>& values) noexcept {
622 for (auto& [key, value] : values) {
623 (void)key;
624 value.audio.source->stop();
625 }
626 values.clear();
627 }
628
629 static void stopAll(std::list<OwnedAudio>& values) noexcept {
630 for (auto& value : values) value.source->stop();
631 values.clear();
632 }
633
634 std::map<std::string, PreviewAudio> current_;
635 std::list<OwnedAudio> transients_;
636 std::map<std::string, PreviewAudio> preparedStates_;
637 std::list<OwnedAudio> preparedInstants_;
638 std::set<std::string> preparedRetained_;
639};
640
641class AudioActionProvider final : public eve::action::IActionNotifyProvider,
643 private AudioClient {
644public:
645 explicit AudioActionProvider(std::shared_ptr<AudioBinding> binding) : AudioClient(std::move(binding)) {}
647 if (!binding_->audio)
649 eve::Diagnostic::error(eve::DiagnosticCode::NotFound, "Audio module is unavailable", "audio"));
650 auto handler = std::make_shared<AudioActionHandler>(binding_);
651 auto instant = registry.registerHandler("presentation:audio", handler);
652 if (!instant) return instant;
653 return registry.registerHandler("presentation:audio-state", std::move(handler));
654 }
655
656 eve::Result<std::unique_ptr<eve::action::IActionPreviewSink>> createActionPreviewSink() override {
657 if (!binding_->audio)
659 eve::DiagnosticCode::NotFound, "Audio preview requires the Audio module", "audio"));
661 std::make_unique<AudioActionPreviewSink>(binding_));
662 }
663};
664
665} // namespace
666
668 std::shared_ptr<AudioBinding> binding;
669 AudioQueryImpl query;
670 AudioActionProvider actions;
671 ActionAudioWaveformProvider waveform;
672 AudioActionParameterSink parameters;
673 explicit Impl(Audio& audio)
674 : binding(std::make_shared<AudioBinding>(AudioBinding{&audio, {}})),
675 query(binding),
678};
679
680AudioCapabilities::AudioCapabilities(Audio& audio) : impl_(std::make_unique<Impl>(audio)) {
681 eve::cap::provide<eve::IAudioQuery>(&impl_->query);
682 eve::cap::provide<eve::action::IActionAudioWaveformProvider>(&impl_->waveform);
683 eve::cap::addListener<eve::action::IActionParameterSink>(&impl_->parameters);
684 eve::cap::addListener<eve::action::IActionNotifyProvider>(&impl_->actions);
685 eve::cap::addListener<eve::action::IActionPreviewSinkProvider>(&impl_->actions);
686}
687
689 eve::cap::revoke<eve::IAudioQuery>(&impl_->query);
690 eve::cap::revoke<eve::action::IActionAudioWaveformProvider>(&impl_->waveform);
691 eve::cap::removeListener<eve::action::IActionParameterSink>(&impl_->parameters);
692 eve::cap::removeListener<eve::action::IActionNotifyProvider>(&impl_->actions);
693 eve::cap::removeListener<eve::action::IActionPreviewSinkProvider>(&impl_->actions);
694 impl_->binding->close();
695}
696
697} // namespace eve::audio
Typed audio action-block payload contract.
Optional audio waveform projection for action editors.
LogicalId target
ActionParameterOperation operation
Extensible notify descriptors, validation and runtime routing.
Typed continuous parameter-curve action block.
Presentation-neutral action preview frame contracts.
Typed spatial payload shared by presentation action blocks.
Value::Object payload
LogicalId itemId
bool & active
float duration
std::map< std::string, std::vector< Key >, std::less<> > channels
int root
Definition AnimSmr.cpp:119
eve::action::ActionExecutionId executionId
Audio * audio
ActiveSource owned
double fadeOutDuration
std::shared_ptr< AudioBinding > binding_
eve::Duration endTime
double volume
eve::EntitySpatialPose pose
std::vector< AudioClient * > clients
eve::action::ActionSpatialBinding spatial
bool fadeOutOnExit
audio_editing::AudioWaveformResult waveform
std::vector< std::unique_ptr< ScriptClimbingEventSink > > live
SQObjectPtr key
Definition ECS.cpp:155
Optional ECS-entity to world-pose capability.
std::string message
DiagnosticCode code
const GltfImportRequest & request
ShaderImageInput shape
wgpu::PopErrorScopeStatus status
float v
float blend
size_t offset
bool present
Poco::JSON::Object::Ptr result
std::uint64_t bytes
HSQOBJECT handler
MeleePoint3 a
Definition MeleeHit.cpp:40
ssq::Object frame
std::string error
Definition Package.cpp:174
eve::action::ActionVfxBinding binding
double mediaTime
std::array< uint32_t, 9 > parameters
std::string path
Definition PlayHost.cpp:111
std::vector< ActionSpec > actions
Definition PlayHost.cpp:127
PrimitiveHandle handle
std::set< std::string > values
const eve::script::BindingContractRegistry & registry
Object::Ptr value
std::string hash
bool found
std::string_view source
size_t end
double current
TacticalUnit * unit
float offsetX
float offsetY
uint32_t seed
Definition TreeMesh.cpp:276
uint32_t index
const VegetationPresetContext & context
glm::vec3 point
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Signed, fixed-resolution simulation duration in nanoseconds.
Definition Time.h:43
static Result< Duration > fromSeconds(double seconds)
Convert finite seconds to the nearest nanosecond.
Definition Time.cpp:17
static constexpr Duration zero() noexcept
Return zero duration.
Definition Time.h:60
double seconds() const noexcept
Return this duration as seconds for legacy/presentation APIs.
Definition Time.cpp:29
Audio control surface (provided by the audio module).
Definition AudioQuery.h:8
Human-readable, scoped identifier in the form namespace:name.
Definition Identity.h:414
const std::string & format() const noexcept
Returns the canonical namespace:name representation.
Definition Identity.h:439
eve::Result< ResourcePin > pin(Resource *resource)
Keeps one cached resource alive across unload()/clear()/reload.
Definition Resource.cpp:311
static ResourceManager & getInstance()
Returns the instance.
Definition Resource.cpp:15
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
Structured status and zero or more diagnostics for an operation.
Definition Status.h:70
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
std::map< std::string, Value > Object
Definition Value.h:34
Canonical notify descriptor owner and runtime handler router.
Optional synchronous audio waveform service consumed by the action editor.
Consumer-owned handler for one registered notify type.
Optional module provider that installs handlers into a new registry.
Optional open target for continuous action parameters.
Optional owner-thread provider of one independently owned action preview layer.
Host boundary for 3D animation, VFX, audio and camera preview.
AudioCapabilities(Audio &audio)
Publish capabilities only after the audio device is initialized.
~AudioCapabilities()
Revoke registrations and invalidate all retained clients.
OpenAL audio module: device management, master listener state, and Source factory....
Definition Audio.h:34
constexpr std::uint64_t value() const noexcept
Returns the underlying value at an explicit protocol boundary.
static constexpr StrongUint64 zero() noexcept
Returns the zero value for this strong type.
RAII keep-alive for one RuntimeObjectRegistry entry.
T * get() const noexcept
Borrows the pinned object; valid until the pin is released.
Raw PCM audio buffer with format metadata (samples/rate/bit depth/channels).
Definition SoundData.h:15
ActionParameterOperation
Composition operation applied by a target-specific parameter sink.
@ FollowTarget
Re-evaluate position and rotation from the anchor every update.
@ WorldTransformAtStart
Capture the complete world transform once on Enter.
double sample(const Heightmap &map, double u, double v)
Sample.
Build metadata (engine git commit, build time, third-party version).
Definition Build.cpp:16
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Result< EntitySpatialPose > resolveEntitySpatialPose(ecs::EntityHandle entity, std::string_view bone)
Resolve through registered providers in deterministic registration order.
StatusCode
Stable outcome category for an operation.
Definition Status.h:28
std::optional< std::reference_wrapper< T > > OptionalRef
Optional borrowed reference; it does not extend T's lifetime.
Definition BorrowedRef.h:24
Renderer-neutral owning world pose resolved for an ECS entity.
Owning per-step sample of one currently active timeline state.
Owning validated settings shared by Audio runtime and editor preview.
static Result< ActionAudioBinding > fromPayload(const Value::Object &payload, ActionAudioShape shape)
Decode an audio payload transactionally.
One normalized min/max envelope bucket in timeline display order.
Owning request for a bounded audio-block waveform projection.
Owning waveform projection returned by an optional audio provider.
double clipDurationSeconds
Decoded source duration used for diagnostics and host labels.
Context linking a routed event to its action execution.
Owning continuous parameter sample emitted by ActionBlockRuntime.
Complete frame atomically prepared and then presented by a preview host.
Validated spatial settings decoded from a notify payload.
Owning event projection returned by the runtime sampler.
ActionTimelineEventKind kind
ActionSpatialBinding spatial
ActionAudioWaveformProvider waveform
std::shared_ptr< AudioBinding > binding
uint32_t bucket