diff --git a/README.md b/README.md index 0d17d69..391d9c3 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ A collection of SuperCollider plugins developed by Jeff Martin (www.jeffreymarti ## List of Plugins ### PV_PlayBufStretch -A phase vocoder STFT buffer player for time stretching, for use with PV_RecordBuf in the sc3plugins distribution. It incorporates two different optional phase locking algorithms. +A phase vocoder STFT buffer player for time stretching, for use with PV_RecordBuf in the sc3plugins distribution. It has four different phase interpolation modes--the traditional method, two phase locking strategies, and the RTPGHI algorithm. ### PV_CFreeze A SuperCollider implementation of Jean-François Charles' Max patch for freezing [(the Max patch is available here)](https://newfloremusic.gumroad.com/). diff --git a/src/pv/CMakeLists.txt b/src/pv/CMakeLists.txt index 74de74a..739604e 100644 --- a/src/pv/CMakeLists.txt +++ b/src/pv/CMakeLists.txt @@ -1,11 +1,15 @@ -# Create the project library add_library(pv MODULE pv.cpp) +add_library(hashtable STATIC hashtable.cpp) +add_library(peakFinder STATIC peakFinder.cpp) add_library(pvCFreeze STATIC pvCFreeze.cpp) add_library(pvOther STATIC pvOther.cpp) add_library(pvStretch STATIC pvStretch.cpp) +set_target_properties(hashtable PROPERTIES POSITION_INDEPENDENT_CODE ON) +set_target_properties(peakFinder PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(pvCFreeze PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(pvOther PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(pvStretch PROPERTIES POSITION_INDEPENDENT_CODE ON) +target_link_libraries(pvStretch PRIVATE hashtable peakFinder) target_link_libraries(pv PRIVATE pvCFreeze pvOther pvStretch) if(SUPERNOVA) diff --git a/src/pv/PV_PlayBufStretch.schelp b/src/pv/PV_PlayBufStretch.schelp index 6a7bb2b..34fdee7 100644 --- a/src/pv/PV_PlayBufStretch.schelp +++ b/src/pv/PV_PlayBufStretch.schelp @@ -7,19 +7,22 @@ related:: Guides/FFT-Overview Description:: PV_PlayBufStretch is a phase vocoder buffer player for time stretching. It differs from link::Classes/PV_BufRd:: -in that it has a phase locking feature. Phase locking is a strategy that is used to reduce -"phasiness"--a reverberant sound caused by phase misalignment in adjacent bins. -The idea is that you want the phases of peak bins to dominate the phases of adjacent bins. -This makes sense intuitively because we know that in an FFT, the energy of a partial is spread -across several bins. PV_PlayBufStretch implements two classic phase locking algorithms--an -algorithm by Miller Puckette,footnote::Puckette, Miller. "Phase-locked vocoder." 1995 IEEE Workshop on Applications of Signal Processing to Audio and Acoustics (1995), 222-225.:: -and a later peak-picking algorithm (called "identity phase locking") -by Jean Laroche and Mark Dolson.footnote::Laroche, Jean, and Mark Dolson. "Improved Phase Vocoder Time-Scale Modification of Audio." IEEE Transactions on Speech and Audio Processing, 7, no. 3 (1999), 323-332.:: - -You will want to choose the algorithm based on the sound it produces. In some cases, you may not -wish to use phase locking at all. Traditionally, one would use a hop size of 0.25 or less along with an -appropriate window (like the Hann window) in the STFT. Laroche and Dolson write that for identity -phase locking, a hop size of 0.5 is feasible. +in that it has four different phase interpolation modes: + +list:: +## Mode 0 is the classical phase vocoder. +## Mode 1 is a simple phase locking strategy devised by Miller Puckette footnote::Puckette, Miller. "Phase-locked vocoder." 1995 IEEE Workshop on Applications of Signal Processing to Audio and Acoustics (1995), 222-225.::. +## Mode 2 is a peak-picking phase locking strategy by Jean Laroche and Mark Dolson footnote::Laroche, Jean, and Mark Dolson. "Improved Phase Vocoder Time-Scale Modification of Audio." IEEE Transactions on Speech and Audio Processing, 7, no. 3 (1999), 323-332.::. +## Mode 3 is the real-time phase gradient heap integration (RTPGHI) algorithm by Zdeněk Průša and Nicki Holighaus footnote::Průša, Zdeněk and Nicki Holighaus. "Phase Vocoder Done Right."::. +:: + +In the classical phase vocoder, the phases of adjacent bins slowly drift out of alignment. +This causes a reverberant sound effect called "phasiness." Modes 1-3 of PV_PlayBufStretch +attempt to alleviate this problem by synchronizing the phases of adjacent bins to some extent. + +You will want to choose the algorithm based on the sound it produces. +Traditionally, one would use a hop size of 0.25 or less along with an +appropriate window (like the Hann window) in the STFT. classmethods:: @@ -47,9 +50,10 @@ result in time shrink. Negative rates result in backwards playback. argument::loop Whether (1.0) or not (0.0) to loop when the end of the stftBuffer is reached -argument::phaseLock -The phase locking strategy to adopt. 0.0 means no phase locking, 1.0 means Puckette-style -phase locking, and 2.0 means Laroche/Dolson identity phase locking. +argument::mode +The phase vocoder mode to adopt. 0 - classical phase vocoder, 1 - Puckette-style +phase locking, 2 - Laroche/Dolson identity phase locking, 3 - RTPGHI phase gradient algorithm. +The default is 3. argument::peakRadius The radius for the peak-picker in the Laroche/Dolson identity phase locking @@ -58,6 +62,9 @@ strong::peakRadius:: bins to either side. This parameter can only be set on cons and is clipped internally to the range [1, 32]. Laroche and Dolson suggest a radius of 2, which is the default here. +argument::tol +The tolerance for the RTPGHI algorithm. It is clipped internally to between 0 and 1. + argument::doneAction The action to take after playback is completed @@ -86,13 +93,13 @@ SynthDef(\rec, { }).add; SynthDef(\play2, { - arg recBuf, rate=1, phaseLock=0, loop=0, startPos=0; + arg recBuf, rate=1, mode=0, tol=0.1, loop=0, startPos=0; var sig, chain; // Note that you must specify the appropriate hop size in FFTTrigger. // Also note that the FFT size must be the same as the FFT size of // the original analysis. chain = FFTTrigger(LocalBuf(2048), 0.25, 1.0); - chain = PV_PlayBufStretch(chain, recBuf, startPos, rate, loop, phaseLock, 2.0, Done.freeSelf); + chain = PV_PlayBufStretch(chain, recBuf, startPos, rate, loop, mode, 2.0, tol, Done.freeSelf); // Use the same window type that was used for analysis. sig = IFFT(chain, 1); Out.ar(0, Pan2.ar(sig)); @@ -100,7 +107,7 @@ SynthDef(\play2, { ) Synth(\rec, [\recBuf, y, \soundBuf, z]); -b = Synth(\play2, [\recBuf, y, \rate, 0.5, \loop, 1.0, \startPos, 0.0, \phaseLock, 2.0]); +b = Synth(\play2, [\recBuf, y, \rate, 0.5, \loop, 1.0, \startPos, 0.0, \mode, 3, \tol, 0.1]); // A more unusual take. Here we modulate the playback rate, and it can go negative. ( diff --git a/src/pv/hashtable.cpp b/src/pv/hashtable.cpp new file mode 100644 index 0000000..74dd2f7 --- /dev/null +++ b/src/pv/hashtable.cpp @@ -0,0 +1,214 @@ +/* +File: hashtable.cpp +Author: Jeff Martin + +Description: +A simple int hash set (table size must be power of 2) + +Copyright © 2026 by Jeffrey Martin. All rights reserved. +Website: https://www.jeffreymartincomposer.com + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "hashtable.hpp" +#include +#include + +// hash function from claude +// table bits is the power of 2 size of the table +static inline uint32_t hash32(uint32_t key, int table_bits) { + return (key * 2654435769u) >> (32 - table_bits); +} + +FlexPlugins::IntHashSet::IntHashSet(double maxLoadFactor) : + m_table(nullptr), + m_rehashTable(nullptr), + m_originalAlloc(nullptr), + m_size(0), + m_maxSize(0), + m_tableBits(0), + m_currentLoadFactor(0), + m_hasTombstones(false) +{ + if (maxLoadFactor > 0 && maxLoadFactor < 1) { + m_maxLoadFactor = maxLoadFactor; + } else { + m_maxLoadFactor = 0.7; + } +} + +void FlexPlugins::IntHashSet::clear() { + m_size = 0; + m_hasTombstones = false; + m_currentLoadFactor = 0; + for (size_t i = 0; i < m_maxSize; i++) { + m_table[i].isTombstone = false; + m_table[i].isNull = true; + m_table[i].data = 0; + } +} + +size_t FlexPlugins::IntHashSet::maxSize() const { + return m_maxSize; +} + +size_t FlexPlugins::IntHashSet::size() const { + return m_size; +} + +void FlexPlugins::IntHashSet::memLoad(void* mem, size_t nbytes) { + m_table = static_cast(mem); + m_originalAlloc = mem; + m_maxSize = (nbytes / 2) / sizeof(IntHashSetNode); + // hash table size must be power of 2 + m_tableBits = static_cast(std::log2(static_cast(m_maxSize))); + m_maxSize = 0x1 << m_tableBits; + // the upper half of the allocation will be the rehash table + m_rehashTable = m_table + m_maxSize; + for (size_t i = 0; i < m_maxSize; i++) { + m_table[i] = IntHashSetNode(); + } +} + +void* FlexPlugins::IntHashSet::memRetrieve() { + return m_originalAlloc; +} + +size_t FlexPlugins::IntHashSet::memSize(size_t maxSize) const { + // need to allocate 2x size because we need second rehash table + return maxSize * 2 * sizeof(IntHashSetNode); +} + +bool FlexPlugins::IntHashSet::insert(int data) { + if (m_currentLoadFactor > m_maxLoadFactor) { + if (m_hasTombstones) { + IntHashSetNode *swap = m_table; + m_table = m_rehashTable; + m_rehashTable = swap; + m_hasTombstones = false; + m_size = 0; + m_currentLoadFactor = 0; + for (size_t i = 0; i < m_maxSize; i++) { + m_table[i].data = 0; + m_table[i].isNull = true; + m_table[i].isTombstone = false; + } + for (size_t i = 0; i < m_maxSize; i++) { + if (!m_rehashTable[i].isNull) { + bool result = insert(m_rehashTable[i].data); + if (!result) return false; + } + } + } + if (m_currentLoadFactor > m_maxLoadFactor) { + return false; + } + } + + // hash and insert the data + size_t idx = hash32(static_cast(data), m_tableBits); + if (m_table[idx].isNull && !m_table[idx].isTombstone) { + m_table[idx].data = data; + m_table[idx].isNull = false; + m_size++; + m_currentLoadFactor += 1/static_cast(m_maxSize); + return true; + } else if (m_table[idx].data == data && !m_table[idx].isTombstone) { + // no duplicate inserts allowed + return false; + } else { + // linear probing + for (size_t i = idx+1; i < m_maxSize; i++) { + if (m_table[i].isNull && !m_table[i].isTombstone) { + m_table[i].data = data; + m_table[i].isNull = false; + m_size++; + m_currentLoadFactor += 1/static_cast(m_maxSize); + return true; + } else if (m_table[i].data == data && !m_table[i].isTombstone) { + // no duplicate inserts allowed + return false; + } + } + for (size_t i = 0; i < idx; i++) { + if (m_table[i].isNull && !m_table[i].isTombstone) { + m_table[i].data = data; + m_table[i].isNull = false; + m_size++; + m_currentLoadFactor += 1/static_cast(m_maxSize); + return true; + } else if (m_table[i].data == data && !m_table[i].isTombstone) { + // no duplicate inserts allowed + return false; + } + } + return false; + } +} + +int FlexPlugins::IntHashSet::ifind(int data) { + int idx = static_cast(hash32(static_cast(data), m_tableBits)); + if (m_table[idx].isNull && !m_table[idx].isTombstone) { + return -1; + } else { + if (!m_table[idx].isNull && m_table[idx].data == data) { + return idx; + } else { + for (int i = idx+1; i < m_maxSize; i++) { + // the probing would have stopped here, so the item was not inserted + if (m_table[i].isNull) { + if (!m_table[i].isTombstone) { + return -1; + } + } else if (m_table[i].data == data) { + return i; + } + } + for (int i = 0; i < idx; i++) { + // the probing would have stopped here, so the item was not inserted + if (m_table[i].isNull) { + if (!m_table[i].isTombstone) { + return -1; + } + } else if (m_table[i].data == data) { + return i; + } + } + } + return -1; + } +} + +bool FlexPlugins::IntHashSet::find(int data) { + if (ifind(data) >= 0) { + return true; + } else { + return false; + } +} + +bool FlexPlugins::IntHashSet::remove(int data) { + int idx = ifind(data); + if (idx < 0) { + return false; + } else { + m_table[idx].data = 0; + m_table[idx].isNull = true; + m_table[idx].isTombstone = true; + m_hasTombstones = true; + m_size--; + return true; + } +} \ No newline at end of file diff --git a/src/pv/hashtable.hpp b/src/pv/hashtable.hpp new file mode 100644 index 0000000..fa85d0f --- /dev/null +++ b/src/pv/hashtable.hpp @@ -0,0 +1,118 @@ +/* +File: hashtable.hpp +Author: Jeff Martin + +Description: +A simple int hash set (table size must be power of 2) + +Copyright © 2026 by Jeffrey Martin. All rights reserved. +Website: https://www.jeffreymartincomposer.com + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include + +namespace FlexPlugins { + class TestIntHashSet; + + struct IntHashSetNode { + IntHashSetNode() : data(0), isTombstone(false), isNull(true) {} + int data; + bool isTombstone; + bool isNull; + }; + + /// A key-only hash table with linear probing. No resizing is allowed-- + /// once the load factor is exceeded, all entries will fail until an + /// item has been removed from the table. This is to avoid + /// reallocation on the fly. + class IntHashSet { + public: + /// Creates a new IntHashSet + IntHashSet(double maxLoadFactor=0.7); + + /// Inserts an item into the hash set using linear probing + /// + /// \param data The data to insert + /// \returns Whether or not insertion was successful + bool insert(int data); + + /// Finds an item in the hash set + /// + /// \param data The data to find + /// \returns Whether or not the data is present + bool find(int data); + + /// Removes an item from the hash set + /// + /// \param data The data to remove + /// \returns Whether or not the data was removed + bool remove(int data); + + /// Clears the hash set + void clear(); + + /// Gets the maximum number of items that can be stored in the hash set + /// + /// \returns The maximum number of items that can be stored in the hash set + size_t maxSize() const; + + /// Loads memory into the hash set + /// + /// \param mem The memory to load + /// \param nbytes The number of bytes allocated + void memLoad(void* mem, size_t nbytes); + + /// Retrieves the hash set memory for destruction + /// + /// \returns The memory allocated for the hash set + void* memRetrieve(); + + /// Gets the size required for memory allocation for the hash set + /// + /// \param maxSize The max size needed + /// \returns The size required for the hash set memory + size_t memSize(size_t maxSize) const; + + /// Gets the number of items stored in the hash set + /// + /// \returns The number of items stored in the hash set + size_t size() const; + + double currentLoadFactor() const { return m_currentLoadFactor; } + double maxLoadFactor() const { return m_maxLoadFactor; } + size_t tableBits() const { return m_tableBits; } + bool hasTombstones() const { return m_hasTombstones; } + + private: + /// Finds the index of an item if it is stored in the hash set + /// + /// \param data The data to find + /// \returns The index if it is present, or -1 + int ifind(int data); + + IntHashSetNode* m_table; + IntHashSetNode* m_rehashTable; + void* m_originalAlloc; + size_t m_size; + size_t m_maxSize; + size_t m_tableBits; + double m_currentLoadFactor; + double m_maxLoadFactor; + bool m_hasTombstones; + + friend class TestIntHashSet; + }; +} diff --git a/src/pv/peakFinder.cpp b/src/pv/peakFinder.cpp new file mode 100644 index 0000000..1e98717 --- /dev/null +++ b/src/pv/peakFinder.cpp @@ -0,0 +1,137 @@ +/* +File: peakFinder.cpp +Author: Jeff Martin + +Description: +A peak finder for the Laroche/Dolson phase locking algorithm. + +Copyright © 2026 by Jeffrey Martin. All rights reserved. +Website: https://www.jeffreymartincomposer.com + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include "peakFinder.hpp" + +FlexPlugins::Peak::Peak(size_t peak) : peak(peak) {} +FlexPlugins::Peak::Peak(size_t peak, size_t leftValley, size_t rightValley) : peak(peak), leftValley(leftValley), rightValley(rightValley) {} + +FlexPlugins::PeakFinder::PeakFinder(size_t fftSize, size_t radius) { + m_maxSize = fftSize/2-1; + m_radius = radius; + m_size = 0; + peaks = nullptr; + m_queueL = nullptr; + m_queueR = nullptr; +} + +void FlexPlugins::PeakFinder::memLoad(void* arr) { + size_t *data = (size_t*)arr; + m_queueL = data; + m_queueR = data + m_radius; + peaks = (Peak*)(data + 2 * m_radius); +} + +size_t FlexPlugins::PeakFinder::memSize() const { + return m_radius * 2 * sizeof(size_t) + m_maxSize * sizeof(Peak); +} + +void* FlexPlugins::PeakFinder::memRetrieve() { + return (void*)m_queueL; +} + +void FlexPlugins::PeakFinder::clear() { + m_size = 0; +} + +size_t FlexPlugins::PeakFinder::maxSize() const { + return m_maxSize; +} + +size_t FlexPlugins::PeakFinder::size() const { + return m_size; +} + +void FlexPlugins::PeakFinder::analyze(const SCPolarBuf *buf) { + // We can only perform the analysis if we have enough bins + if (m_queueL && m_maxSize > m_radius * 2 + 1) { + m_size = 0; // clear any existing data + + size_t i = m_radius; + while (i < m_maxSize - m_radius) { + bool isMax = true; + for (size_t j = i - m_radius; j < i; j++) { + if (buf->bin[j].mag >= buf->bin[i].mag) { + isMax = false; + break; + } + } + for (size_t j = i + 1; j <= i + m_radius; j++) { + if (buf->bin[j].mag >= buf->bin[i].mag) { + isMax = false; + break; + } + } + if (isMax) { + peaks[m_size] = Peak(i); + m_size++; + i += m_radius + 1; + } else { + i++; + } + } + + // Find the left valley for the first peak, and the right valley + // for the last peak. + if (m_size > 0) { + float min = buf->bin[0].mag; + size_t argmin = 0; + size_t k = 1; + for (; k < peaks[0].peak; k++) { + if (buf->bin[k].mag < min) { + min = buf->bin[k].mag; + argmin = k; + } + } + peaks[0].leftValley = argmin; + k = peaks[m_size-1].peak + 1; + min = buf->bin[k].mag; + argmin = k; + for (k++; k < m_maxSize; k++) { + if (buf->bin[k].mag < min) { + min = buf->bin[k].mag; + argmin = k; + } + } + peaks[m_size-1].rightValley = argmin; + } + + // Find the remaining left and right valleys + if (m_size > 1) { + for (size_t j = 0; j < m_size-1; j++) { + size_t k = peaks[j].peak + 1; + float min = buf->bin[k].mag; + size_t argmin = k; + for (k++; k < peaks[j+1].peak; k++) { + if (buf->bin[k].mag < min) { + min = buf->bin[k].mag; + argmin = k; + } + } + peaks[j].rightValley = argmin - 1; + peaks[j+1].leftValley = argmin; + } + } + } +} \ No newline at end of file diff --git a/src/pv/peakFinder.hpp b/src/pv/peakFinder.hpp new file mode 100644 index 0000000..aca68cf --- /dev/null +++ b/src/pv/peakFinder.hpp @@ -0,0 +1,82 @@ +/* +File: peakFinder.hpp +Author: Jeff Martin + +Description: +A peak finder for the Laroche/Dolson phase locking algorithm. + +Copyright © 2026 by Jeffrey Martin. All rights reserved. +Website: https://www.jeffreymartincomposer.com + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include +#include "FFT_UGens.h" + +namespace FlexPlugins { + class Peak { + public: + Peak(size_t peak); + Peak(size_t peak, size_t leftValley, size_t rightValley); + size_t peak, leftValley, rightValley; + }; + + class PeakFinder { + public: + /// Constructs the PeakFinder + /// + /// \param fftSize The FFT size + PeakFinder(size_t fftSize, size_t radius); + + /// Finds peaks in the provided SCPolarBuf. Note that this buffer must correspond + /// to the original FFT size provided for the PeakFinder--otherwise memory errors may occur. + /// + /// \param buf The buffer to analyze + void analyze(const SCPolarBuf *buf); + + /// Loads memory from the external SuperCollider allocator. Memory is allocated + /// using RTAlloc() and the size is specified by the memSize() method. + /// + /// \param arr The allocated memory + void memLoad(void *arr); + + /// Gets the memory size required for the PeakFinder + size_t memSize() const; + + /// Gets the max size of the PeakFinder + /// + /// \returns The max size + size_t maxSize() const; + + /// Gets the current size of the PeakFinder (the number of peaks stored) + /// + /// \returns The current size + size_t size() const; + + /// Clears the PeakFinder + void clear(); + + /// Gets a pointer to the memory that was allocated for the PeakFinder + /// so that it can be deallocated + /// + /// \return The memory pointer + void* memRetrieve(); + + Peak *peaks; + private: + size_t m_maxSize, m_size, m_radius; + size_t *m_queueL, *m_queueR; + }; +} \ No newline at end of file diff --git a/src/pv/pqueue.hpp b/src/pv/pqueue.hpp new file mode 100644 index 0000000..0bd9f83 --- /dev/null +++ b/src/pv/pqueue.hpp @@ -0,0 +1,328 @@ +/* +File: pqueue.hpp +Author: Jeff Martin + +Description: +A min and max heap implemented using arrays. +Functions as a priority queue. + +Copyright © 2026 by Jeffrey Martin. All rights reserved. +Website: https://www.jeffreymartincomposer.com + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include +#include + +namespace FlexPlugins { + template + class TestMinPQueue; + + template + class TestMaxPQueue; + + template + class PQueue { + public: + PQueue(); + + /// Clears the queue + void clear(); + + virtual bool insert(K key, V val) = 0; + + virtual std::pair pop() = 0; + + /// Peeks at the top of the priority queue without removing it + /// + /// \returns The top element on the priority queue + std::pair peek() const; + + /// Gets the maximum number of items that can be stored in the priority queue + /// + /// \returns The maximum number of items that can be stored in the priority queue + size_t maxSize() const; + + /// Loads memory into the priority queue + /// + /// \param mem The memory to load + /// \param nbytes The number of bytes allocated + void memLoad(void* mem, size_t nbytes); + + /// Retrieves the priority queue memory for destruction + /// + /// \returns The memory allocated for the priority queue + void* memRetrieve(); + + /// Gets the size required for memory allocation for the priority queue + /// + /// \param queueSize The intended size of the priority queue + /// \returns The size required for the priority queue memory + size_t memSize(size_t queueSize) const; + + /// Gets the number of items stored in the priority queue + /// + /// \returns The number of items stored in the priority queue + size_t size() const; + + protected: + std::pair* m_heap; + size_t m_size; + size_t m_maxSize; + }; + + template + class MinPQueue : public PQueue { + public: + /// Constructs the priority queue + /// + /// \param maxSize The max size allowed in the priority queue + MinPQueue() : PQueue() {} + + /// Inserts an element into the priority queue + /// + /// \param data The data to insert + /// \returns Whether or not the insert was successful + bool insert(K key, V val) override; + + /// Removes and returns the top element on the priority queue + /// + /// \returns The top element on the priority queue + std::pair pop() override; + + friend class TestMinPQueue; + }; + + template + class MaxPQueue : public PQueue { + public: + /// Constructs the priority queue + /// + /// \param maxSize The max size allowed in the priority queue + MaxPQueue() : PQueue() {} + + /// Inserts an element into the priority queue + /// + /// \param data The data to insert + /// \returns Whether or not the insert was successful + bool insert(K key, V val) override; + + /// Removes and returns the top element on the priority queue + /// + /// \returns The top element on the priority queue + std::pair pop() override; + + friend class TestMaxPQueue; + }; +} + +template +FlexPlugins::PQueue::PQueue() { + this->m_maxSize = 0; + this->m_heap = nullptr; + this->m_size = 0; +} + +template +void FlexPlugins::PQueue::clear() { + this->m_size = 0; +} + +template +size_t FlexPlugins::PQueue::maxSize() const { + return this->m_maxSize - 1; +} + +template +size_t FlexPlugins::PQueue::memSize(size_t queueSize) const { + return (queueSize + 1) * sizeof(std::pair); +} + +template +void FlexPlugins::PQueue::memLoad(void* mem, size_t nbytes) { + this->m_heap = static_cast*>(mem); + this->m_maxSize = nbytes / sizeof(std::pair); +} + +template +void* FlexPlugins::PQueue::memRetrieve() { + return static_cast(this->m_heap); +} + +template +std::pair FlexPlugins::PQueue::peek() const { + if (this->m_size > 1) { + return this->m_heap[1]; + } else { + return 0; + } +} + +template +size_t FlexPlugins::PQueue::size() const { + if (this->m_size > 0) { + return this->m_size - 1; + } else { + return 0; + } +} + +template +bool FlexPlugins::MinPQueue::insert(K key, V val) { + if (this->m_size == 0) { + this->m_size++; + } + if (this->m_size == this->m_maxSize) { + return false; + } else { + size_t idx = this->m_size; + this->m_heap[idx] = std::pair(key, val); + this->m_size++; + + // Bubble up + while (idx > 1) { + size_t parentIdx = idx; + if (parentIdx % 2 == 1) + parentIdx--; + parentIdx >>= 1; + if (this->m_heap[idx].first < this->m_heap[parentIdx].first) { + std::pair swapVal = this->m_heap[idx]; + this->m_heap[idx] = this->m_heap[parentIdx]; + this->m_heap[parentIdx] = swapVal; + } + idx = parentIdx; + } + return true; + } +} + +template +bool FlexPlugins::MaxPQueue::insert(K key, V val) { + if (this->m_size == 0) { + this->m_size++; + } + if (this->m_size == this->m_maxSize) { + return false; + } else { + size_t idx = this->m_size; + this->m_heap[idx] = std::pair(key, val); + this->m_size++; + + // Bubble up + while (idx > 1) { + size_t parentIdx = idx; + if (parentIdx % 2 == 1) + parentIdx--; + parentIdx >>= 1; + if (this->m_heap[idx].first > this->m_heap[parentIdx].first) { + std::pair swapVal = this->m_heap[idx]; + this->m_heap[idx] = this->m_heap[parentIdx]; + this->m_heap[parentIdx] = swapVal; + } + idx = parentIdx; + } + return true; + } +} + +template +std::pair FlexPlugins::MinPQueue::pop() { + if (this->m_size > 1) { + std::pair val = this->m_heap[1]; + this->m_heap[1] = this->m_heap[this->m_size-1]; + this->m_size--; + size_t idx = 1; + // Bubble down + while (idx < this->m_size) { + size_t leftChild = idx * 2; + size_t rightChild = leftChild + 1; + if (rightChild < this->m_size) { + if (this->m_heap[leftChild].first <= this->m_heap[rightChild].first && this->m_heap[idx].first > this->m_heap[leftChild].first) { + std::pair swapVal = this->m_heap[leftChild]; + this->m_heap[leftChild] = this->m_heap[idx]; + this->m_heap[idx] = swapVal; + idx = leftChild; + } else if (this->m_heap[leftChild].first > this->m_heap[rightChild].first && this->m_heap[idx].first > this->m_heap[rightChild].first) { + std::pair swapVal = this->m_heap[rightChild]; + this->m_heap[rightChild] = this->m_heap[idx]; + this->m_heap[idx] = swapVal; + idx = rightChild; + } else { + break; + } + } else if (leftChild < this->m_size) { + if (this->m_heap[idx].first > this->m_heap[leftChild].first) { + std::pair swapVal = this->m_heap[leftChild]; + this->m_heap[leftChild] = this->m_heap[idx]; + this->m_heap[idx] = swapVal; + idx = leftChild; + } + break; + } else { + break; + } + } + return val; + } else { + std::pair val; + val.first = 0; + return val; + } +} + +template +std::pair FlexPlugins::MaxPQueue::pop() { + if (this->m_size > 1) { + std::pair val = this->m_heap[1]; + this->m_heap[1] = this->m_heap[this->m_size-1]; + this->m_size--; + size_t idx = 1; + // Bubble down + while (idx < this->m_size) { + size_t leftChild = idx * 2; + size_t rightChild = leftChild + 1; + if (rightChild < this->m_size) { + if (this->m_heap[leftChild].first >= this->m_heap[rightChild].first && this->m_heap[idx].first < this->m_heap[leftChild].first) { + std::pair swapVal = this->m_heap[leftChild]; + this->m_heap[leftChild] = this->m_heap[idx]; + this->m_heap[idx] = swapVal; + idx = leftChild; + } else if (this->m_heap[leftChild].first < this->m_heap[rightChild].first && this->m_heap[idx].first < this->m_heap[rightChild].first) { + std::pair swapVal = this->m_heap[rightChild]; + this->m_heap[rightChild] = this->m_heap[idx]; + this->m_heap[idx] = swapVal; + idx = rightChild; + } else { + break; + } + } else if (leftChild < this->m_size) { + if (this->m_heap[idx].first < this->m_heap[leftChild].first) { + std::pair swapVal = this->m_heap[leftChild]; + this->m_heap[leftChild] = this->m_heap[idx]; + this->m_heap[idx] = swapVal; + idx = leftChild; + } + break; + } else { + break; + } + } + return val; + } else { + std::pair val; + val.first = 0; + return val; + } +} \ No newline at end of file diff --git a/src/pv/pv.sc b/src/pv/pv.sc index b584a81..2c7de03 100644 --- a/src/pv/pv.sc +++ b/src/pv/pv.sc @@ -75,7 +75,7 @@ PV_MagXFade : PV_ChainUGen { // A phase vocoder buffer player PV_PlayBufStretch : PV_ChainUGen { *new { - arg buffer, stftBuffer, startPos=0.0, rate=1.0, loop=0.0, phaseLock=0.0, peakRadius=2.0, doneAction=0; - ^this.multiNew('control', buffer, stftBuffer, startPos, rate, loop, phaseLock, peakRadius, doneAction); + arg buffer, stftBuffer, startPos=0.0, rate=1.0, loop=0.0, mode=0, peakRadius=2.0, tol=0.1, doneAction=0; + ^this.multiNew('control', buffer, stftBuffer, startPos, rate, loop, mode, peakRadius, tol, doneAction); } } \ No newline at end of file diff --git a/src/pv/pvStretch.cpp b/src/pv/pvStretch.cpp index 74ea4e1..973d4fd 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -23,10 +23,11 @@ along with this program. If not, see . */ #include "pvStretch.hpp" +#include "FFT_UGens.h" #include "SC_Constants.h" +#include "SC_InterfaceTable.h" #include #include -#define INTERP(a, b, pos) (a + (b-a) * pos) extern InterfaceTable *ft; @@ -44,16 +45,39 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { m_frameNext = nullptr; m_framePrev1 = nullptr; m_framePrev2 = nullptr; - size_t peakRadius = static_cast(sc_clip(in0(6), 1.f, 32.f)); - m_peakFinder = (PeakFinder*)RTAlloc(mWorld, sizeof(PeakFinder)); - new (m_peakFinder) PeakFinder(static_cast(buf->samples), peakRadius); - m_peakFinder->memLoad(RTAlloc(mWorld, m_peakFinder->memSize())); + m_cTimeGradient = nullptr; + m_pTimeGradient = nullptr; + m_freqGradient = nullptr; + + const size_t fftSize = static_cast(buf->samples); + // Set up the Laroche/Dolson peak finder + m_peakFinder = static_cast(RTAlloc(mWorld, sizeof(PeakFinder))); + new (m_peakFinder) PeakFinder(fftSize, static_cast(sc_clip(in0(6), 1.f, 32.f))); + m_peakFinder->memLoad(RTAlloc(mWorld, m_peakFinder->memSize())); + + // Set up the hash set and heap for the RTPGHI algorithm + m_setI = static_cast(RTAlloc(mWorld, sizeof(IntHashSet))); + new (m_setI) IntHashSet(0.7); + m_setI->memLoad(RTAlloc(mWorld, m_setI->memSize(fftSize * 2)), m_setI->memSize(fftSize * 2)); + m_pgHeap = static_cast>*>(RTAlloc(mWorld, sizeof(MaxPQueue>))); + new (m_pgHeap) MaxPQueue>(); + m_pgHeap->memLoad(RTAlloc(mWorld, m_pgHeap->memSize(fftSize)), m_pgHeap->memSize(fftSize)); + + // Set up the time and frequency gradient vectors + const size_t numScBins = fftSize/2-1; + m_cTimeGradient = static_cast(RTAlloc(mWorld, sizeof(float) * numScBins)); + m_pTimeGradient = static_cast(RTAlloc(mWorld, sizeof(float) * numScBins)); + m_freqGradient = static_cast(RTAlloc(mWorld, sizeof(float) * numScBins)); + for (size_t k = 0; k < numScBins; k++) { + m_cTimeGradient[k] = 0; + m_pTimeGradient[k] = 0; + m_freqGradient[k] = 0; + } + // Configure position - float startPos = sc_clip(in0(2), 0.0, 1.0); - m_pos = 0.f; - m_startPos = startPos; - m_firstFrame = true; + m_pos = 0.f; // the current position in the buffer + m_startPos = -1.f; // this forces the first frame to read phase data directly set_calc_function(); next(1); @@ -67,6 +91,20 @@ FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { } RTFree(mWorld, m_peakFinder); } + if (m_setI) { + void *reservedMem = m_setI->memRetrieve(); + if (reservedMem) { + RTFree(mWorld, reservedMem); + } + RTFree(mWorld, m_setI); + } + if (m_pgHeap) { + void *reservedMem = m_pgHeap->memRetrieve(); + if (reservedMem) { + RTFree(mWorld, reservedMem); + } + RTFree(mWorld, m_pgHeap); + } if (m_outFramePrev) { RTFree(mWorld, m_outFramePrev); } @@ -79,6 +117,15 @@ FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { if (m_framePrev2) { RTFree(mWorld, m_framePrev2); } + if (m_cTimeGradient) { + RTFree(mWorld, m_cTimeGradient); + } + if (m_pTimeGradient) { + RTFree(mWorld, m_pTimeGradient); + } + if (m_freqGradient) { + RTFree(mWorld, m_freqGradient); + } } void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { @@ -122,6 +169,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { // Basic information const size_t stftBufFftSize = static_cast(bufData[0]); const size_t stftBufHopSize = static_cast(bufData[1] * stftBufFftSize); // in frames, not fraction + const size_t stftBufNumOrigAudioFrames = (stftFrames - 1) * stftBufHopSize + stftBufFftSize; // number of original audio samples for RTPGHI algorithm const int stftBufWinType = static_cast(bufData[2]); // -1, 0, or 1. This information is probably extraneous. if (stftBufFftSize != buf->samples) { @@ -141,20 +189,24 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { float *frameNext = (float*)RTAlloc(mWorld, stftBufFftSize * sizeof(float)); float *framePrev1 = (float*)RTAlloc(mWorld, stftBufFftSize * sizeof(float)); float *framePrev2 = (float*)RTAlloc(mWorld, stftBufFftSize * sizeof(float)); + // uggggghh m_outFramePrev = (SCPolarBuf*)outFramePrev; m_frameNext = (SCPolarBuf*)frameNext; m_framePrev1 = (SCPolarBuf*)framePrev1; m_framePrev2 = (SCPolarBuf*)framePrev2; } - float startPos = sc_clip(in0(2), 0.0, 1.0); + float startPos = sc_clip(in0(2), 0.f, 1.f); const float rate = in0(3); const float loop = in0(4); + + // If we're on the first frame, we'll just read phase data directly. + bool firstFrame = false; + // If the start position changed, we jump directly to the new start position. if (startPos != m_startPos) { m_startPos = startPos; - m_firstFrame = true; - // std::cout << "Start pos changed\n"; + firstFrame = true; } // Now that we've run setup, we're ready to read STFT data and perform phase vocoder stretching. @@ -163,7 +215,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { float newPos = m_pos + rate; if (newPos > stftFrames - 1) { if (loop && rate > 0) { - m_firstFrame = true; + firstFrame = true; startPos = 0; } else if (rate <= 0) { // clip it to the last possible frame if we're working backwards @@ -172,12 +224,12 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { float *outBuf = out(0); outBuf[0] = -1.f; RELEASE_SNDBUF_SHARED(stftBuf); - DoneAction(static_cast(in0(7)), this); + DoneAction(static_cast(in0(8)), this); return; } } else if (newPos < 0) { if (loop && rate < 0) { - m_firstFrame = true; + firstFrame = true; startPos = 1; } else if (rate >= 0) { // clip it to the first frame if we're working forwards @@ -186,22 +238,22 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { float *outBuf = out(0); outBuf[0] = -1.f; RELEASE_SNDBUF_SHARED(stftBuf); - DoneAction(static_cast(in0(7)), this); + DoneAction(static_cast(in0(8)), this); return; } } // The first frame has to be cloned directly from the STFT buffer with no phase adjustments. // This is essential to make sure that subsequent phase calculations are correctly aligned. - if (m_firstFrame) { + if (firstFrame) { // Compute the index of the first frame size_t firstFrameIdx = static_cast(std::round(startPos * (stftFrames-1))); // Copy the FFT data over - SCPolarBuf *p = ToPolarApx(buf); + SCPolarBuf *outFrame = ToPolarApx(buf); const float *currentFftFrame = stftData + (firstFrameIdx * stftBufFftSize); // Fill the output buffer - fillPolarBuf(currentFftFrame, p, stftBufFftSize); + fillPolarBuf(currentFftFrame, outFrame, stftBufFftSize); // We always need to store the resultant FFT frame in the UGen. // It is used in the next call to PV_PlayBufStretch_next, for @@ -210,131 +262,225 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { // We have to advance by one frame because we need to be able to compute frequency for time stretching. m_pos = static_cast(firstFrameIdx + 1); - m_firstFrame = false; + firstFrame = false; } // For frames other than the first frame, we'll need to perform phase computation. else { - size_t phaseLock = sc_clip(static_cast(in0(5)), 0, 2); - SCPolarBuf *p = ToPolarApx(buf); - size_t roundedPos = static_cast(std::round(newPos)); + // The phase computation mode + size_t mode = sc_clip(static_cast(in0(5)), 0, 3); + SCPolarBuf *outFrame = ToPolarApx(buf); + + // The closest frame to the current position + int roundedPos = static_cast(std::round(newPos)); - // If we're right smack on a specific FFT frame, we don't - // need to do any magnitude or frequency interpolation, so - // we only need the current and previous FFT frames from the buffer. - if (std::abs(roundedPos-newPos) < 1e-3) { - size_t lastPos = rate >= 0 ? roundedPos - 1 : roundedPos + 1; - if (lastPos < 0) { - lastPos = roundedPos + 1; - } else if (lastPos >= stftFrames) { - lastPos = roundedPos - 1; - } - fillPolarBuf(stftData + (roundedPos * stftBufFftSize), m_frameNext, stftBufFftSize); - fillPolarBuf(stftData + (lastPos * stftBufFftSize), m_framePrev1, stftBufFftSize); - // Render the output FFT frame - switch (phaseLock) { - case 1: - Stretch2Puckette( - m_frameNext, - m_framePrev1, - p, - m_outFramePrev, - stftBufFftSize, - stftBufHopSize - ); - break; - case 2: - Stretch2LarocheDolson( - m_frameNext, - m_framePrev1, - p, - m_outFramePrev, - m_peakFinder, - stftBufFftSize, - stftBufHopSize - ); - break; - default: - Stretch2( - m_frameNext, - m_framePrev1, - p, - m_outFramePrev, - stftBufFftSize, - stftBufHopSize - ); + // For traditional phase vocoder methods (classical phase vocoder, phase locking), + // we use a two-frame stretch or a three-frame stretch depending on the current position. + if (mode < 3) { + // If we're right smack on a specific FFT frame, we don't + // need to do any magnitude or frequency interpolation, so + // we only need the current and previous FFT frames from the buffer. + if (std::abs(roundedPos-newPos) < 1e-3) { + size_t lastPos = rate >= 0 ? roundedPos - 1 : roundedPos + 1; + if (lastPos < 0) { + lastPos = roundedPos + 1; + } else if (lastPos >= stftFrames) { + lastPos = roundedPos - 1; + } + fillPolarBuf(stftData + (roundedPos * stftBufFftSize), m_frameNext, stftBufFftSize); + fillPolarBuf(stftData + (lastPos * stftBufFftSize), m_framePrev1, stftBufFftSize); + // Render the output FFT frame + switch (mode) { + case 1: + Stretch2Puckette( + m_frameNext, + m_framePrev1, + outFrame, + m_outFramePrev, + stftBufFftSize, + stftBufHopSize + ); + break; + case 2: + Stretch2LarocheDolson( + m_frameNext, + m_framePrev1, + outFrame, + m_outFramePrev, + stftBufFftSize, + stftBufHopSize + ); + break; + default: + Stretch2( + m_frameNext, + m_framePrev1, + outFrame, + m_outFramePrev, + stftBufFftSize, + stftBufHopSize + ); + } + + // Copy the magnitude data over + powerLinearInterp(nullptr, m_frameNext, outFrame, stftBufFftSize, 1.f); + } else { + // Otherwise we're between two FFT frames, and we're going to have to + // interpolate magnitude and frequency data. + int lo, hi, loMinus1; + float posFrac; + if (rate >= 0) { + lo = static_cast(std::floor(newPos)); + hi = static_cast(std::ceil(newPos)); + loMinus1 = lo == 0 ? 0 : lo - 1; + posFrac = newPos - static_cast(lo); + } else { + hi = static_cast(std::floor(newPos)); + lo = static_cast(std::ceil(newPos)); + loMinus1 = lo + 1; + if (loMinus1 >= stftFrames) loMinus1 = lo; + posFrac = newPos - static_cast(hi); + } + + // We are in between these two frames + fillPolarBuf(stftData + (hi * stftBufFftSize), m_frameNext, stftBufFftSize); + fillPolarBuf(stftData + (lo * stftBufFftSize), m_framePrev1, stftBufFftSize); + // This is the frame right before that. It's needed to compute the previous instantaneous frequencies. + fillPolarBuf(stftData + (loMinus1 * stftBufFftSize), m_framePrev2, stftBufFftSize); + + // Render the output FFT frame + switch (mode) { + case 1: + Stretch3Puckette( + m_frameNext, + m_framePrev1, + m_framePrev2, + outFrame, + m_outFramePrev, + posFrac, + stftBufFftSize, + stftBufHopSize + ); + break; + case 2: + Stretch3LarocheDolson( + m_frameNext, + m_framePrev1, + m_framePrev2, + outFrame, + m_outFramePrev, + posFrac, + stftBufFftSize, + stftBufHopSize + ); + break; + default: + Stretch3( + m_frameNext, + m_framePrev1, + m_framePrev2, + outFrame, + m_outFramePrev, + posFrac, + stftBufFftSize, + stftBufHopSize + ); + } + + // Interpolate the magnitude data using power level + powerLinearInterp(m_framePrev1, m_frameNext, outFrame, stftBufFftSize, posFrac); } - } else { - // Otherwise we're between two FFT frames, and we're going to have to - // interpolate magnitude and frequency data. - size_t lo, hi, loprev; - if (rate >= 0) { - lo = static_cast(std::floor(newPos)); - hi = static_cast(std::ceil(newPos)); - loprev = lo == 0 ? 0 : lo - 1; + } + + // RTPGHI algorithm, mode 3 + else { + // Determine position between two adjacent STFT frames + float lo, hi, posFrac; + + // Determine current, previous, and next indices + size_t currIdx, prevIdx, nextIdx; + + // Need to alias the buffers so their names make logical sense + SCPolarBuf *currentFrame = m_framePrev1; + SCPolarBuf *nextFrame = m_frameNext; + SCPolarBuf *prevFrame = m_framePrev2; + + if (rate >= 0) { + currIdx = static_cast(sc_clip(roundedPos, 0, stftFrames-1)); + prevIdx = static_cast(sc_clip(roundedPos-1, 0, stftFrames-1)); + nextIdx = static_cast(sc_clip(roundedPos+1, 0, stftFrames-1)); + lo = sc_clip(std::floor(newPos), 0.f, static_cast(stftFrames-1)); + hi = sc_clip(std::ceil(newPos), 0.f, static_cast(stftFrames-1)); + posFrac = newPos - lo; } else { - hi = static_cast(std::floor(newPos)); - lo = static_cast(std::ceil(newPos)); - loprev = lo + 1; - if (loprev >= stftFrames) loprev = lo; + currIdx = static_cast(sc_clip(roundedPos, 0, stftFrames-1)); + prevIdx = static_cast(sc_clip(roundedPos+1, 0, stftFrames-1)); + nextIdx = static_cast(sc_clip(roundedPos-1, 0, stftFrames-1)); + hi = static_cast(sc_clip(std::floor(newPos), 0.f, stftFrames-1)); + lo = static_cast(sc_clip(std::ceil(newPos), 0.f, stftFrames-1)); + posFrac = newPos - hi; } - // We are in between these two frames - fillPolarBuf(stftData + (hi * stftBufFftSize), m_frameNext, stftBufFftSize); - fillPolarBuf(stftData + (lo * stftBufFftSize), m_framePrev1, stftBufFftSize); - // This is the frame right before that. It's needed to compute the previous instantaneous frequencies. - fillPolarBuf(stftData + (loprev * stftBufFftSize), m_framePrev2, stftBufFftSize); - // Render the output FFT frame - switch (phaseLock) { - case 1: - Stretch3Puckette( - m_frameNext, - m_framePrev1, - m_framePrev2, - p, - m_outFramePrev, - newPos-static_cast(lo), - stftBufFftSize, - stftBufHopSize - ); - break; - case 2: - Stretch3LarocheDolson( - m_frameNext, - m_framePrev1, - m_framePrev2, - p, - m_outFramePrev, - m_peakFinder, - newPos-static_cast(lo), - stftBufFftSize, - stftBufHopSize - ); - break; - default: - Stretch3( - m_frameNext, - m_framePrev1, - m_framePrev2, - p, - m_outFramePrev, - newPos-static_cast(lo), - stftBufFftSize, - stftBufHopSize - ); + fillPolarBuf(stftData + (currIdx * stftBufFftSize), currentFrame, stftBufFftSize); + fillPolarBuf(stftData + (prevIdx * stftBufFftSize), prevFrame, stftBufFftSize); + fillPolarBuf(stftData + (nextIdx * stftBufFftSize), nextFrame, stftBufFftSize); + + // Update the previous time gradient + size_t numScBins = stftBufFftSize/2-1; + for (size_t k = 0; k < numScBins; k++) { + m_pTimeGradient[k] = m_cTimeGradient[k]; + } + + // Compute the time and frequency partial derivatives + if (currIdx == prevIdx) { + cDiffTime(currentFrame, nullptr, nextFrame, m_cTimeGradient, stftBufFftSize, stftBufHopSize); + } else if (currIdx == nextIdx) { + cDiffTime(currentFrame, prevFrame, nullptr, m_cTimeGradient, stftBufFftSize, stftBufHopSize); + } else { + cDiffTime(currentFrame, prevFrame, nextFrame, m_cTimeGradient, stftBufFftSize, stftBufHopSize); + } + cDiffFreq(currentFrame, m_freqGradient, stftBufFftSize, static_cast(stftBufNumOrigAudioFrames)); + + // We don't allow tol to be exactly 0 or 1. + const double tol = sc_clip(static_cast(in0(7)), 1e-20, 1 - 1e-20); + + Stretch2_RTPGHI( + currentFrame, + prevFrame, + m_cTimeGradient, + m_pTimeGradient, + m_freqGradient, + outFrame, + m_outFramePrev, + 1.0, // because we are keeping the same hop size + tol, + stftBufFftSize, + stftBufHopSize, + static_cast(stftBufNumOrigAudioFrames) + ); + + // Interpolate the magnitude data using power + if (std::abs(roundedPos-newPos) < 1e-3) { + powerLinearInterp(currentFrame, nullptr, outFrame, stftBufFftSize, 1); + } else if (currIdx == lo) { + powerLinearInterp(currentFrame, nextFrame, outFrame, stftBufFftSize, posFrac); + } + else { + powerLinearInterp(prevFrame, currentFrame, outFrame, stftBufFftSize, posFrac); } } + // We always need to store the resultant FFT frame in the UGen. - // It is used in the next call to PV_PlayBufStretch_next, for + // It is used in the next call to PV_PlayBufStretch_next for // phase vocoder calculations. - copyPolarBuf(p, m_outFramePrev, static_cast(numbins)); + copyPolarBuf(outFrame, m_outFramePrev, static_cast(numbins)); m_pos = newPos; } RELEASE_SNDBUF_SHARED(stftBuf); } -/// Computes a single frame of STFT data for time stretching. +/// Computes a single frame of STFT phases for time stretching. /// The assumption is that we are positioned exactly at `frame`, and we therefore /// just need framePrev to compute the instantaneous frequency. We also do not /// need to perform any magnitude or frequency interpolation. @@ -350,13 +496,10 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2( const SCPolarBuf *framePrev, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - size_t fftSize, - size_t hopSize) { - outFrame->dc = frame->dc; - outFrame->nyq = frame->nyq; + const size_t fftSize, + const size_t hopSize +) { for (size_t k = 0; k < fftSize/2-1; k++) { - outFrame->bin[k].mag = frame->bin[k].mag; - // Compute the instantaneous frequency float omegaK = twopi * (k+1) / fftSize; float phaseInc = frame->bin[k].phase - framePrev->bin[k].phase - hopSize * omegaK; @@ -371,7 +514,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2( } } -/// Computes a single frame of STFT data for time stretching. +/// Computes a single frame of STFT phases for time stretching. /// The assumption is that we are positioned exactly at `frame`, and we therefore /// just need framePrev to compute the instantaneous frequency. We also do not /// need to perform any magnitude or frequency interpolation. @@ -389,13 +532,10 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2Puckette( const SCPolarBuf *framePrev, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - size_t fftSize, - size_t hopSize) { - outFrame->dc = frame->dc; - outFrame->nyq = frame->nyq; + const size_t fftSize, + const size_t hopSize +) { for (size_t k = 0; k < fftSize/2-1; k++) { - outFrame->bin[k].mag = frame->bin[k].mag; - // Compute the instantaneous frequency float omegaK = twopi * (k+1) / fftSize; float phaseInc = frame->bin[k].phase - framePrev->bin[k].phase - hopSize * omegaK; @@ -424,7 +564,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2Puckette( } } -/// Computes a single frame of STFT data for time stretching, +/// Computes a single frame of STFT phases for time stretching, /// using the Laroche/Dolson identity phase locking scheme. /// The assumption is that we are positioned exactly at `frame`, and we therefore /// just need framePrev to compute the instantaneous frequency. We also do not @@ -441,21 +581,16 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( const SCPolarBuf *frame, const SCPolarBuf *framePrev, SCPolarBuf *outFrame, - const SCPolarBuf *outFramePrev, - PeakFinder *peakFinder, - size_t fftSize, - size_t hopSize) { - outFrame->dc = frame->dc; - outFrame->nyq = frame->nyq; - + const SCPolarBuf *outFramePrev, + const size_t fftSize, + const size_t hopSize +) { // Acquire peaks - peakFinder->analyze(frame); + m_peakFinder->analyze(frame); - if (peakFinder->size() == 0) { + if (m_peakFinder->size() == 0) { // No phase locking if no peaks were acquired for (size_t k = 0; k < fftSize/2-1; k++) { - outFrame->bin[k].mag = frame->bin[k].mag; - // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; double phaseInc = frame->bin[k].phase - framePrev->bin[k].phase - hopSize * omegaK; @@ -470,9 +605,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( } } else { // Update any bins that occur below the lowest peak's region of influence - for (size_t k = 0; k < peakFinder->peaks[0].leftValley; k++) { - outFrame->bin[k].mag = frame->bin[k].mag; - + for (size_t k = 0; k < m_peakFinder->peaks[0].leftValley; k++) { // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; double phaseInc = frame->bin[k].phase - framePrev->bin[k].phase - hopSize * omegaK; @@ -487,9 +620,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( } // Update any bins that occur above the highest peak's region of influence - for (size_t k = peakFinder->peaks[peakFinder->size()-1].rightValley + 1; k < fftSize / 2 - 1; k++) { - outFrame->bin[k].mag = frame->bin[k].mag; - + for (size_t k = m_peakFinder->peaks[m_peakFinder->size()-1].rightValley + 1; k < fftSize / 2 - 1; k++) { // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; double phaseInc = frame->bin[k].phase - framePrev->bin[k].phase - hopSize * omegaK; @@ -504,10 +635,9 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( } // Update all other peaks - for (size_t n = 0; n < peakFinder->size(); n++) { + for (size_t n = 0; n < m_peakFinder->size(); n++) { // First we compute the new phase for the peak bin as usual - Peak peak = peakFinder->peaks[n]; - outFrame->bin[peak.peak].mag = frame->bin[peak.peak].mag; + Peak peak = m_peakFinder->peaks[n]; // Compute the instantaneous frequency double omegaK = twopi * (peak.peak+1) / fftSize; @@ -523,14 +653,12 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( // Then we update the phases of all other peaks for (size_t o = peak.leftValley; o < peak.peak; o++) { - outFrame->bin[o].mag = frame->bin[o].mag; outFrame->bin[o].phase = sc_wrap( outFrame->bin[peak.peak].phase + frame->bin[o].phase - frame->bin[peak.peak].phase, 0.f, static_cast(twopi)); } for (size_t o = peak.peak + 1; o <= peak.rightValley; o++) { - outFrame->bin[o].mag = frame->bin[o].mag; outFrame->bin[o].phase = sc_wrap( outFrame->bin[peak.peak].phase + frame->bin[o].phase - frame->bin[peak.peak].phase, 0.f, @@ -540,7 +668,97 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( } } -/// Computes a single frame of STFT data for time stretching. +/// Computes a single frame of STFT phases for time stretching, +/// using the RTPGHI algorithm. +/// +/// \param currentFrame The current STFT frame +/// \param prevFrame The previous STFT frame +/// \param cTimeDiff The current time gradient vector +/// \param pTimeDiff The previous time gradient vector +/// \param cFreqDiff The current frequency gradient vector +/// \param [out] outFrame The frame to write output STFT data to +/// \param outFramePrev The previous output frame +/// \param alpha The stretch factor +/// \param tol The magnitude tolerance for phase calculation (0 < tol < 1) +/// \param fftSize The FFT size +/// \param hopSize The hop size +/// \param signalLen The signal length +void FlexPlugins::PV_PlayBufStretch::Stretch2_RTPGHI( + const SCPolarBuf *currentFrame, + const SCPolarBuf *prevFrame, + const float *cTimeDiff, + const float *pTimeDiff, + const float *cFreqDiff, + SCPolarBuf *outFrame, + const SCPolarBuf *outFramePrev, + const float alpha, + const double tol, + const size_t fftSize, + const size_t hopSize, + const double signalLen +) { + RGen* rgen = mParent->mRGen; + uint32 s1 = rgen->s1; + uint32 s2 = rgen->s2; + uint32 s3 = rgen->s3; + + size_t numScBins = fftSize/2-1; + + // 1--compute abstol + double abstol = 0.0; + for (size_t k = 0; k < numScBins; k++) { + if (currentFrame->bin[k].mag * tol > abstol) { + abstol = currentFrame->bin[k].mag * tol; + } + if (prevFrame->bin[k].mag * tol > abstol) { + abstol = prevFrame->bin[k].mag * tol; + } + } + + // 4--set up heap + m_pgHeap->clear(); + + // 2--make I + // 3--rand phases for non-I bins + // 5--initialize heap + m_setI->clear(); + for (size_t k = 0; k < numScBins; k++) { + if (prevFrame->bin[k].mag > abstol) { + m_setI->insert(k); + m_pgHeap->insert(prevFrame->bin[k].mag, {k, -1}); + } else { + outFrame->bin[k].phase = rgen->frand() * twopi; + } + } + + // 6--heap integration + while (m_setI->size() > 0) { + std::pair> bin = m_pgHeap->pop(); + size_t m_h = bin.second.first; + int n = bin.second.second; + if (n < 0) { + if (m_setI->find(m_h)) { + outFrame->bin[m_h].phase = outFramePrev->bin[m_h].phase + + static_cast(hopSize) * (cTimeDiff[m_h] + pTimeDiff[m_h]) / 2.0; + m_setI->remove(m_h); + m_pgHeap->insert(currentFrame->bin[m_h].mag, {m_h, 0}); + } + } else { + if (m_setI->find(m_h+1)) { + outFrame->bin[m_h+1].phase = outFrame->bin[m_h].phase + (alpha * signalLen) / (2.0 * static_cast(fftSize)) * (cFreqDiff[m_h] + cFreqDiff[m_h+1]); + m_setI->remove(m_h+1); + m_pgHeap->insert(currentFrame->bin[m_h+1].mag, {m_h+1, 0}); + } + if (m_setI->find(m_h-1)) { + outFrame->bin[m_h-1].phase = outFrame->bin[m_h].phase + (alpha * signalLen) / (2.0 * static_cast(fftSize)) * (cFreqDiff[m_h] + cFreqDiff[m_h-1]); + m_setI->remove(m_h-1); + m_pgHeap->insert(currentFrame->bin[m_h-1].mag, {m_h-1, 0}); + } + } + } +} + +/// Computes a single frame of STFT phases for time stretching. /// The assumption is that we are positioned between framePrev1 and frameNext. /// This means we will need to interpolate frequency data. So we will need to /// compute two frequencies for each bin, and that means we need three STFT frames. @@ -559,14 +777,10 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3( const SCPolarBuf *framePrev2, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - float pos, - size_t fftSize, - size_t hopSize) { - outFrame->dc = INTERP(framePrev1->dc, frameNext->dc, pos); - outFrame->nyq = INTERP(framePrev1->nyq, frameNext->nyq, pos); + const float pos, + const size_t fftSize, + const size_t hopSize) { for (size_t k = 0; k < fftSize/2-1; k++) { - outFrame->bin[k].mag = INTERP(framePrev1->bin[k].mag, frameNext->bin[k].mag, pos); - float omegaK = twopi * (k+1) / fftSize; // Compute the next instantaneous frequency @@ -580,7 +794,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3( float instantaneousFreqPrev = omegaK + phaseInc/hopSize; // Interpolate the instantaneous frequency - float instantaneousFreq = INTERP(instantaneousFreqPrev, instantaneousFreqNext, pos); + float instantaneousFreq = interp(instantaneousFreqPrev, instantaneousFreqNext, pos); // Compute the new phase outFrame->bin[k].phase = sc_wrap( @@ -590,7 +804,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3( } } -/// Computes a single frame of STFT data for time stretching. +/// Computes a single frame of STFT phases for time stretching. /// The assumption is that we are positioned between framePrev1 and frameNext. /// This means we will need to interpolate frequency data. So we will need to /// compute two frequencies for each bin, and that means we need three STFT frames. @@ -611,14 +825,11 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3Puckette( const SCPolarBuf *framePrev2, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - float pos, - size_t fftSize, - size_t hopSize) { - outFrame->dc = INTERP(framePrev1->dc, frameNext->dc, pos); - outFrame->nyq = INTERP(framePrev1->nyq, frameNext->nyq, pos); + const float pos, + const size_t fftSize, + const size_t hopSize +) { for (size_t k = 0; k < fftSize/2-1; k++) { - outFrame->bin[k].mag = INTERP(framePrev1->bin[k].mag, frameNext->bin[k].mag, pos); - float omegaK = twopi * (k+1) / fftSize; // Compute the next instantaneous frequency @@ -632,7 +843,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3Puckette( float instantaneousFreqPrev = omegaK + phaseInc/hopSize; // Interpolate the instantaneous frequency - float instantaneousFreq = INTERP(instantaneousFreqPrev, instantaneousFreqNext, pos); + float instantaneousFreq = interp(instantaneousFreqPrev, instantaneousFreqNext, pos); // In Puckette-style phase locking, we make a substitution for the previous phase, // in order to "lock" phases of adjacent bins together. @@ -656,7 +867,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3Puckette( } } -/// Computes a single frame of STFT data for time stretching, +/// Computes a single frame of STFT phases for time stretching, /// using the Laroche/Dolson identity phase locking scheme. /// The assumption is that we are positioned exactly at `frame`, and we therefore /// just need framePrev to compute the instantaneous frequency. We also do not @@ -667,7 +878,6 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3Puckette( /// \param framePrev2 The previous STFT frame before that (required for instantaneous frequency interpolation) /// \param [out] outFrame The output STFT frame /// \param outFramePrev The previously computed output STFT frame -/// \param peakFinder The PeakFinder instance for determining peak locations in the magnitude spectrum /// \param pos The position between framePrev1 and frameNext (0 < pos < 1) /// \param fftSize The FFT size /// \param hopSize The hop size @@ -677,13 +887,10 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( const SCPolarBuf *framePrev2, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - PeakFinder *peakFinder, - double pos, - size_t fftSize, - size_t hopSize) { - outFrame->dc = INTERP(framePrev1->dc, frameNext->dc, pos); - outFrame->nyq = INTERP(framePrev1->nyq, frameNext->nyq, pos); - + const double pos, + const size_t fftSize, + const size_t hopSize +) { // Get the closest bin for phase relationships const SCPolarBuf *cframe = nullptr; if (pos >= 0.5) { @@ -693,12 +900,11 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( } // Acquire peaks - peakFinder->analyze(cframe); + m_peakFinder->analyze(cframe); - if (peakFinder->size() == 0) { + if (m_peakFinder->size() == 0) { // No phase locking if no peaks were acquired for (size_t k = 0; k < fftSize/2-1; k++) { - outFrame->bin[k].mag = INTERP(framePrev1->bin[k].mag, frameNext->bin[k].mag, pos); double omegaK = twopi * (k+1) / fftSize; @@ -713,7 +919,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( double instantaneousFreqPrev = omegaK + phaseInc/hopSize; // Interpolate the instantaneous frequency - double instantaneousFreq = INTERP(instantaneousFreqPrev, instantaneousFreqNext, pos); + double instantaneousFreq = interp(instantaneousFreqPrev, instantaneousFreqNext, pos); // Compute the new phase outFrame->bin[k].phase = sc_wrap( @@ -723,9 +929,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( } } else { // Update any bins that occur below the lowest peak's region of influence - for (size_t k = 0; k < peakFinder->peaks[0].leftValley; k++) { - outFrame->bin[k].mag = INTERP(framePrev1->bin[k].mag, frameNext->bin[k].mag, pos); - + for (size_t k = 0; k < m_peakFinder->peaks[0].leftValley; k++) { // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; @@ -739,7 +943,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( double instantaneousFreqPrev = omegaK + phaseInc/hopSize; // Interpolate the instantaneous frequency - double instantaneousFreq = INTERP(instantaneousFreqPrev, instantaneousFreqNext, pos); + double instantaneousFreq = interp(instantaneousFreqPrev, instantaneousFreqNext, pos); // Compute the phase outFrame->bin[k].phase = sc_wrap( @@ -749,9 +953,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( } // Update any bins that occur above the highest peak's region of influence - for (size_t k = peakFinder->peaks[peakFinder->size()-1].rightValley + 1; k < fftSize / 2 - 1; k++) { - outFrame->bin[k].mag = INTERP(framePrev1->bin[k].mag, frameNext->bin[k].mag, pos); - + for (size_t k = m_peakFinder->peaks[m_peakFinder->size()-1].rightValley + 1; k < fftSize / 2 - 1; k++) { // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; @@ -765,7 +967,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( double instantaneousFreqPrev = omegaK + phaseInc/hopSize; // Interpolate the instantaneous frequency - double instantaneousFreq = INTERP(instantaneousFreqPrev, instantaneousFreqNext, pos); + double instantaneousFreq = interp(instantaneousFreqPrev, instantaneousFreqNext, pos); // Compute the phase outFrame->bin[k].phase = sc_wrap( @@ -774,10 +976,9 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( static_cast(twopi)); } - for (size_t n = 0; n < peakFinder->size(); n++) { + for (size_t n = 0; n < m_peakFinder->size(); n++) { // First we compute the new phase for the peak bin as usual - Peak peak = peakFinder->peaks[n]; - outFrame->bin[peak.peak].mag = INTERP(framePrev1->bin[peak.peak].mag, frameNext->bin[peak.peak].mag, pos); + Peak peak = m_peakFinder->peaks[n]; // Compute the instantaneous frequency double omegaK = twopi * (peak.peak+1) / fftSize; @@ -792,7 +993,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( double instantaneousFreqPrev = omegaK + phaseInc/hopSize; // Interpolate the instantaneous frequency - double instantaneousFreq = INTERP(instantaneousFreqPrev, instantaneousFreqNext, pos); + double instantaneousFreq = interp(instantaneousFreqPrev, instantaneousFreqNext, pos); // Compute the phase outFrame->bin[peak.peak].phase = sc_wrap( @@ -802,14 +1003,12 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( // Then we update all bins in the region of influence for (size_t o = peak.leftValley; o < peak.peak; o++) { - outFrame->bin[o].mag = INTERP(framePrev1->bin[o].mag, frameNext->bin[o].mag, pos); outFrame->bin[o].phase = sc_wrap( outFrame->bin[peak.peak].phase + cframe->bin[o].phase - cframe->bin[peak.peak].phase, 0.f, static_cast(twopi)); } for (size_t o = peak.peak + 1; o <= peak.rightValley; o++) { - outFrame->bin[o].mag = INTERP(framePrev1->bin[o].mag, frameNext->bin[o].mag, pos); outFrame->bin[o].phase = sc_wrap( outFrame->bin[peak.peak].phase + cframe->bin[o].phase - cframe->bin[peak.peak].phase, 0.f, @@ -824,7 +1023,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( /// \param fftBuf The FFT frame from the STFT buffer /// \param [out] polarBuf The SCPolarBuf to copy to /// \param fftSize The FFT size -void FlexPlugins::PV_PlayBufStretch::fillPolarBuf(const float *fftBuf, SCPolarBuf *polarBuf, size_t fftSize) { +void FlexPlugins::fillPolarBuf(const float *fftBuf, SCPolarBuf *polarBuf, const size_t fftSize) { polarBuf->dc = fftBuf[0]; polarBuf->nyq = fftBuf[1]; for (size_t n = 2, k = 0; n < fftSize; n+=2, k++) { @@ -840,7 +1039,7 @@ void FlexPlugins::PV_PlayBufStretch::fillPolarBuf(const float *fftBuf, SCPolarBu /// \param sourceBuf The source buffer /// \param [out] destBuf The destination buffer /// \param numbins The number of bins in the SCPolarBuf (fftSize/2-1) -void FlexPlugins::PV_PlayBufStretch::copyPolarBuf(const SCPolarBuf *sourceBuf, SCPolarBuf *destBuf, size_t numbins) { +void FlexPlugins::copyPolarBuf(const SCPolarBuf *sourceBuf, SCPolarBuf *destBuf, const size_t numbins) { destBuf->dc = sourceBuf->dc; destBuf->nyq = sourceBuf->nyq; for (size_t n = 0; n < numbins; n++) { @@ -849,114 +1048,150 @@ void FlexPlugins::PV_PlayBufStretch::copyPolarBuf(const SCPolarBuf *sourceBuf, S } } -FlexPlugins::Peak::Peak(size_t peak) : peak(peak) {} -FlexPlugins::Peak::Peak(size_t peak, size_t leftValley, size_t rightValley) : peak(peak), leftValley(leftValley), rightValley(rightValley) {} - -FlexPlugins::PeakFinder::PeakFinder(size_t fftSize, size_t radius) { - m_maxSize = fftSize/2-1; - m_radius = radius; - m_size = 0; - peaks = nullptr; - m_queueL = nullptr; - m_queueR = nullptr; -} - -void FlexPlugins::PeakFinder::memLoad(void* arr) { - size_t *data = (size_t*)arr; - m_queueL = data; - m_queueR = data + m_radius; - peaks = (Peak*)(data + 2 * m_radius); -} - -size_t FlexPlugins::PeakFinder::memSize() const { - return m_radius * 2 * sizeof(size_t) + m_maxSize * sizeof(Peak); -} - -void* FlexPlugins::PeakFinder::memRetrieve() { - return (void*)m_queueL; -} - -void FlexPlugins::PeakFinder::clear() { - m_size = 0; +/// Computes the centered frequency gradient vector for a FFT frame +/// +/// \param currentFrame The current FFT frame in the STFT matrix +/// \param [out] freqGradient The output frequency gradient vector +/// \param fftSize The FFT size +/// \param signalLen The total length of the signal in samples +void FlexPlugins::cDiffFreq( + const SCPolarBuf *currentFrame, + float *freqGradient, + const size_t fftSize, + const double signalLen +) { + size_t numScBins = fftSize/2-1; + const double bARecip = static_cast(fftSize) / signalLen; + // compute forward derivative for first bin and backward derivative for last bin + freqGradient[0] = bARecip * princargRtpghi(currentFrame->bin[1].phase - currentFrame->bin[0].phase); + // fftSize/2-2 is the highest index of the bins because we aren't counting dc and nyquist + freqGradient[fftSize/2-2] = bARecip * princargRtpghi(currentFrame->bin[fftSize/2-2].phase - currentFrame->bin[fftSize/2-3].phase); + // compute centered derivatives for all other bins + for (size_t i = 1; i < numScBins-1; i++) { + freqGradient[i] = bARecip * ( + princargRtpghi(currentFrame->bin[i+1].phase - currentFrame->bin[i].phase) + + princargRtpghi(currentFrame->bin[i].phase - currentFrame->bin[i-1].phase) + ) / 2; + } } -size_t FlexPlugins::PeakFinder::maxSize() const { - return m_maxSize; +/// Computes the centered time phase gradient vector +/// +/// \param currentFrame The current FFT frame +/// \param prevFrame The previous FFT frame +/// \param nextFrame The next FFT frame +/// \param [out] timeGradient The output time gradient vector +/// \param fftSize The FFT size +/// \param hopSize The analysis hop size +void FlexPlugins::cDiffTime( + const SCPolarBuf *currentFrame, + const SCPolarBuf *prevFrame, + const SCPolarBuf *nextFrame, + float *timeGradient, + const size_t fftSize, + const size_t hopSize +) { + size_t numScBins = fftSize/2-1; + if (prevFrame && nextFrame) { + // centered differentiation + for (size_t k = 0; k < numScBins; k++) { + const double backwardDiff = princargRtpghi( + currentFrame->bin[k].phase - prevFrame->bin[k].phase - + twopi * (k+1) * static_cast(hopSize) / static_cast(fftSize) + ) / static_cast(hopSize) + twopi * (k+1) / static_cast(fftSize); + const double forwardDiff = princargRtpghi( + nextFrame->bin[k].phase - currentFrame->bin[k].phase - + twopi * (k+1) * static_cast(hopSize) / static_cast(fftSize) + ) / static_cast(hopSize) + twopi * (k+1) / static_cast(fftSize); + timeGradient[k] = (backwardDiff + forwardDiff) / 2; + } + } else if (nextFrame) { + // right differentiation + for (size_t k = 0; k < numScBins; k++) { + timeGradient[k] = princargRtpghi( + nextFrame->bin[k].phase - currentFrame->bin[k].phase - + twopi * (k+1) * static_cast(hopSize) / static_cast(fftSize) + ) / static_cast(hopSize) + twopi * (k+1) / static_cast(fftSize); + } + } else { + // left differentiation + for (size_t k = 0; k < numScBins; k++) { + timeGradient[k] = princargRtpghi( + currentFrame->bin[k].phase - prevFrame->bin[k].phase - + twopi * (k+1) * static_cast(hopSize) / static_cast(fftSize) + ) / static_cast(hopSize) + twopi * (k+1) / static_cast(fftSize); + } + } } -size_t FlexPlugins::PeakFinder::size() const { - return m_size; +/// Linearly interpolates the magnitude of two STFT frames +/// +/// \param prevFrame The previous STFT frame +/// \param nextFrame The next STFT frame +/// \param [out] out The output STFT frame +/// \param fftSize The FFT size +/// \param pos The position between the two frames (0 <= pos <= 1) +void FlexPlugins::magLinearInterp( + const SCPolarBuf *prevFrame, + const SCPolarBuf *nextFrame, + SCPolarBuf *out, + const size_t fftSize, + const float pos +) { + size_t numScBins = fftSize/2-1; + if (prevFrame && nextFrame) { + out->dc = interp(prevFrame->dc, nextFrame->dc, pos); + out->nyq = interp(prevFrame->nyq, nextFrame->nyq, pos); + for (size_t k = 0; k < numScBins; k++) { + out->bin[k].mag = interp(prevFrame->bin[k].mag, nextFrame->bin[k].mag, pos); + } + } else if (prevFrame) { + out->dc = prevFrame->dc; + out->nyq = prevFrame->nyq; + for (size_t k = 0; k < numScBins; k++) { + out->bin[k].mag = prevFrame->bin[k].mag; + } + } else if (nextFrame) { + out->dc = nextFrame->dc; + out->nyq = nextFrame->nyq; + for (size_t k = 0; k < numScBins; k++) { + out->bin[k].mag = nextFrame->bin[k].mag; + } + } } -void FlexPlugins::PeakFinder::analyze(const SCPolarBuf *buf) { - // We can only perform the analysis if we have enough bins - if (m_queueL && m_maxSize > m_radius * 2 + 1) { - m_size = 0; // clear any existing data - - size_t i = m_radius; - while (i < m_maxSize - m_radius) { - bool isMax = true; - for (size_t j = i - m_radius; j < i; j++) { - if (buf->bin[j].mag >= buf->bin[i].mag) { - isMax = false; - break; - } - } - for (size_t j = i + 1; j <= i + m_radius; j++) { - if (buf->bin[j].mag >= buf->bin[i].mag) { - isMax = false; - break; - } - } - if (isMax) { - peaks[m_size] = Peak(i); - m_size++; - i += m_radius + 1; - } else { - i++; - } +/// Linearly interpolates the magnitude of two STFT frames using the power +/// +/// \param prevFrame The previous STFT frame +/// \param nextFrame The next STFT frame +/// \param [out] out The output STFT frame +/// \param fftSize The FFT size +/// \param pos The position between the two frames (0 <= pos <= 1) +void FlexPlugins::powerLinearInterp( + const SCPolarBuf *prevFrame, + const SCPolarBuf *nextFrame, + SCPolarBuf *out, + const size_t fftSize, + const float pos +) { + size_t numScBins = fftSize/2-1; + if (prevFrame && nextFrame) { + out->dc = interpPower(prevFrame->dc, nextFrame->dc, pos); + out->nyq = interpPower(prevFrame->nyq, nextFrame->nyq, pos); + for (size_t k = 0; k < numScBins; k++) { + out->bin[k].mag = interpPower(prevFrame->bin[k].mag, nextFrame->bin[k].mag, pos); } - - // Find the left valley for the first peak, and the right valley - // for the last peak. - if (m_size > 0) { - float min = buf->bin[0].mag; - size_t argmin = 0; - size_t k = 1; - for (; k < peaks[0].peak; k++) { - if (buf->bin[k].mag < min) { - min = buf->bin[k].mag; - argmin = k; - } - } - peaks[0].leftValley = argmin; - k = peaks[m_size-1].peak + 1; - min = buf->bin[k].mag; - argmin = k; - for (k++; k < m_maxSize; k++) { - if (buf->bin[k].mag < min) { - min = buf->bin[k].mag; - argmin = k; - } - } - peaks[m_size-1].rightValley = argmin; - } - - // Find the remaining left and right valleys - if (m_size > 1) { - for (size_t j = 0; j < m_size-1; j++) { - size_t k = peaks[j].peak + 1; - float min = buf->bin[k].mag; - size_t argmin = k; - for (k++; k < peaks[j+1].peak; k++) { - if (buf->bin[k].mag < min) { - min = buf->bin[k].mag; - argmin = k; - } - } - peaks[j].rightValley = argmin - 1; - peaks[j+1].leftValley = argmin; - } + } else if (prevFrame) { + out->dc = prevFrame->dc; + out->nyq = prevFrame->nyq; + for (size_t k = 0; k < numScBins; k++) { + out->bin[k].mag = prevFrame->bin[k].mag; + } + } else if (nextFrame) { + out->dc = nextFrame->dc; + out->nyq = nextFrame->nyq; + for (size_t k = 0; k < numScBins; k++) { + out->bin[k].mag = nextFrame->bin[k].mag; } } } diff --git a/src/pv/pvStretch.hpp b/src/pv/pvStretch.hpp index 29f83d3..0451b31 100644 --- a/src/pv/pvStretch.hpp +++ b/src/pv/pvStretch.hpp @@ -24,61 +24,85 @@ along with this program. If not, see . #pragma once #include "SC_PlugIn.hpp" #include "FFT_UGens.h" +#include "peakFinder.hpp" +#include "hashtable.hpp" +#include "pqueue.hpp" +#include "utilities.hpp" namespace FlexPlugins { - class Peak { - public: - Peak(size_t peak); - Peak(size_t peak, size_t leftValley, size_t rightValley); - size_t peak, leftValley, rightValley; - }; - - class PeakFinder { - public: - /// Constructs the PeakFinder - /// - /// \param fftSize The FFT size - PeakFinder(size_t fftSize, size_t radius); - - /// Finds peaks in the provided SCPolarBuf. Note that this buffer must correspond - /// to the original FFT size provided for the PeakFinder--otherwise memory errors may occur. - /// - /// \param buf The buffer to analyze - void analyze(const SCPolarBuf *buf); - - /// Loads memory from the external SuperCollider allocator. Memory is allocated - /// using RTAlloc() and the size is specified by the memSize() method. - /// - /// \param arr The allocated memory - void memLoad(void *arr); - - /// Gets the memory size required for the PeakFinder - size_t memSize() const; - - /// Gets the max size of the PeakFinder - /// - /// \returns The max size - size_t maxSize() const; - - /// Gets the current size of the PeakFinder (the number of peaks stored) - /// - /// \returns The current size - size_t size() const; - - /// Clears the PeakFinder - void clear(); - - /// Gets a pointer to the memory that was allocated for the PeakFinder - /// so that it can be deallocated - /// - /// \return The memory pointer - void* memRetrieve(); - - Peak *peaks; - private: - size_t m_maxSize, m_size, m_radius; - size_t *m_queueL, *m_queueR; - }; + /// Computes the centered frequency gradient vector for a FFT frame + /// + /// \param currentFrame The current FFT frame in the STFT matrix + /// \param [out] freqGradient The output frequency gradient vector + /// \param fftSize The FFT size + /// \param signalLen The total length of the signal in samples + void cDiffFreq( + const SCPolarBuf *currentFrame, + float *freqGradient, + const size_t fftSize, + const double signalLen + ); + + /// Computes the centered time phase gradient vector + /// + /// \param currentFrame The current FFT frame + /// \param prevFrame The previous FFT frame + /// \param nextFrame The next FFT frame + /// \param [out] timeGradient The output time gradient vector + /// \param fftSize The FFT size + /// \param hopSize The analysis hop size + void cDiffTime( + const SCPolarBuf *currentFrame, + const SCPolarBuf *prevFrame, + const SCPolarBuf *nextFrame, + float *timeGradient, + const size_t fftSize, + const size_t hopSize + ); + + /// Copies data from one SCPolarBuf to another + /// + /// \param sourceBuf The source buffer + /// \param [out] destBuf The destination buffer + /// \param numbins The number of bins in the SCPolarBuf (fftSize/2-1) + void copyPolarBuf(const SCPolarBuf *sourceBuf, SCPolarBuf *destBuf, size_t numbins); + + /// Fills a SCPolarBuf with saved STFT data from a single frame + /// + /// \param fftBuf The FFT frame from the STFT buffer + /// \param [out] polarBuf The SCPolarBuf to copy to + /// \param fftSize The FFT size + void fillPolarBuf(const float *fftBuf, SCPolarBuf *polarBuf, size_t fftSize); + + /// Linearly interpolates the magnitude of two STFT frames + /// + /// \param prevFrame The previous STFT frame + /// \param nextFrame The next STFT frame + /// \param [out] out The output STFT frame + /// \param fftSize The FFT size + /// \param pos The position between the two frames (0 <= pos <= 1) + void magLinearInterp( + const SCPolarBuf *prevFrame, + const SCPolarBuf *nextFrame, + SCPolarBuf *out, + const size_t fftSize, + const float pos + ); + + /// Linearly interpolates the magnitude of two STFT frames using the power + /// + /// \param prevFrame The previous STFT frame + /// \param nextFrame The next STFT frame + /// \param [out] out The output STFT frame + /// \param fftSize The FFT size + /// \param pos The position between the two frames (0 <= pos <= 1) + void powerLinearInterp( + const SCPolarBuf *prevFrame, + const SCPolarBuf *nextFrame, + SCPolarBuf *out, + const size_t fftSize, + const float pos + ); /// Stores the state of a PV_PlayBufStretch UGen instance class PV_PlayBufStretch : public SCUnit { @@ -89,7 +113,7 @@ namespace FlexPlugins { private: void next(int inNumSamples); - /// Computes a single frame of STFT data for time stretching. + /// Computes a single frame of STFT phases for time stretching. /// The assumption is that we are positioned exactly at `frame`, and we therefore /// just need framePrev to compute the instantaneous frequency. We also do not /// need to perform any magnitude or frequency interpolation. @@ -105,10 +129,11 @@ namespace FlexPlugins { const SCPolarBuf *framePrev, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - size_t fftSize, - size_t hopSize); + const size_t fftSize, + const size_t hopSize + ); - /// Computes a single frame of STFT data for time stretching. + /// Computes a single frame of STFT phases for time stretching. /// The assumption is that we are positioned exactly at `frame`, and we therefore /// just need framePrev to compute the instantaneous frequency. We also do not /// need to perform any magnitude or frequency interpolation. @@ -126,10 +151,11 @@ namespace FlexPlugins { const SCPolarBuf *framePrev, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - size_t fftSize, - size_t hopSize); + const size_t fftSize, + const size_t hopSize + ); - /// Computes a single frame of STFT data for time stretching, + /// Computes a single frame of STFT phases for time stretching, /// using the Laroche/Dolson identity phase locking scheme. /// The assumption is that we are positioned exactly at `frame`, and we therefore /// just need framePrev to compute the instantaneous frequency. We also do not @@ -139,7 +165,6 @@ namespace FlexPlugins { /// \param framePrev The previous STFT frame /// \param [out] outFrame The output STFT frame /// \param outFramePrev The previously computed output STFT frame - /// \param peakFinder The PeakFinder instance for determining peak locations in the magnitude spectrum /// \param fftSize The FFT size /// \param hopSize The hop size void Stretch2LarocheDolson( @@ -147,11 +172,43 @@ namespace FlexPlugins { const SCPolarBuf *framePrev, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - PeakFinder *peakFinder, - size_t fftSize, - size_t hopSize); + const size_t fftSize, + const size_t hopSize + ); - /// Computes a single frame of STFT data for time stretching. + /// Computes a single frame of STFT phases for time stretching, + /// using the RTPGHI algorithm. + /// + /// \param currentFrame The current STFT frame + /// \param prevFrame The previous STFT frame + /// \param cTimeDiff The current time gradient vector + /// \param pTimeDiff The previous time gradient vector + /// \param cFreqDiff The current frequency gradient vector + /// \param [out] outFrame The frame to write output STFT data to + /// \param outFramePrev The previous output frame + /// \param alpha The stretch factor + /// \param tol The magnitude tolerance for phase calculation (0 < tol < 1) + /// \param fftSize The FFT size + /// \param hopSize The hop size + /// \param signalLen The signal length + /// \param pgHeap The phase gradient heap + /// \param setI The bin tracker + void Stretch2_RTPGHI( + const SCPolarBuf *currentFrame, + const SCPolarBuf *prevFrame, + const float *cTimeDiff, + const float *pTimeDiff, + const float *cFreqDiff, + SCPolarBuf *outFrame, + const SCPolarBuf *outFramePrev, + const float alpha, + const double tol, + const size_t fftSize, + const size_t hopSize, + const double signalLen + ); + + /// Computes a single frame of STFT phases for time stretching. /// The assumption is that we are positioned between framePrev1 and frameNext. /// This means we will need to interpolate frequency data. So we will need to /// compute two frequencies for each bin, and that means we need three STFT frames. @@ -170,11 +227,12 @@ namespace FlexPlugins { const SCPolarBuf *framePrev2, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - float pos, - size_t fftSize, - size_t hopSize); + const float pos, + const size_t fftSize, + const size_t hopSize + ); - /// Computes a single frame of STFT data for time stretching. + /// Computes a single frame of STFT phases for time stretching. /// The assumption is that we are positioned between framePrev1 and frameNext. /// This means we will need to interpolate frequency data. So we will need to /// compute two frequencies for each bin, and that means we need three STFT frames. @@ -195,11 +253,12 @@ namespace FlexPlugins { const SCPolarBuf *framePrev2, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - float pos, - size_t fftSize, - size_t hopSize); + const float pos, + const size_t fftSize, + const size_t hopSize + ); - /// Computes a single frame of STFT data for time stretching, + /// Computes a single frame of STFT phases for time stretching, /// using the Laroche/Dolson identity phase locking scheme. /// The assumption is that we are positioned exactly at `frame`, and we therefore /// just need framePrev to compute the instantaneous frequency. We also do not @@ -210,34 +269,19 @@ namespace FlexPlugins { /// \param framePrev2 The previous STFT frame before that (required for instantaneous frequency interpolation) /// \param [out] outFrame The output STFT frame /// \param outFramePrev The previously computed output STFT frame - /// \param peakFinder The PeakFinder instance for determining peak locations in the magnitude spectrum /// \param pos The position between framePrev1 and frameNext (0 < pos < 1) /// \param fftSize The FFT size /// \param hopSize The hop size - static void Stretch3LarocheDolson( + void Stretch3LarocheDolson( const SCPolarBuf *frameNext, const SCPolarBuf *framePrev1, const SCPolarBuf *framePrev2, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - PeakFinder *peakFinder, - double pos, - size_t fftSize, - size_t hopSize); - - /// Fills a SCPolarBuf with saved STFT data from a single frame - /// - /// \param fftBuf The FFT frame from the STFT buffer - /// \param [out] polarBuf The SCPolarBuf to copy to - /// \param fftSize The FFT size - void fillPolarBuf(const float *fftBuf, SCPolarBuf *polarBuf, size_t fftSize); - - /// Copies data from one SCPolarBuf to another - /// - /// \param sourceBuf The source buffer - /// \param [out] destBuf The destination buffer - /// \param numbins The number of bins in the SCPolarBuf (fftSize/2-1) - void copyPolarBuf(const SCPolarBuf *sourceBuf, SCPolarBuf *destBuf, size_t numbins); + const double pos, + const size_t fftSize, + const size_t hopSize + ); /// The index of the buffer with STFT data float m_fbufnum; @@ -260,6 +304,17 @@ namespace FlexPlugins { /// The peak finding utility for the Laroche/Dolson stretching algorithm PeakFinder *m_peakFinder; + /// The frequency bin tracker for the RTPGHI algorithm + IntHashSet *m_setI; + + /// The heap for the RTPGHI algorithm + MaxPQueue> *m_pgHeap; + + /// Gradient vectors for the RTPGHI algorithm + float *m_freqGradient; + float *m_cTimeGradient; + float *m_pTimeGradient; + /// Between 0 and 1; represents the start position of playback. /// If it jumps during playback, playback will be restarted /// at the new m_startPos. @@ -269,9 +324,5 @@ namespace FlexPlugins { /// integer index of the current STFT frame (from 0 to M-1). /// Used for interpolating position. float m_pos; - - /// For the first frame, we need to read phase data directly - /// instead of computing it. - bool m_firstFrame; }; } diff --git a/src/pv/utilities.hpp b/src/pv/utilities.hpp new file mode 100644 index 0000000..241e79a --- /dev/null +++ b/src/pv/utilities.hpp @@ -0,0 +1,82 @@ +/* +File: utilities.hpp +Author: Jeff Martin + +Description: +A collection of utilities for phase vocoder stuff + +Copyright © 2026 by Jeffrey Martin. All rights reserved. +Website: https://www.jeffreymartincomposer.com + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . +*/ + +#include +#include "SC_Constants.h" + +/// Linear interpolation between a and b +/// +/// \param a The first value +/// \param b The second value +/// \param pos The position between a and b (0 <= pos <= 1) +/// \return The interpolated value +inline double interp(double a, double b, double pos) { + return a + (b-a) * pos; +} + +/// Linear interpolation between a and b +/// +/// \param a The first value +/// \param b The second value +/// \param pos The position between a and b (0 <= pos <= 1) +/// \return The interpolated value +inline float interp(float a, float b, float pos) { + return a + (b-a) * pos; +} + +/// Power interpolation between a and b +/// +/// \param a The first value +/// \param b The second value +/// \param pos The position between a and b (0 <= pos <= 1) +/// \return The interpolated value +inline double interpPower(double a, double b, double pos) { + return std::sqrt(a*a + (b*b-a*a) * pos); +} + +/// Power interpolation between a and b +/// +/// \param a The first value +/// \param b The second value +/// \param pos The position between a and b (0 <= pos <= 1) +/// \return The interpolated value +inline float interpPower(float a, float b, float pos) { + return std::sqrt(a*a + (b*b-a*a) * pos); +} + +/// Principal argument computation for the RTPGHI algorithm +/// +/// \param theta The phase to compute the principal argument for +/// \return The principal argment between 0 and 2pi +inline double princargRtpghi(double theta) { + return theta - twopi * std::round(theta / twopi); +} + +/// Principal argument computation for the RTPGHI algorithm +/// +/// \param theta The phase to compute the principal argument for +/// \return The principal argment between 0 and 2pi +inline float princargRtpghi(float theta) { + return theta - twopi * std::round(theta / static_cast(twopi)); +} \ No newline at end of file