| 35 | TempoAnalyzer::~TempoAnalyzer() FL_NOEXCEPT = default; |
| 36 | |
| 37 | void TempoAnalyzer::update(shared_ptr<Context> context) { |
| 38 | mRetainedFFT = context->getFFT16(); |
| 39 | const fft::Bins& fft = *mRetainedFFT; |
| 40 | u32 timestamp = context->getTimestamp(); |
| 41 | |
| 42 | // Calculate spectral flux for onset detection |
| 43 | float flux = calculateSpectralFlux(fft); |
| 44 | |
| 45 | // Update adaptive threshold |
| 46 | updateAdaptiveThreshold(); |
| 47 | |
| 48 | // Detect onsets |
| 49 | if (detectOnset(timestamp)) { |
| 50 | mOnsetTimes.push_back(timestamp); |
| 51 | if (mOnsetTimes.size() > MAX_ONSET_HISTORY) { |
| 52 | mOnsetTimes.pop_front(); |
| 53 | } |
| 54 | |
| 55 | // Update tempo hypotheses |
| 56 | updateHypotheses(timestamp); |
| 57 | } |
| 58 | |
| 59 | mPreviousFlux = flux; |
| 60 | |
| 61 | // Update per-bin magnitudes for next frame's spectral flux calculation |
| 62 | size numBins = fl::min(static_cast<size>(8), fft.raw().size()); |
| 63 | for (size i = 0; i < numBins && i < mPreviousMagnitudes.size(); i++) { |
| 64 | mPreviousMagnitudes[i] = fft.raw()[i]; |
| 65 | } |
| 66 | |
| 67 | // Prune weak hypotheses |
| 68 | pruneHypotheses(); |
| 69 | |
| 70 | // Update current tempo based on best hypothesis |
| 71 | updateCurrentTempo(); |
| 72 | |
| 73 | // Update stability analysis |
| 74 | updateStability(); |
| 75 | |
| 76 | // Silence gate: fade confidence toward 0 during silence. The BPM estimate |
| 77 | // itself survives unchanged so beat sync is seamless on audio re-entry. |
| 78 | // dt derived from timestamp deltas (ms→s). First frame: dt=0 → pass-through. |
| 79 | float dt = 0.0f; |
| 80 | if (mHasPrevTimestamp && timestamp >= mPrevTimestamp) { |
| 81 | dt = static_cast<float>(timestamp - mPrevTimestamp) * 0.001f; |
| 82 | } |
| 83 | mPrevTimestamp = timestamp; |
| 84 | mHasPrevTimestamp = true; |
| 85 | |
| 86 | const bool isSilent = context->isSilent(); |
| 87 | mConfidence = mConfidenceEnvelope.update(isSilent, mConfidence, dt); |
| 88 | |
| 89 | // Track state changes for fireCallbacks() |
| 90 | float bpmDiff = fl::abs(mCurrentBPM - mPreviousBPM); |
| 91 | mBpmChanged = (bpmDiff > 5.0f); |
| 92 | mPreviousBPM = mCurrentBPM; |
| 93 | } |
| 94 | |