spectrograms 0.1.0

A focused Rust library for computing spectrograms with a simple, unified API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
# Spectrograms Integration Guide

A comprehensive walkthrough for integrating spectrogram computation into your Rust and Python projects.

## Table of Contents

- [Introduction]#introduction
- [Installation]#installation
- [Core Concepts]#core-concepts
- [Quick Start]#quick-start
- [Building Spectrograms]#building-spectrograms
  - [Linear Spectrograms]#linear-spectrograms
  - [Mel Spectrograms]#mel-spectrograms
  - [ERB Spectrograms]#erb-spectrograms
- [Amplitude Scales]#amplitude-scales
- [Efficient Plan Reuse]#efficient-plan-reuse
- [Computing FFT and STFT]#computing-fft-and-stft
- [Streaming and Online Processing]#streaming-and-online-processing
- [Advanced Features]#advanced-features
  - [MFCC]#mfcc
  - [Chromagram]#chromagram
  - [CQT]#cqt
- [Performance Tips]#performance-tips
- [Common Patterns]#common-patterns

---

## Introduction

This library provides **high-performance spectrogram computation** with both Rust and Python APIs. It features:

- **Multiple frequency scales**: Linear, Mel, ERB, CQT
- **Multiple amplitude scales**: Power, Magnitude, Decibels
- **Plan-based computation**: Reuse FFT plans for 2-10x speedup on batch processing
- **Two FFT backends**: FFTW (fastest) or RealFFT (pure Rust)
- **Zero-copy design**: Minimal allocations for efficient memory usage
- **Streaming support**: Frame-by-frame processing for real-time applications

---

## Installation

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```toml
# Cargo.toml
[dependencies]
spectrograms = "0.1"

# Or with pure-Rust FFT
spectrograms = {
  version = "0.1",
  default-features = false,
  features = ["realfft"]
}
```

</td>
<td>

```bash
# Install from PyPI (when published)
pip install spectrograms

# Or install from source
cd python
pip install .

# Or with maturin for development
cd python
maturin develop
```

</td>
</tr>
</table>

---

## Core Concepts

### What is a Spectrogram?

A **spectrogram** is a visual representation of the spectrum of frequencies in a signal as they vary with time. It's computed using the **Short-Time Fourier Transform (STFT)**, which applies FFT to overlapping windows of the signal.

### Key Parameters

- **`n_fft`**: FFT window size (e.g., 512, 1024, 2048). Larger = better frequency resolution, worse time resolution
- **`hop_size`**: Samples between successive frames (e.g., 256). Smaller = more overlap, better time resolution
- **`window`**: Window function to reduce spectral leakage (Hanning, Hamming, Blackman, etc.)
- **`centre`**: Whether to pad signal for centered frames (recommended: true)

### The Plan Pattern

This library uses a **plan-based computation model**:

1. **One-shot**: Simple `compute()` function - creates plan internally (convenient but slower for batches)
2. **Plan reuse**: Create plan once with `SpectrogramPlanner`, reuse for multiple signals (2-10x faster)

---

## Quick Start

### Generate a Test Signal

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use std::f64::consts::PI;

// Generate 1 second of 440 Hz sine wave
let sample_rate = 16000.0;
let samples: Vec<f64> = (0..16000)
    .map(|i| {
        let t = i as f64 / sample_rate;
        (2.0 * PI * 440.0 * t).sin()
    })
    .collect();
```

</td>
<td>

```python
import numpy as np

# Generate 1 second of 440 Hz sine wave
sample_rate = 16000
t = np.linspace(0, 1, sample_rate, dtype=np.float64)
samples = np.sin(2 * np.pi * 440 * t)
```

</td>
</tr>
</table>

### Compute Your First Spectrogram

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

// Configure STFT parameters
let stft = StftParams::new(
    512,                 // n_fft
    256,                 // hop_size
    WindowType::Hanning, // window function
    true                 // centre frames
)?;

let params = SpectrogramParams::new(
    stft,
    sample_rate
)?;

// Compute power spectrogram
let spec = LinearPowerSpectrogram::compute(
    &samples,
    &params,
    None
)?;

println!("Shape: {} bins × {} frames",
    spec.n_bins(), spec.n_frames());
```

</td>
<td>

```python
import spectrograms as sg

# Configure STFT parameters
stft = sg.StftParams(
    n_fft=512,
    hop_size=256,
    window=sg.WindowType.hanning(),
    centre=True
)

params = sg.SpectrogramParams(
    stft,
    sample_rate=sample_rate
)

# Compute power spectrogram
spec = sg.compute_linear_power_spectrogram(
    samples,
    params
)

print(f"Shape: {spec.n_bins} bins × {spec.n_frames} frames")
```

</td>
</tr>
</table>

---

## Building Spectrograms

### Linear Spectrograms

Linear spectrograms use **equally-spaced frequency bins** corresponding to FFT output bins.

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;

// Power spectrum (|X|²)
let power = LinearPowerSpectrogram::compute(
    &samples, &params, None
)?;

// Magnitude spectrum (|X|)
let magnitude = LinearMagnitudeSpectrogram::compute(
    &samples, &params, None
)?;

// Decibel scale (10·log₁₀(power))
let db_params = LogParams::new(-80.0)?; // floor at -80 dB
let db = LinearDbSpectrogram::compute(
    &samples, &params, Some(db_params)
)?;

// Access data
let frequencies = db.axes().frequencies();
let times = db.axes().times();
let data = db.data(); // ndarray::Array2<f64>
```

</td>
<td>

```python
import spectrograms as sg

stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)

# Power spectrum (|X|²)
power = sg.compute_linear_power_spectrogram(
    samples, params
)

# Magnitude spectrum (|X|)
magnitude = sg.compute_linear_magnitude_spectrogram(
    samples, params
)

# Decibel scale (10·log₁₀(power))
db_params = sg.LogParams(floor_db=-80.0)
db = sg.compute_linear_db_spectrogram(
    samples, params, db_params
)

# Access data
frequencies = db.frequencies  # numpy array
times = db.times              # numpy array
data = db.data                # numpy array (n_bins × n_frames)
```

</td>
</tr>
</table>

### Mel Spectrograms

Mel spectrograms apply a **mel-scale filterbank** to emphasize perceptually-relevant frequencies.

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;

// Configure mel filterbank
let mel = MelParams::new(
    80,      // n_mels: number of mel bands
    0.0,     // f_min: minimum frequency (Hz)
    8000.0   // f_max: maximum frequency (Hz)
)?;

// Mel power spectrogram
let mel_power = MelPowerSpectrogram::compute(
    &samples, &params, &mel, None
)?;

// Mel dB spectrogram (most common for ML)
let db = LogParams::new(-80.0)?;
let mel_db = MelDbSpectrogram::compute(
    &samples, &params, &mel, Some(&db)
)?;

// Access mel frequencies
let mel_freqs = mel_db.axes().frequencies();
println!("Mel bands: {} bins", mel_db.n_bins());
```

</td>
<td>

```python
import spectrograms as sg

stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)

# Configure mel filterbank
mel = sg.MelParams(
    n_mels=80,
    f_min=0.0,
    f_max=8000.0
)

# Mel power spectrogram
mel_power = sg.compute_mel_power_spectrogram(
    samples, params, mel
)

# Mel dB spectrogram (most common for ML)
db = sg.LogParams(floor_db=-80.0)
mel_db = sg.compute_mel_db_spectrogram(
    samples, params, mel, db
)

# Access mel frequencies
mel_freqs = mel_db.frequencies
print(f"Mel bands: {mel_db.n_bins} bins")
```

</td>
</tr>
</table>

### ERB Spectrograms

ERB (Equivalent Rectangular Bandwidth) spectrograms use a **gammatone filterbank** modeling auditory perception.

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;

// Configure ERB filterbank
let erb = ErbParams::new(
    64,      // n_bands: number of ERB bands
    50.0,    // f_min: minimum frequency (Hz)
    8000.0   // f_max: maximum frequency (Hz)
)?;

// ERB power spectrogram
let erb_power = ErbPowerSpectrogram::compute(
    &samples, &params, &erb, None
)?;

// ERB dB spectrogram
let db = LogParams::new(-80.0)?;
let erb_db = ErbDbSpectrogram::compute(
    &samples, &params, &erb, Some(&db)
)?;
```

</td>
<td>

```python
import spectrograms as sg

stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)

# Configure ERB filterbank
erb = sg.ErbParams(
    n_bands=64,
    f_min=50.0,
    f_max=8000.0
)

# ERB power spectrogram
erb_power = sg.compute_erb_power_spectrogram(
    samples, params, erb
)

# ERB dB spectrogram
db = sg.LogParams(floor_db=-80.0)
erb_db = sg.compute_erb_db_spectrogram(
    samples, params, erb, db
)
```

</td>
</tr>
</table>

---

## Amplitude Scales

The library supports three amplitude scales for converting complex FFT output to real values:

| Scale | Formula | Use Case |
|-------|---------|----------|
| **Power** | `\|X\|²` | Energy analysis, ML features |
| **Magnitude** | `\|X\|` | Spectral analysis, phase vocoder |
| **Decibels** | `10·log₁₀(power)` | Visualization, perceptual analysis |

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;

// Power: raw energy values
let power = LinearPowerSpectrogram::compute(
    &samples, &params, None
)?;

// Magnitude: sqrt of power
let magnitude = LinearMagnitudeSpectrogram::compute(
    &samples, &params, None
)?;

// Decibels: logarithmic scale
let db_params = LogParams::new(-80.0)?; // clip below -80 dB
let db = LinearDbSpectrogram::compute(
    &samples, &params, Some(db_params)
)?;

// Verify relationship: magnitude = sqrt(power)
let power_val = power.data()[[10, 5]];
let mag_val = magnitude.data()[[10, 5]];
assert!((mag_val - power_val.sqrt()).abs() < 1e-10);
```

</td>
<td>

```python
import spectrograms as sg
import numpy as np

stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)

# Power: raw energy values
power = sg.compute_linear_power_spectrogram(
    samples, params
)

# Magnitude: sqrt of power
magnitude = sg.compute_linear_magnitude_spectrogram(
    samples, params
)

# Decibels: logarithmic scale
db_params = sg.LogParams(floor_db=-80.0)
db = sg.compute_linear_db_spectrogram(
    samples, params, db_params
)

# Verify relationship: magnitude = sqrt(power)
power_val = power.data[10, 5]
mag_val = magnitude.data[10, 5]
assert np.isclose(mag_val, np.sqrt(power_val))
```

</td>
</tr>
</table>

---

## Efficient Plan Reuse

For **batch processing** or **repeated computations**, creating a plan once and reusing it is **2-10x faster** than calling `compute()` repeatedly.

### Why Plan Reuse Matters

FFT plans are expensive to create but cheap to execute. Plan creation involves:
- Allocating FFT workspace buffers
- Computing optimal FFT algorithm
- Creating window function samples
- Building frequency mapping matrices (for Mel/ERB)

### Batch Processing Example

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

// Generate multiple test signals
let signals: Vec<Vec<f64>> = vec![
    generate_sine(220.0),  // A3
    generate_sine(440.0),  // A4
    generate_sine(880.0),  // A5
];

let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;
let mel = MelParams::new(80, 0.0, 8000.0)?;
let db = LogParams::new(-80.0)?;

// ❌ SLOW: Creates plan for each signal
for signal in &signals {
    let spec = MelDbSpectrogram::compute(
        signal, &params, &mel, Some(&db)
    )?;
    // Process spec...
}

// ✅ FAST: Create plan once, reuse
let planner = SpectrogramPlanner::new();
let mut plan = planner.mel_db_plan(
    &params, &mel, Some(&db)
)?;

for signal in &signals {
    let spec = plan.compute(signal)?;
    // Process spec... (2-10x faster!)
}
```

</td>
<td>

```python
import spectrograms as sg

# Generate multiple test signals
signals = [
    generate_sine(220.0),  # A3
    generate_sine(440.0),  # A4
    generate_sine(880.0),  # A5
]

stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)
mel = sg.MelParams(80, 0.0, 8000.0)
db = sg.LogParams(-80.0)

# ❌ SLOW: Creates plan for each signal
for signal in signals:
    spec = sg.compute_mel_db_spectrogram(
        signal, params, mel, db
    )
    # Process spec...

# ✅ FAST: Create plan once, reuse
planner = sg.SpectrogramPlanner()
plan = planner.mel_db_plan(params, mel, db)

for signal in signals:
    spec = plan.compute(signal)
    # Process spec... (2-10x faster!)
```

</td>
</tr>
</table>

### Plan Creation Methods

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let planner = SpectrogramPlanner::new();

// Linear spectrograms
let linear_power = planner.linear_plan::<Power>(&params, None)?;
let linear_mag = planner.linear_plan::<Magnitude>(&params, None)?;
let linear_db = planner.linear_plan::<Decibels>(&params, Some(&db))?;

// Mel spectrograms
let mel_power = planner.mel_power_plan(&params, &mel)?;
let mel_mag = planner.mel_magnitude_plan(&params, &mel)?;
let mel_db = planner.mel_db_plan(&params, &mel, Some(&db))?;

// ERB spectrograms
let erb_power = planner.erb_power_plan(&params, &erb)?;
let erb_mag = planner.erb_magnitude_plan(&params, &erb)?;
let erb_db = planner.erb_db_plan(&params, &erb, Some(&db))?;
```

</td>
<td>

```python
import spectrograms as sg

planner = sg.SpectrogramPlanner()

# Linear spectrograms
linear_power = planner.linear_power_plan(params)
linear_mag = planner.linear_magnitude_plan(params)
linear_db = planner.linear_db_plan(params, db)

# Mel spectrograms
mel_power = planner.mel_power_plan(params, mel)
mel_mag = planner.mel_magnitude_plan(params, mel)
mel_db = planner.mel_db_plan(params, mel, db)

# ERB spectrograms
erb_power = planner.erb_power_plan(params, erb)
erb_mag = planner.erb_magnitude_plan(params, erb)
erb_db = planner.erb_db_plan(params, erb, db)
```

</td>
</tr>
</table>

---

## Computing FFT and STFT

### Direct STFT Computation

For advanced use cases, you can compute the raw STFT (complex-valued spectrogram):

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;
use num_complex::Complex;

let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;

// Compute STFT using planner
let planner = SpectrogramPlanner::new();
let plan = planner.stft_plan(&params)?;

// Get complex STFT output
let stft_result = plan.compute_stft(&samples)?;

// stft_result contains:
// - Complex spectrum: Array2<Complex<f64>>
// - Shape: (n_fft/2 + 1, n_frames)

// Extract magnitude and phase
for (bin_idx, frame_idx) in [(10, 5)] {
    let c = stft_result[[bin_idx, frame_idx]];
    let magnitude = c.norm();
    let phase = c.arg();
    println!("Bin {} Frame {}: mag={:.2e}, phase={:.2}",
        bin_idx, frame_idx, magnitude, phase);
}
```

</td>
<td>

```python
import spectrograms as sg
import numpy as np

stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)

# Compute STFT (returns complex array)
stft_result = sg.compute_stft(samples, params)

# stft_result is a complex numpy array
# Shape: (n_fft/2 + 1, n_frames)

# Extract magnitude and phase
magnitude = np.abs(stft_result)
phase = np.angle(stft_result)

# Access specific bin/frame
c = stft_result[10, 5]
print(f"Bin 10 Frame 5: mag={np.abs(c):.2e}, phase={np.angle(c):.2f}")
```

</td>
</tr>
</table>

### Computing Power Spectrum from STFT

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

// Compute STFT
let planner = SpectrogramPlanner::new();
let stft_plan = planner.stft_plan(&params)?;
let stft = stft_plan.compute_stft(&samples)?;

// Convert to power spectrum manually
let power: Vec<Vec<f64>> = stft
    .axis_iter(ndarray::Axis(1))  // iterate over frames
    .map(|frame| {
        frame.iter()
            .map(|c| c.norm_sqr())  // |X|²
            .collect()
    })
    .collect();

// Or use the built-in method
let spec = LinearPowerSpectrogram::compute(
    &samples, &params, None
)?;
```

</td>
<td>

```python
import spectrograms as sg
import numpy as np

# Compute STFT
stft = sg.compute_stft(samples, params)

# Convert to power spectrum manually
power = np.abs(stft) ** 2  # |X|²

# Or use the built-in method
spec = sg.compute_linear_power_spectrogram(
    samples, params
)

# Verify they match
assert np.allclose(power, spec.data)
```

</td>
</tr>
</table>

---

## Streaming and Online Processing

For **real-time applications**, you can process audio **frame-by-frame** without computing the entire spectrogram.

### Frame-by-Frame Processing

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;
let mel = MelParams::new(40, 0.0, 8000.0)?;

// Create plan (do this once at startup)
let planner = SpectrogramPlanner::new();
let mut plan = planner.mel_power_plan(&params, &mel)?;

// Buffer for incoming audio
let mut buffer = Vec::new();

// As audio chunks arrive...
for chunk in audio_stream {
    buffer.extend_from_slice(&chunk);

    // Compute as many frames as possible
    let n_fft = stft.n_fft();
    let hop_size = stft.hop_size();
    let frames_available =
        (buffer.len() - n_fft) / hop_size + 1;

    for frame_idx in 0..frames_available {
        // Compute single frame
        let frame_data = plan.compute_frame(
            &buffer, frame_idx
        )?;

        // Process frame in real-time
        process_frame(&frame_data);
    }

    // Keep samples needed for next frames
    let samples_to_keep = n_fft +
        (frames_available - 1) * hop_size;
    buffer.drain(0..buffer.len() - samples_to_keep);
}
```

</td>
<td>

```python
import spectrograms as sg
import numpy as np

stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)
mel = sg.MelParams(40, 0.0, 8000.0)

# Create plan (do this once at startup)
planner = sg.SpectrogramPlanner()
plan = planner.mel_power_plan(params, mel)

# Buffer for incoming audio
buffer = np.array([], dtype=np.float64)

# As audio chunks arrive...
for chunk in audio_stream:
    buffer = np.concatenate([buffer, chunk])

    # Compute as many frames as possible
    frames_available = (
        (len(buffer) - stft.n_fft) // stft.hop_size + 1
    )

    for frame_idx in range(frames_available):
        # Compute single frame
        frame_data = plan.compute_frame(buffer, frame_idx)

        # Process frame in real-time
        process_frame(frame_data)

    # Keep samples needed for next frames
    samples_to_keep = (
        stft.n_fft + (frames_available - 1) * stft.hop_size
    )
    buffer = buffer[-samples_to_keep:]
```

</td>
</tr>
</table>

### Real-Time Feature Extraction

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let mut plan = planner.mel_power_plan(&params, &mel)?;
let mut buffer = Vec::new();

for chunk in audio_stream {
    buffer.extend_from_slice(&chunk);

    let frames_available =
        (buffer.len() - stft.n_fft()) / stft.hop_size() + 1;

    if frames_available > 0 {
        // Get latest frame
        let frame = plan.compute_frame(
            &buffer, frames_available - 1
        )?;

        // Extract features on the fly
        let energy: f64 = frame.iter().sum();
        let max_bin = frame.iter()
            .enumerate()
            .max_by(|(_, a), (_, b)|
                a.partial_cmp(b).unwrap()
            )
            .map(|(i, _)| i)
            .unwrap();

        println!("Energy: {:.2e}, Peak bin: {}",
            energy, max_bin);

        // Update buffer
        let keep = stft.n_fft() +
            (frames_available - 1) * stft.hop_size();
        buffer.drain(0..buffer.len() - keep);
    }
}
```

</td>
<td>

```python
import spectrograms as sg
import numpy as np

plan = planner.mel_power_plan(params, mel)
buffer = np.array([], dtype=np.float64)

for chunk in audio_stream:
    buffer = np.concatenate([buffer, chunk])

    frames_available = (
        (len(buffer) - stft.n_fft) // stft.hop_size + 1
    )

    if frames_available > 0:
        # Get latest frame
        frame = plan.compute_frame(
            buffer, frames_available - 1
        )

        # Extract features on the fly
        energy = np.sum(frame)
        max_bin = np.argmax(frame)

        print(f"Energy: {energy:.2e}, Peak bin: {max_bin}")

        # Update buffer
        keep = stft.n_fft + (frames_available - 1) * stft.hop_size
        buffer = buffer[-keep:]
```

</td>
</tr>
</table>

---

## Advanced Features

### MFCC

**Mel-Frequency Cepstral Coefficients** are widely used in speech recognition and audio classification.

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;

// Configure MFCC parameters
let mfcc_params = MfccParams::new(
    13,    // n_mfcc: number of coefficients
    80,    // n_mels: mel bands
    0.0,   // f_min
    8000.0 // f_max
)?;

// Compute MFCCs
let mfccs = mfcc(&samples, &params, &mfcc_params)?;

// mfccs.data is Array2<f64> with shape (n_mfcc, n_frames)
println!("MFCCs: {} coefficients × {} frames",
    mfccs.n_mfcc(), mfccs.n_frames());

// Access first frame MFCCs
let first_frame = mfccs.data().column(0);
for (i, &coef) in first_frame.iter().enumerate() {
    println!("  MFCC {}: {:.3}", i, coef);
}
```

</td>
<td>

```python
import spectrograms as sg

stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)

# Configure MFCC parameters
mfcc_params = sg.MfccParams(
    n_mfcc=13,
    n_mels=80,
    f_min=0.0,
    f_max=8000.0
)

# Compute MFCCs
mfccs = sg.compute_mfcc(samples, params, mfcc_params)

# mfccs is a numpy array with shape (n_mfcc, n_frames)
print(f"MFCCs: {mfccs.shape[0]} coefficients × {mfccs.shape[1]} frames")

# Access first frame MFCCs
first_frame = mfccs[:, 0]
for i, coef in enumerate(first_frame):
    print(f"  MFCC {i}: {coef:.3f}")
```

</td>
</tr>
</table>

### Chromagram

**Chromagrams** (pitch class profiles) map frequencies to 12 semitone bins (C, C#, D, ..., B).

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let stft = StftParams::new(2048, 512, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;

// Configure chromagram parameters
let chroma_params = ChromaParams::new(
    12,     // n_chroma: always 12 for standard chromagram
    ChromaNorm::L2  // normalization method
)?;

// Compute chromagram
let chroma = chromagram(&samples, &params, &chroma_params)?;

// chroma.data is Array2<f64> with shape (12, n_frames)
println!("Chromagram: {} pitch classes × {} frames",
    chroma.n_chroma(), chroma.n_frames());

// Find dominant pitch class in first frame
let first_frame = chroma.data().column(0);
let (pitch_class, energy) = first_frame.iter()
    .enumerate()
    .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
    .unwrap();

let pitch_names = ["C", "C#", "D", "D#", "E", "F",
                   "F#", "G", "G#", "A", "A#", "B"];
println!("Dominant pitch: {} (energy: {:.3})",
    pitch_names[pitch_class], energy);
```

</td>
<td>

```python
import spectrograms as sg

stft = sg.StftParams(2048, 512, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)

# Configure chromagram parameters
chroma_params = sg.ChromaParams(
    n_chroma=12,
    norm="l2"
)

# Compute chromagram
chroma = sg.compute_chromagram(
    samples, params, chroma_params
)

# chroma is a numpy array with shape (12, n_frames)
print(f"Chromagram: {chroma.shape[0]} pitch classes × {chroma.shape[1]} frames")

# Find dominant pitch class in first frame
first_frame = chroma[:, 0]
pitch_class = np.argmax(first_frame)
energy = first_frame[pitch_class]

pitch_names = ["C", "C#", "D", "D#", "E", "F",
               "F#", "G", "G#", "A", "A#", "B"]
print(f"Dominant pitch: {pitch_names[pitch_class]} (energy: {energy:.3f})")
```

</td>
</tr>
</table>

### CQT

**Constant-Q Transform** provides logarithmic frequency spacing ideal for music analysis.

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

let stft = StftParams::new(2048, 512, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, 16000.0)?;

// Configure CQT parameters
let cqt_params = CqtParams::new(
    84,     // n_bins: typically 7 octaves × 12 bins/octave
    12,     // bins_per_octave
    55.0,   // f_min: A1 note
    None    // f_max: computed from n_bins
)?;

// Compute CQT
let cqt_result = cqt(&samples, &params, &cqt_params)?;

// cqt_result.spectrogram is a CqtPowerSpectrogram
let spec = &cqt_result.spectrogram;
println!("CQT: {} bins × {} frames",
    spec.n_bins(), spec.n_frames());

// Access CQT frequencies (logarithmically spaced)
let freqs = spec.axes().frequencies();
println!("Frequency range: {:.1} Hz to {:.1} Hz",
    freqs[0], freqs[freqs.len() - 1]);
```

</td>
<td>

```python
import spectrograms as sg

stft = sg.StftParams(2048, 512, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, 16000)

# Configure CQT parameters
cqt_params = sg.CqtParams(
    n_bins=84,
    bins_per_octave=12,
    f_min=55.0,
    f_max=None  # computed from n_bins
)

# Compute CQT
cqt_result = sg.compute_cqt(samples, params, cqt_params)

# cqt_result is a Spectrogram object
print(f"CQT: {cqt_result.n_bins} bins × {cqt_result.n_frames} frames")

# Access CQT frequencies (logarithmically spaced)
freqs = cqt_result.frequencies
print(f"Frequency range: {freqs[0]:.1f} Hz to {freqs[-1]:.1f} Hz")
```

</td>
</tr>
</table>

---

## Performance Tips

### 1. Always Reuse Plans for Batch Processing

<table>
<tr>
<th>❌ Slow</th>
<th>✅ Fast</th>
</tr>
<tr>
<td>

```rust
// Creates FFT plan for EACH signal
for signal in signals {
    let spec = MelDbSpectrogram::compute(
        signal, &params, &mel, Some(&db)
    )?;
}
```

</td>
<td>

```rust
// Creates FFT plan ONCE
let mut plan = planner.mel_db_plan(&params, &mel, Some(&db))?;
for signal in signals {
    let spec = plan.compute(signal)?;
}
```

</td>
</tr>
</table>

### 2. Use Power-of-2 FFT Sizes

FFT algorithms are significantly faster when `n_fft` is a power of 2:

```rust
// ✅ Good: powers of 2
let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let stft = StftParams::new(1024, 512, WindowType::Hanning, true)?;
let stft = StftParams::new(2048, 1024, WindowType::Hanning, true)?;

// ❌ Slower: non-power-of-2
let stft = StftParams::new(1000, 500, WindowType::Hanning, true)?;
```

### 3. Choose the Right FFT Backend

- **FFTW** (default): Fastest, but requires C library dependency
- **RealFFT**: Pure Rust, slower but no external dependencies

```toml
# Use FFTW for maximum performance (default)
[dependencies]
spectrograms = "0.1"

# Use RealFFT for portability
[dependencies]
spectrograms = { version = "0.1", default-features = false, features = ["realfft"] }
```

### 4. Optimize Hop Size

Smaller `hop_size` = more frames = slower computation:

```rust
// High time resolution (slow)
let stft = StftParams::new(512, 128, WindowType::Hanning, true)?;  // 75% overlap

// Balanced (common)
let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;  // 50% overlap

// Lower time resolution (fast)
let stft = StftParams::new(512, 512, WindowType::Hanning, true)?;  // 0% overlap
```

### 5. Preallocate Output Buffers (Rust Only)

For maximum performance in Rust, you can preallocate output buffers:

```rust
let mut plan = planner.mel_db_plan(&params, &mel, Some(&db))?;

// Preallocate output buffer
let mut output = Array2::<f64>::zeros((plan.freq_axis().n_bins(), 100));

for signal in signals {
    // Compute into preallocated buffer (avoids allocation)
    plan.compute_into(signal, &mut output)?;
    // Process output...
}
```

---

## Common Patterns

### Pattern 1: Audio File to Mel Spectrogram

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;

// Load audio (using hound crate)
let reader = hound::WavReader::open("audio.wav")?;
let sample_rate = reader.spec().sample_rate as f64;
let samples: Vec<f64> = reader
    .into_samples::<i16>()
    .map(|s| s.unwrap() as f64 / 32768.0)
    .collect();

// Configure parameters
let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
let params = SpectrogramParams::new(stft, sample_rate)?;
let mel = MelParams::new(80, 0.0, sample_rate / 2.0)?;
let db = LogParams::new(-80.0)?;

// Compute mel spectrogram
let spec = MelDbSpectrogram::compute(
    &samples, &params, &mel, Some(&db)
)?;

// Save as numpy array (using ndarray-npy)
ndarray_npy::write_npy("spectrogram.npy", spec.data())?;
```

</td>
<td>

```python
import spectrograms as sg
import soundfile as sf
import numpy as np

# Load audio
samples, sample_rate = sf.read("audio.wav", dtype='float64')

# If stereo, convert to mono
if samples.ndim > 1:
    samples = samples.mean(axis=1)

# Configure parameters
stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
params = sg.SpectrogramParams(stft, sample_rate)
mel = sg.MelParams(80, 0.0, sample_rate / 2)
db = sg.LogParams(-80.0)

# Compute mel spectrogram
spec = sg.compute_mel_db_spectrogram(
    samples, params, mel, db
)

# Save as numpy array
np.save("spectrogram.npy", spec.data)
```

</td>
</tr>
</table>

### Pattern 2: Process Directory of Audio Files

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;
use std::path::Path;

fn process_directory(
    dir: &Path,
    pattern: &str
) -> Result<(), Box<dyn std::error::Error>> {
    // Configure parameters
    let stft = StftParams::new(512, 256, WindowType::Hanning, true)?;
    let params = SpectrogramParams::new(stft, 16000.0)?;
    let mel = MelParams::new(80, 0.0, 8000.0)?;
    let db = LogParams::new(-80.0)?;

    // Create plan ONCE
    let planner = SpectrogramPlanner::new();
    let mut plan = planner.mel_db_plan(&params, &mel, Some(&db))?;

    // Process all files
    for entry in glob::glob(pattern)? {
        let path = entry?;
        let samples = load_audio(&path)?;

        let spec = plan.compute(&samples)?;

        // Save or process spec
        let output = path.with_extension("npy");
        ndarray_npy::write_npy(&output, spec.data())?;

        println!("Processed: {}", path.display());
    }

    Ok(())
}
```

</td>
<td>

```python
import spectrograms as sg
import soundfile as sf
import numpy as np
from pathlib import Path

def process_directory(dir_path, pattern="*.wav"):
    # Configure parameters
    stft = sg.StftParams(512, 256, sg.WindowType.hanning(), True)
    params = sg.SpectrogramParams(stft, 16000)
    mel = sg.MelParams(80, 0.0, 8000.0)
    db = sg.LogParams(-80.0)

    # Create plan ONCE
    planner = sg.SpectrogramPlanner()
    plan = planner.mel_db_plan(params, mel, db)

    # Process all files
    for audio_file in Path(dir_path).glob(pattern):
        samples, sr = sf.read(audio_file, dtype='float64')

        if samples.ndim > 1:
            samples = samples.mean(axis=1)

        spec = plan.compute(samples)

        # Save or process spec
        output = audio_file.with_suffix('.npy')
        np.save(output, spec.data)

        print(f"Processed: {audio_file}")
```

</td>
</tr>
</table>

### Pattern 3: Extract Spectral Features

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;
use ndarray::s;

// Compute power spectrogram
let spec = LinearPowerSpectrogram::compute(
    &samples, &params, None
)?;

// Spectral centroid (weighted mean frequency)
let freqs = spec.axes().frequencies();
let mut centroids = Vec::new();

for frame in spec.data().axis_iter(ndarray::Axis(1)) {
    let sum_power: f64 = frame.iter().sum();
    let weighted_sum: f64 = frame.iter()
        .enumerate()
        .map(|(i, &p)| freqs[i] * p)
        .sum();

    let centroid = weighted_sum / (sum_power + 1e-10);
    centroids.push(centroid);
}

// Spectral rolloff (95% of energy)
let mut rolloffs = Vec::new();

for frame in spec.data().axis_iter(ndarray::Axis(1)) {
    let total: f64 = frame.iter().sum();
    let threshold = 0.95 * total;

    let mut cumsum = 0.0;
    let rolloff_idx = frame.iter()
        .position(|&p| {
            cumsum += p;
            cumsum >= threshold
        })
        .unwrap_or(0);

    rolloffs.push(freqs[rolloff_idx]);
}
```

</td>
<td>

```python
import spectrograms as sg
import numpy as np

# Compute power spectrogram
spec = sg.compute_linear_power_spectrogram(
    samples, params
)

freqs = spec.frequencies

# Spectral centroid (weighted mean frequency)
centroids = np.sum(
    freqs[:, np.newaxis] * spec.data, axis=0
) / (np.sum(spec.data, axis=0) + 1e-10)

# Spectral rolloff (95% of energy)
cumsum = np.cumsum(spec.data, axis=0)
total = cumsum[-1, :]
threshold = 0.95 * total

rolloff_indices = np.argmax(
    cumsum >= threshold[np.newaxis, :], axis=0
)
rolloffs = freqs[rolloff_indices]

# Spectral bandwidth
# (standard deviation of spectrum around centroid)
bandwidths = np.sqrt(
    np.sum(
        ((freqs[:, np.newaxis] - centroids[np.newaxis, :]) ** 2) * spec.data,
        axis=0
    ) / (np.sum(spec.data, axis=0) + 1e-10)
)
```

</td>
</tr>
</table>

### Pattern 4: Spectrogram Augmentation for ML

<table>
<tr>
<th>Rust</th>
<th>Python</th>
</tr>
<tr>
<td>

```rust
use spectrograms::*;
use ndarray::{Array2, Axis};
use rand::Rng;

// Compute base spectrogram
let spec = MelDbSpectrogram::compute(
    &samples, &params, &mel, Some(&db)
)?;

// Time masking (SpecAugment)
fn time_mask(
    data: &mut Array2<f64>,
    mask_width: usize
) {
    let n_frames = data.ncols();
    let mut rng = rand::thread_rng();
    let start = rng.gen_range(0..n_frames - mask_width);

    data.slice_mut(s![.., start..start + mask_width])
        .fill(-80.0);  // Fill with floor value
}

// Frequency masking
fn freq_mask(
    data: &mut Array2<f64>,
    mask_height: usize
) {
    let n_bins = data.nrows();
    let mut rng = rand::thread_rng();
    let start = rng.gen_range(0..n_bins - mask_height);

    data.slice_mut(s![start..start + mask_height, ..])
        .fill(-80.0);
}

let mut augmented = spec.data().clone();
time_mask(&mut augmented, 10);
freq_mask(&mut augmented, 5);
```

</td>
<td>

```python
import spectrograms as sg
import numpy as np

# Compute base spectrogram
spec = sg.compute_mel_db_spectrogram(
    samples, params, mel, db
)

# Time masking (SpecAugment)
def time_mask(data, mask_width):
    n_frames = data.shape[1]
    start = np.random.randint(0, n_frames - mask_width)
    data[:, start:start + mask_width] = -80.0
    return data

# Frequency masking
def freq_mask(data, mask_height):
    n_bins = data.shape[0]
    start = np.random.randint(0, n_bins - mask_height)
    data[start:start + mask_height, :] = -80.0
    return data

# Apply augmentation
augmented = spec.data.copy()
augmented = time_mask(augmented, mask_width=10)
augmented = freq_mask(augmented, mask_height=5)
```

</td>
</tr>
</table>

---

## Summary

This guide covered:

- **Installation** for both Rust and Python
-**Basic spectrogram computation** with linear, mel, and ERB scales
-**Amplitude scales** (power, magnitude, decibels)
-**Efficient plan reuse** for 2-10x speedup on batch processing
-**FFT and STFT computation** for advanced use cases
-**Streaming processing** for real-time applications
-**Advanced features** (MFCC, chromagram, CQT)
-**Performance optimization** tips
-**Common patterns** for real-world applications

### Key Takeaways

1. **For single computations**: Use convenience functions (`compute_*`)
2. **For batch processing**: Use `SpectrogramPlanner` and reuse plans (2-10x faster)
3. **For real-time**: Use `compute_frame()` for streaming processing
4. **For performance**: Use power-of-2 FFT sizes and FFTW backend

### Next Steps

- Check out the [examples/]../examples/ directory for more code examples
- Read the [API documentation]https://docs.rs/spectrograms for detailed reference
- See [CLAUDE.md]../CLAUDE.md for architecture details and development guidelines

---

**Questions or issues?** Open an issue on [GitHub](https://github.com/user/spectrograms/issues)!