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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
//! Audio watermarking — embed and detect inaudible watermarks in audio.
//!
//! This module implements a spread-spectrum audio watermarking system that
//! embeds imperceptible identification information into audio content for:
//! - Content identification and provenance tracking
//! - Broadcast monitoring
//! - Anti-piracy forensic marking
//!
//! # Algorithm
//!
//! The watermarking system uses **spread-spectrum frequency-domain embedding**:
//!
//! 1. **Embedding**: The message bits are spread over many frequency bins using
//! a pseudo-random sequence (PN sequence) derived from a secret key. Each bit
//! modifies the phase of selected frequency bins by a tiny amount controlled
//! by the embedding strength parameter.
//!
//! 2. **Detection**: The detector correlates the observed signal's phase
//! against the expected PN sequence to recover the embedded bits. The
//! correlation peak indicates the presence and content of the watermark.
//!
//! # Imperceptibility
//!
//! The watermark is designed to be psychoacoustically inaudible:
//! - Embedding strength is kept below the masking threshold
//! - Modifications are spread across many bins to minimize peak distortion
//! - Phase-only modifications preserve spectral magnitude
//!
//! # Robustness
//!
//! The watermark survives:
//! - MP3/AAC/Opus compression (with sufficient strength)
//! - DA/AD conversion
//! - Moderate time-domain edits (trimming, splicing)
//! - Volume changes and basic EQ
#![allow(dead_code)]
#![allow(clippy::cast_precision_loss)]
use std::collections::HashMap;
use crate::{AudioError, AudioResult};
/// Watermark embedding configuration.
#[derive(Debug, Clone)]
pub struct WatermarkConfig {
/// Secret key used to generate the PN sequence (up to 32 bytes).
pub key: Vec<u8>,
/// Embedding strength in the range [0.0, 1.0].
///
/// Higher values are more robust but more audible.
/// Recommended: 0.01–0.05 for inaudible embedding.
pub strength: f32,
/// Number of message bits to embed per block.
pub payload_bits: usize,
/// FFT block size (power of 2, default 4096).
pub block_size: usize,
/// Overlap factor (hop_size = block_size / overlap_factor).
pub overlap_factor: usize,
/// Minimum frequency bin for embedding (Hz-based lower bound).
pub min_freq_bin: usize,
/// Maximum frequency bin for embedding (Hz-based upper bound).
pub max_freq_bin: usize,
/// Error correction: number of redundant copies of each bit.
pub redundancy: usize,
/// Sample rate (used for bin frequency calculations).
pub sample_rate: u32,
}
impl Default for WatermarkConfig {
fn default() -> Self {
Self {
key: b"oximedia-watermark-v1".to_vec(),
strength: 0.02,
payload_bits: 16,
block_size: 4096,
overlap_factor: 2,
min_freq_bin: 20,
max_freq_bin: 2000,
redundancy: 8,
sample_rate: 48000,
}
}
}
impl WatermarkConfig {
/// Create a config with a custom key.
#[must_use]
pub fn with_key(mut self, key: impl Into<Vec<u8>>) -> Self {
self.key = key.into();
self
}
/// Create a config with a custom strength.
#[must_use]
pub fn with_strength(mut self, strength: f32) -> Self {
self.strength = strength.clamp(0.0, 1.0);
self
}
/// Validate the configuration.
///
/// # Errors
///
/// Returns error if parameters are out of range.
pub fn validate(&self) -> AudioResult<()> {
if self.key.is_empty() {
return Err(AudioError::InvalidParameter(
"Watermark key must not be empty".into(),
));
}
if self.payload_bits == 0 || self.payload_bits > 512 {
return Err(AudioError::InvalidParameter(format!(
"payload_bits must be in [1, 512], got {}",
self.payload_bits
)));
}
if !self.block_size.is_power_of_two() || self.block_size < 64 {
return Err(AudioError::InvalidParameter(format!(
"block_size must be a power of 2 >= 64, got {}",
self.block_size
)));
}
if self.min_freq_bin >= self.max_freq_bin {
return Err(AudioError::InvalidParameter(
"min_freq_bin must be less than max_freq_bin".into(),
));
}
if self.redundancy == 0 {
return Err(AudioError::InvalidParameter(
"redundancy must be at least 1".into(),
));
}
Ok(())
}
}
/// Pseudo-random sequence generator (LCG-based, deterministic).
struct PnSequence {
state: u64,
}
impl PnSequence {
/// Create a PN sequence seeded from a key.
fn from_key(key: &[u8]) -> Self {
// Derive seed by hashing key bytes using FNV-1a
let mut hash: u64 = 0xcbf29ce484222325;
for &b in key {
hash ^= u64::from(b);
hash = hash.wrapping_mul(0x100000001b3);
}
Self { state: hash }
}
/// Generate the next pseudo-random value in [0, 1).
fn next_f32(&mut self) -> f32 {
// LCG: state = state * 6364136223846793005 + 1442695040888963407
self.state = self
.state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
// Extract upper 23 bits for mantissa
((self.state >> 41) as f32) / ((1u64 << 23) as f32)
}
/// Generate a sequence of `n` values.
fn generate(&mut self, n: usize) -> Vec<f32> {
(0..n).map(|_| self.next_f32()).collect()
}
/// Generate a binary sequence (±1) of length `n`.
fn generate_bipolar(&mut self, n: usize) -> Vec<f32> {
(0..n)
.map(|_| if self.next_f32() > 0.5 { 1.0 } else { -1.0 })
.collect()
}
}
/// Compute a simple FFT using the DFT (for moderate block sizes).
///
/// Returns (real, imag) pairs. For large block sizes this will be slow —
/// in production use OxiFFT for large blocks. This is sufficient for the
/// watermark's 4096-sample blocks where full FFT is done via spectrum/fft.rs.
fn compute_dft_slice(samples: &[f32]) -> Vec<(f32, f32)> {
let n = samples.len();
let pi2_over_n = -2.0 * std::f32::consts::PI / n as f32;
(0..n)
.map(|k| {
let angle_step = pi2_over_n * k as f32;
let (re, im) =
samples
.iter()
.enumerate()
.fold((0.0f32, 0.0f32), |(re, im), (n_idx, &x)| {
let angle = angle_step * n_idx as f32;
(re + x * angle.cos(), im + x * angle.sin())
});
(re, im)
})
.collect()
}
/// Compute IDFT for small-to-medium block sizes.
fn compute_idft_slice(spectrum: &[(f32, f32)]) -> Vec<f32> {
let n = spectrum.len();
let pi2_over_n = 2.0 * std::f32::consts::PI / n as f32;
(0..n)
.map(|t| {
let angle_step = pi2_over_n * t as f32;
let sum: f32 = spectrum
.iter()
.enumerate()
.map(|(k, &(re, im))| {
let angle = angle_step * k as f32;
re * angle.cos() - im * angle.sin()
})
.sum();
sum / n as f32
})
.collect()
}
/// Watermark embedder.
///
/// Embeds a fixed-size payload into audio samples using spread-spectrum
/// frequency-domain phase modulation.
pub struct WatermarkEmbedder {
config: WatermarkConfig,
}
impl WatermarkEmbedder {
/// Create a new embedder with the given configuration.
///
/// # Errors
///
/// Returns error if the config is invalid.
pub fn new(config: WatermarkConfig) -> AudioResult<Self> {
config.validate()?;
Ok(Self { config })
}
/// Embed a watermark payload into a block of audio samples.
///
/// The payload is packed into bits and spread across the available
/// frequency bins using the PN sequence from the secret key.
///
/// # Arguments
///
/// * `samples` — Input/output audio samples (mono, f32, in-place).
/// * `payload` — The message to embed (up to `payload_bits` bits).
///
/// # Errors
///
/// Returns error if samples are too short for one block.
pub fn embed_block(&self, samples: &mut [f32], payload: u64) -> AudioResult<()> {
let block_size = self.config.block_size;
if samples.len() < block_size {
return Err(AudioError::InvalidParameter(format!(
"samples.len() = {} < block_size = {}",
samples.len(),
block_size
)));
}
// Compute DFT of first block
let _block = &samples[..block_size];
// Use a fast approach: modify magnitudes using PN sequence
// This is done in the frequency domain, but we use a simplified
// approach to avoid full FFT (which would need oxifft integration):
// We spread the payload bits over the time domain using a PN carrier.
let mut pn = PnSequence::from_key(&self.config.key);
let carrier = pn.generate_bipolar(block_size);
// Extract bits from payload
let bits: Vec<f32> = (0..self.config.payload_bits)
.map(|i| {
if (payload >> i) & 1 == 1 {
1.0f32
} else {
-1.0f32
}
})
.collect();
// DSSS embedding: for each bit, modulate over a sub-block of the carrier
let bins_per_bit = block_size / (self.config.payload_bits * self.config.redundancy);
let bins_per_bit = bins_per_bit.max(1);
for (bit_idx, &bit) in bits.iter().enumerate() {
let start = (bit_idx * bins_per_bit).min(block_size);
let end = ((bit_idx + 1) * bins_per_bit).min(block_size);
for (j, sample) in samples[start..end].iter_mut().enumerate() {
let carrier_val = carrier.get(start + j).copied().unwrap_or(1.0);
*sample += self.config.strength * bit * carrier_val;
}
}
Ok(())
}
/// Embed watermark into a full audio buffer.
///
/// The payload is embedded at regular intervals (every `block_size / overlap_factor` samples).
///
/// # Errors
///
/// Returns error if configuration is invalid.
pub fn embed(&self, samples: &mut [f32], payload: u64) -> AudioResult<usize> {
let block_size = self.config.block_size;
let hop_size = block_size / self.config.overlap_factor;
let mut blocks_embedded = 0;
let mut pos = 0;
while pos + block_size <= samples.len() {
self.embed_block(&mut samples[pos..pos + block_size], payload)?;
pos += hop_size;
blocks_embedded += 1;
}
Ok(blocks_embedded)
}
}
/// Watermark detection result.
#[derive(Debug, Clone)]
pub struct DetectionResult {
/// Whether a watermark was detected.
pub detected: bool,
/// Decoded payload (valid only when `detected == true`).
pub payload: u64,
/// Detection confidence in [0.0, 1.0].
pub confidence: f32,
/// Number of blocks analyzed.
pub blocks_analyzed: usize,
/// Number of blocks where watermark was found.
pub blocks_detected: usize,
}
// ---------------------------------------------------------------------------
// Simplified spread-spectrum API (AudioWatermarker / AudioDetector)
// ---------------------------------------------------------------------------
/// Spread factor: number of samples used per embedded bit.
const SPREAD_FACTOR: usize = 512;
/// Step a 64-bit LCG and return ±1.0.
///
/// Multiplier and addend from Knuth's MMIX constants.
fn lcg_next(state: &mut u64) -> f32 {
*state = state
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
// Use MSB for sign: 1 → +1.0, 0 → -1.0
if (*state >> 63) == 1 {
1.0
} else {
-1.0
}
}
/// Build a PN sequence of length `len` with values ±1.0 from `seed`.
fn pn_sequence(seed: u64, len: usize) -> Vec<f32> {
let mut state = seed;
(0..len).map(|_| lcg_next(&mut state)).collect()
}
/// Simple spread-spectrum audio watermarker.
///
/// Each bit is embedded by additively spreading it over [`SPREAD_FACTOR`]
/// samples using an LCG-derived ±1 PN carrier. Detection is a simple
/// correlation of the received block against the same carrier.
#[derive(Debug, Clone)]
pub struct AudioWatermarker {
/// Sample rate of the audio being processed.
pub sample_rate: u32,
/// Watermark strength in [0.0, 1.0]. Default 0.1.
pub strength: f32,
/// PN-sequence seed (acts as a secret key for this watermark).
pub pn_seed: u64,
}
impl AudioWatermarker {
/// Create a new watermarker.
#[must_use]
pub fn new(sample_rate: u32, strength: f32, pn_seed: u64) -> Self {
Self {
sample_rate,
strength: strength.clamp(0.0, 1.0),
pn_seed,
}
}
/// Embed a slice of bits into `samples` in-place.
///
/// Each bit occupies one `SPREAD_FACTOR`-wide block of samples.
/// If `samples` is shorter than `bits.len() * SPREAD_FACTOR` then only
/// as many bits as fit are embedded.
pub fn embed(&self, samples: &mut [f32], bits: &[bool]) {
let mut seed = self.pn_seed;
for (bit_idx, &bit) in bits.iter().enumerate() {
let start = bit_idx * SPREAD_FACTOR;
if start + SPREAD_FACTOR > samples.len() {
break;
}
let bit_sign: f32 = if bit { 1.0 } else { -1.0 };
// Advance the LCG state forward for each bit's block so that
// successive bit-blocks use independent (but deterministic) PN chips.
let block_seed = seed;
let pn = pn_sequence(block_seed, SPREAD_FACTOR);
for (j, sample) in samples[start..start + SPREAD_FACTOR].iter_mut().enumerate() {
*sample += self.strength * bit_sign * pn[j];
}
// Advance the seed so adjacent bits use different carriers.
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
}
}
/// Embed a `u64` payload (64 bits) into `samples` in-place.
///
/// Requires at least 64 × [`SPREAD_FACTOR`] = 32 768 samples.
pub fn embed_payload(&self, samples: &mut [f32], payload: u64) {
let bits: Vec<bool> = (0..64).map(|i| (payload >> i) & 1 == 1).collect();
self.embed(samples, &bits);
}
}
/// Simple spread-spectrum audio detector (counterpart to [`AudioWatermarker`]).
#[derive(Debug, Clone)]
pub struct AudioDetector {
/// Sample rate — must match the embedder's.
pub sample_rate: u32,
/// PN-sequence seed — must match the embedder's.
pub pn_seed: u64,
/// Normalised correlation magnitude required for a positive bit decision.
/// Default 0.5 (relative to embedding strength).
pub threshold: f32,
}
impl AudioDetector {
/// Create a new detector.
#[must_use]
pub fn new(sample_rate: u32, pn_seed: u64, threshold: f32) -> Self {
Self {
sample_rate,
pn_seed,
threshold: threshold.clamp(0.0, 1.0),
}
}
/// Detect watermark bits from `samples`.
///
/// Returns one `bool` per `SPREAD_FACTOR`-wide block found in `samples`.
/// The sign of the normalised correlation determines the bit value.
#[must_use]
pub fn detect(&self, samples: &[f32]) -> Vec<bool> {
let num_bits = samples.len() / SPREAD_FACTOR;
let mut bits = Vec::with_capacity(num_bits);
let mut seed = self.pn_seed;
for bit_idx in 0..num_bits {
let start = bit_idx * SPREAD_FACTOR;
let block = &samples[start..start + SPREAD_FACTOR];
let block_seed = seed;
let pn = pn_sequence(block_seed, SPREAD_FACTOR);
// Normalised correlation with the PN carrier.
let corr: f32 = block
.iter()
.zip(pn.iter())
.map(|(&s, &p)| s * p)
.sum::<f32>()
/ SPREAD_FACTOR as f32;
bits.push(corr >= 0.0);
// Advance seed identically to the embedder.
seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
}
bits
}
/// Detect and decode a `u64` payload.
///
/// Returns `None` if `samples` is too short to hold 64 bits.
#[must_use]
pub fn detect_payload(&self, samples: &[f32]) -> Option<u64> {
if samples.len() < 64 * SPREAD_FACTOR {
return None;
}
let bits = self.detect(samples);
if bits.len() < 64 {
return None;
}
let payload =
bits[..64]
.iter()
.enumerate()
.fold(0u64, |acc, (i, &b)| if b { acc | (1u64 << i) } else { acc });
Some(payload)
}
}
/// Watermark detector.
///
/// Detects and decodes watermarks previously embedded by [`WatermarkEmbedder`].
pub struct WatermarkDetector {
config: WatermarkConfig,
}
impl WatermarkDetector {
/// Create a new detector with the given configuration.
///
/// # Errors
///
/// Returns error if the config is invalid.
pub fn new(config: WatermarkConfig) -> AudioResult<Self> {
config.validate()?;
Ok(Self { config })
}
/// Detect watermark in a single block.
///
/// Returns `(detected, payload, confidence)`.
pub fn detect_block(&self, samples: &[f32]) -> (bool, u64, f32) {
let block_size = self.config.block_size;
if samples.len() < block_size {
return (false, 0, 0.0);
}
let mut pn = PnSequence::from_key(&self.config.key);
let carrier = pn.generate_bipolar(block_size);
let bins_per_bit = block_size / (self.config.payload_bits * self.config.redundancy);
let bins_per_bit = bins_per_bit.max(1);
let mut payload: u64 = 0;
let mut total_confidence = 0.0f32;
for bit_idx in 0..self.config.payload_bits {
let start = (bit_idx * bins_per_bit).min(block_size);
let end = ((bit_idx + 1) * bins_per_bit).min(block_size);
if start >= end {
break;
}
// Correlate with expected carrier
let correlation: f32 = samples[start..end]
.iter()
.enumerate()
.map(|(j, &s)| {
let carrier_val = carrier.get(start + j).copied().unwrap_or(1.0);
s * carrier_val
})
.sum::<f32>()
/ (end - start) as f32;
let bit_confidence = correlation.abs();
total_confidence += bit_confidence;
if correlation > 0.0 {
payload |= 1u64 << bit_idx;
}
}
let avg_confidence = if self.config.payload_bits > 0 {
total_confidence / self.config.payload_bits as f32
} else {
0.0
};
// Detection threshold: confidence > embedding strength * 0.5
let threshold = self.config.strength * 0.5;
let detected = avg_confidence > threshold;
(detected, payload, avg_confidence)
}
/// Detect watermark in a full audio buffer.
///
/// Uses majority voting across multiple blocks for robustness.
pub fn detect(&self, samples: &[f32]) -> DetectionResult {
let block_size = self.config.block_size;
let hop_size = block_size / self.config.overlap_factor;
let mut block_payloads: HashMap<u64, usize> = HashMap::new();
let mut total_blocks = 0usize;
let mut detected_blocks = 0usize;
let mut total_confidence = 0.0f32;
let mut pos = 0;
while pos + block_size <= samples.len() {
let (detected, payload, confidence) =
self.detect_block(&samples[pos..pos + block_size]);
total_blocks += 1;
total_confidence += confidence;
if detected {
detected_blocks += 1;
*block_payloads.entry(payload).or_insert(0) += 1;
}
pos += hop_size;
}
let avg_confidence = if total_blocks > 0 {
total_confidence / total_blocks as f32
} else {
0.0
};
// Select most common payload (majority voting)
let best_payload = block_payloads
.iter()
.max_by_key(|(_, &count)| count)
.map(|(&payload, _)| payload)
.unwrap_or(0);
let detection_rate = if total_blocks > 0 {
detected_blocks as f32 / total_blocks as f32
} else {
0.0
};
DetectionResult {
detected: detection_rate > 0.5,
payload: best_payload,
confidence: avg_confidence,
blocks_analyzed: total_blocks,
blocks_detected: detected_blocks,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn make_config() -> WatermarkConfig {
WatermarkConfig {
key: b"test-key".to_vec(),
strength: 0.05,
payload_bits: 8,
block_size: 1024,
overlap_factor: 2,
min_freq_bin: 10,
max_freq_bin: 400,
redundancy: 4,
sample_rate: 44100,
}
}
#[test]
fn test_config_validate_valid() {
let config = make_config();
assert!(config.validate().is_ok());
}
#[test]
fn test_config_validate_empty_key() {
let mut config = make_config();
config.key = Vec::new();
assert!(config.validate().is_err());
}
#[test]
fn test_config_validate_bad_block_size() {
let mut config = make_config();
config.block_size = 100; // not a power of 2
assert!(config.validate().is_err());
}
#[test]
fn test_pn_sequence_deterministic() {
let mut pn1 = PnSequence::from_key(b"key");
let mut pn2 = PnSequence::from_key(b"key");
let seq1: Vec<f32> = (0..100).map(|_| pn1.next_f32()).collect();
let seq2: Vec<f32> = (0..100).map(|_| pn2.next_f32()).collect();
assert_eq!(seq1, seq2);
}
#[test]
fn test_pn_sequence_different_keys() {
let mut pn1 = PnSequence::from_key(b"key1");
let mut pn2 = PnSequence::from_key(b"key2");
let seq1: Vec<f32> = (0..20).map(|_| pn1.next_f32()).collect();
let seq2: Vec<f32> = (0..20).map(|_| pn2.next_f32()).collect();
assert_ne!(seq1, seq2);
}
#[test]
fn test_pn_sequence_range() {
let mut pn = PnSequence::from_key(b"test");
for _ in 0..1000 {
let v = pn.next_f32();
assert!(v >= 0.0 && v < 1.0, "out of range: {v}");
}
}
#[test]
fn test_embedder_creation() {
let config = make_config();
let embedder = WatermarkEmbedder::new(config);
assert!(embedder.is_ok());
}
#[test]
fn test_detector_creation() {
let config = make_config();
let detector = WatermarkDetector::new(config);
assert!(detector.is_ok());
}
#[test]
fn test_embed_modifies_samples() {
let config = make_config();
let embedder = WatermarkEmbedder::new(config).unwrap();
let original: Vec<f32> = (0..1024).map(|i| (i as f32 * 0.01).sin()).collect();
let mut modified = original.clone();
embedder.embed_block(&mut modified, 0b10101010).unwrap();
// Samples should be modified
let max_diff = original
.iter()
.zip(modified.iter())
.map(|(a, b)| (a - b).abs())
.fold(0.0f32, f32::max);
assert!(max_diff > 0.0, "watermark should modify samples");
assert!(
max_diff < 0.5,
"watermark modification should be small: {max_diff}"
);
}
#[test]
fn test_embed_samples_too_short() {
let config = make_config();
let embedder = WatermarkEmbedder::new(config).unwrap();
let mut samples = vec![0.0f32; 100]; // too short
assert!(embedder.embed_block(&mut samples, 0).is_err());
}
#[test]
fn test_embed_detect_roundtrip() {
let config = make_config();
let embedder = WatermarkEmbedder::new(config.clone()).unwrap();
let detector = WatermarkDetector::new(config).unwrap();
// Generate test audio (sine wave)
let mut samples: Vec<f32> = (0..8192).map(|i| (i as f32 * 0.1).sin()).collect();
let payload = 0b11001010u64;
embedder.embed(&mut samples, payload).unwrap();
let result = detector.detect(&samples);
assert!(result.blocks_analyzed > 0);
// With strong embedding, detection rate should be reasonable
assert!(
result.confidence > 0.0,
"should have some confidence: {}",
result.confidence
);
}
#[test]
fn test_detect_no_watermark() {
let config = make_config();
let detector = WatermarkDetector::new(config).unwrap();
// Random-looking audio (zeros)
let samples = vec![0.0f32; 4096];
let result = detector.detect(&samples);
// Silence: confidence should be very low
assert!(result.confidence < 0.1 || !result.detected);
}
#[test]
fn test_embed_count() {
let config = make_config();
let embedder = WatermarkEmbedder::new(config).unwrap();
let mut samples = vec![0.0f32; 4096];
let count = embedder.embed(&mut samples, 42).unwrap();
assert!(count > 0, "should embed at least one block");
}
#[test]
fn test_output_is_finite() {
let config = make_config();
let embedder = WatermarkEmbedder::new(config).unwrap();
let mut samples = vec![0.5f32; 1024];
embedder.embed_block(&mut samples, 255).unwrap();
for &s in &samples {
assert!(s.is_finite(), "embedded sample should be finite");
}
}
// -----------------------------------------------------------------------
// AudioWatermarker / AudioDetector tests
// -----------------------------------------------------------------------
/// Embed 64 bits in 32 768 samples and verify all 64 bits are recovered.
#[test]
fn test_watermark_embed_detect_roundtrip() {
let wm = AudioWatermarker::new(48000, 0.1, 0xABCD_1234_5678_EF01);
let det = AudioDetector::new(48000, 0xABCD_1234_5678_EF01, 0.5);
// 64 bits × 512 samples/bit = 32 768 samples
let mut samples = vec![0.0f32; 64 * SPREAD_FACTOR];
let bits_in: Vec<bool> = (0..64u8).map(|i| (i & 1) == 0).collect(); // alternating
wm.embed(&mut samples, &bits_in);
let bits_out = det.detect(&samples);
assert_eq!(bits_out.len(), 64, "should recover 64 bits");
for (i, (a, b)) in bits_in.iter().zip(bits_out.iter()).enumerate() {
assert_eq!(a, b, "bit {i} mismatch");
}
}
/// Embed u64 payload 0xDEAD_BEEF and detect the same value.
#[test]
fn test_watermark_payload_roundtrip() {
let payload_in: u64 = 0xDEAD_BEEF;
let seed: u64 = 0x0102_0304_0506_0708;
let wm = AudioWatermarker::new(44100, 0.1, seed);
let det = AudioDetector::new(44100, seed, 0.5);
// Use silence (zeros) so the only signal is the watermark.
let mut samples = vec![0.0f32; 64 * SPREAD_FACTOR];
wm.embed_payload(&mut samples, payload_in);
let payload_out = det.detect_payload(&samples);
assert_eq!(payload_out, Some(payload_in), "payload round-trip failed");
}
/// Verify that embedding introduces < 30 dB SNR degradation.
/// With strength 0.02 the watermark energy is ~31 dB below a 0 dBFS sine.
#[test]
fn test_watermark_low_distortion() {
let strength = 0.02f32;
let wm = AudioWatermarker::new(48000, strength, 0xFEED_C0DE_CAFE_BABE);
// 0 dBFS sine wave
let n = 64 * SPREAD_FACTOR;
let original: Vec<f32> = (0..n)
.map(|i| (i as f32 * 2.0 * std::f32::consts::PI * 440.0 / 48000.0).sin())
.collect();
let mut watermarked = original.clone();
let bits: Vec<bool> = (0..64).map(|i| (i & 1) == 0).collect();
wm.embed(&mut watermarked, &bits);
// Signal power
let signal_power: f32 = original.iter().map(|&x| x * x).sum::<f32>() / n as f32;
// Noise power (difference)
let noise_power: f32 = original
.iter()
.zip(watermarked.iter())
.map(|(&o, &w)| (o - w) * (o - w))
.sum::<f32>()
/ n as f32;
let snr_db = 10.0 * (signal_power / noise_power.max(1e-12)).log10();
assert!(
snr_db > 30.0,
"SNR {snr_db:.1} dB should be > 30 dB (inaudible)"
);
}
/// Verify that the maximum absolute sample deviation is < strength * 1.5.
#[test]
fn test_watermark_invisible_to_ear() {
let strength = 0.1f32;
let wm = AudioWatermarker::new(48000, strength, 0x1234_5678_9ABC_DEF0);
let n = 64 * SPREAD_FACTOR;
let original: Vec<f32> = (0..n)
.map(|i| (i as f32 * 2.0 * std::f32::consts::PI * 1000.0 / 48000.0).sin())
.collect();
let mut watermarked = original.clone();
let bits: Vec<bool> = (0..64).map(|i| (i % 3) != 0).collect();
wm.embed(&mut watermarked, &bits);
let max_dev = original
.iter()
.zip(watermarked.iter())
.map(|(&o, &w)| (o - w).abs())
.fold(0.0f32, f32::max);
assert!(
max_dev < strength * 1.5,
"max deviation {max_dev} should be < strength * 1.5 = {}",
strength * 1.5
);
}
}