From ae4a6c0ba72e30c9752707eec5744d94a8ebfbf8 Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Sat, 21 Nov 2026 12:06:55 -0600 Subject: [PATCH 1/9] initial refactor to align better with RTPGHI algorithm; added memory allocation and deallocation needed --- src/pv/CMakeLists.txt | 6 +- src/pv/PV_PlayBufStretch.schelp | 7 +- src/pv/hashtable.cpp | 214 ++++++++++++++++++++ src/pv/hashtable.hpp | 118 +++++++++++ src/pv/peakFinder.cpp | 137 +++++++++++++ src/pv/peakFinder.hpp | 82 ++++++++ src/pv/pqueue.hpp | 328 ++++++++++++++++++++++++++++++ src/pv/pv.sc | 2 +- src/pv/pvStretch.cpp | 347 ++++++++++++++++++-------------- src/pv/pvStretch.hpp | 117 ++++++----- src/pv/utilities.hpp | 82 ++++++++ 11 files changed, 1226 insertions(+), 214 deletions(-) create mode 100644 src/pv/hashtable.cpp create mode 100644 src/pv/hashtable.hpp create mode 100644 src/pv/peakFinder.cpp create mode 100644 src/pv/peakFinder.hpp create mode 100644 src/pv/pqueue.hpp create mode 100644 src/pv/utilities.hpp 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..d56df95 100644 --- a/src/pv/PV_PlayBufStretch.schelp +++ b/src/pv/PV_PlayBufStretch.schelp @@ -47,9 +47,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 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..4edfcf8 --- /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() { + m_maxSize = 0; + m_heap = nullptr; + m_size = 0; +} + +template +void FlexPlugins::PQueue::clear() { + m_size = 0; +} + +template +size_t FlexPlugins::PQueue::maxSize() const { + return 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) { + m_heap = static_cast*>(mem); + m_maxSize = nbytes / sizeof(std::pair); +} + +template +void* FlexPlugins::PQueue::memRetrieve() { + return static_cast(m_heap); +} + +template +std::pair FlexPlugins::PQueue::peek() const { + if (m_size > 1) { + return m_heap[1]; + } else { + return 0; + } +} + +template +size_t FlexPlugins::PQueue::size() const { + if (m_size > 0) { + return 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..c653219 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; + arg buffer, stftBuffer, startPos=0.0, rate=1.0, loop=0.0, mode=0, peakRadius=2.0, doneAction=0; ^this.multiNew('control', buffer, stftBuffer, startPos, rate, loop, phaseLock, peakRadius, doneAction); } } \ No newline at end of file diff --git a/src/pv/pvStretch.cpp b/src/pv/pvStretch.cpp index 74ea4e1..b2b8d66 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -24,9 +24,9 @@ along with this program. If not, see . #include "pvStretch.hpp" #include "SC_Constants.h" +#include "SC_InterfaceTable.h" #include #include -#define INTERP(a, b, pos) (a + (b-a) * pos) extern InterfaceTable *ft; @@ -44,11 +44,27 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { m_frameNext = nullptr; m_framePrev1 = nullptr; m_framePrev2 = nullptr; + + size_t fftSize = static_cast(buf->samples); + size_t numScBins = fftSize/2-1; + + // Set up the Laroche/Dolson peak finder 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 = static_cast(RTAlloc(mWorld, sizeof(PeakFinder))); + new (m_peakFinder) PeakFinder(fftSize, peakRadius); 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))); + m_setI->memLoad(RTAlloc(mWorld, m_setI->memSize(static_cast(fftSize * 2))), m_setI->memSize(static_cast(fftSize * 2))); + m_pgHeap = static_cast>*>(RTAlloc(mWorld, sizeof(MaxPQueue>*))); + m_pgHeap->memLoad(RTAlloc(mWorld, m_pgHeap->memSize(static_cast(fftSize * 2))), m_pgHeap->memSize(static_cast(fftSize * 2))); + + // Set up the time and frequency gradient vectors + 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)); + // Configure position float startPos = sc_clip(in0(2), 0.0, 1.0); m_pos = 0.f; @@ -67,6 +83,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, reservedMem); + } if (m_outFramePrev) { RTFree(mWorld, m_outFramePrev); } @@ -79,6 +109,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 +161,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) { @@ -264,6 +304,8 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { stftBufHopSize ); } + + powerLinearInterp(m_framePrev1, m_frameNext, p, stftBufFftSize, 1.f); } else { // Otherwise we're between two FFT frames, and we're going to have to // interpolate magnitude and frequency data. @@ -323,7 +365,11 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { stftBufHopSize ); } + + powerLinearInterp(m_framePrev1, m_frameNext, p, stftBufFftSize, newPos-static_cast(lo)); } + + // We always need to store the resultant FFT frame in the UGen. // It is used in the next call to PV_PlayBufStretch_next, for // phase vocoder calculations. @@ -351,12 +397,9 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2( SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, size_t fftSize, - size_t hopSize) { - outFrame->dc = frame->dc; - outFrame->nyq = frame->nyq; + 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; @@ -390,12 +433,9 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2Puckette( SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, size_t fftSize, - size_t hopSize) { - outFrame->dc = frame->dc; - outFrame->nyq = frame->nyq; + 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; @@ -444,18 +484,14 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( const SCPolarBuf *outFramePrev, PeakFinder *peakFinder, size_t fftSize, - size_t hopSize) { - outFrame->dc = frame->dc; - outFrame->nyq = frame->nyq; - + size_t hopSize +) { // Acquire peaks peakFinder->analyze(frame); if (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; @@ -471,8 +507,6 @@ 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; - // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; double phaseInc = frame->bin[k].phase - framePrev->bin[k].phase - hopSize * omegaK; @@ -488,8 +522,6 @@ 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; - // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; double phaseInc = frame->bin[k].phase - framePrev->bin[k].phase - hopSize * omegaK; @@ -507,7 +539,6 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( for (size_t n = 0; n < 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; // Compute the instantaneous frequency double omegaK = twopi * (peak.peak+1) / fftSize; @@ -523,14 +554,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, @@ -562,11 +591,7 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3( float pos, size_t fftSize, size_t hopSize) { - outFrame->dc = INTERP(framePrev1->dc, frameNext->dc, pos); - outFrame->nyq = INTERP(framePrev1->nyq, frameNext->nyq, pos); 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 +605,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( @@ -613,12 +638,9 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3Puckette( 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); + 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 +654,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. @@ -680,10 +702,8 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( 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); - + size_t hopSize +) { // Get the closest bin for phase relationships const SCPolarBuf *cframe = nullptr; if (pos >= 0.5) { @@ -698,7 +718,6 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( if (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 +732,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( @@ -724,8 +743,6 @@ 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); - // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; @@ -739,7 +756,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( @@ -750,8 +767,6 @@ 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); - // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; @@ -765,7 +780,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( @@ -777,7 +792,6 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( for (size_t n = 0; n < 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); // Compute the instantaneous frequency double omegaK = twopi * (peak.peak+1) / fftSize; @@ -792,7 +806,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 +816,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, @@ -849,114 +861,139 @@ 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::PV_PlayBufStretch::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::PV_PlayBufStretch::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::PV_PlayBufStretch::magLinearInterp(const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, SCPolarBuf *out, size_t fftSize, const double pos) { + size_t numScBins = fftSize/2-1; + if (prevFrame && nextFrame) { + out->dc = interp(prevFrame->dc, nextFrame->dc, static_cast(pos)); + out->nyq = interp(prevFrame->nyq, nextFrame->nyq, static_cast(pos)); + for (size_t k = 0; k < numScBins; k++) { + out->bin[k].mag = interp(prevFrame->bin[k].mag, nextFrame->bin[k].mag, static_cast(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::PV_PlayBufStretch::powerLinearInterp(const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, SCPolarBuf *out, size_t fftSize, const double pos) { + size_t numScBins = fftSize/2-1; + if (prevFrame && nextFrame) { + out->dc = interpPower(prevFrame->dc, nextFrame->dc, static_cast(pos)); + out->nyq = interpPower(prevFrame->nyq, nextFrame->nyq, static_cast(pos)); + for (size_t k = 0; k < numScBins; k++) { + out->bin[k].mag = interpPower(prevFrame->bin[k].mag, nextFrame->bin[k].mag, static_cast(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; } } -} +} \ No newline at end of file diff --git a/src/pv/pvStretch.hpp b/src/pv/pvStretch.hpp index 29f83d3..9ea5110 100644 --- a/src/pv/pvStretch.hpp +++ b/src/pv/pvStretch.hpp @@ -24,62 +24,12 @@ 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; - }; - /// Stores the state of a PV_PlayBufStretch UGen instance class PV_PlayBufStretch : public SCUnit { public: @@ -239,6 +189,54 @@ namespace FlexPlugins { /// \param numbins The number of bins in the SCPolarBuf (fftSize/2-1) void copyPolarBuf(const SCPolarBuf *sourceBuf, SCPolarBuf *destBuf, size_t numbins); + /// 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 + ); + + /// 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, size_t fftSize, const double 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, size_t fftSize, const double pos); + /// The index of the buffer with STFT data float m_fbufnum; @@ -260,6 +258,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. 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 From 5332ac836b33d0f32da560260c60ee2300a3dbf4 Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Sat, 21 Nov 2026 14:45:21 -0600 Subject: [PATCH 2/9] first attempt at incorporating rtpghi; errors in ugen free --- src/pv/PV_PlayBufStretch.schelp | 3 + src/pv/pv.sc | 4 +- src/pv/pvStretch.cpp | 381 +++++++++++++++++++++++--------- src/pv/pvStretch.hpp | 46 +++- 4 files changed, 323 insertions(+), 111 deletions(-) diff --git a/src/pv/PV_PlayBufStretch.schelp b/src/pv/PV_PlayBufStretch.schelp index d56df95..590c028 100644 --- a/src/pv/PV_PlayBufStretch.schelp +++ b/src/pv/PV_PlayBufStretch.schelp @@ -59,6 +59,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 diff --git a/src/pv/pv.sc b/src/pv/pv.sc index c653219..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, mode=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 b2b8d66..c18c993 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -23,6 +23,7 @@ along with this program. If not, see . */ #include "pvStretch.hpp" +#include "FFT_UGens.h" #include "SC_Constants.h" #include "SC_InterfaceTable.h" #include @@ -64,6 +65,11 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { 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); @@ -76,6 +82,7 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { } FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { + Print("Destructor running\n..."); if (m_peakFinder) { void *reservedMem = m_peakFinder->memRetrieve(); if (reservedMem) { @@ -83,6 +90,7 @@ FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { } RTFree(mWorld, m_peakFinder); } + Print("Peak finder destroyed\n..."); if (m_setI) { void *reservedMem = m_setI->memRetrieve(); if (reservedMem) { @@ -90,6 +98,7 @@ FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { } RTFree(mWorld, m_setI); } + Print("Set I destroyed\n..."); if (m_pgHeap) { void *reservedMem = m_pgHeap->memRetrieve(); if (reservedMem) { @@ -97,27 +106,35 @@ FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { } RTFree(mWorld, reservedMem); } + Print("PgHeap destroyed\n..."); if (m_outFramePrev) { RTFree(mWorld, m_outFramePrev); } + Print("Outp destroyed\n..."); if (m_frameNext) { RTFree(mWorld, m_frameNext); } + Print("Next destroyed\n..."); if (m_framePrev1) { RTFree(mWorld, m_framePrev1); } + Print("P1 destroyed\n..."); if (m_framePrev2) { RTFree(mWorld, m_framePrev2); } + Print("P2 destroyed\n..."); if (m_cTimeGradient) { RTFree(mWorld, m_cTimeGradient); } + Print("CG destroyed\n..."); if (m_pTimeGradient) { RTFree(mWorld, m_pTimeGradient); } + Print("PG destroyed\n..."); if (m_freqGradient) { RTFree(mWorld, m_freqGradient); } + Print("FG destroyed\n..."); } void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { @@ -212,7 +229,7 @@ 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(0, this); return; } } else if (newPos < 0) { @@ -226,7 +243,7 @@ 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(0, this); return; } } @@ -255,121 +272,185 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { // 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); + size_t phaseLock = sc_clip(static_cast(in0(5)), 0, 3); SCPolarBuf *p = ToPolarApx(buf); size_t 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 + if (phaseLock < 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 (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 + ); + } + + powerLinearInterp(m_framePrev1, m_frameNext, p, stftBufFftSize, 1.f); + } 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; + } else { + hi = static_cast(std::floor(newPos)); + lo = static_cast(std::ceil(newPos)); + loprev = lo + 1; + if (loprev >= stftFrames) loprev = lo; + } + + // 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 + ); + } + + powerLinearInterp(m_framePrev1, m_frameNext, p, stftBufFftSize, newPos-static_cast(lo)); } - - powerLinearInterp(m_framePrev1, m_frameNext, p, stftBufFftSize, 1.f); - } else { - // Otherwise we're between two FFT frames, and we're going to have to - // interpolate magnitude and frequency data. + } + + // RTPGHI algorithm + else { + // Determine position between two adjacent STFT frames size_t lo, hi, loprev; + SCPolarBuf *currentFrame, *nextFrame, *prevFrame; + if (rate >= 0) { lo = static_cast(std::floor(newPos)); hi = static_cast(std::ceil(newPos)); loprev = lo == 0 ? 0 : lo - 1; + currentFrame = m_framePrev1; + fillPolarBuf(stftData + (roundedPos * stftBufFftSize), m_framePrev1, stftBufFftSize); + if (roundedPos + 1 <= stftFrames) { + nextFrame = m_frameNext; + fillPolarBuf(stftData + ((roundedPos+1) * stftBufFftSize), m_frameNext, stftBufFftSize); + } else { + nextFrame = nullptr; + } + if (roundedPos - 1 >= 0) { + prevFrame = m_framePrev2; + fillPolarBuf(stftData + ((roundedPos+1) * stftBufFftSize), m_framePrev2, stftBufFftSize); + } else { + prevFrame = nullptr; + } } else { hi = static_cast(std::floor(newPos)); lo = static_cast(std::ceil(newPos)); loprev = lo + 1; if (loprev >= stftFrames) loprev = lo; + currentFrame = m_framePrev1; + fillPolarBuf(stftData + (roundedPos * stftBufFftSize), m_framePrev1, stftBufFftSize); + if (roundedPos + 1 <= stftFrames) { + prevFrame = m_framePrev2; + fillPolarBuf(stftData + ((roundedPos+1) * stftBufFftSize), m_framePrev2, stftBufFftSize); + } else { + prevFrame = nullptr; + } + if (roundedPos - 1 >= 0) { + nextFrame = m_frameNext; + fillPolarBuf(stftData + ((roundedPos+1) * stftBufFftSize), m_frameNext, stftBufFftSize); + } else { + nextFrame = nullptr; + } } - // 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 - ); + size_t numScBins = stftBufFftSize/2-1; + for (size_t k = 0; k < numScBins; k++) { + m_pTimeGradient[k] = m_cTimeGradient[k]; } - powerLinearInterp(m_framePrev1, m_frameNext, p, stftBufFftSize, newPos-static_cast(lo)); + cDiffTime(currentFrame, prevFrame, nextFrame, m_cTimeGradient, stftBufFftSize, stftBufHopSize); + cDiffFreq(currentFrame, m_freqGradient, stftBufFftSize, static_cast(stftBufNumOrigAudioFrames)); + double tol = sc_clip(static_cast(in0(7)), 1e-20, 1 - 1e-20); + Stretch2_RTPGHI(currentFrame, prevFrame, m_cTimeGradient, m_pTimeGradient, m_freqGradient, p, m_outFramePrev, static_cast(rate), tol, stftBufFftSize, stftBufHopSize, static_cast(stftBufNumOrigAudioFrames), m_pgHeap, m_setI); + + if (std::abs(roundedPos-newPos) < 1e-3) { + powerLinearInterp(currentFrame, nullptr, p, stftBufFftSize, 1); + } else { + powerLinearInterp(prevFrame, currentFrame, p, stftBufFftSize, newPos-static_cast(lo)); + } } - // We always need to store the resultant FFT frame in the UGen. // It is used in the next call to PV_PlayBufStretch_next, for // phase vocoder calculations. @@ -380,7 +461,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { 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. @@ -414,7 +495,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. @@ -464,7 +545,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 @@ -569,7 +650,7 @@ 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. /// 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. @@ -615,7 +696,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. @@ -678,7 +759,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 @@ -996,4 +1077,98 @@ void FlexPlugins::PV_PlayBufStretch::powerLinearInterp(const SCPolarBuf *prevFra out->bin[k].mag = nextFrame->bin[k].mag; } } +} + +/// 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 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, + MaxPQueue> *pgHeap, + IntHashSet *setI +) { + // load RNG here!! + size_t numScBins = fftSize/2-1; + + pgHeap->clear(); + + // 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 + pgHeap->clear(); + + // 2--make I + // 3--rand phases for non-I bins + // 5--initialize heap + setI->clear(); + for (size_t k = 0; k < numScBins; k++) { + if (prevFrame->bin[k].mag > abstol) { + setI->insert(k); + pgHeap->insert(prevFrame->bin[k].mag, {k, -1}); + } else { + outFrame->bin[k].mag = currentFrame->bin[k].mag; + // replace RNG call here! + outFrame->bin[k].phase = (static_cast(rand()) / static_cast(RAND_MAX)) * twopi; + } + } + + // 6--heap integration + while (setI->size() > 0) { + std::pair> bin = pgHeap->pop(); + size_t m_h = bin.second.first; + int n = bin.second.second; + if (n < 0) { + if (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; + setI->remove(m_h); + pgHeap->insert(currentFrame->bin[m_h].mag, {m_h, 0}); + } + } else { + if (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]); + setI->remove(m_h+1); + pgHeap->insert(currentFrame->bin[m_h+1].mag, {m_h+1, 0}); + } + if (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]); + setI->remove(m_h-1); + pgHeap->insert(currentFrame->bin[m_h-1].mag, {m_h-1, 0}); + } + } + } } \ No newline at end of file diff --git a/src/pv/pvStretch.hpp b/src/pv/pvStretch.hpp index 9ea5110..c0a7e5a 100644 --- a/src/pv/pvStretch.hpp +++ b/src/pv/pvStretch.hpp @@ -39,7 +39,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. @@ -58,7 +58,7 @@ namespace FlexPlugins { size_t fftSize, 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. @@ -79,7 +79,7 @@ namespace FlexPlugins { size_t fftSize, 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 @@ -101,7 +101,7 @@ namespace FlexPlugins { size_t fftSize, 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. @@ -124,7 +124,7 @@ namespace FlexPlugins { size_t fftSize, 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. @@ -149,7 +149,7 @@ namespace FlexPlugins { size_t fftSize, 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 @@ -237,6 +237,40 @@ namespace FlexPlugins { /// \param pos The position between the two frames (0 <= pos <= 1) void powerLinearInterp(const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, SCPolarBuf *out, size_t fftSize, const double pos); + /// 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, + MaxPQueue> *pgHeap, + IntHashSet *setI + ); + /// The index of the buffer with STFT data float m_fbufnum; From e73ce876977c328f07c9d1e97017914f8474b9b3 Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Sun, 22 Nov 2026 16:28:42 -0600 Subject: [PATCH 3/9] bugfixes in rtpghi --- src/pv/PV_PlayBufStretch.schelp | 6 +- src/pv/pqueue.hpp | 24 ++--- src/pv/pvStretch.cpp | 155 ++++++++++++++++++-------------- 3 files changed, 102 insertions(+), 83 deletions(-) diff --git a/src/pv/PV_PlayBufStretch.schelp b/src/pv/PV_PlayBufStretch.schelp index 590c028..1836ab0 100644 --- a/src/pv/PV_PlayBufStretch.schelp +++ b/src/pv/PV_PlayBufStretch.schelp @@ -90,13 +90,13 @@ SynthDef(\rec, { }).add; SynthDef(\play2, { - arg recBuf, rate=1, phaseLock=0, loop=0, startPos=0; + arg recBuf, rate=1, mode=0, 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, 0.1, Done.freeSelf); // Use the same window type that was used for analysis. sig = IFFT(chain, 1); Out.ar(0, Pan2.ar(sig)); @@ -104,7 +104,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, 2]); // A more unusual take. Here we modulate the playback rate, and it can go negative. ( diff --git a/src/pv/pqueue.hpp b/src/pv/pqueue.hpp index 4edfcf8..0bd9f83 100644 --- a/src/pv/pqueue.hpp +++ b/src/pv/pqueue.hpp @@ -130,19 +130,19 @@ namespace FlexPlugins { template FlexPlugins::PQueue::PQueue() { - m_maxSize = 0; - m_heap = nullptr; - m_size = 0; + this->m_maxSize = 0; + this->m_heap = nullptr; + this->m_size = 0; } template void FlexPlugins::PQueue::clear() { - m_size = 0; + this->m_size = 0; } template size_t FlexPlugins::PQueue::maxSize() const { - return m_maxSize - 1; + return this->m_maxSize - 1; } template @@ -152,19 +152,19 @@ size_t FlexPlugins::PQueue::memSize(size_t queueSize) const { template void FlexPlugins::PQueue::memLoad(void* mem, size_t nbytes) { - m_heap = static_cast*>(mem); - m_maxSize = nbytes / sizeof(std::pair); + this->m_heap = static_cast*>(mem); + this->m_maxSize = nbytes / sizeof(std::pair); } template void* FlexPlugins::PQueue::memRetrieve() { - return static_cast(m_heap); + return static_cast(this->m_heap); } template std::pair FlexPlugins::PQueue::peek() const { - if (m_size > 1) { - return m_heap[1]; + if (this->m_size > 1) { + return this->m_heap[1]; } else { return 0; } @@ -172,8 +172,8 @@ std::pair FlexPlugins::PQueue::peek() const { template size_t FlexPlugins::PQueue::size() const { - if (m_size > 0) { - return m_size - 1; + if (this->m_size > 0) { + return this->m_size - 1; } else { return 0; } diff --git a/src/pv/pvStretch.cpp b/src/pv/pvStretch.cpp index c18c993..b0d7359 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -57,9 +57,11 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { // Set up the hash set and heap for the RTPGHI algorithm m_setI = static_cast(RTAlloc(mWorld, sizeof(IntHashSet))); - m_setI->memLoad(RTAlloc(mWorld, m_setI->memSize(static_cast(fftSize * 2))), m_setI->memSize(static_cast(fftSize * 2))); - m_pgHeap = static_cast>*>(RTAlloc(mWorld, sizeof(MaxPQueue>*))); - m_pgHeap->memLoad(RTAlloc(mWorld, m_pgHeap->memSize(static_cast(fftSize * 2))), m_pgHeap->memSize(static_cast(fftSize * 2))); + 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 * 4)), m_pgHeap->memSize(fftSize * 4)); // Set up the time and frequency gradient vectors m_cTimeGradient = static_cast(RTAlloc(mWorld, sizeof(float) * numScBins)); @@ -82,7 +84,6 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { } FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { - Print("Destructor running\n..."); if (m_peakFinder) { void *reservedMem = m_peakFinder->memRetrieve(); if (reservedMem) { @@ -90,7 +91,6 @@ FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { } RTFree(mWorld, m_peakFinder); } - Print("Peak finder destroyed\n..."); if (m_setI) { void *reservedMem = m_setI->memRetrieve(); if (reservedMem) { @@ -98,43 +98,34 @@ FlexPlugins::PV_PlayBufStretch::~PV_PlayBufStretch() { } RTFree(mWorld, m_setI); } - Print("Set I destroyed\n..."); if (m_pgHeap) { void *reservedMem = m_pgHeap->memRetrieve(); if (reservedMem) { RTFree(mWorld, reservedMem); } - RTFree(mWorld, reservedMem); + RTFree(mWorld, m_pgHeap); } - Print("PgHeap destroyed\n..."); if (m_outFramePrev) { RTFree(mWorld, m_outFramePrev); } - Print("Outp destroyed\n..."); if (m_frameNext) { RTFree(mWorld, m_frameNext); } - Print("Next destroyed\n..."); if (m_framePrev1) { RTFree(mWorld, m_framePrev1); } - Print("P1 destroyed\n..."); if (m_framePrev2) { RTFree(mWorld, m_framePrev2); } - Print("P2 destroyed\n..."); if (m_cTimeGradient) { RTFree(mWorld, m_cTimeGradient); } - Print("CG destroyed\n..."); if (m_pTimeGradient) { RTFree(mWorld, m_pTimeGradient); } - Print("PG destroyed\n..."); if (m_freqGradient) { RTFree(mWorld, m_freqGradient); } - Print("FG destroyed\n..."); } void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { @@ -274,7 +265,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { else { size_t phaseLock = sc_clip(static_cast(in0(5)), 0, 3); SCPolarBuf *p = ToPolarApx(buf); - size_t roundedPos = static_cast(std::round(newPos)); + int roundedPos = static_cast(std::round(newPos)); // For traditional phase vocoder methods if (phaseLock < 3) { @@ -392,62 +383,62 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { // RTPGHI algorithm else { // Determine position between two adjacent STFT frames - size_t lo, hi, loprev; - SCPolarBuf *currentFrame, *nextFrame, *prevFrame; - - if (rate >= 0) { - lo = static_cast(std::floor(newPos)); - hi = static_cast(std::ceil(newPos)); - loprev = lo == 0 ? 0 : lo - 1; - currentFrame = m_framePrev1; - fillPolarBuf(stftData + (roundedPos * stftBufFftSize), m_framePrev1, stftBufFftSize); - if (roundedPos + 1 <= stftFrames) { - nextFrame = m_frameNext; - fillPolarBuf(stftData + ((roundedPos+1) * stftBufFftSize), m_frameNext, stftBufFftSize); - } else { - nextFrame = nullptr; - } - if (roundedPos - 1 >= 0) { - prevFrame = m_framePrev2; - fillPolarBuf(stftData + ((roundedPos+1) * stftBufFftSize), m_framePrev2, stftBufFftSize); - } else { - prevFrame = nullptr; - } + size_t lo, hi; + float 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 = static_cast(sc_clip(std::floor(newPos), 0, stftFrames-1)); + hi = static_cast(sc_clip(std::ceil(newPos), 0, stftFrames-1)); + posFrac = newPos - static_cast(lo); } else { - hi = static_cast(std::floor(newPos)); - lo = static_cast(std::ceil(newPos)); - loprev = lo + 1; - if (loprev >= stftFrames) loprev = lo; - currentFrame = m_framePrev1; - fillPolarBuf(stftData + (roundedPos * stftBufFftSize), m_framePrev1, stftBufFftSize); - if (roundedPos + 1 <= stftFrames) { - prevFrame = m_framePrev2; - fillPolarBuf(stftData + ((roundedPos+1) * stftBufFftSize), m_framePrev2, stftBufFftSize); - } else { - prevFrame = nullptr; - } - if (roundedPos - 1 >= 0) { - nextFrame = m_frameNext; - fillPolarBuf(stftData + ((roundedPos+1) * stftBufFftSize), m_frameNext, stftBufFftSize); - } else { - nextFrame = nullptr; - } + 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, stftFrames-1)); + lo = static_cast(sc_clip(std::ceil(newPos), 0, stftFrames-1)); + posFrac = newPos - static_cast(hi); } + 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]; } - cDiffTime(currentFrame, prevFrame, nextFrame, m_cTimeGradient, stftBufFftSize, stftBufHopSize); + // Compute the current gradients + 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)); - double tol = sc_clip(static_cast(in0(7)), 1e-20, 1 - 1e-20); + + const double tol = sc_clip(static_cast(in0(7)), 1e-20, 1 - 1e-20); Stretch2_RTPGHI(currentFrame, prevFrame, m_cTimeGradient, m_pTimeGradient, m_freqGradient, p, m_outFramePrev, static_cast(rate), tol, stftBufFftSize, stftBufHopSize, static_cast(stftBufNumOrigAudioFrames), m_pgHeap, m_setI); - if (std::abs(roundedPos-newPos) < 1e-3) { powerLinearInterp(currentFrame, nullptr, p, stftBufFftSize, 1); - } else { - powerLinearInterp(prevFrame, currentFrame, p, stftBufFftSize, newPos-static_cast(lo)); + } else if (currIdx == lo) { + powerLinearInterp(currentFrame, nextFrame, p, stftBufFftSize, posFrac); + } + else { + powerLinearInterp(prevFrame, currentFrame, p, stftBufFftSize, posFrac); } } @@ -461,6 +452,28 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { RELEASE_SNDBUF_SHARED(stftBuf); } +struct FrameIndices { + FrameIndices() : prevFrame1(0), prevFrame2(0), currentFrame(0), nextFrame(0) {} + size_t prevFrame2, prevFrame1, currentFrame, nextFrame; +}; + +FrameIndices getFrameIndices(const float pos, const size_t numStftFrames, const float rate) { + FrameIndices indices; + int roundedPos = static_cast(std::round(pos)); + if (rate >= 0) { + indices.currentFrame = static_cast(sc_clip(roundedPos, 0, numStftFrames-1)); + indices.prevFrame1 = static_cast(sc_clip(roundedPos-1, 0, numStftFrames-1)); + indices.prevFrame2 = static_cast(sc_clip(roundedPos-2, 0, numStftFrames-1)); + indices.nextFrame = static_cast(sc_clip(roundedPos+1, 0, numStftFrames-1)); + } else { + indices.currentFrame = static_cast(sc_clip(roundedPos, 0, numStftFrames-1)); + indices.prevFrame1 = static_cast(sc_clip(roundedPos+1, 0, numStftFrames-1)); + indices.prevFrame2 = static_cast(sc_clip(roundedPos+2, 0, numStftFrames-1)); + indices.nextFrame = static_cast(sc_clip(roundedPos-1, 0, numStftFrames-1)); + } + return indices; +} + /// 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 @@ -1112,10 +1125,12 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2_RTPGHI( MaxPQueue> *pgHeap, IntHashSet *setI ) { - // load RNG here!! - size_t numScBins = fftSize/2-1; + RGen* rgen = mParent->mRGen; + uint32 s1 = rgen->s1; \ + uint32 s2 = rgen->s2; \ + uint32 s3 = rgen->s3; - pgHeap->clear(); + size_t numScBins = fftSize/2-1; // 1--compute abstol double abstol = 0.0; @@ -1138,11 +1153,15 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2_RTPGHI( for (size_t k = 0; k < numScBins; k++) { if (prevFrame->bin[k].mag > abstol) { setI->insert(k); - pgHeap->insert(prevFrame->bin[k].mag, {k, -1}); + //pgHeap->insert(prevFrame->bin[k].mag, {k, -1}); } else { - outFrame->bin[k].mag = currentFrame->bin[k].mag; - // replace RNG call here! - outFrame->bin[k].phase = (static_cast(rand()) / static_cast(RAND_MAX)) * twopi; + outFrame->bin[k].phase = rgen->frand() * twopi; + } + } + + for (size_t k = 0; k < numScBins; k++) { + if (prevFrame->bin[k].mag > abstol) { + pgHeap->insert(prevFrame->bin[k].mag, {k, -1}); } } @@ -1171,4 +1190,4 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2_RTPGHI( } } } -} \ No newline at end of file +} From 738b22868eb783a249c39c3584725bb8c296f2cf Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Sun, 22 Nov 2026 17:11:46 -0600 Subject: [PATCH 4/9] help file fix --- src/pv/PV_PlayBufStretch.schelp | 29 +-- src/pv/pvStretch.cpp | 400 ++++++++++++++++---------------- src/pv/pvStretch.hpp | 242 +++++++++---------- 3 files changed, 339 insertions(+), 332 deletions(-) diff --git a/src/pv/PV_PlayBufStretch.schelp b/src/pv/PV_PlayBufStretch.schelp index 1836ab0..1b9a4bf 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:: diff --git a/src/pv/pvStretch.cpp b/src/pv/pvStretch.cpp index b0d7359..9903ab8 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -45,14 +45,15 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { m_frameNext = nullptr; m_framePrev1 = nullptr; m_framePrev2 = nullptr; + m_cTimeGradient = nullptr; + m_pTimeGradient = nullptr; + m_freqGradient = nullptr; - size_t fftSize = static_cast(buf->samples); - size_t numScBins = fftSize/2-1; + const size_t fftSize = static_cast(buf->samples); // Set up the Laroche/Dolson peak finder - size_t peakRadius = static_cast(sc_clip(in0(6), 1.f, 32.f)); m_peakFinder = static_cast(RTAlloc(mWorld, sizeof(PeakFinder))); - new (m_peakFinder) PeakFinder(fftSize, peakRadius); + 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 @@ -64,6 +65,7 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { m_pgHeap->memLoad(RTAlloc(mWorld, m_pgHeap->memSize(fftSize * 4)), m_pgHeap->memSize(fftSize * 4)); // 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)); @@ -74,10 +76,8 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { } // Configure position - float startPos = sc_clip(in0(2), 0.0, 1.0); m_pos = 0.f; - m_startPos = startPos; - m_firstFrame = true; + m_startPos = sc_clip(in0(2), 0.0, 1.0); set_calc_function(); next(1); @@ -195,14 +195,16 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { 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 (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. @@ -211,7 +213,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 @@ -225,7 +227,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { } } 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 @@ -241,15 +243,15 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { // 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 @@ -258,17 +260,17 @@ 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, 3); - SCPolarBuf *p = ToPolarApx(buf); + size_t mode = sc_clip(static_cast(in0(5)), 0, 3); + SCPolarBuf *outFrame = ToPolarApx(buf); int roundedPos = static_cast(std::round(newPos)); // For traditional phase vocoder methods - if (phaseLock < 3) { + 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. @@ -282,12 +284,12 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { fillPolarBuf(stftData + (roundedPos * stftBufFftSize), m_frameNext, stftBufFftSize); fillPolarBuf(stftData + (lastPos * stftBufFftSize), m_framePrev1, stftBufFftSize); // Render the output FFT frame - switch (phaseLock) { + switch (mode) { case 1: Stretch2Puckette( m_frameNext, m_framePrev1, - p, + outFrame, m_outFramePrev, stftBufFftSize, stftBufHopSize @@ -297,9 +299,8 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { Stretch2LarocheDolson( m_frameNext, m_framePrev1, - p, + outFrame, m_outFramePrev, - m_peakFinder, stftBufFftSize, stftBufHopSize ); @@ -308,42 +309,44 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { Stretch2( m_frameNext, m_framePrev1, - p, + outFrame, m_outFramePrev, stftBufFftSize, stftBufHopSize ); } - powerLinearInterp(m_framePrev1, m_frameNext, p, stftBufFftSize, 1.f); + // Copy the magnitude data over + powerLinearInterp(m_framePrev1, 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. - size_t lo, hi, loprev; + size_t lo, hi, loMinus1; if (rate >= 0) { lo = static_cast(std::floor(newPos)); hi = static_cast(std::ceil(newPos)); - loprev = lo == 0 ? 0 : lo - 1; + loMinus1 = lo == 0 ? 0 : lo - 1; } else { hi = static_cast(std::floor(newPos)); lo = static_cast(std::ceil(newPos)); - loprev = lo + 1; - if (loprev >= stftFrames) loprev = lo; + loMinus1 = lo + 1; + if (loMinus1 >= stftFrames) loMinus1 = lo; } // 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); + fillPolarBuf(stftData + (loMinus1 * stftBufFftSize), m_framePrev2, stftBufFftSize); + // Render the output FFT frame - switch (phaseLock) { + switch (mode) { case 1: Stretch3Puckette( m_frameNext, m_framePrev1, m_framePrev2, - p, + outFrame, m_outFramePrev, newPos-static_cast(lo), stftBufFftSize, @@ -355,9 +358,8 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { m_frameNext, m_framePrev1, m_framePrev2, - p, + outFrame, m_outFramePrev, - m_peakFinder, newPos-static_cast(lo), stftBufFftSize, stftBufHopSize @@ -368,7 +370,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { m_frameNext, m_framePrev1, m_framePrev2, - p, + outFrame, m_outFramePrev, newPos-static_cast(lo), stftBufFftSize, @@ -376,11 +378,12 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { ); } - powerLinearInterp(m_framePrev1, m_frameNext, p, stftBufFftSize, newPos-static_cast(lo)); + // Interpolate the magnitude data using power level + powerLinearInterp(m_framePrev1, m_frameNext, outFrame, stftBufFftSize, newPos-static_cast(lo)); } } - // RTPGHI algorithm + // RTPGHI algorithm, mode 3 else { // Determine position between two adjacent STFT frames size_t lo, hi; @@ -430,50 +433,45 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { } 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, p, m_outFramePrev, static_cast(rate), tol, stftBufFftSize, stftBufHopSize, static_cast(stftBufNumOrigAudioFrames), m_pgHeap, m_setI); + + Stretch2_RTPGHI( + currentFrame, + prevFrame, + m_cTimeGradient, + m_pTimeGradient, + m_freqGradient, + outFrame, + m_outFramePrev, + static_cast(rate), + tol, + stftBufFftSize, + stftBufHopSize, + static_cast(stftBufNumOrigAudioFrames) + ); + + // Interpolate the magnitude data using power if (std::abs(roundedPos-newPos) < 1e-3) { - powerLinearInterp(currentFrame, nullptr, p, stftBufFftSize, 1); + powerLinearInterp(currentFrame, nullptr, outFrame, stftBufFftSize, 1); } else if (currIdx == lo) { - powerLinearInterp(currentFrame, nextFrame, p, stftBufFftSize, posFrac); + powerLinearInterp(currentFrame, nextFrame, outFrame, stftBufFftSize, posFrac); } else { - powerLinearInterp(prevFrame, currentFrame, p, stftBufFftSize, posFrac); + 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 // phase vocoder calculations. - copyPolarBuf(p, m_outFramePrev, static_cast(numbins)); + copyPolarBuf(outFrame, m_outFramePrev, static_cast(numbins)); m_pos = newPos; } RELEASE_SNDBUF_SHARED(stftBuf); } -struct FrameIndices { - FrameIndices() : prevFrame1(0), prevFrame2(0), currentFrame(0), nextFrame(0) {} - size_t prevFrame2, prevFrame1, currentFrame, nextFrame; -}; - -FrameIndices getFrameIndices(const float pos, const size_t numStftFrames, const float rate) { - FrameIndices indices; - int roundedPos = static_cast(std::round(pos)); - if (rate >= 0) { - indices.currentFrame = static_cast(sc_clip(roundedPos, 0, numStftFrames-1)); - indices.prevFrame1 = static_cast(sc_clip(roundedPos-1, 0, numStftFrames-1)); - indices.prevFrame2 = static_cast(sc_clip(roundedPos-2, 0, numStftFrames-1)); - indices.nextFrame = static_cast(sc_clip(roundedPos+1, 0, numStftFrames-1)); - } else { - indices.currentFrame = static_cast(sc_clip(roundedPos, 0, numStftFrames-1)); - indices.prevFrame1 = static_cast(sc_clip(roundedPos+1, 0, numStftFrames-1)); - indices.prevFrame2 = static_cast(sc_clip(roundedPos+2, 0, numStftFrames-1)); - indices.nextFrame = static_cast(sc_clip(roundedPos-1, 0, numStftFrames-1)); - } - return indices; -} - /// 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 @@ -490,8 +488,8 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2( const SCPolarBuf *framePrev, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - size_t fftSize, - size_t hopSize + const size_t fftSize, + const size_t hopSize ) { for (size_t k = 0; k < fftSize/2-1; k++) { // Compute the instantaneous frequency @@ -526,8 +524,8 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2Puckette( const SCPolarBuf *framePrev, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - size_t fftSize, - size_t hopSize + const size_t fftSize, + const size_t hopSize ) { for (size_t k = 0; k < fftSize/2-1; k++) { // Compute the instantaneous frequency @@ -575,15 +573,14 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( const SCPolarBuf *frame, const SCPolarBuf *framePrev, SCPolarBuf *outFrame, - const SCPolarBuf *outFramePrev, - PeakFinder *peakFinder, - size_t fftSize, - size_t hopSize + 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++) { // Compute the instantaneous frequency @@ -600,7 +597,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++) { + 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; @@ -615,7 +612,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++) { + 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; @@ -630,9 +627,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]; + Peak peak = m_peakFinder->peaks[n]; // Compute the instantaneous frequency double omegaK = twopi * (peak.peak+1) / fftSize; @@ -663,6 +660,96 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2LarocheDolson( } } +/// 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 @@ -682,9 +769,9 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3( 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) { for (size_t k = 0; k < fftSize/2-1; k++) { float omegaK = twopi * (k+1) / fftSize; @@ -730,9 +817,9 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3Puckette( 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 ) { for (size_t k = 0; k < fftSize/2-1; k++) { float omegaK = twopi * (k+1) / fftSize; @@ -783,7 +870,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 @@ -793,10 +879,9 @@ void FlexPlugins::PV_PlayBufStretch::Stretch3LarocheDolson( const SCPolarBuf *framePrev2, SCPolarBuf *outFrame, const SCPolarBuf *outFramePrev, - PeakFinder *peakFinder, - double pos, - size_t fftSize, - size_t hopSize + const double pos, + const size_t fftSize, + const size_t hopSize ) { // Get the closest bin for phase relationships const SCPolarBuf *cframe = nullptr; @@ -807,9 +892,9 @@ 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++) { @@ -836,7 +921,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++) { + for (size_t k = 0; k < m_peakFinder->peaks[0].leftValley; k++) { // Compute the instantaneous frequency double omegaK = twopi * (k+1) / fftSize; @@ -860,7 +945,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++) { + 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; @@ -883,9 +968,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]; + Peak peak = m_peakFinder->peaks[n]; // Compute the instantaneous frequency double omegaK = twopi * (peak.peak+1) / fftSize; @@ -930,7 +1015,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 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++) { @@ -946,7 +1031,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 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++) { @@ -955,14 +1040,13 @@ void FlexPlugins::PV_PlayBufStretch::copyPolarBuf(const SCPolarBuf *sourceBuf, S } } - /// 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::PV_PlayBufStretch::cDiffFreq( +void cDiffFreq( const SCPolarBuf *currentFrame, float *freqGradient, const size_t fftSize, @@ -991,7 +1075,7 @@ void FlexPlugins::PV_PlayBufStretch::cDiffFreq( /// \param [out] timeGradient The output time gradient vector /// \param fftSize The FFT size /// \param hopSize The analysis hop size -void FlexPlugins::PV_PlayBufStretch::cDiffTime( +void cDiffTime( const SCPolarBuf *currentFrame, const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, @@ -1039,7 +1123,13 @@ void FlexPlugins::PV_PlayBufStretch::cDiffTime( /// \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::PV_PlayBufStretch::magLinearInterp(const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, SCPolarBuf *out, size_t fftSize, const double pos) { +void magLinearInterp( + const SCPolarBuf *prevFrame, + const SCPolarBuf *nextFrame, + SCPolarBuf *out, + const size_t fftSize, + const double pos +) { size_t numScBins = fftSize/2-1; if (prevFrame && nextFrame) { out->dc = interp(prevFrame->dc, nextFrame->dc, static_cast(pos)); @@ -1069,7 +1159,13 @@ void FlexPlugins::PV_PlayBufStretch::magLinearInterp(const SCPolarBuf *prevFrame /// \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::PV_PlayBufStretch::powerLinearInterp(const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, SCPolarBuf *out, size_t fftSize, const double pos) { +void powerLinearInterp( + const SCPolarBuf *prevFrame, + const SCPolarBuf *nextFrame, + SCPolarBuf *out, + const size_t fftSize, + const double pos +) { size_t numScBins = fftSize/2-1; if (prevFrame && nextFrame) { out->dc = interpPower(prevFrame->dc, nextFrame->dc, static_cast(pos)); @@ -1091,103 +1187,3 @@ void FlexPlugins::PV_PlayBufStretch::powerLinearInterp(const SCPolarBuf *prevFra } } } - -/// 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 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, - MaxPQueue> *pgHeap, - IntHashSet *setI -) { - 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 - pgHeap->clear(); - - // 2--make I - // 3--rand phases for non-I bins - // 5--initialize heap - setI->clear(); - for (size_t k = 0; k < numScBins; k++) { - if (prevFrame->bin[k].mag > abstol) { - setI->insert(k); - //pgHeap->insert(prevFrame->bin[k].mag, {k, -1}); - } else { - outFrame->bin[k].phase = rgen->frand() * twopi; - } - } - - for (size_t k = 0; k < numScBins; k++) { - if (prevFrame->bin[k].mag > abstol) { - pgHeap->insert(prevFrame->bin[k].mag, {k, -1}); - } - } - - // 6--heap integration - while (setI->size() > 0) { - std::pair> bin = pgHeap->pop(); - size_t m_h = bin.second.first; - int n = bin.second.second; - if (n < 0) { - if (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; - setI->remove(m_h); - pgHeap->insert(currentFrame->bin[m_h].mag, {m_h, 0}); - } - } else { - if (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]); - setI->remove(m_h+1); - pgHeap->insert(currentFrame->bin[m_h+1].mag, {m_h+1, 0}); - } - if (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]); - setI->remove(m_h-1); - pgHeap->insert(currentFrame->bin[m_h-1].mag, {m_h-1, 0}); - } - } - } -} diff --git a/src/pv/pvStretch.hpp b/src/pv/pvStretch.hpp index c0a7e5a..60aaf97 100644 --- a/src/pv/pvStretch.hpp +++ b/src/pv/pvStretch.hpp @@ -30,6 +30,80 @@ along with this program. If not, see . #include "utilities.hpp" namespace FlexPlugins { + /// 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 double 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 double pos + ); + /// Stores the state of a PV_PlayBufStretch UGen instance class PV_PlayBufStretch : public SCUnit { public: @@ -55,8 +129,9 @@ 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 phases for time stretching. /// The assumption is that we are positioned exactly at `frame`, and we therefore @@ -76,8 +151,9 @@ 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 phases for time stretching, /// using the Laroche/Dolson identity phase locking scheme. @@ -89,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( @@ -97,9 +172,41 @@ 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 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. @@ -120,9 +227,10 @@ 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 phases for time stretching. /// The assumption is that we are positioned between framePrev1 and frameNext. @@ -145,9 +253,10 @@ 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 phases for time stretching, /// using the Laroche/Dolson identity phase locking scheme. @@ -160,117 +269,20 @@ 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); - - /// 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 double pos, const size_t fftSize, const size_t hopSize ); - /// 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, size_t fftSize, const double 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, size_t fftSize, const double pos); - - /// 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, - MaxPQueue> *pgHeap, - IntHashSet *setI - ); - /// The index of the buffer with STFT data float m_fbufnum; @@ -312,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; }; } From 24a4523f718bc6dedb7cf1b52776d6882cf4c061 Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Sun, 22 Nov 2026 17:52:21 -0600 Subject: [PATCH 5/9] memsize fix; namespace issue fix --- src/pv/pvStretch.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/pv/pvStretch.cpp b/src/pv/pvStretch.cpp index 9903ab8..9f53629 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -62,7 +62,7 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { 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 * 4)), m_pgHeap->memSize(fftSize * 4)); + 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; @@ -1015,7 +1015,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 fillPolarBuf(const float *fftBuf, SCPolarBuf *polarBuf, const 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++) { @@ -1031,7 +1031,7 @@ void fillPolarBuf(const float *fftBuf, SCPolarBuf *polarBuf, const size_t fftSiz /// \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, const 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++) { @@ -1046,7 +1046,7 @@ void copyPolarBuf(const SCPolarBuf *sourceBuf, SCPolarBuf *destBuf, const size_t /// \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( +void FlexPlugins::cDiffFreq( const SCPolarBuf *currentFrame, float *freqGradient, const size_t fftSize, @@ -1075,7 +1075,7 @@ void cDiffFreq( /// \param [out] timeGradient The output time gradient vector /// \param fftSize The FFT size /// \param hopSize The analysis hop size -void cDiffTime( +void FlexPlugins::cDiffTime( const SCPolarBuf *currentFrame, const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, @@ -1123,7 +1123,7 @@ void cDiffTime( /// \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( +void FlexPlugins::magLinearInterp( const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, SCPolarBuf *out, @@ -1159,7 +1159,7 @@ void magLinearInterp( /// \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( +void FlexPlugins::powerLinearInterp( const SCPolarBuf *prevFrame, const SCPolarBuf *nextFrame, SCPolarBuf *out, From 6d3217ba69fe1469e6e31f97ce8f67bfd7c7f02b Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Sun, 22 Nov 2026 18:35:19 -0600 Subject: [PATCH 6/9] fixed rate issue in rtpghi --- src/pv/pvStretch.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pv/pvStretch.cpp b/src/pv/pvStretch.cpp index 9f53629..66c3344 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -444,7 +444,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { m_freqGradient, outFrame, m_outFramePrev, - static_cast(rate), + sc_clip(1.0/static_cast(rate), 1e-3, 1e3), tol, stftBufFftSize, stftBufHopSize, From 9530cd022597af3b8c49408c6341bd264e61dbd8 Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Sun, 22 Nov 2026 18:35:45 -0600 Subject: [PATCH 7/9] formatting fix --- src/pv/pvStretch.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/pv/pvStretch.cpp b/src/pv/pvStretch.cpp index 66c3344..13fa3ee 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -690,8 +690,8 @@ void FlexPlugins::PV_PlayBufStretch::Stretch2_RTPGHI( const double signalLen ) { RGen* rgen = mParent->mRGen; - uint32 s1 = rgen->s1; \ - uint32 s2 = rgen->s2; \ + uint32 s1 = rgen->s1; + uint32 s2 = rgen->s2; uint32 s3 = rgen->s3; size_t numScBins = fftSize/2-1; From 3aafe7d3d56e428ad69ed49cd764df9bd5f2cc10 Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Sun, 22 Nov 2026 18:41:06 -0600 Subject: [PATCH 8/9] doc updates --- README.md | 2 +- src/pv/PV_PlayBufStretch.schelp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) 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/PV_PlayBufStretch.schelp b/src/pv/PV_PlayBufStretch.schelp index 1b9a4bf..34fdee7 100644 --- a/src/pv/PV_PlayBufStretch.schelp +++ b/src/pv/PV_PlayBufStretch.schelp @@ -93,13 +93,13 @@ SynthDef(\rec, { }).add; SynthDef(\play2, { - arg recBuf, rate=1, mode=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, mode, 2.0, 0.1, 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)); @@ -107,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, \mode, 2]); +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. ( From a2ef8fe8150708513f1892c4ec20d6db4c746665 Mon Sep 17 00:00:00 2001 From: Jeff Martin Date: Tue, 24 Nov 2026 08:43:17 -0600 Subject: [PATCH 9/9] fixed rate bug in pv_playbufstretch --- src/pv/pvStretch.cpp | 76 ++++++++++++++++++++++++-------------------- src/pv/pvStretch.hpp | 4 +-- 2 files changed, 44 insertions(+), 36 deletions(-) diff --git a/src/pv/pvStretch.cpp b/src/pv/pvStretch.cpp index 13fa3ee..973d4fd 100644 --- a/src/pv/pvStretch.cpp +++ b/src/pv/pvStretch.cpp @@ -76,8 +76,8 @@ FlexPlugins::PV_PlayBufStretch::PV_PlayBufStretch() { } // Configure position - m_pos = 0.f; - m_startPos = sc_clip(in0(2), 0.0, 1.0); + 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); @@ -189,6 +189,7 @@ 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; @@ -202,6 +203,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { // 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; firstFrame = true; @@ -222,7 +224,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { float *outBuf = out(0); outBuf[0] = -1.f; RELEASE_SNDBUF_SHARED(stftBuf); - DoneAction(0, this); + DoneAction(static_cast(in0(8)), this); return; } } else if (newPos < 0) { @@ -236,7 +238,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { float *outBuf = out(0); outBuf[0] = -1.f; RELEASE_SNDBUF_SHARED(stftBuf); - DoneAction(0, this); + DoneAction(static_cast(in0(8)), this); return; } } @@ -265,11 +267,15 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { // For frames other than the first frame, we'll need to perform phase computation. else { + // 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)); - // For traditional phase vocoder methods + // 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 @@ -317,20 +323,23 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { } // Copy the magnitude data over - powerLinearInterp(m_framePrev1, m_frameNext, outFrame, stftBufFftSize, 1.f); + 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. - size_t lo, hi, loMinus1; + int lo, hi, loMinus1; + float posFrac; if (rate >= 0) { - lo = static_cast(std::floor(newPos)); - hi = static_cast(std::ceil(newPos)); + 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)); + 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 @@ -348,7 +357,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { m_framePrev2, outFrame, m_outFramePrev, - newPos-static_cast(lo), + posFrac, stftBufFftSize, stftBufHopSize ); @@ -360,7 +369,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { m_framePrev2, outFrame, m_outFramePrev, - newPos-static_cast(lo), + posFrac, stftBufFftSize, stftBufHopSize ); @@ -372,22 +381,21 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { m_framePrev2, outFrame, m_outFramePrev, - newPos-static_cast(lo), + posFrac, stftBufFftSize, stftBufHopSize ); } // Interpolate the magnitude data using power level - powerLinearInterp(m_framePrev1, m_frameNext, outFrame, stftBufFftSize, newPos-static_cast(lo)); + powerLinearInterp(m_framePrev1, m_frameNext, outFrame, stftBufFftSize, posFrac); } } // RTPGHI algorithm, mode 3 else { // Determine position between two adjacent STFT frames - size_t lo, hi; - float posFrac; + float lo, hi, posFrac; // Determine current, previous, and next indices size_t currIdx, prevIdx, nextIdx; @@ -401,16 +409,16 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { 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 = static_cast(sc_clip(std::floor(newPos), 0, stftFrames-1)); - hi = static_cast(sc_clip(std::ceil(newPos), 0, stftFrames-1)); - posFrac = newPos - static_cast(lo); + 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 { 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, stftFrames-1)); - lo = static_cast(sc_clip(std::ceil(newPos), 0, stftFrames-1)); - posFrac = newPos - static_cast(hi); + 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; } fillPolarBuf(stftData + (currIdx * stftBufFftSize), currentFrame, stftBufFftSize); @@ -423,7 +431,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { m_pTimeGradient[k] = m_cTimeGradient[k]; } - // Compute the current gradients + // Compute the time and frequency partial derivatives if (currIdx == prevIdx) { cDiffTime(currentFrame, nullptr, nextFrame, m_cTimeGradient, stftBufFftSize, stftBufHopSize); } else if (currIdx == nextIdx) { @@ -444,7 +452,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { m_freqGradient, outFrame, m_outFramePrev, - sc_clip(1.0/static_cast(rate), 1e-3, 1e3), + 1.0, // because we are keeping the same hop size tol, stftBufFftSize, stftBufHopSize, @@ -463,7 +471,7 @@ void FlexPlugins::PV_PlayBufStretch::next(int inNumSamples) { } // 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(outFrame, m_outFramePrev, static_cast(numbins)); m_pos = newPos; @@ -1128,14 +1136,14 @@ void FlexPlugins::magLinearInterp( const SCPolarBuf *nextFrame, SCPolarBuf *out, const size_t fftSize, - const double pos + const float pos ) { size_t numScBins = fftSize/2-1; if (prevFrame && nextFrame) { - out->dc = interp(prevFrame->dc, nextFrame->dc, static_cast(pos)); - out->nyq = interp(prevFrame->nyq, nextFrame->nyq, static_cast(pos)); + 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, static_cast(pos)); + out->bin[k].mag = interp(prevFrame->bin[k].mag, nextFrame->bin[k].mag, pos); } } else if (prevFrame) { out->dc = prevFrame->dc; @@ -1164,14 +1172,14 @@ void FlexPlugins::powerLinearInterp( const SCPolarBuf *nextFrame, SCPolarBuf *out, const size_t fftSize, - const double pos + const float pos ) { size_t numScBins = fftSize/2-1; if (prevFrame && nextFrame) { - out->dc = interpPower(prevFrame->dc, nextFrame->dc, static_cast(pos)); - out->nyq = interpPower(prevFrame->nyq, nextFrame->nyq, static_cast(pos)); + 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, static_cast(pos)); + out->bin[k].mag = interpPower(prevFrame->bin[k].mag, nextFrame->bin[k].mag, pos); } } else if (prevFrame) { out->dc = prevFrame->dc; diff --git a/src/pv/pvStretch.hpp b/src/pv/pvStretch.hpp index 60aaf97..0451b31 100644 --- a/src/pv/pvStretch.hpp +++ b/src/pv/pvStretch.hpp @@ -86,7 +86,7 @@ namespace FlexPlugins { const SCPolarBuf *nextFrame, SCPolarBuf *out, const size_t fftSize, - const double pos + const float pos ); /// Linearly interpolates the magnitude of two STFT frames using the power @@ -101,7 +101,7 @@ namespace FlexPlugins { const SCPolarBuf *nextFrame, SCPolarBuf *out, const size_t fftSize, - const double pos + const float pos ); /// Stores the state of a PV_PlayBufStretch UGen instance