From 89a2407debe74ea5317010d64de3188cb084b093 Mon Sep 17 00:00:00 2001 From: reuk Date: Mon, 25 Nov 2024 17:06:56 +0000 Subject: [PATCH] AudioFormatReader: Update searchForLevel to work for more than two channels --- .../format/juce_AudioFormatReader.cpp | 53 +++++++------------ 1 file changed, 18 insertions(+), 35 deletions(-) diff --git a/modules/juce_audio_formats/format/juce_AudioFormatReader.cpp b/modules/juce_audio_formats/format/juce_AudioFormatReader.cpp index 57efbccf7d..5d61027bc5 100644 --- a/modules/juce_audio_formats/format/juce_AudioFormatReader.cpp +++ b/modules/juce_audio_formats/format/juce_AudioFormatReader.cpp @@ -299,11 +299,12 @@ int64 AudioFormatReader::searchForLevel (int64 startSample, return -1; const int bufferSize = 4096; - HeapBlock tempSpace (bufferSize * 2 + 64); + const size_t channels = numChannels; + HeapBlock tempSpace (bufferSize * channels + 64); + std::vector channelPointers (channels); - int* tempBuffer[3] = { tempSpace.get(), - tempSpace.get() + bufferSize, - nullptr }; + for (auto [index, ptr] : enumerate (channelPointers, size_t{})) + ptr = tempSpace + (bufferSize * index); int consecutive = 0; int64 firstMatchPos = -1; @@ -326,7 +327,7 @@ int64 AudioFormatReader::searchForLevel (int64 startSample, if (bufferStart >= lengthInSamples) break; - read (tempBuffer, 2, bufferStart, numThisTime, false); + read (channelPointers.data(), (int) channels, bufferStart, numThisTime, false); auto num = numThisTime; while (--num >= 0) @@ -334,43 +335,25 @@ int64 AudioFormatReader::searchForLevel (int64 startSample, if (numSamplesToSearch < 0) --startSample; - bool matches = false; auto index = (int) (startSample - bufferStart); - if (usesFloatingPointData) + const auto matches = std::invoke ([&] { - const float sample1 = std::abs (((float*) tempBuffer[0]) [index]); - - if (sample1 >= magnitudeRangeMinimum - && sample1 <= magnitudeRangeMaximum) + if (usesFloatingPointData) { - matches = true; + return std::any_of (channelPointers.begin(), channelPointers.end(), [&] (const auto& ptr) + { + const float sample = std::abs (((float*) ptr) [index]); + return magnitudeRangeMinimum <= sample && sample <= magnitudeRangeMaximum; + }); } - else if (numChannels > 1) - { - const float sample2 = std::abs (((float*) tempBuffer[1]) [index]); - matches = (sample2 >= magnitudeRangeMinimum - && sample2 <= magnitudeRangeMaximum); - } - } - else - { - const int sample1 = std::abs (tempBuffer[0] [index]); - - if (sample1 >= intMagnitudeRangeMinimum - && sample1 <= intMagnitudeRangeMaximum) + return std::any_of (channelPointers.begin(), channelPointers.end(), [&] (const auto& ptr) { - matches = true; - } - else if (numChannels > 1) - { - const int sample2 = std::abs (tempBuffer[1][index]); - - matches = (sample2 >= intMagnitudeRangeMinimum - && sample2 <= intMagnitudeRangeMaximum); - } - } + const int sample = std::abs (ptr[index]); + return intMagnitudeRangeMinimum <= sample && sample <= intMagnitudeRangeMaximum; + }); + }); if (matches) {