dsprb 2.0.0 → 2.1.1

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.
data/README.md CHANGED
@@ -1,58 +1,62 @@
1
- # dsprb
1
+ # dsprb · 純 Ruby 語音訊號分析
2
2
 
3
- Speech signal processing and acoustic feature extraction in pure Ruby. No dependencies, no native
4
- extensions, no pseudo-random number generator anywhere.
3
+ Speech signal analysis in pure Ruby: WAV decoding, power spectra, MFCC, YIN pitch tracking,
4
+ formant frequencies and bandwidths by linear prediction, spectral moments, energy measures,
5
+ biquad filters and decimation. No dependencies, no native extensions, deterministic output.
5
6
 
6
- Extracted from [taiwancards](https://github.com/taiwancards/taiwancards), where it turns learner
7
- recordings into the feature sequences its pronunciation scorer compares.
7
+ 用純 Ruby 做語音訊號分析:讀 WAV 檔、算功率頻譜跟 MFCC、用 YIN 追基頻、用線性預測求共振峰的頻率跟頻寬,
8
+ 還有頻譜動差、能量、雙二階濾波器跟降取樣。沒有相依套件,不用編譯原生擴充,同樣的輸入一定得到同樣的結果。
8
9
 
9
- ## The problem
10
+ **English** · [中文](#中文)
10
11
 
11
- A waveform is a poor representation for comparison. Two recordings of the same syllable differ in
12
- amplitude, in microphone response, in speaking rate, and in every sample value, while agreeing on
13
- everything a listener perceives: the pitch contour, the resonances of the vocal tract, the noise
14
- spectrum of the fricatives.
12
+ ## English
15
13
 
16
- Extracting those invariants is the work of acoustic phonetics, and it decomposes into a small set
17
- of classical algorithms. This library implements them directly: framing and windowing, the discrete
18
- Fourier transform, mel filterbanks and the cepstrum, the YIN period estimator, linear prediction
19
- and its all-pole envelope, spectral moments, and the filters that condition a signal beforehand.
14
+ Two recordings of the same syllable differ in amplitude, microphone, speaking rate and every sample
15
+ value, yet agree on what a listener hears: the pitch contour, the resonances of the vocal tract,
16
+ the noise spectrum of the fricatives. This library measures those quantities with the classical
17
+ algorithms of acoustic phonetics. [taiwancards](https://github.com/taiwancards/taiwancards) uses
18
+ it to score learners' pronunciation of Taiwanese Mandarin.
20
19
 
21
- ## Install
20
+ ### Install
21
+
22
+ Ruby 3.4 or later.
22
23
 
23
24
  ```ruby
24
25
  gem "dsprb"
25
26
  ```
26
27
 
27
- ## Waveforms
28
+ ```sh
29
+ gem install dsprb
30
+ ```
31
+
32
+ The gem is `dsprb`; the module is `DSP`. An invalid size, rate or range raises `ArgumentError`
33
+ naming the argument and the value; an unknown window name raises `DSP::UnknownStrategyError`.
34
+
35
+ ### Waveforms
28
36
 
29
- `DSP::Wav` decodes 8, 16, 24 and 32 bit PCM as well as 32 and 64 bit IEEE float, including
30
- `WAVE_FORMAT_EXTENSIBLE`, and downmixes multi-channel streams to mono. Everything downstream takes
31
- a `DSP::Waveform`, so the sample rate travels with the samples and cannot be mismatched by accident.
37
+ `DSP::Wav` decodes 8, 16, 24 and 32 bit PCM and 32 and 64 bit IEEE float, including
38
+ `WAVE_FORMAT_EXTENSIBLE`, and averages multi-channel streams to mono. Anything else raises
39
+ `DSP::FormatError`. Every analysis takes a `DSP::Waveform`, which carries the sample rate with the
40
+ samples.
32
41
 
33
42
  ```ruby
34
43
  require "dsprb"
35
44
 
36
- signal = DSP.read("utterance.wav")
45
+ signal = DSP.read("utterance.wav") # or DSP.decode(bytes)
37
46
 
38
47
  signal.length # => 16000
39
48
  signal.sample_rate # => 16000.0
40
49
  signal.duration # => 1.0
41
50
  signal.nyquist # => 8000.0
42
- ```
43
-
44
- Signals synthesized in memory are ordinary arrays:
45
51
 
46
- ```ruby
47
- signal = DSP::Waveform.new(samples: samples, sample_rate: 16_000)
52
+ DSP::Waveform.new(samples: samples, sample_rate: 16_000) # from an array of numbers
48
53
  ```
49
54
 
50
- ## Fundamental frequency
55
+ ### Pitch
51
56
 
52
57
  `DSP::Yin` implements the YIN estimator: squared difference over lag, cumulative mean
53
- normalization, absolute-threshold period selection, and parabolic refinement of the chosen minimum.
54
- The signal is decimated to a working rate before the search, which is what makes an O(window × lag)
55
- method affordable in Ruby.
58
+ normalization, absolute-threshold period selection and parabolic refinement. The signal is first
59
+ decimated to a working rate, which keeps the O(window × lag) search affordable in Ruby.
56
60
 
57
61
  ```ruby
58
62
  track = DSP.pitch(signal)
@@ -60,74 +64,122 @@ track = DSP.pitch(signal)
60
64
  track.length # => 120
61
65
  track.hop_seconds # => 0.008
62
66
  track.voiced_ratio # => 1.0
63
- track.voiced_f0 # => [196.08, ...]
67
+ track.voiced_f0 # => [196.04, ...]
68
+ track.times # frame start times, in seconds
69
+ track.confidence # 1 - d'(τ), the depth of the chosen dip, 0.0 when unvoiced
64
70
 
65
71
  track.each_voiced { |frequency, time, confidence| ... }
66
72
  ```
67
73
 
68
- Unvoiced frames report `0.0` rather than `nil`, so a track is always a dense numeric sequence.
69
- Confidence is `1 - d'(τ)`, the depth of the selected minimum.
74
+ Unvoiced frames report `0.0`, so `track.f0` is always a dense numeric sequence. Options of
75
+ `DSP.pitch` and `DSP::Yin.new`:
70
76
 
71
- Silence carries no pitch and is most of a short recording, so `minimum_rms` skips the lag search on
72
- frames quieter than it and reports them unvoiced:
77
+ | Option | Default | Meaning |
78
+ | -------------------- | -------- | --------------------------------------------------------------- |
79
+ | `minimum_frequency:` | `70.0` | lowest f0 searched, Hz |
80
+ | `maximum_frequency:` | `500.0` | highest f0 searched, Hz |
81
+ | `hop_seconds:` | `0.008` | frame step |
82
+ | `threshold:` | `0.15` | the first dip below it is taken as the period |
83
+ | `voiced_threshold:` | `0.35` | a frame whose deepest dip stays above it is unvoiced |
84
+ | `working_rate:` | `5512.5` | integer decimation toward this rate before the search, Hz |
85
+ | `minimum_rms:` | `0.0` | frames quieter than this are reported unvoiced without a search |
73
86
 
74
- ```ruby
75
- DSP.pitch(signal, minimum_rms: 0.01)
76
- ```
87
+ Silence carries no pitch and is most of a short recording; a gate such as `minimum_rms: 0.01`
88
+ skips the search there.
77
89
 
78
- ## Cepstral features
90
+ ### Cepstral features
79
91
 
80
- `DSP::Mfcc` composes a power spectrum, a mel filterbank and a DCT-II. The filterbank supports
81
- vocal tract length warping, which rescales the band centers to compensate for speaker anatomy.
92
+ `DSP::Mfcc` chains a power spectrum, a mel filterbank and a DCT-II.
82
93
 
83
94
  ```ruby
84
95
  frames = DSP.mfcc(signal)
85
96
 
86
- frames.length # => 98
87
- frames.first.length # => 13
97
+ frames.length # => 98
98
+ frames.first.length # => 13
99
+
100
+ DSP.mfcc(signal, coefficients: 20, filters: 40, warp: 1.1)
101
+ ```
102
+
103
+ `DSP.mfcc` takes `coefficients:` (13), `window_seconds:` (0.025), `hop_seconds:` (0.010) and
104
+ `size:`, the FFT size. The size defaults to the smallest power of two that holds a frame: 512 at
105
+ 16 kHz, 1024 at 22050 Hz; a size shorter than the frame raises `ArgumentError`. Filterbank options
106
+ pass through: `filters:` (26), `low:` (50.0 Hz), `high:` (Nyquist) and `warp:` (1.0), the vocal
107
+ tract length factor that scales the band centers; above 1 the bank moves up, which suits shorter
108
+ vocal tracts. Frames are Hamming-windowed after a 0.97 preemphasis; `DSP::Mfcc#sequence` changes
109
+ either:
110
+
111
+ ```ruby
112
+ mfcc = DSP::Mfcc.for(sample_rate: 16_000, coefficients: 20, filters: 40)
113
+ mfcc.sequence(signal, window: :hann, preemphasis: nil)
88
114
  ```
89
115
 
90
- The pieces stay separately usable, so a log-mel spectrogram costs one call:
116
+ The stages work on their own, for example a log-mel spectrogram:
91
117
 
92
118
  ```ruby
93
- spectrum = DSP::Spectrum.new(512)
119
+ spectrum = DSP::Spectrum.new(512) # FFT size, a power of two
94
120
  filterbank = DSP::MelFilterbank.new(sample_rate: 16_000, size: 512, filters: 26, warp: 1.05)
121
+ window = DSP::Window.hamming(400) # also hann, blackman, rectangular
95
122
 
96
123
  log_mel = signal.frames(window: 400, hop: 160).map do |frame|
97
- filterbank.log_energies(spectrum.power(DSP::Window.apply(frame, DSP::Window.hamming(400))))
124
+ filterbank.log_energies(spectrum.power(DSP::Window.apply(frame, window)))
98
125
  end
99
126
  ```
100
127
 
101
- ## Resonances
128
+ `Spectrum#power` returns `size / 2 + 1` bins. A frame shorter than the size is zero padded; samples
129
+ past the size are ignored. `#magnitude`, `#frequencies(sample_rate)` and
130
+ `#bin_of(frequency, sample_rate)` complete it.
131
+
132
+ ### Formants
133
+
134
+ `DSP::Formants` Hamming-windows and pre-emphasizes a frame, fits an all-pole model to it by the
135
+ Levinson-Durbin recursion and reads the formants from the roots of the predictor polynomial, which
136
+ `DSP::Polynomial.roots` finds by the Aberth-Ehrlich iteration. A root r e^{iω} above the real axis
137
+ is a resonance at ω fs / 2π with bandwidth −ln(r) fs / π. Roots within 50 Hz of 0 or Nyquist and
138
+ roots wider than 1000 Hz are discarded, the rest are sorted by frequency. Two formants 300 Hz
139
+ apart, as F1 and F2 of [u], stay two formants.
102
140
 
103
- `DSP::Lpc` fits an all-pole model by the Levinson-Durbin recursion and exposes the spectral
104
- envelope it implies. `DSP::Formants` picks the envelope maxima, refines them parabolically on the
105
- log magnitude, and merges peaks that a single resonance split in two.
141
+ The whole waveform is one analysis frame: pass 20 to 30 ms of a vowel, not a recording.
106
142
 
107
143
  ```ruby
108
- DSP.formants(vowel)
109
- # => [752.8, 2335.8, 3695.6, 5416.1]
144
+ DSP.formants(vowel) # => [F1, F2, F3, F4] in Hz, fewer if fewer roots qualify
110
145
 
111
- DSP::Formants.new.peaks(vowel).first.amplitude
112
- # => 2.91
146
+ peak = DSP::Formants.new.peaks(vowel).first
147
+ peak.frequency # Hz
148
+ peak.bandwidth # Hz, below 1000
149
+ peak.amplitude # natural log of the all-pole envelope at that frequency
113
150
  ```
114
151
 
115
- The predictor itself is available when the envelope matters more than the peaks:
152
+ Options of `DSP.formants` and `DSP::Formants.new`: `maximum_frequency:` (5500.0 Hz), the analysis
153
+ ceiling; `count:` (4), the number of formants, which sets the model order to 2 × count + 2;
154
+ `edge_margin:` (50.0 Hz). The ceiling is reached by decimating by an integer factor, the largest
155
+ that keeps the rate at or above twice the ceiling: 22050 and 44100 Hz input are analysed at
156
+ 11025 Hz, 48000 Hz at 12000 Hz, but 16000 Hz input is not decimated and is analysed up to 8000 Hz.
157
+ Lower the ceiling to 5000 Hz for adult male voices.
158
+
159
+ On the vowels of 1047 recorded syllables from three voices, the median difference from Praat's
160
+ Burg analysis is 7 Hz for F1 and 11 Hz for F2; the
161
+ [CHANGELOG](CHANGELOG.md#210--2026-12-06) breaks this down by vowel for one of the voices.
162
+
163
+ The predictor and the root finder are public:
116
164
 
117
165
  ```ruby
118
166
  model = DSP::Lpc.solve(frame, order: 10)
119
167
 
120
- model.order # => 10
121
- model.error # => residual energy of the prediction
122
- model.envelope(points: 512)
168
+ model.order # => 10
169
+ model.coefficients # [1.0, a1, ..., a10]
170
+ model.error # residual energy of the prediction
171
+ model.envelope(points: 512) # 1 / |A(e^{iω})|² from 0 to Nyquist
172
+
173
+ DSP::Polynomial.roots([1.0, -3.0, 2.0]) # => the roots 2 and 1, as Complex
123
174
  ```
124
175
 
125
- ## Spectral moments
176
+ ### Spectral moments
126
177
 
127
- Centroid, spread, skewness and excess kurtosis of the power spectrum over a chosen band. These are
128
- the standard descriptors of fricative noise, where place of articulation shifts the centroid.
178
+ Centroid, spread, skewness and excess kurtosis of a power spectrum over a band, the standard
179
+ descriptors of fricative noise. The band defaults to 500 Hz up to 200 Hz below Nyquist.
129
180
 
130
181
  ```ruby
182
+ power = DSP::Spectrum.new(1024).power(frame)
131
183
  moments = DSP::SpectralMoments.of(power, sample_rate: 16_000, size: 1024, low: 500.0)
132
184
 
133
185
  moments.centroid # => 4904.8
@@ -136,72 +188,304 @@ moments.skewness # => 0.742
136
188
  moments.kurtosis # => -0.708
137
189
  ```
138
190
 
139
- ## Energy, filters, resampling
191
+ ### Energy, filters, resampling
140
192
 
141
193
  ```ruby
142
- DSP::Energy.frame_db(frame) # root mean square, in decibels
143
- DSP::Energy.zero_crossing_rate(frame) # crossings per sample interval
144
- DSP::Energy.envelope_db(samples, window: 400, hop: 160) # sliding energy, one value per hop
194
+ DSP::Energy.frame_db(frame) # mean power, in decibels
195
+ DSP::Energy.zero_crossing_rate(frame) # crossings per sample interval
196
+ DSP::Energy.envelope_db(samples, window: 400, hop: 160) # sliding energy, one value per hop
197
+
198
+ DSP.highpass(signal, cutoff: 60.0) # removes rumble and DC offset
199
+ DSP.lowpass(signal, cutoff: 4000.0, sections: 2) # two Q = 0.707 biquads, -6 dB at cutoff
200
+ DSP::Biquad.lowpass(sample_rate: 16_000, cutoff: 1000.0, q: 2.0).apply(samples)
201
+ DSP.decimate(signal, 4) # windowed-sinc low-pass, every 4th sample
202
+
203
+ DSP::Framing.preemphasis(samples, coefficient: 0.97)
204
+ DSP::Curve.resample(contour, 16) # contours onto a common grid
205
+ DSP::Scales.hz_to_semitones(392.0, reference: 196.0) # => 12.0
206
+ DSP::Scales.hz_to_mel(1000.0) # => 999.99
207
+ ```
145
208
 
146
- DSP.highpass(signal, cutoff: 60.0) # removes rumble and DC offset
147
- DSP.lowpass(signal, cutoff: 4000.0, sections: 2) # cascaded Butterworth sections
148
- DSP.decimate(signal, 4) # windowed-sinc anti-aliasing
209
+ ### Limits
149
210
 
150
- DSP::Curve.resample(contour, 16) # contours onto a common grid
151
- DSP::Scales.hz_to_semitones(392.0, reference: 196.0) # => 12.0
152
- ```
211
+ - Speed is that of Ruby. On Ruby 4.0 with YJIT and 22050 Hz input, `Formants#call` takes about
212
+ 0.3 ms per 25 ms frame and `Yin#call` about 26 ms for 2 s of a vowel at 120 to 180 Hz, 40 ms for
213
+ 2 s of noise.
214
+ - WAV is the only file format. Rates change only by integer decimation.
215
+ - FFT sizes are powers of two, at least 4.
216
+ - An f0 within about 0.5 % of `maximum_frequency` can come out unvoiced: parabolic refinement may
217
+ place it just above the maximum. Set the maximum a little above the highest f0 you expect.
153
218
 
154
- ## In practice
219
+ ### Used in taiwancards
155
220
 
156
221
  [taiwancards](https://github.com/taiwancards/taiwancards) teaches Taiwanese Mandarin and scores
157
- learner recordings against native templates. Its analysis stage is a pipeline over this library.
222
+ learner recordings against native templates with this library.
223
+
224
+ - **Conditioning.** The recording is decimated by an integer factor toward 22050 Hz. The energy
225
+ envelope and zero crossing rate find the speech; the energy envelopes of a copy low-passed at
226
+ 800 Hz and a copy high-passed at 1200 Hz separate the onset of voicing from the release burst.
227
+ - **Tone.** Mandarin lexical tone is carried by the f0 contour. The track from `DSP.pitch` is
228
+ cleaned of octave errors, converted to semitones and resampled to 16 points with
229
+ `DSP::Curve.resample`, where the four tones become comparable shapes.
230
+ - **Timbre.** Thirteen MFCC per frame, with the warp set per speaker so that a child and an adult
231
+ saying the same vowel land close together.
232
+ - **Vowel quality.** F1 and F2 place a vowel on the vowel plane, where ㄧ, ㄩ and ㄨ differ.
233
+ - **Fricatives.** Spectral moments separate ㄕ from ㄙ by centroid and skewness.
158
234
 
159
- **Conditioning.** The recording is high-passed to strip rumble and any DC offset, then the energy
160
- envelope and zero crossing rate locate the speech boundaries and the syllable onsets.
235
+ The sequences differ in length because speaking rate differs, so they are aligned and averaged
236
+ with [dtwrb](https://github.com/taiwancards/dtwrb), the companion library for dynamic time warping
237
+ and barycenter averaging.
161
238
 
162
- **Tone.** Mandarin lexical tone _is_ the fundamental frequency contour, so `DSP.pitch` carries the
163
- primary signal rather than a secondary cue. The track is cleaned of octave errors, then
164
- `DSP::Curve.resample` brings contours of different duration onto a fixed 16-point grid where the
165
- four tones become comparable shapes.
239
+ ### Design
240
+
241
+ Every stage is an object that precomputes what it can and then freezes: `DSP::Fourier::Radix2`
242
+ its twiddle factors, `DSP::MelFilterbank` its bands, `DSP::Decimator` its kernel,
243
+ `DSP::Lpc::Envelope` its cosine grid, `DSP::Dct::Two` its basis. They hold no mutable state and
244
+ are safe to share across threads; build them once, outside the loop. `DSP::Window.hamming` and its
245
+ siblings, `DSP::Decimator.for`, `DSP::Dct::Two.for` and `DSP::Lpc::Envelope.for` return one shared
246
+ frozen instance per parameter set.
166
247
 
167
- **Timbre.** Thirteen MFCC per frame describe the spectral envelope independently of pitch. Vocal
168
- tract length warping is set per speaker, so a child and an adult producing the same vowel land in
169
- the same region of the feature space.
248
+ `DSP::Spectrum` uses `DSP::Fourier::Real` by default. Any object with `#power(frame)` can replace
249
+ it, or a complex transform with `#call(real, imaginary)` and `#size`, such as
250
+ `DSP::Fourier::Radix2`. `DSP::Mfcc#sequence` takes any window function that answers
251
+ `#call(length)`.
170
252
 
171
- **Vowel quality.** The first two formants place a vowel on the F1/F2 plane, which is where the
172
- contrast between ㄧ, ㄩ and ㄨ actually lives.
253
+ `DSP::Waveform`, `DSP::PitchTrack`, `DSP::SpectralMoments`, `DSP::Biquad`, `DSP::Lpc::Model` and
254
+ `DSP::Formants::Peak` are `Data` value objects: frozen, compared by value, copied with `#with`.
173
255
 
174
- **Fricatives.** Spectral moments separate the sibilants: the retroflex ㄕ and the alveolar ㄙ differ
175
- mainly in centroid and skewness, not in duration or energy.
256
+ Developed and maintained in Taipei, Taiwan by Den Patin 丁丹旭 (<hi@dpat.in>), independent
257
+ researcher, linguist and software engineer.
176
258
 
177
- The resulting sequences vary in length because speaking rate varies, so they are aligned and
178
- averaged with [dtwrb](https://github.com/taiwancards/dtwrb), the companion library for dynamic time
179
- warping and barycenter averaging.
259
+ ### License
180
260
 
181
- Speech is one application. Anything sampled as a numeric signal — vibration, biosignals, sonar,
182
- telemetry — uses the same spectral and predictive machinery.
261
+ MIT — see [LICENSE](LICENSE).
183
262
 
184
- ## Design
263
+ ## 中文
185
264
 
186
- Every stage is an object that precomputes what it can and then freezes: `DSP::Fourier::Radix2`
187
- caches its twiddle factors, `DSP::MelFilterbank` its triangular bands, `DSP::Decimator` its kernel,
188
- `DSP::Lpc::Envelope` its cosine grid, `DSP::Dct::Two` its basis. They hold no mutable state and are
189
- safe to reuse across threads. Build them once, outside the loop.
265
+ 同一個音節錄兩次,音量、麥克風、說話速度跟每一個取樣值都不一樣,可是聽的人聽到的東西是一樣的:音高的走勢、
266
+ 聲道的共振,還有擦音的噪音頻譜。這個函式庫用聲學語音學的經典演算法把這些量算出來。
267
+ [taiwancards](https://github.com/taiwancards/taiwancards) 用它幫學習者的臺灣華語發音打分數。
190
268
 
191
- What depends on nothing but its own sizes is shared rather than rebuilt. Through `DSP::Prepared`,
192
- `DSP::Window.hamming`, `DSP::Decimator.for`, `DSP::Dct::Two.for` and `DSP::Lpc::Envelope.for` hand
193
- back one frozen instance per parameter set, so framing a signal does not pay to construct the same
194
- window on every frame. Argument validation is shared the same way through `DSP::Check`, so a
195
- rejected argument reports identically wherever it enters.
269
+ ### 安裝
196
270
 
197
- Collaborators are injected rather than assumed: the transform behind a `DSP::Spectrum`, the window
198
- function of an MFCC sequence, the filterbank of a `DSP::Mfcc`. A spectrum uses `DSP::Fourier::Real`
199
- by default, which needs only `#power(frame)`; injecting a complex transform such as
200
- `DSP::Fourier::Radix2` needs `#call(real, imaginary)` and `#size`.
271
+ 需要 Ruby 3.4 以上。
201
272
 
202
- `DSP::Waveform`, `DSP::PitchTrack`, `DSP::SpectralMoments`, `DSP::Biquad`, `DSP::Lpc::Model` and
203
- `DSP::Formants::Peak` are `Data` value objects: frozen, compared by value, copied with `#with`.
273
+ ```ruby
274
+ gem "dsprb"
275
+ ```
276
+
277
+ ```sh
278
+ gem install dsprb
279
+ ```
280
+
281
+ 套件叫 `dsprb`,模組叫 `DSP`。大小、取樣率或範圍不對的時候會丟出 `ArgumentError`,訊息裡會寫出是哪個
282
+ 參數、收到什麼值;窗函數的名字打錯會丟出 `DSP::UnknownStrategyError`。
283
+
284
+ ### 波形
285
+
286
+ `DSP::Wav` 可以讀 8、16、24、32 位元的 PCM 跟 32、64 位元的 IEEE 浮點數,`WAVE_FORMAT_EXTENSIBLE`
287
+ 也可以;多聲道會平均成單聲道。其他格式會丟出 `DSP::FormatError`。所有分析都吃 `DSP::Waveform`,取樣率
288
+ 跟取樣值放在同一個物件裡,不會配錯。
289
+
290
+ ```ruby
291
+ require "dsprb"
292
+
293
+ signal = DSP.read("utterance.wav") # 或 DSP.decode(bytes)
294
+
295
+ signal.length # => 16000
296
+ signal.sample_rate # => 16000.0
297
+ signal.duration # => 1.0
298
+ signal.nyquist # => 8000.0
299
+
300
+ DSP::Waveform.new(samples: samples, sample_rate: 16_000) # 直接用數字陣列建立
301
+ ```
302
+
303
+ ### 基頻
304
+
305
+ `DSP::Yin` 實作 YIN:算每個延遲的平方差、做累積平均正規化、取第一個低過門檻的谷當週期,再用拋物線內插
306
+ 微調。分析前會先把訊號降取樣到工作取樣率,O(窗長 × 延遲) 的搜尋在 Ruby 裡才跑得動。
307
+
308
+ ```ruby
309
+ track = DSP.pitch(signal)
310
+
311
+ track.length # => 120
312
+ track.hop_seconds # => 0.008
313
+ track.voiced_ratio # => 1.0
314
+ track.voiced_f0 # => [196.04, ...]
315
+ track.times # 每個音框的起點,單位是秒
316
+ track.confidence # 1 - d'(τ),選到的谷有多深;無聲是 0.0
317
+
318
+ track.each_voiced { |frequency, time, confidence| ... }
319
+ ```
320
+
321
+ 無聲的音框回傳 `0.0`,不是 `nil`,所以 `track.f0` 一定是連續的數字陣列。`DSP.pitch` 跟 `DSP::Yin.new`
322
+ 的參數:
323
+
324
+ - `minimum_frequency:`,預設 `70.0`:搜尋的最低基頻(Hz)。
325
+ - `maximum_frequency:`,預設 `500.0`:搜尋的最高基頻(Hz)。
326
+ - `hop_seconds:`,預設 `0.008`:音框間隔。
327
+ - `threshold:`,預設 `0.15`:第一個低過這個值的谷就當成週期。
328
+ - `voiced_threshold:`,預設 `0.35`:最深的谷還高過這個值,這個音框就算無聲。
329
+ - `working_rate:`,預設 `5512.5`:用整數倍降取樣,取最大的倍數,但取樣率不會低過這個值。
330
+ - `minimum_rms:`,預設 `0.0`:比這個還小聲的音框直接當無聲,不做搜尋。
331
+
332
+ 靜音沒有音高,而且常常佔了短錄音的大半;設個門檻,像是 `minimum_rms: 0.01`,靜音的部分就不用搜尋。
333
+
334
+ ### 倒頻譜特徵
335
+
336
+ `DSP::Mfcc` 把功率頻譜、梅爾濾波器組跟 DCT-II 串在一起。
337
+
338
+ ```ruby
339
+ frames = DSP.mfcc(signal)
340
+
341
+ frames.length # => 98
342
+ frames.first.length # => 13
343
+
344
+ DSP.mfcc(signal, coefficients: 20, filters: 40, warp: 1.1)
345
+ ```
346
+
347
+ `DSP.mfcc` 的參數有 `coefficients:`(13)、`window_seconds:`(0.025)、`hop_seconds:`(0.010)跟
348
+ FFT 大小 `size:`。`size:` 預設是裝得下一個音框的最小 2 的次方:16 kHz 是 512,22050 Hz 是 1024;給的
349
+ 大小比音框短會丟出 `ArgumentError`。濾波器組的參數會直接傳下去:`filters:`(26)、`low:`(50.0 Hz)、
350
+ `high:`(奈奎斯特頻率)跟 `warp:`(1.0)。`warp:` 是聲道長度正規化的係數,會等比例移動每個頻帶的中心;
351
+ 比 1 大的話整組往高頻移,適合聲道比較短的人。每個音框先做 0.97 的預強調,再乘 Hamming 窗;要換的話用
352
+ `DSP::Mfcc#sequence`:
353
+
354
+ ```ruby
355
+ mfcc = DSP::Mfcc.for(sample_rate: 16_000, coefficients: 20, filters: 40)
356
+ mfcc.sequence(signal, window: :hann, preemphasis: nil)
357
+ ```
358
+
359
+ 每個步驟也可以單獨用,像是算對數梅爾頻譜圖:
360
+
361
+ ```ruby
362
+ spectrum = DSP::Spectrum.new(512) # FFT 大小,要是 2 的次方
363
+ filterbank = DSP::MelFilterbank.new(sample_rate: 16_000, size: 512, filters: 26, warp: 1.05)
364
+ window = DSP::Window.hamming(400) # 另外還有 hann、blackman、rectangular
365
+
366
+ log_mel = signal.frames(window: 400, hop: 160).map do |frame|
367
+ filterbank.log_energies(spectrum.power(DSP::Window.apply(frame, window)))
368
+ end
369
+ ```
370
+
371
+ `Spectrum#power` 回傳 `size / 2 + 1` 個頻率點。音框比 FFT 大小短的話後面補零,超過的部分直接忽略。
372
+ 另外還有 `#magnitude`、`#frequencies(sample_rate)` 跟 `#bin_of(frequency, sample_rate)`。
373
+
374
+ ### 共振峰
375
+
376
+ `DSP::Formants` 先把音框乘上 Hamming 窗、做預強調,用 Levinson-Durbin 遞迴求全極點模型,再從預測多項式的
377
+ 根讀出共振峰;根是 `DSP::Polynomial.roots` 用 Aberth-Ehrlich 迭代法求的。實軸上方的根 r e^{iω} 就是
378
+ 一個共振,頻率是 ω fs / 2π,頻寬是 −ln(r) fs / π。離 0 Hz 或奈奎斯特頻率不到 50 Hz 的根、頻寬超過
379
+ 1000 Hz 的根都會丟掉,剩下的照頻率排好。像 [u] 的 F1 跟 F2 只差 300 Hz,也會分成兩個共振峰。
380
+
381
+ 整段波形就是一個分析音框,所以要傳 20 到 30 ms 的母音進去,不要傳整段錄音。
382
+
383
+ ```ruby
384
+ DSP.formants(vowel) # => [F1, F2, F3, F4],單位 Hz;符合條件的根不夠的話會比較少
385
+
386
+ peak = DSP::Formants.new.peaks(vowel).first
387
+ peak.frequency # Hz
388
+ peak.bandwidth # Hz,一定不到 1000
389
+ peak.amplitude # 全極點包絡在這個頻率的自然對數
390
+ ```
391
+
392
+ `DSP.formants` 跟 `DSP::Formants.new` 的參數:`maximum_frequency:`(5500.0 Hz)是分析的上限;
393
+ `count:`(4)是要幾個共振峰,模型的階數是 2 × count + 2;`edge_margin:`(50.0 Hz)。上限是靠整數倍
394
+ 降取樣做到的,取最大的倍數,但取樣率不會低過上限的兩倍:22050 跟 44100 Hz 的輸入會在 11025 Hz 分析,
395
+ 48000 Hz 在 12000 Hz,可是 16000 Hz 的輸入不會降取樣,會分析到 8000 Hz。成年男性的聲音可以把上限調到
396
+ 5000 Hz。
397
+
398
+ 在三個發音人、1047 個錄音音節的母音上,跟 Praat 的 Burg 分析比,F1 的差距中位數是 7 Hz,F2 是 11 Hz;
399
+ 其中一個發音人每個母音的數字列在 [CHANGELOG](CHANGELOG.md#210--2026-12-06) 的表裡。
400
+
401
+ 預測器跟求根的函式也可以直接用:
402
+
403
+ ```ruby
404
+ model = DSP::Lpc.solve(frame, order: 10)
405
+
406
+ model.order # => 10
407
+ model.coefficients # [1.0, a1, ..., a10]
408
+ model.error # 預測的殘差能量
409
+ model.envelope(points: 512) # 1 / |A(e^{iω})|²,從 0 到奈奎斯特頻率
410
+
411
+ DSP::Polynomial.roots([1.0, -3.0, 2.0]) # => 兩個根 2 跟 1,型別是 Complex
412
+ ```
413
+
414
+ ### 頻譜動差
415
+
416
+ 在一段頻帶裡算功率頻譜的質心、展度、偏態跟超額峰態,是描述擦音噪音最常用的量。頻帶預設從 500 Hz 到
417
+ 奈奎斯特頻率減 200 Hz。
418
+
419
+ ```ruby
420
+ power = DSP::Spectrum.new(1024).power(frame)
421
+ moments = DSP::SpectralMoments.of(power, sample_rate: 16_000, size: 1024, low: 500.0)
422
+
423
+ moments.centroid # => 4904.8
424
+ moments.spread # => 1064.8
425
+ moments.skewness # => 0.742
426
+ moments.kurtosis # => -0.708
427
+ ```
428
+
429
+ ### 能量、濾波、重新取樣
430
+
431
+ ```ruby
432
+ DSP::Energy.frame_db(frame) # 平均功率,單位 dB
433
+ DSP::Energy.zero_crossing_rate(frame) # 每個取樣間隔的過零次數
434
+ DSP::Energy.envelope_db(samples, window: 400, hop: 160) # 滑動能量,每個間隔一個值
435
+
436
+ DSP.highpass(signal, cutoff: 60.0) # 去掉低頻雜音跟直流偏移
437
+ DSP.lowpass(signal, cutoff: 4000.0, sections: 2) # 兩個 Q = 0.707 的雙二階,截止頻率 -6 dB
438
+ DSP::Biquad.lowpass(sample_rate: 16_000, cutoff: 1000.0, q: 2.0).apply(samples)
439
+ DSP.decimate(signal, 4) # 先用加窗 sinc 低通,再每 4 點取 1 點
440
+
441
+ DSP::Framing.preemphasis(samples, coefficient: 0.97)
442
+ DSP::Curve.resample(contour, 16) # 把曲線對到同一組格點
443
+ DSP::Scales.hz_to_semitones(392.0, reference: 196.0) # => 12.0
444
+ DSP::Scales.hz_to_mel(1000.0) # => 999.99
445
+ ```
446
+
447
+ ### 限制
448
+
449
+ - 速度就是 Ruby 的速度。在 Ruby 4.0 開 YJIT、輸入 22050 Hz 的情況下,`Formants#call` 一個 25 ms
450
+ 的音框大約 0.3 ms;`Yin#call` 跑 2 秒 120 到 180 Hz 的母音大約 26 ms,2 秒的噪音大約 40 ms。
451
+ - 檔案格式只支援 WAV。取樣率只能用整數倍降取樣來改。
452
+ - FFT 大小要是 2 的次方,最小是 4。
453
+ - 基頻離 `maximum_frequency` 不到 0.5 % 左右的時候,拋物線內插可能把它推到上限外面,結果變成無聲。
454
+ 上限請設得比預期的最高基頻再高一點。
455
+
456
+ ### 在 taiwancards 裡怎麼用
457
+
458
+ [taiwancards](https://github.com/taiwancards/taiwancards) 是教臺灣華語的網站,用這個函式庫把學習者的
459
+ 錄音跟母語者的範本比較、打分數。
460
+
461
+ - **前處理。** 錄音先用整數倍降取樣到接近 22050 Hz。能量包絡跟過零率找出說話的範圍;再把一份低通到
462
+ 800 Hz、一份高通到 1200 Hz,比較兩份的能量包絡,分出聲帶開始振動的時間點跟除阻的爆破。
463
+ - **聲調。** 華語的字調就在基頻曲線上。`DSP.pitch` 的結果先修掉八度錯誤、換成半音,再用
464
+ `DSP::Curve.resample` 取樣成 16 個點,四個聲調就變成可以直接比較的形狀。
465
+ - **音色。** 每個音框 13 個 MFCC,`warp:` 依每個人設定,小孩跟大人唸同一個母音會落在差不多的位置。
466
+ - **母音。** F1 跟 F2 決定母音在母音圖上的位置,ㄧ、ㄩ、ㄨ 的差別就在這裡。
467
+ - **擦音。** 頻譜動差的質心跟偏態可以分出 ㄕ 跟 ㄙ。
468
+
469
+ 說話速度不一樣,序列的長度也不一樣,所以再用姊妹函式庫 [dtwrb](https://github.com/taiwancards/dtwrb)
470
+ 做動態時間扭曲跟重心平均。
471
+
472
+ ### 設計
473
+
474
+ 每個步驟都是一個物件,能先算的先算好,然後凍結:`DSP::Fourier::Radix2` 存旋轉因子,
475
+ `DSP::MelFilterbank` 存頻帶,`DSP::Decimator` 存濾波器係數,`DSP::Lpc::Envelope` 存餘弦表,
476
+ `DSP::Dct::Two` 存基底。這些物件沒有可變的狀態,可以在多個執行緒裡共用;建一次就好,不要放在迴圈裡建。
477
+ `DSP::Window.hamming` 這類窗函數、`DSP::Decimator.for`、`DSP::Dct::Two.for` 跟
478
+ `DSP::Lpc::Envelope.for` 同樣的參數只會建一個共用的凍結物件。
479
+
480
+ `DSP::Spectrum` 預設用 `DSP::Fourier::Real`。可以換成任何有 `#power(frame)` 的物件,或是有
481
+ `#call(real, imaginary)` 跟 `#size` 的複數轉換,像 `DSP::Fourier::Radix2`。`DSP::Mfcc#sequence`
482
+ 的 `window:` 可以是任何有 `#call(length)` 的窗函數。
483
+
484
+ `DSP::Waveform`、`DSP::PitchTrack`、`DSP::SpectralMoments`、`DSP::Biquad`、`DSP::Lpc::Model` 跟
485
+ `DSP::Formants::Peak` 都是 `Data` 值物件:凍結、用值比較、用 `#with` 複製。
486
+
487
+ 由 Den Patin 丁丹旭(<hi@dpat.in>)在臺灣臺北開發與維護。獨立研究者,做語言學跟軟體工程。
204
488
 
205
- ## License
489
+ ### 授權條款
206
490
 
207
- WTFPL — see [LICENSE](LICENSE).
491
+ MIT,詳見 [LICENSE](LICENSE)。
data/lib/dsprb/biquad.rb CHANGED
@@ -1,7 +1,9 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module DSP
4
- Biquad = Data.define(:b0, :b1, :b2, :a1, :a2) do
4
+ Biquad = Data.define(:b0, :b1, :b2, :a1, :a2)
5
+
6
+ class Biquad
5
7
  # Maximally flat passband alignment.
6
8
  BUTTERWORTH_Q = Math.sqrt(2.0) / 2.0
7
9
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  module DSP
4
4
  class Decimator
5
- # An odd tap count keeps the FIR linear phase, so decimation adds no group delay skew.
5
+ # An odd tap count centers the symmetric kernel on a sample, so the output is not shifted in time.
6
6
  DEFAULT_TAPS = 31
7
7
 
8
8
  # Cutoff as a fraction of the decimated rate, leaving a transition margin below Nyquist.