yodel 0.1.4

Bell 202 AFSK (1200/2200 Hz) software modem: no-std, allocation-free, streaming modulator
Documentation
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
//! WSPR TX tests: source encoding, channel coding, sync vector, and
//! audio synthesis.
//!
//! Provenance note: no full 162-symbol vector from an independent
//! published source is asserted here, because we could not certify one
//! from spec knowledge alone without risking a fabricated citation.
//! Instead this suite carries (a) invariant proofs (interleaver is a
//! permutation, encoder linearity/zero behaviour, symbol range and
//! count, sync-vector spot checks against the published table), (b) a
//! first-principles re-derivation of the whole pipeline inside the
//! test (independent code path, same spec), and (c) a frozen
//! regression snapshot of this implementation's output for
//! "K1ABC FN42 37" — labeled as generated by this implementation, so
//! it detects regressions, not spec errors. The RX slice will close the
//! loop against real off-air decoders.
#![cfg(feature = "wspr")]

use yodel::geo::GeoError;
use yodel::wspr::{
    DATA_BITS, POLY_A, POLY_B, SYMBOL_COUNT, SYNC_VECTOR, WsprConfig, WsprError, WsprMessage,
    WsprModulator, convolutional_encode, interleave,
};
use yodel::{MaidenheadGrid, SampleRate};

/// A locator from text, panicking on invalid input: these tests are
/// about the WSPR encoding, and locator parsing has its own suite in
/// `yodel::geo`.
fn grid(text: &str) -> MaidenheadGrid {
    MaidenheadGrid::new(text).expect("valid locator")
}

// ---- source encoding: callsign ----

/// The 28-bit callsign value, re-derived from the spec formula
/// independently of the library internals.
fn expected_callsign_value(aligned: &[u8; 6]) -> u32 {
    fn v(c: u8) -> u32 {
        match c {
            b'0'..=b'9' => u32::from(c - b'0'),
            b'A'..=b'Z' => u32::from(c - b'A') + 10,
            b' ' => 36,
            _ => panic!("bad char"),
        }
    }
    let mut n = v(aligned[0]);
    n = n * 36 + v(aligned[1]);
    n = n * 10 + v(aligned[2]);
    // Last three: A=0..Z=25, space=26.
    for &c in &aligned[3..] {
        n = n * 27 + if c == b' ' { 26 } else { u32::from(c - b'A') };
    }
    n
}

/// The 15-bit grid value plus power, per the spec formula.
fn expected_m(grid: &[u8; 4], power: u8) -> u32 {
    let lon_f = u32::from(grid[0] - b'A');
    let lat_f = u32::from(grid[1] - b'A');
    let lon_s = u32::from(grid[2] - b'0');
    let lat_s = u32::from(grid[3] - b'0');
    let g = (179 - 10 * lon_f - lon_s) * 180 + 10 * lat_f + lat_s;
    g * 128 + u32::from(power) + 64
}

/// Extracts bit `i` (0 = MSB of byte 0) from the packed bytes.
fn packed_bit(packed: &[u8; 11], i: usize) -> u32 {
    u32::from((packed[i / 8] >> (7 - i % 8)) & 1)
}

/// Reassembles the 28-bit callsign / 22-bit grid+power values from the
/// packed bytes.
fn unpack(packed: &[u8; 11]) -> (u32, u32) {
    let mut n = 0u32;
    for i in 0..28 {
        n = (n << 1) | packed_bit(packed, i);
    }
    let mut m = 0u32;
    for i in 28..50 {
        m = (m << 1) | packed_bit(packed, i);
    }
    (n, m)
}

#[test]
fn callsign_alignment_and_packing() {
    // Digit in second position: shifted right behind a space.
    let msg = WsprMessage::new("K1ABC", grid("FN42"), 37).unwrap();
    assert_eq!(msg.callsign(), b" K1ABC");
    let (n, m) = unpack(&msg.pack());
    assert_eq!(n, expected_callsign_value(b" K1ABC"));
    assert_eq!(m, expected_m(b"FN42", 37));

    // Digit already third: unchanged.
    let msg = WsprMessage::new("KA1ABC", grid("FN42"), 37).unwrap();
    assert_eq!(msg.callsign(), b"KA1ABC");

    // Lower case is normalized (the locator by `MaidenheadGrid`).
    let msg = WsprMessage::new("g4xyz", grid("io90"), 30).unwrap();
    assert_eq!(msg.callsign(), b" G4XYZ");
    assert_eq!(msg.grid().as_str(), "IO90");
}

#[test]
fn short_callsigns_pack() {
    // 4-char call with digit second: " K1AB ".
    let msg = WsprMessage::new("K1AB", grid("AA00"), 0).unwrap();
    assert_eq!(msg.callsign(), b" K1AB ");
    // Minimal 3-char call: " W1A  " — wait, W1A has digit second, so
    // aligned as " W1A  ".
    let msg = WsprMessage::new("W1A", grid("RR99"), 60).unwrap();
    assert_eq!(msg.callsign(), b" W1A  ");
}

#[test]
fn callsign_rejections() {
    // Compound (suffixed) calls are not type-1.
    assert_eq!(
        WsprMessage::new("K1ABC/P", grid("FN42"), 37),
        Err(WsprError::CallsignCompound)
    );
    // No digit in position 2 or 3: unalignable.
    assert_eq!(
        WsprMessage::new("ABCDEF", grid("FN42"), 37),
        Err(WsprError::CallsignShape)
    );
    // Six chars with digit second cannot shift.
    assert_eq!(
        WsprMessage::new("A1BCDE", grid("FN42"), 37),
        Err(WsprError::CallsignShape)
    );
    // Empty and overlong.
    assert!(matches!(
        WsprMessage::new("", grid("FN42"), 37),
        Err(WsprError::CallsignLength { len: 0 })
    ));
    assert!(matches!(
        WsprMessage::new("KA1ABCD", grid("FN42"), 37),
        Err(WsprError::CallsignLength { .. })
    ));
    // Punctuation.
    assert!(matches!(
        WsprMessage::new("K1A-C", grid("FN42"), 37),
        Err(WsprError::CallsignChar { .. })
    ));
    // Digit in a letters-only tail position.
    assert!(matches!(
        WsprMessage::new("KA1A2C", grid("FN42"), 37),
        Err(WsprError::CallsignChar { .. })
    ));
}

/// The callsign and grid arguments of [`WsprMessage::new`] can no
/// longer be transposed.
///
/// The primary proof is static and therefore not expressible as an
/// assertion: `WsprMessage::new("FN42", "K1ABC", 37)` used to compile
/// (two `&str` parameters) and now does not, because the second
/// parameter is a `MaidenheadGrid` and `&str` does not coerce to one.
/// What remains testable is that neither string is valid in the other's
/// role, so no accidental transposition can survive anywhere in the
/// pipeline — including the one shape that used to pass validation
/// "only by luck".
#[test]
fn callsign_and_grid_cannot_be_transposed() {
    // A locator in the callsign slot: "FN42" aligns (third character is
    // a digit) and is rejected only by the letters-only tail rule — the
    // near-miss that motivated the type change.
    assert_eq!(
        WsprMessage::new("FN42", grid("FN42"), 37),
        Err(WsprError::CallsignChar { ch: '2', index: 3 })
    );
    // A callsign in the locator slot never even becomes a locator: five
    // characters is not a Maidenhead length.
    assert_eq!(
        MaidenheadGrid::new("K1ABC"),
        Err(GeoError::BadGridLength { got: 5 })
    );
    // Nor do the shorter, more plausible-looking calls.
    assert_eq!(
        MaidenheadGrid::new("K1AB"),
        Err(GeoError::BadGridChar {
            got: b'1',
            position: 1
        })
    );
}

// ---- source encoding: grid + power ----

#[test]
fn grid_corners_pack_in_range() {
    // AA00 (max longitude term) and RR99 (min): both must fit 15 bits.
    for wire in [b"AA00", b"RR99"] {
        let g = core::str::from_utf8(wire).unwrap();
        let msg = WsprMessage::new("K1ABC", grid(g), 37).unwrap();
        let (_, m) = unpack(&msg.pack());
        assert_eq!(m, expected_m(wire, 37));
        assert!(m >> 7 < (1 << 15), "grid value must be 15 bits");
    }
}

/// The locator packing against **independently published** values.
///
/// This is the known-answer test that [`grid_corners_pack_in_range`]
/// above is not: `expected_m` restates the same formula the encoder
/// uses, so the two agree by construction and would go on agreeing if
/// the formula were wrong. That is exactly how this crate shipped an
/// IL2P implementation that could not exchange a frame with anybody
/// while every round-trip test passed (`docs/APRS_CONFORMANCE.md`
/// §6.1).
///
/// PROVENANCE: the two values below are quoted from G4JNT's "The WSPR
/// Coding Process" (Andy Talbot, 2009), which states the locator range
/// runs "from `AA00` (32220) to `RR99` (179)", and the callsign
/// maximum `37 * 36 * 10 * 27 * 27 * 27 = 262177560`. That document is
/// a published algorithm description, not source code, so quoting its
/// worked values carries no licensing encumbrance -- the same footing
/// as the APRS protocol reference and the IL2P specification vectors
/// this crate already cites.
#[test]
fn locator_packing_matches_the_published_values() {
    // M = M1 * 128 + power + 64, so M1 is the top 15 bits of M.
    for (locator, published_m1) in [("AA00", 32_220u32), ("RR99", 179)] {
        let msg = WsprMessage::new("K1ABC", grid(locator), 37).expect("valid");
        let (_, m) = unpack(&msg.pack());
        assert_eq!(
            m >> 7,
            published_m1,
            "{locator} must pack to the published M1 value"
        );
        // ...and the power term occupies the low 7 bits, per M above.
        assert_eq!(m & 0x7f, 37 + 64);
    }

    // The published callsign-space bound. A wrong radix anywhere in the
    // successive-multiply chain moves this.
    assert_eq!(37 * 36 * 10 * 27 * 27 * 27, 262_177_560u32);
    // The largest packable callsign is the last character of every
    // position, which must land just under the published bound.
    let widest = WsprMessage::new("999ZZZ", grid("AA00"), 60).expect("valid");
    let (n, _) = unpack(&widest.pack());
    assert!(
        n < 262_177_560,
        "callsign value {n} exceeds the published bound"
    );
}

/// Malformed locator text never reaches WSPR: `MaidenheadGrid` rejects
/// it, with the same coverage the module's own validator used to give
/// (short, long, field letter past `R`, letter where a digit belongs).
#[test]
fn grid_text_rejections() {
    assert_eq!(
        MaidenheadGrid::new("FN4"),
        Err(GeoError::BadGridLength { got: 3 })
    );
    assert_eq!(
        MaidenheadGrid::new("FN421"),
        Err(GeoError::BadGridLength { got: 5 })
    );
    // Field letters beyond R.
    assert_eq!(
        MaidenheadGrid::new("SN42"),
        Err(GeoError::BadGridChar {
            got: b'S',
            position: 0
        })
    );
    // Letter where a square digit belongs.
    assert_eq!(
        MaidenheadGrid::new("FNA2"),
        Err(GeoError::BadGridChar {
            got: b'A',
            position: 2
        })
    );
}

/// A well-formed locator finer than a square is rejected, not
/// truncated: the type-1 grid field is exactly four characters, and
/// silently dropping the subsquare would transmit a place the operator
/// did not name.
#[test]
fn finer_grids_are_rejected_not_truncated() {
    assert_eq!(
        WsprMessage::new("K1ABC", grid("FN42ab"), 37),
        Err(WsprError::GridLength { len: 6 })
    );
    assert_eq!(
        WsprMessage::new("K1ABC", grid("FN42ab12"), 37),
        Err(WsprError::GridLength { len: 8 })
    );
}

#[test]
fn power_bounds_and_standard_values() {
    assert!(WsprMessage::new("K1ABC", grid("FN42"), 0).is_ok());
    assert!(WsprMessage::new("K1ABC", grid("FN42"), 60).is_ok());
    assert!(WsprMessage::new("K1ABC", grid("FN42"), 33).is_ok());
    assert_eq!(
        WsprMessage::new("K1ABC", grid("FN42"), 61),
        Err(WsprError::PowerOutOfRange { got: 61 })
    );
    // 5 dBm does not end in 0/3/7.
    assert_eq!(
        WsprMessage::new("K1ABC", grid("FN42"), 5),
        Err(WsprError::PowerNotStandard { got: 5 })
    );
}

#[test]
fn packed_tail_bits_are_zero() {
    let packed = WsprMessage::new("K1ABC", grid("FN42"), 37).unwrap().pack();
    // Bits 50..88 are the zero tail of the source encoding.
    for i in DATA_BITS..88 {
        assert_eq!(packed_bit(&packed, i), 0, "bit {i} must be zero");
    }
}

// ---- convolutional encoder ----

#[test]
fn conv_encoder_zero_input_gives_zero_output() {
    // A linear code: the all-zero input maps to the all-zero codeword.
    let out = convolutional_encode(&[0u8; 11]);
    assert_eq!(out, [0u8; SYMBOL_COUNT]);
}

#[test]
fn conv_encoder_kat_single_leading_one() {
    // Input 0x80 00 ...: a single 1 as the first bit. The register
    // then holds ...0001 shifted left once per subsequent bit, so
    // coded pair k is (bit 31-? ...) — concretely, output pair k
    // equals (POLY_A >> k & 1, POLY_B >> k & 1) while the 1 is still
    // inside the 32-bit register (k < 32), and 0 afterwards. This is a
    // hand-derivable known answer from the encoder definition.
    let mut packed = [0u8; 11];
    packed[0] = 0x80;
    let out = convolutional_encode(&packed);
    for k in 0..81 {
        let (ea, eb) = if k < 32 {
            (((POLY_A >> k) & 1) as u8, ((POLY_B >> k) & 1) as u8)
        } else {
            (0, 0)
        };
        assert_eq!(out[2 * k], ea, "poly A parity at input bit {k}");
        assert_eq!(out[2 * k + 1], eb, "poly B parity at input bit {k}");
    }
}

#[test]
fn conv_encoder_is_linear() {
    // encode(a) XOR encode(b) == encode(a XOR b) for a linear code.
    let a = WsprMessage::new("K1ABC", grid("FN42"), 37).unwrap().pack();
    let b = WsprMessage::new("G4XYZ", grid("IO90"), 30).unwrap().pack();
    let mut x = [0u8; 11];
    for i in 0..11 {
        x[i] = a[i] ^ b[i];
    }
    let ea = convolutional_encode(&a);
    let eb = convolutional_encode(&b);
    let ex = convolutional_encode(&x);
    for i in 0..SYMBOL_COUNT {
        assert_eq!(ea[i] ^ eb[i], ex[i], "linearity at coded bit {i}");
    }
}

// ---- interleaver ----

#[test]
fn interleaver_is_a_permutation() {
    // Tag each input position with a distinct value and check every
    // value appears exactly once after interleaving. u8 range suffices
    // for 162 positions when split across two runs of 0..=161 values.
    let mut seen = [false; SYMBOL_COUNT];
    // Use two passes of 0/1 patterns to identify positions uniquely:
    // simpler — run the map on unit vectors' parity via linearity is
    // overkill; instead recompute the mapping directly.
    let mut input = [0u8; SYMBOL_COUNT];
    for round in 0..SYMBOL_COUNT {
        input.fill(0);
        input[round] = 1;
        let out = interleave(&input);
        let pos = out.iter().position(|&b| b == 1).expect("bit lost");
        assert_eq!(out.iter().filter(|&&b| b == 1).count(), 1, "bit duplicated");
        assert!(!seen[pos], "two inputs land at {pos}");
        seen[pos] = true;
    }
    assert!(seen.iter().all(|&s| s), "not surjective");
}

#[test]
fn interleaver_matches_bit_reversal_definition() {
    // First input bit lands at reverse(0)=0; second at reverse(1)=128;
    // third at reverse(2)=64; fourth at reverse(3)=192 which is >= 162
    // so it is skipped and the fourth input bit lands at reverse(4)=32.
    let mut input = [0u8; SYMBOL_COUNT];
    input[0] = 1;
    input[1] = 1;
    input[2] = 1;
    input[3] = 1;
    let out = interleave(&input);
    for (i, &b) in out.iter().enumerate() {
        let expect = matches!(i, 0 | 128 | 64 | 32);
        assert_eq!(b == 1, expect, "position {i}");
    }
}

// ---- sync vector & channel symbols ----

#[test]
fn sync_vector_spot_checks() {
    // Spot checks against the published 162-element table (G4JNT's
    // WSPR coding-process description).
    assert_eq!(SYNC_VECTOR.len(), SYMBOL_COUNT);
    assert_eq!(&SYNC_VECTOR[..8], &[1, 1, 0, 0, 0, 0, 0, 0]);
    assert_eq!(&SYNC_VECTOR[8..16], &[1, 0, 0, 0, 1, 1, 1, 0]);
    assert_eq!(&SYNC_VECTOR[80..90], &[0, 0, 1, 0, 1, 1, 0, 0, 0, 1]);
    assert_eq!(&SYNC_VECTOR[154..], &[0, 0, 0, 1, 1, 0, 0, 0]);
    assert!(SYNC_VECTOR.iter().all(|&b| b <= 1));
}

#[test]
fn channel_symbols_shape() {
    let symbols = WsprMessage::new("K1ABC", grid("FN42"), 37)
        .unwrap()
        .channel_symbols();
    assert_eq!(symbols.len(), SYMBOL_COUNT);
    assert!(symbols.iter().all(|&s| s <= 3));
    // The sync bit is recoverable: symbol % 2 == sync everywhere.
    for i in 0..SYMBOL_COUNT {
        assert_eq!(symbols[i] & 1, SYNC_VECTOR[i], "sync parity at {i}");
    }
}

#[test]
fn channel_symbols_end_to_end_rederivation() {
    // Re-derive the whole pipeline from the spec formulas in this test
    // (independent code path) and compare with the library.
    let msg = WsprMessage::new("G4XYZ", grid("IO90"), 30).unwrap();

    let n = expected_callsign_value(b" G4XYZ");
    let m = expected_m(b"IO90", 30);
    let bits50: u64 = (u64::from(n) << 22) | u64::from(m);

    // 81 encoder input bits, MSB of the 50-bit value first.
    let mut coded = [0u8; SYMBOL_COUNT];
    let mut reg: u32 = 0;
    for k in 0..81 {
        let bit = if k < 50 {
            ((bits50 >> (49 - k)) & 1) as u32
        } else {
            0
        };
        reg = (reg << 1) | bit;
        coded[2 * k] = ((reg & POLY_A).count_ones() & 1) as u8;
        coded[2 * k + 1] = ((reg & POLY_B).count_ones() & 1) as u8;
    }

    // Bit-reversed interleave.
    let mut data = [0u8; SYMBOL_COUNT];
    let mut k = 0usize;
    for i in 0..=255u8 {
        let j = usize::from(i.reverse_bits());
        if j < SYMBOL_COUNT {
            data[j] = coded[k];
            k += 1;
        }
    }

    let mut expected = [0u8; SYMBOL_COUNT];
    for i in 0..SYMBOL_COUNT {
        expected[i] = SYNC_VECTOR[i] + 2 * data[i];
    }
    assert_eq!(msg.channel_symbols(), expected);
}

/// Frozen regression snapshot for "K1ABC FN42 37".
///
/// PROVENANCE: generated by THIS implementation (not an independently
/// published vector) and frozen so any regression in packing, encoding
/// or interleaving is caught. It is cross-checked structurally by the
/// invariant tests above; independent verification against real
/// decoders lands with the RX slice.
#[rustfmt::skip]
const K1ABC_FN42_37_SNAPSHOT: [u8; SYMBOL_COUNT] = [
    3, 3, 0, 0, 2, 0, 0, 0, 1, 0, 2, 0, 1, 3, 1, 2, 2, 2, 1, 0,
    0, 3, 2, 3, 1, 3, 3, 2, 2, 0, 2, 0, 0, 0, 3, 2, 0, 1, 2, 3,
    2, 2, 0, 0, 2, 2, 3, 2, 1, 1, 0, 2, 3, 3, 2, 1, 0, 2, 2, 1,
    3, 2, 1, 2, 2, 2, 0, 3, 3, 0, 3, 0, 3, 0, 1, 2, 1, 0, 2, 1,
    2, 0, 3, 2, 1, 3, 2, 0, 0, 3, 3, 2, 3, 0, 3, 2, 2, 0, 3, 0,
    2, 0, 2, 0, 1, 0, 2, 3, 0, 2, 1, 1, 1, 2, 3, 3, 0, 2, 3, 1,
    2, 1, 2, 2, 2, 1, 3, 3, 2, 0, 0, 0, 0, 1, 0, 3, 2, 0, 1, 3,
    2, 2, 2, 2, 2, 0, 2, 3, 3, 2, 3, 2, 3, 3, 2, 0, 0, 3, 1, 2,
    2, 2,
];

#[test]
fn k1abc_regression_snapshot() {
    let symbols = WsprMessage::new("K1ABC", grid("FN42"), 37)
        .unwrap()
        .channel_symbols();
    assert_eq!(symbols, K1ABC_FN42_37_SNAPSHOT);
}

// ---- audio synthesis ----

#[test]
fn config_validation() {
    let sr12k = SampleRate::new(12_000).unwrap();
    assert!(WsprConfig::new(1_500, sr12k).is_ok());
    // Not a multiple of 375 Hz: symbol timing would be inexact.
    assert_eq!(
        WsprConfig::new(1_500, SampleRate::new(44_100).unwrap()),
        Err(WsprError::SampleRateInexact { got: 44_100 })
    );
    // 48 kHz = 128 × 375: exact.
    let cfg48 = WsprConfig::new(1_500, SampleRate::new(48_000).unwrap()).unwrap();
    assert_eq!(cfg48.samples_per_symbol(), 32_768);
    // Base of 0 Hz and tones at/above Nyquist are rejected.
    assert!(WsprConfig::new(0, sr12k).is_err());
    assert!(WsprConfig::new(6_000, sr12k).is_err());
    // Just below Nyquist minus the 3-tone span is fine.
    assert!(WsprConfig::new(5_990, sr12k).is_ok());
}

#[test]
fn total_sample_count() {
    let cfg = WsprConfig::new(1_500, SampleRate::new(12_000).unwrap()).unwrap();
    assert_eq!(cfg.samples_per_symbol(), 8_192);
    let msg = WsprMessage::new("K1ABC", grid("FN42"), 37).unwrap();
    let mut tx = WsprModulator::for_message(cfg, &msg);
    assert_eq!(tx.total_samples(), 162 * 8_192);
    let mut count = 0u64;
    let mut buf = [0i16; 4_096];
    loop {
        let n = tx.fill_i16(&mut buf);
        count += n as u64;
        if n < buf.len() {
            break;
        }
    }
    assert_eq!(count, 162 * 8_192); // ≈ 110.6 s at 12 kHz
    assert_eq!(tx.next_i16(), None);
}

/// Goertzel magnitude of `samples` at `freq_hz` (f64 accumulation).
fn goertzel(samples: &[i16], freq_hz: f64, sample_rate: f64) -> f64 {
    let w = 2.0 * core::f64::consts::PI * freq_hz / sample_rate;
    let coeff = 2.0 * w.cos();
    let (mut s1, mut s2) = (0.0f64, 0.0f64);
    for &x in samples {
        let s0 = f64::from(x) + coeff * s1 - s2;
        s2 = s1;
        s1 = s0;
    }
    (s1 * s1 + s2 * s2 - coeff * s1 * s2).sqrt()
}

#[test]
fn per_symbol_dominant_tone() {
    let cfg = WsprConfig::new(1_500, SampleRate::new(12_000).unwrap()).unwrap();
    let msg = WsprMessage::new("K1ABC", grid("FN42"), 37).unwrap();
    let symbols = msg.channel_symbols();
    let mut tx = WsprModulator::new(cfg, symbols);
    let spacing = 12_000.0 / 8_192.0;
    let mut buf = [0i16; 8_192];
    // Check a spread of symbols (full 162 × 8192-sample Goertzel ×4
    // would be slow in debug builds).
    for (idx, &sym) in symbols.iter().enumerate() {
        let n = tx.fill_i16(&mut buf);
        assert_eq!(n, buf.len());
        if idx % 20 != 0 {
            continue;
        }
        let mut best = (0usize, 0.0f64);
        for tone in 0..4 {
            let f = 1_500.0 + tone as f64 * spacing;
            let mag = goertzel(&buf, f, 12_000.0);
            if mag > best.1 {
                best = (tone, mag);
            }
        }
        assert_eq!(
            best.0,
            usize::from(sym),
            "dominant tone at symbol {idx} (expected {sym})"
        );
    }
}

#[test]
fn phase_continuity() {
    // Continuous-phase FSK: the step between adjacent samples can never
    // exceed the amplitude swept by the highest tone's phase increment.
    let cfg = WsprConfig::new(1_500, SampleRate::new(12_000).unwrap()).unwrap();
    let msg = WsprMessage::new("G4XYZ", grid("IO90"), 30).unwrap();
    let mut tx = WsprModulator::for_message(cfg, &msg);
    // Highest tone ≈ 1504.4 Hz at 12 kHz: max |Δsample| per step is
    // 2π · f/sr · 32767 ≈ 16 222; allow a small table-quantization pad.
    let max_delta = (2.0 * core::f64::consts::PI * 1_504.5 / 12_000.0 * 32_767.0) as i32 + 64;
    let mut prev = i32::from(tx.next_i16().unwrap());
    // Span several symbol boundaries (first 6 symbols).
    for _ in 0..(6 * 8_192 - 1) {
        let s = i32::from(tx.next_i16().unwrap());
        assert!(
            (s - prev).abs() <= max_delta,
            "phase jump: {prev} -> {s} exceeds {max_delta}"
        );
        prev = s;
    }
}

#[test]
fn f32_path_matches_i16_shape() {
    let cfg = WsprConfig::new(1_500, SampleRate::new(12_000).unwrap()).unwrap();
    let msg = WsprMessage::new("K1ABC", grid("FN42"), 37).unwrap();
    let mut a = WsprModulator::for_message(cfg, &msg);
    let mut b = WsprModulator::for_message(cfg, &msg);
    for _ in 0..10_000 {
        let x = f64::from(a.next_i16().unwrap()) / 32_767.0;
        let y = f64::from(b.next_f32().unwrap());
        // Same phase trajectory; interpolation differs by < 1 table step.
        assert!((x - y).abs() < 2.0e-3, "i16/f32 paths diverge: {x} vs {y}");
    }
}

#[test]
fn iterator_adapter_agrees_with_pull() {
    let cfg = WsprConfig::new(1_500, SampleRate::new(12_000).unwrap()).unwrap();
    let msg = WsprMessage::new("K1ABC", grid("FN42"), 37).unwrap();
    let mut pull = WsprModulator::for_message(cfg, &msg);
    let it = WsprModulator::for_message(cfg, &msg);
    for (i, s) in it.take(20_000).enumerate() {
        assert_eq!(Some(s), pull.next_i16(), "sample {i}");
    }
}