lasprs 0.14.2

Library for Acoustic Signal Processing (Rust edition, with optional Python bindings via pyo3)
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
//! WAV file import: convert .wav files into LASP measurements.
use super::wav_common::*;
use super::{Result, *};
use crate::{daq::RawStreamData, tools::get_modified_timestamp};
use snafu::prelude::*;

impl Measurement {
    #[expect(clippy::doc_overindented_list_items)]
    /// Create a new measurement from a WAV file.
    ///
    /// Reads the WAV file using `hound`, writes the audio data and metadata
    /// into a new HDF5 measurement file, and returns a `SharedMeasurement`.
    /// Audio samples are stored in their native WAV format (e.g. `i16` for
    /// 16-bit, `i32` for 24-bit, `f32` for 32-bit float) to avoid
    /// unnecessary precision loss.
    ///
    /// # Arguments
    ///
    /// * `wav_path`        - Path to the input `.wav` file.
    /// * `output_path`     - Optional path (including filename, without
    ///                        extension) for the resulting `.h5` file. When
    ///                        `None`, the output file is placed next to the
    ///                        WAV file with the same stem.
    /// * `channel_names`   - Optional channel names. Must match the number of
    ///                        channels in the WAV file when provided.
    /// * `sensitivities`   - Optional per-channel sensitivities. Defaults to
    ///                        `1.0` for every channel.
    /// * `quantities`      - Optional per-channel physical quantities. Defaults
    ///                        to `Qty::Number`.
    /// * `comment`         - Optional measurement comment.
    /// * `measurement_type`- Optional `MeasurementType`. Defaults to
    ///                        `MeasurementType::NotSpecific`.
    pub fn from_wav<P: AsRef<Path>>(
        wav_path: P,
        output_path: Option<&Path>,
        channel_names: Option<&[&str]>,
        sensitivities: Option<&[Flt]>,
        quantities: Option<&[Qty]>,
        comment: Option<&str>,
        measurement_type: Option<MeasurementType>,
    ) -> Result<SharedMeasurement> {
        use hound::WavReader;

        let wav_path = wav_path.as_ref();
        ensure!(wav_path.is_file(), FileNotFoundSnafu { filepath: wav_path });
        let timestamp = get_modified_timestamp(wav_path).map_err(|e| {
            FileSnafu {
                filepath: wav_path,
                error: e.to_string(),
            }
            .build()
        })?;
        let reader = WavReader::open(wav_path).map_err(|e| MeasurementError::DataCorrupted {
            possible_error: format!("Failed to open WAV file: {e}"),
        })?;

        let spec = reader.spec();
        let nchannels = spec.channels as usize;
        ensure!(
            nchannels > 0,
            DataCorruptedSnafu {
                possible_error: "No channels found in WAV file",
            }
        );
        ensure!(
            spec.sample_rate > 0,
            DataCorruptedSnafu {
                possible_error: format!("Invalid sample rate: {}", spec.sample_rate),
            }
        );
        let sample_rate = (spec.sample_rate as Flt).try_into().unwrap();
        let dataType = wav_data_type(&spec)?;

        // Determine output file path
        let h5_filepath = if let Some(p) = output_path {
            let mut p = p.to_path_buf();
            p.set_extension(MEASUREMENT_EXTENSION);
            p
        } else {
            let mut p = wav_path.to_path_buf();
            p.set_extension(MEASUREMENT_EXTENSION);
            p
        };
        let h5_filepath =
            std::path::absolute(&h5_filepath).map_err(|_| MeasurementError::DataCorrupted {
                possible_error: "Could not resolve output path".into(),
            })?;
        let writer = MeasurementWriter::new(&h5_filepath)?;
        let measurement_name = measurementName(&h5_filepath)?;

        // Compute total frames so we can determine blocksize / nblocks.
        let bits = spec.bits_per_sample;
        let total_samples = reader.len() as usize;
        let total_frames = total_samples / nchannels;
        ensure!(
            total_frames > 0,
            DataCorruptedSnafu {
                possible_error: "WAV file contains no audio frames"
            }
        );

        // Read samples in their native format and write the audio dataset,
        // keeping the original sample type to avoid unnecessary conversion.
        let channels = DaqChannel::fromMultipleSeparateSlices(
            nchannels,
            channel_names,
            quantities,
            sensitivities,
            measurement_name,
        )?;
        let meta = MeasurementMetadata::new(
            measurement_name,
            sample_rate,
            None,
            dataType,
            channels,
            comment,
            Some(timestamp),
            measurement_type,
            None,
            None,
            false,
        );
        let mut writer = writer.write_meta(meta)?;

        let data = read_wav_samples!(reader, spec.sample_format, bits);
        writer.write(&data)?;

        writer.finish(false)
    }

    #[allow(clippy::doc_overindented_list_items)]
    /// Create a new measurement by merging multiple WAV files into a single
    /// multi-channel measurement.
    ///
    /// Each WAV file contributes one or more channels. All files must have the
    /// same sample rate and sample format (bit depth + int/float). By default
    /// all files must also have the same number of frames; pass a
    /// [`FrameMismatchPolicy`] to handle files with different lengths instead.
    /// Channel names default to the file stem for mono files, or
    /// `<stem>_ch0`, `<stem>_ch1`, … for multi-channel files.
    ///
    /// # Arguments
    ///
    /// * `wav_paths`       - Slice of paths to the input `.wav` files. Must
    ///                        contain at least one path.
    /// * `output_path`     - Path (including filename, without extension) for
    ///                        the resulting `.h5` file.
    /// * `channel_names`   - Optional channel names. When provided, the length
    ///                        must equal the **total** number of channels across
    ///                        all WAV files.
    /// * `sensitivities`   - Optional per-channel sensitivities (same length
    ///                        rule). Defaults to `1.0`.
    /// * `quantities`      - Optional per-channel physical quantities. Defaults
    ///                        to `Qty::Number`.
    /// * `comment`         - Optional measurement comment.
    /// * `measurement_type`- Optional `MeasurementType`. Defaults to
    ///                        `MeasurementType::NotSpecific`.
    /// * `frame_mismatch_policy` - How to handle WAV files with different frame
    ///                        counts. When `None` (the default), a mismatch is
    ///                        an error. Otherwise:
    ///   - [`FrameMismatchPolicy::AppendZeros`] — shorter files are zero-padded
    ///     at the **end** (data left-aligned, beginnings time-aligned).
    ///   - [`FrameMismatchPolicy::PrependZeros`] — shorter files are
    ///     zero-padded at the **beginning** (data right-aligned, endings
    ///     time-aligned).
    ///
    // TODO: Work to builder pattern
    #[expect(clippy::too_many_arguments)]
    pub fn from_wav_files(
        wav_paths: &[&Path],
        output_path: &Path,
        channel_names: Option<&[&str]>,
        sensitivities: Option<&[Flt]>,
        quantities: Option<&[Qty]>,
        comment: Option<&str>,
        measurement_type: Option<MeasurementType>,
        frame_mismatch_policy: Option<FrameMismatchPolicy>,
    ) -> Result<SharedMeasurement> {
        use hound::WavReader;

        ensure!(
            !wav_paths.is_empty(),
            WAVImportSnafu {
                msg: "No WAV files provided"
            }
        );

        // Sort paths alphabetically so channel order is deterministic.
        let mut sorted_paths = wav_paths.to_vec();
        sorted_paths.sort();

        // --- Phase 1: open all files, validate compatibility ---

        // Open the first file to establish the reference format.
        let first_path = sorted_paths[0];
        ensure!(
            first_path.is_file(),
            FileNotFoundSnafu {
                filepath: first_path
            }
        );
        let first_reader =
            WavReader::open(first_path).map_err(|e| MeasurementError::DataCorrupted {
                possible_error: format!("Failed to open WAV file '{}': {e}", first_path.display()),
            })?;
        let ref_spec = first_reader.spec();

        ensure!(
            ref_spec.sample_rate > 0,
            DataCorruptedSnafu {
                possible_error: format!("Invalid sample rate: {}", ref_spec.sample_rate)
            }
        );

        let ref_total_samples = first_reader.len() as usize;
        let ref_channels = ref_spec.channels as usize;
        ensure!(
            ref_channels > 0,
            WAVImportSnafu {
                msg: format!("No channels found in WAV file '{}'", first_path.display())
            }
        );
        let ref_total_frames = ref_total_samples / ref_channels;
        ensure!(
            ref_total_frames > 0,
            WAVImportSnafu {
                msg: "WAV files contain no audio frames"
            }
        );

        // Collect readers and per-file channel counts.
        let mut readers: Vec<WavReader<std::io::BufReader<std::fs::File>>> =
            Vec::with_capacity(wav_paths.len());
        let mut channels_per_file: Vec<usize> = Vec::with_capacity(wav_paths.len());
        let mut frames_per_file: Vec<usize> = Vec::with_capacity(wav_paths.len());
        readers.push(first_reader);
        channels_per_file.push(ref_channels);
        frames_per_file.push(ref_total_frames);

        // Build vector of readers and per-file channel counts.
        for &path in &sorted_paths[1..] {
            ensure!(path.is_file(), FileNotFoundSnafu { filepath: path });
            let reader = WavReader::open(path).map_err(|e| {
                WAVImportSnafu {
                    msg: format!("Failed to open WAV file '{}': {e}", path.display()),
                }
                .build()
            })?;
            let spec = reader.spec();
            let file_channels = spec.channels as usize;
            let file_total_frames = reader.len() as usize / file_channels;

            ensure!(
                spec.sample_rate == ref_spec.sample_rate,
                WAVImportSnafu {
                    msg: format!(
                        "Sample rate mismatch: '{}' has {} Hz, but '{}' has {} Hz",
                        first_path.display(),
                        ref_spec.sample_rate,
                        path.display(),
                        spec.sample_rate
                    )
                }
            );
            ensure!(
                spec.sample_format == ref_spec.sample_format
                    && spec.bits_per_sample == ref_spec.bits_per_sample,
                DataCorruptedSnafu {
                    possible_error: format!(
                        "Sample format mismatch: '{}' is {:?}/{}-bit, but '{}' is {:?}/{}-bit",
                        first_path.display(),
                        ref_spec.sample_format,
                        ref_spec.bits_per_sample,
                        path.display(),
                        spec.sample_format,
                        spec.bits_per_sample
                    )
                }
            );
            ensure!(
                file_total_frames == ref_total_frames || frame_mismatch_policy.is_some(),
                WAVImportSnafu {
                    msg: format!(
                        "Frame count mismatch: '{}' has {} frames, but '{}' has {} frames. \
                         Pass a `FrameMismatchPolicy` to handle files with different amount of frames.",
                        first_path.display(),
                        ref_total_frames,
                        path.display(),
                        file_total_frames
                    ),
                }
            );

            channels_per_file.push(file_channels);
            frames_per_file.push(file_total_frames);
            readers.push(reader);
        }

        let total_channels: usize = channels_per_file.iter().sum();

        // --- Phase 2: derive channel names from file stems ---
        let default_names: Vec<String> = sorted_paths
            .iter()
            .zip(channels_per_file.iter())
            .flat_map(|(path, &nch)| {
                let stem = path
                    .file_stem()
                    .and_then(|s| s.to_str())
                    .unwrap_or("unknown");
                if nch == 1 {
                    vec![stem.to_string()]
                } else {
                    (0..nch).map(|i| format!("{stem}_ch{i}")).collect()
                }
            })
            .collect();

        // --- Phase 3: determine data type ---
        let sample_rate: StrictlyPositive = (ref_spec.sample_rate as Flt).try_into().unwrap();
        let bits = ref_spec.bits_per_sample;
        let dataType = wav_data_type(&ref_spec)?;

        // --- Phase 4: output path ---
        let h5_filepath = {
            let mut p = output_path.to_path_buf();
            p.set_extension(MEASUREMENT_EXTENSION);
            p
        };
        let h5_filepath = std::path::absolute(&h5_filepath).map_err(|e| {
            MeasurementError::InvalidMeasurementName {
                name: h5_filepath.to_string_lossy().into(),
                reason: format! {"{e}"},
            }
        })?;
        let measurement_name = measurementName(&h5_filepath)?;

        // Use the oldest modification time among all input files.
        let timestamp = sorted_paths
            .iter()
            .map(|p| {
                get_modified_timestamp(p).map_err(|e| {
                    FileSnafu {
                        filepath: *p,
                        error: e.to_string(),
                    }
                    .build()
                })
            })
            .collect::<Result<Vec<Flt>>>()?
            .into_iter()
            .fold(Flt::INFINITY, Flt::min);

        // --- Phase 5: read all samples and interleave ---
        //
        // Helper that reads samples from every reader into a single interleaved
        // Vec<T>, where the channel order is: all channels of file 0, then all
        // channels of file 1, etc.  The `policy` determines where each file's
        // data is placed within the output buffer for that channel:
        //
        // - `AppendZeros`:  data starts at frame 0      (zeros at the end)
        // - `PrependZeros`: data ends at the last frame  (zeros at the start)
        fn read_and_interleave<T>(
            readers: Vec<hound::WavReader<std::io::BufReader<std::fs::File>>>,
            channels_per_file: &[usize],
            frames_per_file: &[usize],
            total_channels: usize,
            total_frames: usize,
            policy: FrameMismatchPolicy,
        ) -> Result<Vec<T>>
        where
            T: hound::Sample + Clone + Default,
        {
            let wav_err = |e: hound::Error| MeasurementError::DataCorrupted {
                possible_error: format!("Error reading WAV sample: {e}"),
            };

            // Read each file into its own flat (interleaved) sample vector.
            let per_file: Vec<Vec<T>> = readers
                .into_iter()
                .map(|r| {
                    r.into_samples::<T>()
                        .map(|s| s.map_err(wav_err))
                        .collect::<Result<Vec<T>>>()
                })
                .collect::<Result<Vec<_>>>()?;

            // Merge into one interleaved buffer: for each frame, emit channels
            // from file 0, then file 1, etc.  The buffer is zero-initialised,
            // so any frames not written to remain silent.
            let mut merged: Vec<T> = vec![T::default(); total_frames * total_channels];
            let mut ch_offset = 0usize;
            for ((file_samples, &file_nch), &file_frames) in per_file
                .iter()
                .zip(channels_per_file.iter())
                .zip(frames_per_file.iter())
            {
                let frames_to_copy = file_frames.min(total_frames);

                // Where does this file's data start in the output?
                let dst_offset = match policy {
                    FrameMismatchPolicy::AppendZeros => 0,
                    FrameMismatchPolicy::PrependZeros => total_frames - frames_to_copy,
                };

                for frame in 0..frames_to_copy {
                    for ch in 0..file_nch {
                        merged[(dst_offset + frame) * total_channels + ch_offset + ch] =
                            file_samples[frame * file_nch + ch].clone();
                    }
                }
                ch_offset += file_nch;
            }
            Ok(merged)
        }

        let total_frames = *frames_per_file.iter().max().unwrap();
        // If all files have the same length the policy is irrelevant; default
        // to AppendZeros so the interleave helper always has a value.
        let policy = frame_mismatch_policy.unwrap_or(FrameMismatchPolicy::AppendZeros);

        let writer = MeasurementWriter::new(&h5_filepath)?;

        // Build channel names: use caller-supplied or the defaults derived
        // from file stems.
        let names_for_daq: Option<Vec<&str>> = if channel_names.is_some() {
            channel_names.map(|n| n.to_vec())
        } else {
            Some(default_names.iter().map(|s| s.as_str()).collect())
        };

        let channels = DaqChannel::fromMultipleSeparateSlices(
            total_channels,
            names_for_daq.as_deref(),
            quantities,
            sensitivities,
            measurement_name,
        )?;
        let meta = MeasurementMetadata::new(
            measurement_name,
            sample_rate,
            None,
            dataType,
            channels,
            comment,
            Some(timestamp),
            measurement_type,
            None,
            None,
            false,
        );
        let mut writer = writer.write_meta(meta)?;

        // Read, interleave, and write based on sample format.
        let data = read_and_interleave_wav_samples!(
            readers,
            &channels_per_file,
            &frames_per_file,
            total_channels,
            total_frames,
            policy,
            ref_spec.sample_format,
            bits
        );
        writer.write(&data)?;

        // Open the freshly created file as a Measurement
        writer.finish(false)
    }
}