diff options
Diffstat (limited to 'src')
| -rw-r--r-- | src/decoder.rs | 1 | ||||
| -rw-r--r-- | src/lib.rs | 28 | ||||
| -rw-r--r-- | src/main.rs | 167 |
3 files changed, 129 insertions, 67 deletions
diff --git a/src/decoder.rs b/src/decoder.rs index 1a217d3..4bf075b 100644 --- a/src/decoder.rs +++ b/src/decoder.rs @@ -245,7 +245,6 @@ impl MorseDecoder { } // --- The complex analysis functions below are unchanged --- - fn detect_pitch_stft(&self) -> Result<f32> { let fft_size = 4096; let step_size = fft_size / 4; @@ -4,26 +4,26 @@ mod decoder; pub mod generator; -pub use generator::MorseGenerator; use decoder::MorseDecoder; +pub use generator::MorseGenerator; use anyhow::Result; /// High-level convenience function to decode a WAV file directly -/// +/// /// # Example /// ```no_run /// use ditdah::decode_wav_file; -/// +/// /// let decoded_text = decode_wav_file("morse.wav").unwrap(); /// println!("Decoded: {}", decoded_text); /// ``` pub fn decode_wav_file<P: AsRef<std::path::Path>>(path: P) -> Result<String> { use hound::{SampleFormat, WavReader}; - + let mut reader = WavReader::open(path)?; let spec = reader.spec(); - + // Check supported formats if spec.sample_format != SampleFormat::Int && spec.sample_format != SampleFormat::Float { anyhow::bail!( @@ -31,10 +31,10 @@ pub fn decode_wav_file<P: AsRef<std::path::Path>>(path: P) -> Result<String> { spec.sample_format ); } - + // Create decoder with automatic sample rate conversion let mut decoder = MorseDecoder::new(spec.sample_rate, 12000)?; - + // Read all samples let samples_f32: Vec<f32> = if spec.sample_format == SampleFormat::Int { reader @@ -44,7 +44,7 @@ pub fn decode_wav_file<P: AsRef<std::path::Path>>(path: P) -> Result<String> { } else { reader.samples::<f32>().map(|s| s.unwrap()).collect() }; - + // Convert to mono if necessary let mono_samples: Vec<f32> = if spec.channels > 1 { samples_f32 @@ -54,22 +54,22 @@ pub fn decode_wav_file<P: AsRef<std::path::Path>>(path: P) -> Result<String> { } else { samples_f32 }; - + // Process in chunks for better memory efficiency const CHUNK_SIZE: usize = 4096; for chunk in mono_samples.chunks(CHUNK_SIZE) { decoder.process(chunk)?; } - + decoder.finalize() } /// High-level convenience function to decode audio samples directly -/// +/// /// # Example /// ```no_run /// use ditdah::decode_samples; -/// +/// /// // For real audio data with sufficient length for processing /// let samples = vec![0.0; 48000]; // 4 seconds of audio at 12kHz /// let decoded_text = decode_samples(&samples, 12000).unwrap(); @@ -77,11 +77,11 @@ pub fn decode_wav_file<P: AsRef<std::path::Path>>(path: P) -> Result<String> { /// ``` pub fn decode_samples(samples: &[f32], sample_rate: u32) -> Result<String> { let mut decoder = MorseDecoder::new(sample_rate, 12000)?; - + const CHUNK_SIZE: usize = 4096; for chunk in samples.chunks(CHUNK_SIZE) { decoder.process(chunk)?; } - + decoder.finalize() } diff --git a/src/main.rs b/src/main.rs index c711d3d..98429ee 100644 --- a/src/main.rs +++ b/src/main.rs @@ -16,72 +16,97 @@ struct Cli { /// Path to the input WAV file #[arg(value_name = "FILE", help = "WAV file containing Morse code audio")] wav_file: Option<PathBuf>, - + /// Show detailed processing information #[arg(short, long, help = "Enable verbose output")] verbose: bool, - + /// Show timing information #[arg(short, long, help = "Show processing time")] time: bool, - + /// Generate a test WAV file instead of decoding - #[arg(long, value_name = "TEXT", help = "Generate test WAV file with given text")] + #[arg( + long, + value_name = "TEXT", + help = "Generate test WAV file with given text" + )] generate: Option<String>, - + /// Output file for generation (default: output.wav) - #[arg(short, long, value_name = "FILE", help = "Output file for generated WAV")] + #[arg( + short, + long, + value_name = "FILE", + help = "Output file for generated WAV" + )] output: Option<PathBuf>, - + /// Frequency for generated audio (default: 600 Hz) - #[arg(long, value_name = "HZ", default_value = "600", help = "Frequency in Hz for generated audio")] + #[arg( + long, + value_name = "HZ", + default_value = "600", + help = "Frequency in Hz for generated audio" + )] frequency: f32, - + /// Words per minute for generated audio (default: 20 WPM) - #[arg(long, value_name = "WPM", default_value = "20", help = "Words per minute for generated audio")] + #[arg( + long, + value_name = "WPM", + default_value = "20", + help = "Words per minute for generated audio" + )] wpm: f32, } fn main() -> Result<()> { let cli = Cli::parse(); - + // Set up logging - user can control with RUST_LOG environment variable env_logger::try_init().ok(); - + // Handle generation mode if let Some(text) = &cli.generate { return generate_wav_file(&cli, text); } - + // Validate we have an input file for decoding - let wav_file = cli.wav_file.as_ref() - .ok_or_else(|| anyhow::anyhow!("No input file specified. Use --help for usage information."))?; - + let wav_file = cli.wav_file.as_ref().ok_or_else(|| { + anyhow::anyhow!("No input file specified. Use --help for usage information.") + })?; + // Validate input file exists if !wav_file.exists() { bail!("File not found: {}", wav_file.display()); } - + let start_time = Instant::now(); - + if cli.verbose { println!("Processing: {}", wav_file.display()); } - + // Use the new high-level API - let decoded_text = ditdah::decode_wav_file(wav_file) - .map_err(|e| { - // Provide user-friendly error messages - match e.to_string().as_str() { - s if s.contains("No such file") => anyhow::anyhow!("File not found: {}", wav_file.display()), - s if s.contains("Unsupported sample format") => anyhow::anyhow!("Unsupported audio format. Please use 16-bit or 32-bit WAV files."), - s if s.contains("Could not find a dominant frequency") => anyhow::anyhow!("No Morse code signal detected. Check that the file contains clear Morse audio."), - _ => e + let decoded_text = ditdah::decode_wav_file(wav_file).map_err(|e| { + // Provide user-friendly error messages + match e.to_string().as_str() { + s if s.contains("No such file") => { + anyhow::anyhow!("File not found: {}", wav_file.display()) + } + s if s.contains("Unsupported sample format") => { + anyhow::anyhow!("Unsupported audio format. Please use 16-bit or 32-bit WAV files.") } - })?; - + s if s.contains("Could not find a dominant frequency") => anyhow::anyhow!( + "No Morse code signal detected. Check that the file contains clear Morse audio." + ), + _ => e, + } + })?; + let duration = start_time.elapsed(); - + // Output results if decoded_text.is_empty() { println!("No Morse code detected"); @@ -90,11 +115,11 @@ fn main() -> Result<()> { } } else { println!("Decoded: {}", decoded_text); - + if cli.time { println!("Processing time: {:.2?}", duration); } - + if cli.verbose { println!("Length: {} characters", decoded_text.len()); if decoded_text.len() > 50 { @@ -102,52 +127,90 @@ fn main() -> Result<()> { } } } - + Ok(()) } fn generate_wav_file(cli: &Cli, text: &str) -> Result<()> { use generator::MorseGenerator; - - let output_path = cli.output.as_ref() + + let output_path = cli + .output + .as_ref() .map(|p| p.clone()) .unwrap_or_else(|| PathBuf::from("output.wav")); - + if cli.verbose { - println!("Generating: '{}' at {} Hz, {} WPM", text, cli.frequency, cli.wpm); + println!( + "Generating: '{}' at {} Hz, {} WPM", + text, cli.frequency, cli.wpm + ); println!("Output: {}", output_path.display()); } - + let generator = MorseGenerator::new(12000, cli.frequency, cli.wpm); generator.generate_wav_file(text, &output_path)?; - + println!("Generated: {}", output_path.display()); - + if cli.verbose { - println!("Settings: {} Hz, {} WPM, 12kHz sample rate", cli.frequency, cli.wpm); - + println!( + "Settings: {} Hz, {} WPM, 12kHz sample rate", + cli.frequency, cli.wpm + ); + // Show what the Morse pattern looks like let morse_pattern = text_to_morse_pattern(text); if !morse_pattern.is_empty() { println!("Morse: {}", morse_pattern); } } - + Ok(()) } fn text_to_morse_pattern(text: &str) -> String { let morse_map = [ - ('A', ".-"), ('B', "-..."), ('C', "-.-."), ('D', "-.."), ('E', "."), - ('F', "..-."), ('G', "--."), ('H', "...."), ('I', ".."), ('J', ".---"), - ('K', "-.-"), ('L', ".-.."), ('M', "--"), ('N', "-."), ('O', "---"), - ('P', ".--."), ('Q', "--.-"), ('R', ".-."), ('S', "..."), ('T', "-"), - ('U', "..-"), ('V', "...-"), ('W', ".--"), ('X', "-..-"), ('Y', "-.--"), - ('Z', "--.."), ('1', ".----"), ('2', "..---"), ('3', "...--"), ('4', "....-"), - ('5', "....."), ('6', "-...."), ('7', "--..."), ('8', "---.."), ('9', "----."), + ('A', ".-"), + ('B', "-..."), + ('C', "-.-."), + ('D', "-.."), + ('E', "."), + ('F', "..-."), + ('G', "--."), + ('H', "...."), + ('I', ".."), + ('J', ".---"), + ('K', "-.-"), + ('L', ".-.."), + ('M', "--"), + ('N', "-."), + ('O', "---"), + ('P', ".--."), + ('Q', "--.-"), + ('R', ".-."), + ('S', "..."), + ('T', "-"), + ('U', "..-"), + ('V', "...-"), + ('W', ".--"), + ('X', "-..-"), + ('Y', "-.--"), + ('Z', "--.."), + ('1', ".----"), + ('2', "..---"), + ('3', "...--"), + ('4', "....-"), + ('5', "....."), + ('6', "-...."), + ('7', "--..."), + ('8', "---.."), + ('9', "----."), ('0', "-----"), - ].into_iter().collect::<std::collections::HashMap<_, _>>(); - + ] + .into_iter() + .collect::<std::collections::HashMap<_, _>>(); + text.to_uppercase() .chars() .filter_map(|c| { |
