Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
643 changes: 449 additions & 194 deletions packages/audio-context/index.android.ts

Large diffs are not rendered by default.

Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ add_library(native-audio SHARED
audio_offline.cpp
audio_jni.cpp
audio_worklet.cpp
hrtf_convolver.cpp
hrtf.cpp
convolver.cpp)

# Include small bundled kissfft implementation
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
#include "audio_context.h"
#include "audio_internal.h"
#include "hrtf_convolver.h"

#include <cstring>

Expand Down Expand Up @@ -108,6 +107,7 @@ NativeEngine::scheduleGainEvent(const std::string &gainId, int type, int rate, d
std::lock_guard<std::mutex> lock(scheduledEventsMutex_);
auto &vec = scheduledGainEvents_[gainId];
ParamEvent ev{type, rate, timeNs, value};
ev.callNs = nowNs_.load(std::memory_order_relaxed);
insertSortedByTime(vec, ev);
}

Expand All @@ -118,6 +118,7 @@ NativeEngine::schedulePannerEvent(const std::string &pannerId, int paramType, in
auto &map = scheduledPannerEvents_[pannerId];
auto &vec = map[paramType];
ParamEvent ev{type, rate, timeNs, value};
ev.callNs = nowNs_.load(std::memory_order_relaxed);
insertSortedByTime(vec, ev);
}

Expand All @@ -128,10 +129,30 @@ NativeEngine::scheduleListenerEvent(const std::string &contextId, int paramType,
auto &map = scheduledListenerEvents_[contextId];
auto &vec = map[paramType];
ParamEvent ev{type, rate, timeNs, value};
ev.callNs = nowNs_.load(std::memory_order_relaxed);
insertSortedByTime(vec, ev);
}


std::shared_ptr<std::atomic<float>> NativeEngine::compressorMeter(const std::string &id, bool create) {
std::lock_guard<std::mutex> lock(meterMutex_);
auto it = meters_.find(id);
if (it != meters_.end()) return it->second;
if (!create) return nullptr;
auto meter = std::make_shared<std::atomic<float>>(0.0f);
meters_[id] = meter;
return meter;
}

void NativeEngine::scheduleParamEvent(int target, const std::string &id, int paramType, const ParamEvent &e) {
ParamEvent event = e;
event.callNs = nowNs_.load(std::memory_order_relaxed);
std::lock_guard<std::mutex> lock(scheduledEventsMutex_);
if (target == 0) insertSortedByTime(scheduledGainEvents_[id], event);
else if (target == 1) insertSortedByTime(scheduledPannerEvents_[id][paramType], event);
else insertSortedByTime(scheduledListenerEvents_[id][paramType], event);
}

void NativeEngine::cancelGainEvents(const std::string &gainId, int64_t timeNs) {
std::lock_guard<std::mutex> lock(scheduledEventsMutex_);
auto it = scheduledGainEvents_.find(gainId);
Expand Down Expand Up @@ -471,12 +492,6 @@ NativeEngine::~NativeEngine() {
}
audioBuffers_.clear();

for (auto &pkv: panners_) {
if (pkv.second.hrtf) {
delete pkv.second.hrtf;
pkv.second.hrtf = nullptr;
}
}
panners_.clear();
}

Expand Down Expand Up @@ -741,9 +756,10 @@ void NativeEngine::rebuildAnalyserCaches(NativeEngine::AnalyserData &ad) {
ad.fftCfg = kiss_fft_alloc(n, 0, nullptr, nullptr);

ad.window.resize((size_t) n);
const float twoPiOverN = 2.0f * (float) M_PI / (float) n;
// The spec's Blackman window, alpha 0.16.
for (int i = 0; i < n; ++i) {
ad.window[(size_t) i] = 0.5f * (1.0f - std::cos(twoPiOverN * (float) i));
const double x = 2.0 * M_PI * i / n;
ad.window[(size_t) i] = static_cast<float>(0.42 - 0.5 * std::cos(x) + 0.08 * std::cos(2.0 * x));
}

ad.fin.assign((size_t) n, kiss_fft_cpx{0.0f, 0.0f});
Expand Down Expand Up @@ -837,15 +853,17 @@ static int ensureSmoothedSpectrum(NativeEngine::AnalyserData &ad) {
std::memset(fout, 0, (size_t) n * sizeof(kiss_fft_cpx));
}

const float invN2 = 1.0f / ((float) n * (float) n + 1e-30f);
// Smoothed over time on |X[k]| / N, as the spec says.
const float invN = 1.0f / (float) n;
float tau = (float) std::max(0.0, std::min(1.0, ad.smoothingTimeConstant));
float oneMinus = 1.0f - tau;
float *mag = ad.smoothedMag.data();
for (int i = 0; i < half; ++i) {
float re = fout[i].r;
float im = fout[i].i;
float power = (re * re + im * im) * invN2;
mag[i] = tau * mag[i] + oneMinus * power;
float m = std::sqrt(re * re + im * im) * invN;
float v = tau * mag[i] + oneMinus * m;
mag[i] = std::isfinite(v) ? v : 0.0f;
}
ad.spectrumFrameStamp = widx;
ad.dbCacheFrameStamp = -1;
Expand All @@ -860,7 +878,7 @@ static void ensureDbCacheLocked(NativeEngine::AnalyserData &ad, int half) {
for (int i = 0; i < half; ++i) {
float m = mag[i];
if (m < 1e-20f) m = 1e-20f;
db[i] = 10.0f * std::log10(m);
db[i] = 20.0f * std::log10(m);
}
ad.dbCacheFrameStamp = ad.spectrumFrameStamp;
}
Expand Down Expand Up @@ -953,10 +971,8 @@ int NativeEngine::getAnalyserByteTimeDomainDataInto(const std::string &id, uint8
float *tmp = ad.byteScratch.data();
copyLatestSamples(ad, tmp, n);
for (int i = 0; i < n; ++i) {
float v = tmp[i];
if (v < -1.0f) v = -1.0f;
else if (v > 1.0f) v = 1.0f;
int b = (int) ((v * 0.5f + 0.5f) * 255.0f);
// The spec: floor(128 * (1 + v)), clamped to a byte.
int b = (int) std::floor(128.0f * (1.0f + tmp[i]));
if (b < 0) b = 0;
else if (b > 255) b = 255;
dst[i] = (uint8_t) b;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

#include "kiss_fft.h"

struct HRTFConvolver;
class HrtfPanner;
struct Oversampler;
class Convolver;

#ifdef HAS_OBOE
Expand Down Expand Up @@ -267,6 +268,10 @@ class NativeEngine {
bool loop = false;
std::string playbackRateId;
std::string periodicWaveId;
std::string detuneId;
// Seconds into the buffer; used when loopStart < loopEnd.
double loopStart = 0.0;
double loopEnd = 0.0;
bool playing = false;
// CLOCK_MONOTONIC ns, the same clock as g_audioTimeNanos; 0 means unscheduled.
int64_t startAtNs = 0;
Expand Down Expand Up @@ -307,6 +312,13 @@ class NativeEngine {

std::unordered_map<std::string, BufferData> audioBuffers_;
std::unordered_map<std::string, Voice> audioVoices_;
// A source's detune param and loop points, kept until its voice exists.
struct SourceExtras {
std::string detuneId;
double loopStart = 0.0;
double loopEnd = 0.0;
};
std::unordered_map<std::string, SourceExtras> sourceExtras_;
// Buffers to free once no playing voice reads them; render thread only.
std::vector<std::string> idleFrees_;

Expand Down Expand Up @@ -354,8 +366,6 @@ class NativeEngine {
CMD_ATTACH_PLAYBACK_RATE,
CMD_DETACH_PLAYBACK_RATE,
CMD_FREE_PLAYBACK_RATE,
CMD_SET_PANNER_HRIR,
CMD_SET_PANNER_PARTITION_SIZE,
CMD_CREATE_WORKLET,
CMD_CREATE_DELAY,
CMD_CONNECT,
Expand All @@ -366,7 +376,11 @@ class NativeEngine {
// A biquad's frequency, Q, gain and detune params, in paramIds.
CMD_SET_BIQUAD_PARAM_IDS,
// A convolver's response; null clears it.
CMD_SET_CONVOLVER
CMD_SET_CONVOLVER,
// A source's detune param, in targetId.
CMD_ATTACH_DETUNE,
// A buffer source's loop flag and points.
CMD_SET_SOURCE_LOOP
};

// Graph node kinds; AudioContext.java's NODE_* match.
Expand Down Expand Up @@ -396,6 +410,7 @@ class NativeEngine {
std::string compressorAttackId;
std::string compressorReleaseId;
std::string compressorReductionId;
std::shared_ptr<std::atomic<float>> meter;
std::string playbackRateId;
double gainValue = 1.0;
double maxDelayTime = 1.0;
Expand Down Expand Up @@ -440,11 +455,9 @@ class NativeEngine {
std::shared_ptr<std::vector<float>> pcmFloat;
std::shared_ptr<ExternalRing> externalRing;
std::shared_ptr<WorkletNode> worklet;
std::shared_ptr<std::vector<float>> hrirLeft;
std::shared_ptr<std::vector<float>> hrirRight;
bool clearHrir = false;
int pannerPartitionSize = 0;
bool loop = false;
double loopStart = 0.0;
double loopEnd = 0.0;
std::shared_ptr<std::promise<void>> completion;
int outputIndex = 0;
int inputIndex = 0;
Expand All @@ -456,7 +469,6 @@ class NativeEngine {
std::string periodicWaveId;
std::vector<float> waveShaperCurve;
std::string waveShaperOversample;
std::string pannerBiquadId;
std::vector<std::string> paramIds;
std::shared_ptr<Convolver> convolver;
// CMD_CONNECT / CMD_DISCONNECT: id output -> targetId input (or param targetType).
Expand All @@ -474,6 +486,9 @@ class NativeEngine {

void enqueueCommand(Command &&cmd);

// A DynamicsCompressorNode's reduction meter, by node id.
std::shared_ptr<std::atomic<float>> compressorMeter(const std::string &id, bool create);

private:
static constexpr int kQuantum = 128;

Expand Down Expand Up @@ -511,10 +526,14 @@ class NativeEngine {
std::shared_ptr<WorkletNode> worklet;
std::vector<BiquadState> biquad;
std::vector<std::vector<double>> iir;
std::vector<BiquadState> lowpass;
BiquadCoeffs lowpassCoeffs;
double lowpassCutoff = -1.0;
// A PannerNode's HRTF state, made when it first pans with 'HRTF'.
std::shared_ptr<HrtfPanner> hrtf;
// A WaveShaperNode's per-channel oversampling state.
std::vector<std::shared_ptr<Oversampler>> oversamplers;
std::vector<float> reductionDb;
// A compressor's look-ahead line, channel-major.
std::vector<float> preDelay;
int preDelayPos = 0;
// Param values for this quantum, kQuantum per param.
std::vector<double> params;
std::vector<float> paramValues;
Expand Down Expand Up @@ -597,19 +616,30 @@ class NativeEngine {
std::string attackId;
std::string releaseId;
std::string reductionId;
// Its reduction in dB, read from other threads.
std::shared_ptr<std::atomic<float>> meter;
};
std::unordered_map<std::string, DynamicsCompressor> compressors_;
std::mutex meterMutex_;
std::unordered_map<std::string, std::shared_ptr<std::atomic<float>>> meters_;

public:
enum AutomationRate {
RATE_K = 0, RATE_A = 1
};

enum ParamEventType { EVENT_SET = 0, EVENT_LINEAR, EVENT_EXPONENTIAL, EVENT_TARGET, EVENT_CURVE };

struct ParamEvent {
int type; // 0 = set, 1 = linearRamp
int type; // ParamEventType
int rate; // AutomationRate
int64_t timeNs;
double value;
double timeConstant = 0.0;
int64_t durationNs = 0;
// When it was scheduled: a ramp with no event before it starts here.
int64_t callNs = 0;
std::shared_ptr<const std::vector<float>> curve;
};
private:
std::unordered_map<std::string, std::vector<ParamEvent>> scheduledGainEvents_;
Expand All @@ -624,6 +654,9 @@ class NativeEngine {
void schedulePannerEvent(const std::string &pannerId, int paramType, int type, int rate,
double value, int64_t timeNs);

// Any event on a gain-style (0), panner (1) or listener (2) param.
void scheduleParamEvent(int target, const std::string &id, int paramType, const ParamEvent &event);

void cancelGainEvents(const std::string &gainId, int64_t timeNs);

void cancelPannerEvents(const std::string &pannerId, int paramType, int64_t timeNs);
Expand Down Expand Up @@ -682,7 +715,8 @@ class NativeEngine {
};
std::unordered_map<std::string, WaveShaperData> waveShapers_;
enum PannerPanningModel {
PANNING_EQUALPOWER = 0, PANNING_HRTF = 1
// PANNING_STEREO: a StereoPannerNode, panned by `pan` alone.
PANNING_EQUALPOWER = 0, PANNING_HRTF = 1, PANNING_STEREO = 2
};
struct Panner {
double positionX = 0.0;
Expand All @@ -701,9 +735,6 @@ class NativeEngine {
double coneOuterAngle = 360.0;
double coneOuterGain = 0.0;
std::string contextId;
HRTFConvolver *hrtf = nullptr;
int hrtfPartitionSize = 0;
std::string biquadId;
};
std::unordered_map<std::string, Panner> panners_;

Expand Down
Loading
Loading