Skip to main content

chromaprint/
types.rs

1use std::cell::OnceCell;
2
3/// Number of chroma bands (12 semitones per octave).
4pub const NUM_BANDS: usize = 12;
5
6/// A 12-element chroma feature vector.
7/// Uses f64 to match the C implementation which uses `double` throughout.
8pub type ChromaVector = [f64; NUM_BANDS];
9
10/// Algorithm version selector.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
12#[repr(u8)]
13pub enum Algorithm {
14    Test1 = 0,
15    Test2 = 1,
16    Test3 = 2,
17    Test4 = 3,
18    Test5 = 4,
19}
20
21impl Algorithm {
22    pub fn from_u8(v: u8) -> Option<Self> {
23        match v {
24            0 => Some(Self::Test1),
25            1 => Some(Self::Test2),
26            2 => Some(Self::Test3),
27            3 => Some(Self::Test4),
28            4 => Some(Self::Test5),
29            _ => None,
30        }
31    }
32}
33
34impl Default for Algorithm {
35    fn default() -> Self {
36        Self::Test2
37    }
38}
39
40/// Result of a fingerprinting operation.
41pub struct Fingerprint {
42    /// Raw sub-fingerprints (32-bit values).
43    pub raw: Vec<u32>,
44    /// Algorithm used to generate this fingerprint.
45    pub algorithm: Algorithm,
46    /// Lazily computed compressed+base64 encoded string.
47    encoded: OnceCell<String>,
48    /// Lazily computed SimHash.
49    hash: OnceCell<u32>,
50}
51
52impl Fingerprint {
53    pub fn new(raw: Vec<u32>, algorithm: Algorithm) -> Self {
54        Self {
55            raw,
56            algorithm,
57            encoded: OnceCell::new(),
58            hash: OnceCell::new(),
59        }
60    }
61
62    /// Get the compressed base64-encoded fingerprint string.
63    /// Computed lazily on first access.
64    pub fn encoded(&self) -> &str {
65        self.encoded.get_or_init(|| {
66            crate::fingerprint::compressor::compress(&self.raw, self.algorithm)
67        })
68    }
69
70    /// Get the SimHash of the fingerprint.
71    /// Computed lazily on first access.
72    pub fn hash(&self) -> u32 {
73        *self.hash.get_or_init(|| {
74            crate::fingerprint::simhash::simhash(&self.raw)
75        })
76    }
77}