载入中...
搜索中...
未找到
PcmStream.cpp
浏览该文件的文档.
1// eve-hot-path
2#include "PcmStream.h"
3
4#include "Audio.h"
7
8#include <AL/al.h>
9#include <algorithm>
10#include <array>
11#include <cmath>
12#include <stdexcept>
13#include <vector>
14
15namespace eve::audio {
17 ALuint source = 0;
18 std::array<ALuint, PcmStream::blockCount> buffers{};
19 std::array<int, PcmStream::blockCount> frames{};
20 int rate = 0;
21 int channels = 0;
22 bool wantsPlay = false;
23 bool ended = false;
24 bool paused = false;
25 std::uint64_t played = 0;
26};
27
28namespace {
29Diagnostic closedDiagnostic() {
30 return Diagnostic::error(DiagnosticCode::PreconditionViolation, "PCM stream is closed");
31}
32
33Result<void> alResult() {
34 const auto error = alGetError();
35 if (error != AL_NO_ERROR)
36 return Result<void>::failure(Diagnostic::error(DiagnosticCode::Failed, "OpenAL PCM operation failed",
37 "audio.pcm", {{"alError", std::to_string(error)}}));
38 return Result<void>::success();
39}
40} // namespace
41
42PcmStream::PcmStream(std::shared_ptr<PcmStreamState> state) : state_(std::move(state)) {}
44
45Result<std::unique_ptr<PcmStream>> PcmStream::create(int sampleRate, int channels) {
46 if (sampleRate < 8000 || sampleRate > 192000 || (channels != 1 && channels != 2))
47 return Result<std::unique_ptr<PcmStream>>::failure(
48 Diagnostic::error(DiagnosticCode::InvalidArgument, "PCM requires 8000..192000 Hz and one or two channels"));
49 auto state = std::make_shared<PcmStreamState>();
50 state->rate = sampleRate;
51 state->channels = channels;
52 alGetError();
53 alGenSources(1, &state->source);
54 alGenBuffers(blockCount, state->buffers.data());
55 alSourcei(state->source, AL_SOURCE_RELATIVE, AL_TRUE);
56 alSourcef(state->source, AL_ROLLOFF_FACTOR, 0.f);
57 auto result = alResult();
58 if (!result.ok()) {
59 closeState(state);
60 return Result<std::unique_ptr<PcmStream>>::failure(result.status());
61 }
62 return Result<std::unique_ptr<PcmStream>>::success(std::unique_ptr<PcmStream>(new PcmStream(std::move(state))));
63}
64
65void PcmStream::closeState(const std::shared_ptr<PcmStreamState>& state) {
66 if (state->source) {
67 alSourceStop(state->source);
68 alSourcei(state->source, AL_BUFFER, 0);
69 alDeleteSources(1, &state->source);
70 state->source = 0;
71 }
72 for (auto& buffer : state->buffers) {
73 if (buffer) alDeleteBuffers(1, &buffer);
74 buffer = 0;
75 }
76 state->frames.fill(0);
77}
78
79void PcmStream::close() { closeState(state_); }
80
81void PcmStream::pumpState(const std::shared_ptr<PcmStreamState>& state) {
82 if (!state->source) return;
83 ALint processed = 0;
84 alGetSourcei(state->source, AL_BUFFERS_PROCESSED, &processed);
85 while (processed-- > 0) {
86 ALuint buffer = 0;
87 alSourceUnqueueBuffers(state->source, 1, &buffer);
88 const auto found = std::find(state->buffers.begin(), state->buffers.end(), buffer);
89 if (found != state->buffers.end()) {
90 const auto index = static_cast<size_t>(found - state->buffers.begin());
91 state->played += state->frames[index];
92 state->frames[index] = 0;
93 }
94 }
95 if (state->wantsPlay && !state->paused) {
96 ALint playback = 0, queued = 0;
97 alGetSourcei(state->source, AL_SOURCE_STATE, &playback);
98 alGetSourcei(state->source, AL_BUFFERS_QUEUED, &queued);
99 if (queued > 0 && playback != AL_PLAYING) alSourcePlay(state->source);
100 }
101}
102
103Result<int> PcmStream::submit(std::span<const float> samples) {
104 auto& state = *state_;
105 if (!state.source) return Result<int>::failure(closedDiagnostic());
106 if (state.ended)
108 if (samples.empty() || samples.size() % state.channels != 0 ||
109 samples.size() > static_cast<size_t>(maxBlockFrames * state.channels) ||
110 std::any_of(samples.begin(), samples.end(), [](float v) { return !std::isfinite(v) || v < -1.f || v > 1.f; }))
113 "PCM samples must be finite, normalized, channel-aligned and bounded to 4096 frames"));
114 pumpState(state_);
115 const auto free = std::find(state.frames.begin(), state.frames.end(), 0);
116 if (free == state.frames.end())
118 Diagnostic::error(DiagnosticCode::Conflict, "PCM queue is full; retry this block later"));
119 const auto index = static_cast<size_t>(free - state.frames.begin());
120 std::vector<ALshort> pcm(samples.size());
121 std::transform(samples.begin(), samples.end(), pcm.begin(),
122 [](float v) { return static_cast<ALshort>(std::lround(v < 0.f ? v * 32768.f : v * 32767.f)); });
123 alGetError();
124 alBufferData(state.buffers[index], state.channels == 1 ? AL_FORMAT_MONO16 : AL_FORMAT_STEREO16, pcm.data(),
125 static_cast<ALsizei>(pcm.size() * sizeof(ALshort)), state.rate);
126 auto upload = alResult();
127 if (!upload.ok()) return Result<int>::failure(upload.status());
128 alSourceQueueBuffers(state.source, 1, &state.buffers[index]);
129 auto queued = alResult();
130 if (!queued.ok()) return Result<int>::failure(queued.status());
131 const int accepted = static_cast<int>(samples.size() / state.channels);
132 *free = accepted;
133 pumpState(state_);
134 return Result<int>::success(accepted);
135}
136
138 if (!state_->source) return Result<void>::failure(closedDiagnostic());
139 state_->wantsPlay = true;
140 state_->paused = false;
141 alGetError();
142 pumpState(state_);
143 return alResult();
144}
145
147 if (!state_->source) return Result<void>::failure(closedDiagnostic());
148 alGetError();
149 alSourcePause(state_->source);
150 auto result = alResult();
151 if (!result.ok()) return result;
152 state_->paused = true;
153 return Result<void>::success();
154}
155
157 if (!state_->source) return Result<void>::failure(closedDiagnostic());
158 state_->ended = true;
159 return Result<void>::success();
160}
161
163 if (!state_->source) return Result<void>::failure(closedDiagnostic());
164 alGetError();
165 alSourceStop(state_->source);
166 alSourcei(state_->source, AL_BUFFER, 0);
167 auto result = alResult();
168 if (!result.ok()) return result;
169 state_->frames.fill(0);
170 state_->played = 0;
171 state_->wantsPlay = state_->ended = state_->paused = false;
172 return Result<void>::success();
173}
174
177 info.sampleRate = state_->rate;
178 info.channels = state_->channels;
179 info.playedFrames = state_->played;
180 for (int frames : state_->frames) {
181 info.queuedFrames += frames;
182 if (!frames) ++info.availableBlocks;
183 }
184 if (!state_->source) {
186 info.availableBlocks = 0;
187 } else if (state_->ended && !info.queuedFrames)
189 else if (state_->paused)
191 else if (!state_->wantsPlay)
193 else if (!info.queuedFrames)
195 else
196 info.phase = state_->ended ? PcmStreamPhase::Draining : PcmStreamPhase::Playing;
197 return info;
198}
199
200void exposePcmStream(ssq::Table& table, ssq::Class& audioClass) {
201 auto cls = table.addClass<PcmStream>(
202 "PcmStream",
203 std::function<PcmStream*()>([]() -> PcmStream* { throw std::runtime_error("Use audio.newPcmStream"); }), false);
204 const auto vm = table.getHandle();
205 cls.addFunc("submit", [vm](PcmStream* self, ssq::Array samples) {
206 if (samples.size() > PcmStream::maxBlockFrames * 2)
209 "PCM block exceeds sample limit")),
210 [](int n) { return Value(n); });
211 std::vector<float> values;
212 values.reserve(samples.size());
213 try {
214 for (size_t i = 0; i < samples.size(); ++i) values.push_back(samples.get<float>(i));
215 } catch (const ssq::Exception&) {
217 vm,
219 [](int n) { return Value(n); });
220 }
221 return eve::script::projectResult(vm, self->submit(values), [](int n) { return Value(n); });
222 });
223 cls.addFunc("play", [vm](PcmStream* self) { return eve::script::projectResult(vm, self->play()); });
224 cls.addFunc("pause", [vm](PcmStream* self) { return eve::script::projectResult(vm, self->pause()); });
225 cls.addFunc("finishInput", [vm](PcmStream* self) { return eve::script::projectResult(vm, self->finishInput()); });
226 cls.addFunc("reset", [vm](PcmStream* self) { return eve::script::projectResult(vm, self->reset()); });
227 cls.addFunc("close", &PcmStream::close);
228 cls.addFunc("getInfo", [vm](PcmStream* self) {
229 const auto info = self->getInfo();
230 constexpr std::array names = {"idle", "playing", "paused", "starved", "draining", "finished", "closed"};
231 ssq::Table snapshot(vm);
232 snapshot.set("phase", std::string(names[static_cast<size_t>(info.phase)]));
233 snapshot.set("sampleRate", info.sampleRate);
234 snapshot.set("channels", info.channels);
235 snapshot.set("availableBlocks", info.availableBlocks);
236 snapshot.set("maxBlockFrames", PcmStream::maxBlockFrames);
237 snapshot.set("queuedFrames", info.queuedFrames);
238 snapshot.set("playedFrames", static_cast<std::int64_t>(info.playedFrames));
239 return snapshot;
240 });
241 audioClass.addFunc("newPcmStream", [vm](Audio* self, int rate, int channels) {
242 auto result = self->newPcmStream(rate, channels);
243 if (!result.ok()) return eve::script::projectStatusResult(vm, result.status());
244 auto owned = eve::script::makeOwnedSquirrelInstance(vm, std::move(result).takeValue());
245 if (!owned.ok()) return eve::script::projectStatusResult(vm, owned.status());
246 return eve::script::projectStatusResult(vm, Status::success(), std::move(owned).takeValue());
247 });
248}
249} // namespace eve::audio
std::map< std::string, std::vector< Key >, std::less<> > channels
ActiveSource owned
HSQUIRRELVM vm
Definition ECS.cpp:38
HSQOBJECT cls
Definition ECS.cpp:39
glm::vec3 n
Definition Grass.cpp:63
float v
Poco::JSON::Object::Ptr result
Snapshot snapshot
std::unique_ptr< gpgpu::GpuBuffer > buffer
Definition OnnxGpgpu.cpp:26
size_t queued
Definition OnnxGpgpu.cpp:60
std::string error
Definition Package.cpp:174
std::set< std::string > values
bool found
The single Squirrel projection for common Result, Status and Value.
Explicit Value/Owned/Borrowed semantics at the Squirrel boundary.
uint32_t index
A structured explanation of a failed, degraded, or noteworthy result.
Definition Diagnostic.h:94
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
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
static Status success(StatusCode code=StatusCode::Ok)
Construct a successful status with an explicit non-error outcome.
Definition Status.cpp:19
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
OpenAL audio module: device management, master listener state, and Source factory....
Definition Audio.h:34
Bounded, caller-fed PCM playback, independent of codecs and synthesis. @ownership Caller owns this ob...
Definition PcmStream.h:41
Result< void > pause()
Pause without discarding queued data or reopening ended input.
~PcmStream()
Release all backend resources; must run on the owning thread.
Definition PcmStream.cpp:43
Result< int > submit(std::span< const float > samples)
Copy interleaved normalized samples and queue one block atomically.
Result< void > reset()
Discard queued audio, stop, clear counters and reopen input.
PcmStream(const PcmStream &)=delete
Result< void > play()
Start/resume; empty input becomes Starved and resumes when data arrives.
static constexpr int maxBlockFrames
Maximum frames per submission; stereo has twice as many values.
Definition PcmStream.h:44
static constexpr int blockCount
Maximum simultaneously queued blocks.
Definition PcmStream.h:46
PcmStreamInfo getInfo() const
Cheap snapshot from the last pump/operation; never restarts playback.
void close()
Idempotent final release; subsequent mutating operations return a diagnostic.
Definition PcmStream.cpp:79
Result< void > finishInput()
End input idempotently; play drains queued data without inserting silence.
void exposePcmStream(ssq::Table &table, ssq::Class &audioClass)
Install VM-bound adapters; borrows both handles only during registration.
ssq::Table projectStatusResult(HSQUIRRELVM vm, const Status &status)
Project a checked native status that carries no payload.
ssq::Table projectResult(HSQUIRRELVM vm, Result< void > &&result)
Consume and project a void native Result using the common schema.
eve::Result< ssq::Object > makeOwnedSquirrelInstance(HSQUIRRELVM vm, Owned< T > object)
Creates a Squirrel instance that owns a C++ wrapper through a release hook.
Owning snapshot; frame counts include all channels as one sample frame.
Definition PcmStream.h:23
std::array< int, PcmStream::blockCount > frames
Definition PcmStream.cpp:19
std::array< ALuint, PcmStream::blockCount > buffers
Definition PcmStream.cpp:18
glm::uvec4 info