mqa-identify 0.2.0

A minimal library, to check if a flac file has been encoded by/with MQA
Documentation
#![deny(clippy::pedantic)]

use claxon::FlacReader;

const MQA_MAGIC_WORD: u64 = 0xb_e049_8c88;
const MQA_MAGIC_MASK: u64 = 0xF_FFFF_FFFF;

/// Checks if the given FLAC file is an MQA file by looking for the MQA magic word in the least significant bits of the samples.
/// Note that the magic work may also happen to appear in a non-MQA file, but this is very unlikely.
/// The function checks the first three seconds of audio data, which should be sufficient to find the magic word if it is present.
///
/// # Errors
/// Returns an error if the file cannot be read or is not a valid FLAC file.
///
pub fn identify_mqa(path: impl AsRef<std::path::Path>) -> Result<bool, claxon::Error> {
    let mut decoder = FlacReader::open(path)?;
    let position = decoder.streaminfo().bits_per_sample - 16;

    let first_three_seconds = decoder.streaminfo().sample_rate * 3;
    let mut checked_samples = 0;

    let mut frame_reader = decoder.blocks();
    let mut current_block = frame_reader.read_next_or_eof(vec![]);

    let mut buffer0 = 0u64;
    let mut buffer1 = 0u64;
    let mut buffer2 = 0u64;

    while let Ok(Some(samples)) = current_block {
        for (x, y) in samples.stereo_samples() {
            #[allow(clippy::cast_sign_loss)]
            {
                buffer0 |= ((x ^ y) as u64 >> position) & 1;
                buffer1 |= ((x ^ y) as u64 >> (position + 1)) & 1;
                buffer2 |= ((x ^ y) as u64 >> (position + 2)) & 1;
            }

            if buffer0 == MQA_MAGIC_WORD || buffer1 == MQA_MAGIC_WORD || buffer2 == MQA_MAGIC_WORD {
                return Ok(true);
            }

            buffer0 = (buffer0 << 1) & MQA_MAGIC_MASK;
            buffer1 = (buffer1 << 1) & MQA_MAGIC_MASK;
            buffer2 = (buffer2 << 1) & MQA_MAGIC_MASK;
        }

        checked_samples += samples.len();

        current_block = if checked_samples >= first_three_seconds {
            Ok(None)
        } else {
            frame_reader.read_next_or_eof(samples.into_buffer())
        }
    }

    Ok(false)
}