dtmf_table 1.1.4

A zero-heap, no_std, const-first DTMF keypad frequency table with runtime tolerance helpers. Also available in Python
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
use crate::{DtmfKey as RustDtmfKey, DtmfTable as RustDtmfTable, DtmfTone as RustDtmfTone};
use pyo3::exceptions::PyValueError;
use pyo3::prelude::*;
extern crate std;
use std::collections::hash_map::DefaultHasher;
use std::format;
use std::hash::{Hash, Hasher};

/// A DTMF (Dual-Tone Multi-Frequency) key representing telephony keypad buttons.
///
/// DtmfKey represents one of the 16 standard DTMF keys used in telephony systems:
/// - Digits 0-9
/// - Special characters * and #
/// - Letters A-D (extended keypad)
///
/// Each key corresponds to a unique pair of low and high frequency tones.
///
/// Examples:
///     >>> from dtmf_table import DtmfKey
///     >>> key = DtmfKey.from_char('5')
///     >>> key.to_char()
///     '5'
///     >>> low, high = key.freqs()
///     >>> (low, high)
///     (770, 1336)
#[pyclass(name = "DtmfKey", module = "dtmf_table", from_py_object)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PyDtmfKey {
    inner: RustDtmfKey,
}

#[pymethods]
impl PyDtmfKey {
    /// Create a DtmfKey from a character.
    ///
    /// Args:
    ///     c (str): Single character representing the DTMF key ('0'-'9', '*', '#', 'A'-'D')
    ///
    /// Returns:
    ///     DtmfKey: The corresponding DTMF key
    ///
    /// Raises:
    ///     ValueError: If the character is not a valid DTMF key
    #[staticmethod]
    #[pyo3(signature = (c: "str"), text_signature = "(c: str) -> DtmfKey")]
    fn from_char(c: char) -> PyResult<Self> {
        match RustDtmfKey::from_char(c) {
            Some(key) => Ok(PyDtmfKey { inner: key }),
            None => Err(PyValueError::new_err(format!(
                "Invalid DTMF character: '{}'",
                c
            ))),
        }
    }

    /// Convert the DtmfKey to its character representation.
    ///
    /// Returns:
    ///     str: Single character representing the key
    #[pyo3(signature = (), text_signature = "($self) -> str")]
    const fn to_char(&self) -> char {
        self.inner.to_char()
    }

    /// Get the canonical frequencies for this DTMF key.
    ///
    /// Returns:
    ///     tuple[int, int]: (low_frequency_hz, high_frequency_hz)
    #[pyo3(signature = (), text_signature = "($self) -> tuple[int, int]")]
    const fn freqs(&self) -> (u16, u16) {
        self.inner.freqs()
    }

    fn __str__(&self) -> String {
        self.inner.to_char().to_string()
    }

    fn __repr__(&self) -> String {
        format!("DtmfKey('{}')", self.inner.to_char())
    }

    fn __eq__(&self, other: &PyDtmfKey) -> bool {
        self.inner == other.inner
    }

    fn __hash__(&self) -> u64 {
        let mut hasher = DefaultHasher::new();
        self.inner.hash(&mut hasher);
        hasher.finish()
    }
}

/// A DTMF tone containing a key and its associated frequency pair.
///
/// DtmfTone represents the complete information for a DTMF signal:
/// the key character and its corresponding low and high frequencies.
/// This is useful for iterating over all possible tones or when you need
/// both the key and frequency information together.
///
/// Examples:
///     >>> from dtmf_table import DtmfTable
///     >>> tones = DtmfTable.all_tones()
///     >>> tone = tones[0]  # First tone
///     >>> print(tone)
///     1: (697 Hz, 1209 Hz)
///     >>> tone.key.to_char()
///     '1'
///     >>> (tone.low_hz, tone.high_hz)
///     (697, 1209)
#[pyclass(name = "DtmfTone", module = "dtmf_table", from_py_object)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PyDtmfTone {
    inner: RustDtmfTone,
}

#[pymethods]
impl PyDtmfTone {
    /// Create a new DtmfTone.
    ///
    /// Args:
    ///     key (DtmfKey): The DTMF key
    ///     low_hz (int): Low frequency in Hz
    ///     high_hz (int): High frequency in Hz
    #[new]
    #[pyo3(signature = (key: "DtmfKey", low_hz: "int", high_hz: "int"), text_signature = "(key: DtmfKey, low_hz: int, high_hz: int)")]
    const fn new(key: PyDtmfKey, low_hz: u16, high_hz: u16) -> Self {
        PyDtmfTone {
            inner: RustDtmfTone {
                key: key.inner,
                low_hz,
                high_hz,
            },
        }
    }

    /// The DTMF key for this tone.
    #[getter]
    const fn key(&self) -> PyDtmfKey {
        PyDtmfKey {
            inner: self.inner.key,
        }
    }

    /// Low frequency in Hz.
    #[getter]
    const fn low_hz(&self) -> u16 {
        self.inner.low_hz
    }

    /// High frequency in Hz.
    #[getter]
    const fn high_hz(&self) -> u16 {
        self.inner.high_hz
    }

    fn __str__(&self) -> String {
        format!(
            "{}: ({} Hz, {} Hz)",
            self.inner.key.to_char(),
            self.inner.low_hz,
            self.inner.high_hz
        )
    }

    fn __repr__(&self) -> String {
        format!(
            "DtmfTone(key=DtmfKey('{}'), low_hz={}, high_hz={})",
            self.inner.key.to_char(),
            self.inner.low_hz,
            self.inner.high_hz
        )
    }

    fn __eq__(&self, other: &PyDtmfTone) -> bool {
        self.inner == other.inner
    }
}

/// DTMF frequency lookup table for audio processing applications.
///
/// DtmfTable provides efficient bidirectional mapping between DTMF keys and their
/// canonical frequency pairs. It supports exact lookups, tolerance-based matching
/// for real-world audio analysis, and frequency snapping for noisy estimates.
///
/// The table contains all 16 standard DTMF frequencies used in telephony:
///
/// =======  =======  =======  =======  =======
///          1209 Hz  1336 Hz  1477 Hz  1633 Hz
/// =======  =======  =======  =======  =======
/// 697 Hz      1        2        3        A
/// 770 Hz      4        5        6        B
/// 852 Hz      7        8        9        C
/// 941 Hz      *        0        #        D
/// =======  =======  =======  =======  =======
///
/// Examples:
///     Basic usage:
///
///     >>> from dtmf_table import DtmfTable, DtmfKey
///     >>> table = DtmfTable()
///     >>>
///     >>> # Forward lookup: key to frequencies
///     >>> key = DtmfKey.from_char('5')
///     >>> low, high = table.lookup_key(key)
///     >>> (low, high)
///     (770, 1336)
///
///     Real-world audio analysis:
///
///     >>> # Reverse lookup with tolerance (from FFT peaks)
///     >>> key = table.from_pair_tol_f64(770.2, 1335.8, 5.0)
///     >>> key.to_char() if key else None
///     '5'
///     >>>
///     >>> # Snap noisy frequencies to nearest canonical values
///     >>> key, low, high = table.nearest_u32(768, 1340)
///     >>> (key.to_char(), low, high)
///     ('5', 770, 1336)
#[pyclass(name = "DtmfTable", module = "dtmf_table")]
#[derive(Debug)]
pub struct PyDtmfTable {
    inner: RustDtmfTable,
}

#[pymethods]
impl PyDtmfTable {
    /// Create a new DTMF table instance.
    #[new]
    #[pyo3(signature = (), text_signature = "()")]
    const fn new() -> Self {
        PyDtmfTable {
            inner: RustDtmfTable::new(),
        }
    }

    /// Get all DTMF keys in keypad order.
    ///
    /// Returns:
    ///     list[DtmfKey]: All 16 DTMF keys
    #[staticmethod]
    #[pyo3(signature = (), text_signature = "() -> list[DtmfKey]")]
    fn all_keys() -> Vec<PyDtmfKey> {
        RustDtmfTable::ALL_KEYS
            .iter()
            .map(|&key| PyDtmfKey { inner: key })
            .collect()
    }

    /// Get all DTMF tones in keypad order.
    ///
    /// Returns:
    ///     list[DtmfTone]: All 16 DTMF tones
    #[staticmethod]
    #[pyo3(signature = (), text_signature = "() -> list[DtmfTone]")]
    fn all_tones() -> Vec<PyDtmfTone> {
        RustDtmfTable::ALL_TONES
            .iter()
            .map(|&tone| PyDtmfTone { inner: tone })
            .collect()
    }

    /// Get all DTMF keys as a 4x4 matrix.
    ///
    /// Returns:
    ///     list[list[DtmfKey]]: 4x4 matrix of keys in keypad layout
    #[staticmethod]
    #[pyo3(signature = (), text_signature = "() -> list[list[DtmfKey]]")]
    fn all_keys_matrix() -> Vec<Vec<PyDtmfKey>> {
        let keys = &RustDtmfTable::ALL_KEYS;
        vec![
            keys[0..4].iter().map(|&k| PyDtmfKey { inner: k }).collect(),
            keys[4..8].iter().map(|&k| PyDtmfKey { inner: k }).collect(),
            keys[8..12]
                .iter()
                .map(|&k| PyDtmfKey { inner: k })
                .collect(),
            keys[12..16]
                .iter()
                .map(|&k| PyDtmfKey { inner: k })
                .collect(),
        ]
    }

    /// Get all DTMF tones as a 4x4 matrix.
    ///
    /// Returns:
    ///     list[list[DtmfTone]]: 4x4 matrix of tones in keypad layout
    #[staticmethod]
    #[pyo3(signature = (), text_signature = "() -> list[list[DtmfTone]]")]
    fn all_tones_matrix() -> Vec<Vec<PyDtmfTone>> {
        let tones = &RustDtmfTable::ALL_TONES;
        vec![
            tones[0..4]
                .iter()
                .map(|&t| PyDtmfTone { inner: t })
                .collect(),
            tones[4..8]
                .iter()
                .map(|&t| PyDtmfTone { inner: t })
                .collect(),
            tones[8..12]
                .iter()
                .map(|&t| PyDtmfTone { inner: t })
                .collect(),
            tones[12..16]
                .iter()
                .map(|&t| PyDtmfTone { inner: t })
                .collect(),
        ]
    }

    /// Look up frequencies for a given key.
    ///
    /// Args:
    ///     key (DtmfKey): The DTMF key to look up
    ///
    /// Returns:
    ///     tuple[int, int]: (low_frequency_hz, high_frequency_hz)
    #[staticmethod]
    #[pyo3(signature = (key: "DtmfKey"), text_signature = "(key: DtmfKey) -> tuple[int, int]")]
    const fn lookup_key(key: PyDtmfKey) -> (u16, u16) {
        RustDtmfTable::lookup_key(key.inner)
    }

    /// Find DTMF key from exact frequency pair.
    ///
    /// Args:
    ///     low (int): Low frequency in Hz
    ///     high (int): High frequency in Hz
    ///
    /// Returns:
    ///     DtmfKey or None: The matching key, or None if no exact match
    #[staticmethod]
    #[pyo3(signature = (low: "int", high: "int"), text_signature = "(low: int, high: int) -> DtmfKey | None")]
    fn from_pair_exact(low: u16, high: u16) -> Option<PyDtmfKey> {
        RustDtmfTable::from_pair_exact(low, high).map(|key| PyDtmfKey { inner: key })
    }

    /// Find DTMF key from frequency pair with automatic order normalization.
    ///
    /// Args:
    ///     a (int): First frequency in Hz
    ///     b (int): Second frequency in Hz
    ///
    /// Returns:
    ///     DtmfKey or None: The matching key, or None if no exact match
    #[staticmethod]
    #[pyo3(signature = (a: "int", b: "int"), text_signature = "(a: int, b: int) -> DtmfKey | None")]
    fn from_pair_normalised(a: u16, b: u16) -> Option<PyDtmfKey> {
        RustDtmfTable::from_pair_normalised(a, b).map(|key| PyDtmfKey { inner: key })
    }

    /// Find DTMF key from frequency pair with tolerance (integer version).
    ///
    /// Args:
    ///     low (int): Low frequency in Hz
    ///     high (int): High frequency in Hz
    ///     tol_hz (int): Tolerance in Hz
    ///
    /// Returns:
    ///     DtmfKey or None: The matching key within tolerance, or None
    #[allow(clippy::wrong_self_convention)]
    #[pyo3(signature = (low: "int", high: "int", tol_hz: "int"), text_signature = "(low: int, high: int, tol_hz: int) -> DtmfKey | None")]
    fn from_pair_tol_u32(&self, low: u32, high: u32, tol_hz: u32) -> Option<PyDtmfKey> {
        self.inner
            .from_pair_tol_u32(low, high, tol_hz)
            .map(|key| PyDtmfKey { inner: key })
    }

    /// Find DTMF key from frequency pair with tolerance (float version).
    ///
    /// Args:
    ///     low (float): Low frequency in Hz
    ///     high (float): High frequency in Hz
    ///     tol_hz (float): Tolerance in Hz
    ///
    /// Returns:
    ///     DtmfKey or None: The matching key within tolerance, or None
    #[allow(clippy::wrong_self_convention)]
    #[pyo3(signature = (low: "float", high: "float", tol_hz: "float"), text_signature = "($self, low: float, high: float, tol_hz: float) -> DtmfKey | None")]
    fn from_pair_tol_f64(&self, low: f64, high: f64, tol_hz: f64) -> Option<PyDtmfKey> {
        self.inner
            .from_pair_tol_f64(low, high, tol_hz)
            .map(|key| PyDtmfKey { inner: key })
    }

    /// Find the nearest DTMF key and snap frequencies to canonical values (integer version).
    ///
    /// Args:
    ///     low (int): Low frequency estimate in Hz
    ///     high (int): High frequency estimate in Hz
    ///
    /// Returns:
    ///     tuple[DtmfKey, int, int]: (key, snapped_low_hz, snapped_high_hz)
    #[pyo3(signature = (low: "int", high: "int"), text_signature = "($self, low: int, high: int) -> tuple[DtmfKey, int, int]")]
    fn nearest_u32(&self, low: u32, high: u32) -> (PyDtmfKey, u16, u16) {
        let (key, snapped_low, snapped_high) = self.inner.nearest_u32(low, high);
        (PyDtmfKey { inner: key }, snapped_low, snapped_high)
    }

    /// Find the nearest DTMF key and snap frequencies to canonical values (float version).
    ///
    /// Args:
    ///     low (float): Low frequency estimate in Hz
    ///     high (float): High frequency estimate in Hz
    ///
    /// Returns:
    ///     tuple[DtmfKey, int, int]: (key, snapped_low_hz, snapped_high_hz)
    #[pyo3(signature = (low: "float", high: "float"), text_signature = "($self, low: float, high: float) -> tuple[DtmfKey, int, int]")]
    fn nearest_f64(&self, low: f64, high: f64) -> (PyDtmfKey, u16, u16) {
        let (key, snapped_low, snapped_high) = self.inner.nearest_f64(low, high);
        (PyDtmfKey { inner: key }, snapped_low, snapped_high)
    }

    fn __str__(&self) -> String {
        format!("{:#}", self.inner)
    }

    fn __repr__(&self) -> String {
        "DtmfTable()".to_string()
    }
}

/// Initialize the Python module
#[pymodule]
fn dtmf_table(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_class::<PyDtmfKey>()?;
    m.add_class::<PyDtmfTone>()?;
    m.add_class::<PyDtmfTable>()?;

    // Add module-level constants
    m.add("__version__", env!("CARGO_PKG_VERSION"))?;

    // Add DTMF frequency constants
    m.add(
        "LOWS",
        (
            RustDtmfTable::LOWS[0],
            RustDtmfTable::LOWS[1],
            RustDtmfTable::LOWS[2],
            RustDtmfTable::LOWS[3],
        ),
    )?;
    m.add(
        "HIGHS",
        (
            RustDtmfTable::HIGHS[0],
            RustDtmfTable::HIGHS[1],
            RustDtmfTable::HIGHS[2],
            RustDtmfTable::HIGHS[3],
        ),
    )?;

    m.add(
        "__doc__",
        r#"DTMF (Dual-Tone Multi-Frequency) frequency table for telephony applications.

This library provides efficient, const-first mappings between DTMF keys and their
canonical frequency pairs. Built with Rust for performance, it offers both exact
lookups and tolerance-based matching for real-world audio analysis.

Key Features:
- Zero-allocation const-evaluated mappings
- Bidirectional key ⟷ frequency conversion
- Tolerance-based reverse lookup for FFT analysis
- Frequency snapping for noisy estimates
- Support for all 16 standard DTMF tones

Constants:
    LOWS: Low-band DTMF frequencies in Hz (697, 770, 852, 941)
    HIGHS: High-band DTMF frequencies in Hz (1209, 1336, 1477, 1633)

Classes:
    DtmfKey: Represents a single DTMF key (0-9, *, #, A-D)
    DtmfTone: Combines a key with its frequency pair
    DtmfTable: Main lookup table for conversions and analysis

Example:
    >>> from dtmf_table import DtmfTable, DtmfKey, LOWS, HIGHS
    >>> table = DtmfTable()
    >>> key = DtmfKey.from_char('5')
    >>> low, high = key.freqs()
    >>> print(f"Key {key} = {low}Hz + {high}Hz")
    Key 5 = 770Hz + 1336Hz
    >>> print(f"Low frequencies: {LOWS}")
    Low frequencies: (697, 770, 852, 941)
"#,
    )?;

    Ok(())
}