@audio/stretch-pghi 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (5) hide show
  1. package/LICENSE +25 -0
  2. package/README.md +26 -0
  3. package/package.json +48 -0
  4. package/pghi.d.ts +12 -0
  5. package/pghi.js +200 -0
package/LICENSE ADDED
@@ -0,0 +1,25 @@
1
+ MIT License
2
+
3
+ Copyright (c) Dmitry Iv
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
23
+ ---
24
+
25
+ This work is offered under the Krishnized License (https://github.com/krishnized/license).
package/README.md ADDED
@@ -0,0 +1,26 @@
1
+ # @audio/stretch-pghi
2
+
3
+ Phase Gradient Heap Integration vocoder — "Phase Vocoder Done Right" (Průša & Holighaus, 2017), causal RTPGHI variant. Synthesis phase is integrated from the analysis phase gradients (instantaneous frequency across time, stretched group delay across frequency), visiting bins in order of decreasing magnitude via a max-heap — phase always flows from strong bins into their neighbourhoods.
4
+
5
+ No peak picking, no transient heuristics: chirps, vibrato and dense spectra stay coherent by construction.
6
+
7
+ ```js
8
+ import pghi from '@audio/stretch-pghi'
9
+ let out = pghi(data, { factor: 2 })
10
+ ```
11
+
12
+ | Param | Default | |
13
+ |---|---|---|
14
+ | `factor` | `1` | Time stretch ratio |
15
+ | `frameSize` | `2048` | FFT size (power of 2) |
16
+ | `hopSize` | `frameSize/8` | Hop — gradient integration wants denser frames than peak locking |
17
+ | `tolerance` | `1e-6` | Bins below `tolerance×max` get random phase |
18
+
19
+ **Use when:** modulated material — vibrato, glides, chirps, pitch-unstable sources (measured: beats [`@audio/stretch-pvoc-lock`](../stretch-pvoc-lock) on tones/glissandi, ~4× better than plain pvoc on sweeps).<br>
20
+ **Not for:** steady polyphony — identity phase locking reproduces exact intra-region phase relations that first-order gradient integration only approximates; use [`@audio/stretch-pvoc-lock`](../stretch-pvoc-lock) there.
21
+
22
+ Part of [`@audio/stretch`](../..).
23
+
24
+ ## License
25
+
26
+ [MIT](./LICENSE) · [ॐ](https://github.com/krishnized/license/)
package/package.json ADDED
@@ -0,0 +1,48 @@
1
+ {
2
+ "name": "@audio/stretch-pghi",
3
+ "version": "1.0.0",
4
+ "description": "Phase Gradient Heap Integration vocoder (Průša & Holighaus \"Phase Vocoder Done Right\") — no peak picking, no transient heuristics",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "main": "pghi.js",
8
+ "types": "pghi.d.ts",
9
+ "exports": {
10
+ ".": "./pghi.js",
11
+ "./package.json": "./package.json"
12
+ },
13
+ "files": [
14
+ "pghi.js",
15
+ "pghi.d.ts",
16
+ "README.md",
17
+ "LICENSE"
18
+ ],
19
+ "dependencies": {
20
+ "@audio/stretch-core": "^1.0.0",
21
+ "fourier-transform": "^2.3.0"
22
+ },
23
+ "keywords": [
24
+ "audio",
25
+ "dsp",
26
+ "time-stretch",
27
+ "phase-vocoder",
28
+ "pghi",
29
+ "rtpghi",
30
+ "phase-gradient",
31
+ "stft"
32
+ ],
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "license": "MIT",
37
+ "author": "Dmitry Iv. <dfcreative@gmail.com>",
38
+ "homepage": "https://github.com/audiojs/stretch/tree/main/packages/stretch-pghi",
39
+ "repository": {
40
+ "type": "git",
41
+ "url": "git+https://github.com/audiojs/stretch.git",
42
+ "directory": "packages/stretch-pghi"
43
+ },
44
+ "bugs": "https://github.com/audiojs/stretch/issues",
45
+ "engines": {
46
+ "node": ">=18"
47
+ }
48
+ }
package/pghi.d.ts ADDED
@@ -0,0 +1,12 @@
1
+ import type { StreamWriter, StretchOpts } from '@audio/stretch-core'
2
+
3
+ export interface PghiOpts extends StretchOpts {
4
+ /** Bins below tolerance×frame-max get random phase (no reliable gradient). Default 1e-6 */
5
+ tolerance?: number
6
+ }
7
+
8
+ declare const pghi: {
9
+ (data: Float32Array, opts?: PghiOpts): Float32Array
10
+ (opts?: PghiOpts): StreamWriter
11
+ }
12
+ export default pghi
package/pghi.js ADDED
@@ -0,0 +1,200 @@
1
+ // Phase Gradient Heap Integration vocoder — "Phase Vocoder Done Right"
2
+ // (Průša & Holighaus, DAFx 2017), causal RTPGHI variant.
3
+ //
4
+ // Instead of propagating every bin's phase independently (pvoc) or locking bins
5
+ // to picked peaks (pvoc-lock), synthesis phase is *integrated* from the analysis
6
+ // phase gradients — along time at each bin's instantaneous frequency, along
7
+ // frequency at the stretched local group delay — visiting bins in order of
8
+ // decreasing magnitude via a max-heap, so phase always flows from strong bins
9
+ // into their neighbourhoods. No peak picking, no transient heuristics; chirps,
10
+ // vibrato and dense spectra stay coherent by construction.
11
+ //
12
+ // Bins below `tolerance`·max get random phase (they carry no reliable gradient).
13
+ //
14
+ // References:
15
+ // - Průša, Z. & Holighaus, N. (2017). "Phase Vocoder Done Right." EUSIPCO/DAFx.
16
+ // - Průša, Z. & Søndergaard, P. (2016). "Real-Time Spectrogram Inversion Using
17
+ // Phase Gradient Heap Integration" (RTPGHI). DAFx-16.
18
+
19
+ import { stftBatch, stftStream } from 'fourier-transform/stft'
20
+ import { writer, wrapPhase, stretchOpts, PI2 } from '@audio/stretch-core'
21
+
22
+ // Binary max-heap over (key, item) pairs stored in state-owned arrays.
23
+ function heapPush(keys, items, size, key, item) {
24
+ let i = size
25
+ keys[i] = key; items[i] = item
26
+ while (i > 0) {
27
+ let p = (i - 1) >> 1
28
+ if (keys[p] >= keys[i]) break
29
+ let k = keys[p]; keys[p] = keys[i]; keys[i] = k
30
+ let t = items[p]; items[p] = items[i]; items[i] = t
31
+ i = p
32
+ }
33
+ return size + 1
34
+ }
35
+
36
+ function heapPop(keys, items, size) {
37
+ let last = size - 1
38
+ let top = items[0]
39
+ keys[0] = keys[last]; items[0] = items[last]
40
+ let i = 0
41
+ for (;;) {
42
+ let l = 2 * i + 1, r = l + 1, m = i
43
+ if (l < last && keys[l] > keys[m]) m = l
44
+ if (r < last && keys[r] > keys[m]) m = r
45
+ if (m === i) break
46
+ let k = keys[m]; keys[m] = keys[i]; keys[i] = k
47
+ let t = items[m]; items[m] = items[i]; items[i] = t
48
+ i = m
49
+ }
50
+ return top
51
+ }
52
+
53
+ function makeProcess(tolerance) {
54
+ return function process(mag, phase, state, ctx) {
55
+ let { half, anaHop, synHop, freqPerBin, frameStart } = ctx
56
+ let B = half + 1
57
+ let r = synHop / anaHop
58
+
59
+ if (!state.prevPhase) {
60
+ state.prevPhase = new Float64Array(B)
61
+ state.prevMag = new Float64Array(B)
62
+ state.prevTgrad = new Float64Array(B)
63
+ state.synPrev = new Float64Array(B) // center-origin synthesis phases
64
+ state.tgrad = new Float64Array(B)
65
+ state.fgrad = new Float64Array(B)
66
+ state.p = new Float64Array(B)
67
+ state.heapKeys = new Float64Array(2 * B)
68
+ state.heapItems = new Int32Array(2 * B)
69
+ state.assigned = new Uint8Array(B)
70
+ state.seed = 0x9e3779b9
71
+ state.first = true
72
+ }
73
+
74
+ // Pass pre-pad partial frames through; anchor on the first full frame.
75
+ if (state.first) {
76
+ if (frameStart < 0) return { mag, phase }
77
+ for (let m = 0; m < B; m++) {
78
+ state.prevPhase[m] = phase[m]
79
+ state.prevMag[m] = mag[m]
80
+ state.synPrev[m] = phase[m] + Math.PI * m // to center-origin
81
+ state.prevTgrad[m] = m * freqPerBin * synHop
82
+ }
83
+ state.first = false
84
+ return { mag, phase }
85
+ }
86
+
87
+ let tgrad = state.tgrad, fgrad = state.fgrad
88
+ let assigned = state.assigned, keys = state.heapKeys, items = state.heapItems
89
+ let synPrev = state.synPrev, p = state.p
90
+
91
+ // Time gradient: phase advance per synthesis hop at each bin's instantaneous
92
+ // frequency (standard heterodyned estimate; the center-origin term cancels
93
+ // in the frame-to-frame difference).
94
+ for (let m = 0; m < B; m++) {
95
+ let dp = wrapPhase(phase[m] - state.prevPhase[m] - m * freqPerBin * anaHop)
96
+ tgrad[m] = m * freqPerBin * synHop + r * dp
97
+ }
98
+
99
+ // Frequency gradient (local group delay), from center-origin phases:
100
+ // φc(m) = φ(m) + πm removes the ±π/bin flip of frame-start phases. Under
101
+ // stretch the group delay scales by r — with the center-aligned stft mapping
102
+ // (input t → output t·r at frame centers) that scaling is exact.
103
+ for (let m = 0; m < B; m++) {
104
+ let lo = m > 0 ? wrapPhase(phase[m] - phase[m - 1] + Math.PI) : 0
105
+ let hi = m < half ? wrapPhase(phase[m + 1] - phase[m] + Math.PI) : 0
106
+ let d = m === 0 ? hi : m === half ? lo : 0.5 * (lo + hi)
107
+ fgrad[m] = r * d
108
+ }
109
+
110
+ // Heap integration (mirrors phaseret's rtpghiupdate): every bin significant
111
+ // in the current frame seeds the heap keyed by its PREVIOUS-frame magnitude —
112
+ // strong established bins time-propagate first; newborn bins (tiny prev mag)
113
+ // pop late, so a vertical chain from an established neighbour usually claims
114
+ // them instead. Threshold is relative to the two-frame slab maximum.
115
+ let maxMag = 0
116
+ for (let m = 0; m < B; m++) {
117
+ if (mag[m] > maxMag) maxMag = mag[m]
118
+ if (state.prevMag[m] > maxMag) maxMag = state.prevMag[m]
119
+ }
120
+ let athr = tolerance * maxMag
121
+
122
+ assigned.fill(0)
123
+ let size = 0
124
+ let remaining = 0
125
+ for (let m = 0; m < B; m++) {
126
+ if (mag[m] > athr) {
127
+ size = heapPush(keys, items, size, state.prevMag[m], m) // prev-frame entry: item = m
128
+ remaining++
129
+ }
130
+ }
131
+
132
+ while (size > 0 && remaining > 0) {
133
+ let item = heapPop(keys, items, size)
134
+ size--
135
+ if (item < B) {
136
+ // from previous frame: propagate through time into the same bin
137
+ let m = item
138
+ if (!assigned[m] && mag[m] > athr) {
139
+ p[m] = synPrev[m] + 0.5 * (state.prevTgrad[m] + tgrad[m])
140
+ assigned[m] = 1; remaining--
141
+ size = heapPush(keys, items, size, mag[m], B + m) // current-frame entry: item = B + m
142
+ }
143
+ } else {
144
+ // from current frame: propagate through frequency to neighbours
145
+ let m = item - B
146
+ if (m < half && !assigned[m + 1] && mag[m + 1] > athr) {
147
+ p[m + 1] = p[m] + 0.5 * (fgrad[m] + fgrad[m + 1])
148
+ assigned[m + 1] = 1; remaining--
149
+ size = heapPush(keys, items, size, mag[m + 1], B + m + 1)
150
+ }
151
+ if (m > 0 && !assigned[m - 1] && mag[m - 1] > athr) {
152
+ p[m - 1] = p[m] - 0.5 * (fgrad[m] + fgrad[m - 1])
153
+ assigned[m - 1] = 1; remaining--
154
+ size = heapPush(keys, items, size, mag[m - 1], B + m - 1)
155
+ }
156
+ }
157
+ }
158
+
159
+ // Unreached bins (below tolerance, or islands with no significant history):
160
+ // random phase — they carry no reliable gradient information.
161
+ let seed = state.seed
162
+ for (let m = 0; m < B; m++) {
163
+ if (!assigned[m]) {
164
+ seed = (seed * 1664525 + 1013904223) >>> 0
165
+ p[m] = seed / 0x100000000 * PI2
166
+ }
167
+ }
168
+ state.seed = seed
169
+
170
+ for (let m = 0; m < B; m++) {
171
+ state.prevPhase[m] = phase[m]
172
+ state.prevMag[m] = mag[m]
173
+ state.prevTgrad[m] = tgrad[m]
174
+ state.synPrev[m] = p[m]
175
+ p[m] = p[m] - Math.PI * m // back to frame-start origin for synthesis
176
+ }
177
+
178
+ return { mag, phase: p }
179
+ }
180
+ }
181
+
182
+ // Gradient integration is first-order — it needs denser frames than peak-locked
183
+ // propagation: default hop N/8 (the reference implementation's geometry).
184
+ function pghiOpts(opts) {
185
+ let o = stretchOpts(opts)
186
+ if (opts?.hopSize == null) {
187
+ let hopSize = o.frameSize >> 3
188
+ let factor = opts?.factor ?? 1
189
+ o = { ...o, hopSize, synHop: opts?.synHop ?? hopSize, anaHop: opts?.anaHop ?? hopSize / factor }
190
+ }
191
+ return o
192
+ }
193
+
194
+ export default function pghi(data, opts) {
195
+ let tolerance = (data instanceof Float32Array ? opts?.tolerance : data?.tolerance) ?? 1e-6
196
+ let process = makeProcess(tolerance)
197
+ if (!(data instanceof Float32Array)) return writer(stftStream(process, pghiOpts(data)))
198
+ if ((opts?.factor ?? 1) === 1) return new Float32Array(data)
199
+ return stftBatch(data, process, pghiOpts(opts))
200
+ }