Module: PWN::SDR::Decoder::DSP

Defined in:
lib/pwn/sdr/decoder/dsp.rb

Overview

DSP primitives shared by every PWN::SDR::Decoder::* module.

Default path is pure Ruby operating on Array samples normalised to -1.0..1.0 (48 kHz s16le mono from GQRX UDP — no sox / multimon-ng / minimodem dependency).

When the matching system library is present the hot paths transparently accelerate via PWN::FFI::Volk,Liquid,FFTW:

unpack_s16le  

Packed IQ/FM/magnitude and radix-2 FFT use optional DSPNative first. Build explicitly with ruby ext/pwn_dsp/build.rb; no runtime compilation. process_iq exposes :ruby degradation and keeps caller-owned chunk state. Other accelerated methods fall back to pure Ruby when their backend is missing or raises, so decoders never require a native library at install time. Force pure Ruby for testing with PWN::SDR::Decoder::DSP.native = false

Constant Summary collapse

TWO_PI =
Math::PI * 2
BAUDOT_LTRS =

ITA2 / Baudot 5-bit → ASCII (LTRS + FIGS shift tables). Index = code.

[
  "\0", 'E', "\n", 'A', ' ', 'S', 'I', 'U',
  "\r", 'D', 'R', 'J', 'N', 'F', 'C', 'K',
  'T',  'Z', 'L',  'W', 'H', 'Y', 'P', 'Q',
  'O',  'B', 'G',  nil, 'M', 'X', 'V', nil
].freeze
BAUDOT_FIGS =
[
  "\0", '3', "\n", '-', ' ', "'", '8', '7',
  "\r", '$', '4',  "\a", ',', '!', ':', '(',
  '5',  '+', ')',  '2', '#', '6', '0', '1',
  '9',  '?', '&',  nil, '.', '/', ';', nil
].freeze
MORSE_TABLE =

International Morse Code (dit='.', dah='-') → ASCII.

{
  '.-' => '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', '-----' => '0', '.----' => '1', '..---' => '2',
  '...--' => '3', '....-' => '4', '.....' => '5', '-....' => '6',
  '--...' => '7', '---..' => '8', '----.' => '9', '.-.-.-' => '.',
  '--..--' => ',', '..--..' => '?', '-..-.' => '/', '-....-' => '-',
  '-.--.' => '(', '-.--.-' => ')', '.-...' => '&', '---...' => ':',
  '-...-' => '=', '.-.-.' => '+', '.--.-.' => '@'
}.freeze
CA_G2_TAPS =
{
  1 => [2, 6], 2 => [3, 7], 3 => [4, 8], 4 => [5, 9], 5 => [1, 9],
  6 => [2, 10], 7 => [1, 8], 8 => [2, 9], 9 => [3, 10], 10 => [2, 3],
  11 => [3, 4], 12 => [5, 6], 13 => [6, 7], 14 => [7, 8], 15 => [8, 9],
  16 => [9, 10], 17 => [1, 4], 18 => [2, 5], 19 => [3, 6], 20 => [4, 7],
  21 => [5, 8], 22 => [6, 9], 23 => [1, 3], 24 => [4, 6], 25 => [5, 7],
  26 => [6, 8], 27 => [7, 9], 28 => [8, 10], 29 => [1, 6], 30 => [2, 7],
  31 => [3, 8], 32 => [4, 9]
}.freeze

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.nativeObject

Returns the value of attribute native.



34
35
36
# File 'lib/pwn/sdr/decoder/dsp.rb', line 34

def native
  @native
end

Class Method Details

.authorsObject

Author(s)

0day Inc. [email protected]



1092
1093
1094
# File 'lib/pwn/sdr/decoder/dsp.rb', line 1092

public_class_method def self.authors
  "AUTHOR(S):\n  0day Inc. <[email protected]>\n"
end

.baudot_decode(opts = {}) ⇒ Object

Supported Method Parameters

txt = PWN::SDR::Decoder::DSP.baudot_decode(bits: Array<0|1>) 5-bit ITA2 with LTRS(31)/FIGS(27) shift, LSB-first per character.



383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
# File 'lib/pwn/sdr/decoder/dsp.rb', line 383

public_class_method def self.baudot_decode(opts = {})
  bits = opts[:bits]
  figs = false
  out  = +''
  bits.each_slice(5) do |ch|
    next if ch.length < 5

    code = ch.each_with_index.sum { |b, i| b << i }
    case code
    when 31 then figs = false
    when 27 then figs = true
    else
      tbl = figs ? BAUDOT_FIGS : BAUDOT_LTRS
      c = tbl[code]
      out << c if c
    end
  end
  out
end

.bch_31_21_syndrome(opts = {}) ⇒ Object

BCH(31,21) syndrome — generator poly 0b11101101001 (0x769). Used by POCSAG and FLEX codewords (bits 31..1 are BCH, bit 0 parity).

Supported Method Parameters

syn = PWN::SDR::Decoder::DSP.bch_31_21_syndrome(word: Integer)



369
370
371
372
373
374
375
376
377
# File 'lib/pwn/sdr/decoder/dsp.rb', line 369

public_class_method def self.bch_31_21_syndrome(opts = {})
  word = (opts[:word].to_i >> 1) & 0x7FFFFFFF
  gen  = 0x769
  reg  = word
  30.downto(10) do |i|
    reg ^= (gen << (i - 10)) if (reg >> i).odd?
  end
  reg & 0x3FF
end

.bits_to_int(opts = {}) ⇒ Object

Supported Method Parameters

int = PWN::SDR::Decoder::DSP.bits_to_int(bits: [1,0,1,...])



346
347
348
349
350
351
# File 'lib/pwn/sdr/decoder/dsp.rb', line 346

public_class_method def self.bits_to_int(opts = {})
  bits = opts[:bits]
  v = 0
  bits.each { |b| v = (v << 1) | (b & 1) }
  v
end

.bytes_from_bits(opts = {}) ⇒ Object

Supported Method Parameters

bytes = PWN::SDR::Decoder::DSP.bytes_from_bits( bits: Array<0|1>, lsb_first: false )



774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
# File 'lib/pwn/sdr/decoder/dsp.rb', line 774

public_class_method def self.bytes_from_bits(opts = {})
  bits = opts[:bits]
  lsb  = opts[:lsb_first]
  out  = []
  bits.each_slice(8) do |oct|
    next if oct.length < 8

    v = 0
    if lsb
      oct.each_with_index { |b, i| v |= (b & 1) << i }
    else
      oct.each { |b| v = (v << 1) | (b & 1) }
    end
    out << v
  end
  out
end

.ca_code(opts = {}) ⇒ Object

Supported Method Parameters

chips = PWN::SDR::Decoder::DSP.ca_code(prn: 1..32) Returns Array of ±1.0 length 1023 (GPS L1 C/A Gold code).



997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
# File 'lib/pwn/sdr/decoder/dsp.rb', line 997

public_class_method def self.ca_code(opts = {})
  prn  = opts[:prn].to_i
  taps = CA_G2_TAPS[prn]
  raise "ERROR: PRN #{prn} unsupported" unless taps

  g1 = Array.new(10, 1)
  g2 = Array.new(10, 1)
  out = Array.new(1023)
  1023.times do |i|
    g2i = g2[taps[0] - 1] ^ g2[taps[1] - 1]
    out[i] = (g1[9] ^ g2i) == 1 ? -1.0 : 1.0
    fb1 = g1[2] ^ g1[9]
    fb2 = g2[1] ^ g2[2] ^ g2[5] ^ g2[7] ^ g2[8] ^ g2[9]
    g1.unshift(fb1)
    g1.pop
    g2.unshift(fb2)
    g2.pop
  end
  out
end

.cfft_mag(opts = {}) ⇒ Object

Supported Method Parameters

mag = PWN::SDR::Decoder::DSP.cfft_mag( iq: 'required - interleaved I/Q', n: 'optional - FFT size', shift: 'optional - fftshift so DC is centred (default true)' )

Raises:

  • (ArgumentError)


886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
# File 'lib/pwn/sdr/decoder/dsp.rb', line 886

public_class_method def self.cfft_mag(opts = {})
  iq = opts[:iq]
  n  = (opts[:n] || (iq.length / 2)).to_i
  sh = opts.fetch(:shift, true)
  raise ArgumentError, 'n must be positive' unless n.positive?

  if native && n.nobits?(n - 1) && PWN::FFI.available?(mod: :DSPNative)
    begin
      mag = PWN::FFI::DSPNative.cfft_mag(iq: iq, n: n)
      return sh ? mag.rotate(n / 2) : mag
    rescue StandardError
      # Continue with existing FFTW / Ruby fallback.
    end
  end
  bins =
    if native && PWN::FFI.available?(mod: :FFTW)
      begin
        PWN::FFI::FFTW.cfft(iq: iq, n: n)
      rescue StandardError
        dft_naive(iq: iq, n: n)
      end
    else
      dft_naive(iq: iq, n: n)
    end
  mag = bins.map { |re, im| Math.sqrt((re * re) + (im * im)) }
  sh ? mag.rotate(n / 2) : mag
end

.cmul(opts = {}) ⇒ Object

Supported Method Parameters

out = PWN::SDR::Decoder::DSP.cmul(a: [I,Q,…], b: [I,Q,…], conj_b: false) Element-wise complex multiply (interleaved). Used for correlation / dechirp: X = A · conj(B).



1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
# File 'lib/pwn/sdr/decoder/dsp.rb', line 1023

public_class_method def self.cmul(opts = {})
  a = opts[:a]
  b = opts[:b]
  cj = opts[:conj_b]
  n  = [a.length, b.length].min / 2
  out = Array.new(n * 2)
  i = 0
  while i < n
    ar = a[i * 2].to_f
    ai = a[(i * 2) + 1].to_f
    br = b[i * 2].to_f
    bi = b[(i * 2) + 1].to_f
    bi = -bi if cj
    out[i * 2]       = (ar * br) - (ai * bi)
    out[(i * 2) + 1] = (ar * bi) + (ai * br)
    i += 1
  end
  out
end

.correlate(opts = {}) ⇒ Object

Correlate a real template against magnitude-squared energy for PPM / OOK preambles. Returns best lag + score.

Supported Method Parameters

hit = PWN::SDR::Decoder::DSP.correlate( samples: 'required - Array', template: 'required - Array (same units)' ) → { lag:, score: } or nil



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 548

public_class_method def self.correlate(opts = {})
  samples  = opts[:samples]
  template = opts[:template]
  tlen = template.length
  return nil if tlen.zero? || samples.length < tlen

  best_lag = 0
  best_sc  = -Float::INFINITY
  upto = samples.length - tlen
  i = 0
  while i <= upto
    sc = 0.0
    j = 0
    while j < tlen
      sc += samples[i + j] * template[j]
      j += 1
    end
    if sc > best_sc
      best_sc = sc
      best_lag = i
    end
    i += 1
  end
  { lag: best_lag, score: best_sc }
end

.crc16(opts = {}) ⇒ Object

Supported Method Parameters

crc = PWN::SDR::Decoder::DSP.crc16( bytes: Array, poly: 0x1021, init: 0xFFFF, refin: false, refout: false, xorout: 0x0000 )



798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
# File 'lib/pwn/sdr/decoder/dsp.rb', line 798

public_class_method def self.crc16(opts = {})
  bytes  = opts[:bytes]
  poly   = (opts[:poly]   || 0x1021).to_i
  crc    = (opts[:init]   || 0xFFFF).to_i
  refin  = opts[:refin]
  refout = opts[:refout]
  xorout = (opts[:xorout] || 0).to_i
  bytes.each do |b|
    b = Integer(format('%08b', b & 0xFF).reverse, 2) if refin
    crc ^= (b & 0xFF) << 8
    8.times do
      crc = crc.anybits?(0x8000) ? ((crc << 1) ^ poly) : (crc << 1)
      crc &= 0xFFFF
    end
  end
  crc = Integer(format('%016b', crc).reverse, 2) if refout
  crc ^ xorout
end

.dc_block(opts = {}) ⇒ Object

Supported Method Parameters

y = PWN::SDR::Decoder::DSP.dc_block( samples: 'required - Array', alpha: 'optional - pole (default 0.995)' )



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 183

public_class_method def self.dc_block(opts = {})
  samples = opts[:samples]
  # Prefer liquid FIR DC blocker when caller asks for it (m:) or when
  # alpha is the default AND liquid is available — otherwise keep the
  # classic single-pole IIR so call sites that pass a custom alpha
  # stay bit-identical to pure Ruby.
  if native && opts[:m] && PWN::FFI.available?(mod: :Liquid)
    begin
      return PWN::FFI::Liquid.dc_block(
        samples: samples,
        m: opts[:m],
        as_db: opts[:as_db] || 60.0
      )
    rescue StandardError
      # fall through
    end
  end

  alpha  = (opts[:alpha] || 0.995).to_f
  y_prev = 0.0
  x_prev = 0.0
  samples.map do |x|
    y = x - x_prev + (alpha * y_prev)
    x_prev = x
    y_prev = y
    y
  end
end

.dft_naive(opts = {}) ⇒ Object

Ruby radix-2 FFT for power-of-two sizes; exact O(n²) DFT otherwise.

Supported Method Parameters

bins = PWN::SDR::Decoder::DSP.dft_naive(iq:, n:)

Raises:

  • (ArgumentError)


918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
# File 'lib/pwn/sdr/decoder/dsp.rb', line 918

public_class_method def self.dft_naive(opts = {})
  iq = opts[:iq]
  n  = (opts[:n] || (iq.length / 2)).to_i
  raise ArgumentError, 'n must be positive' unless n.positive?

  if n.nobits?(n - 1)
    bins = Array.new(n) { |i| [iq[2 * i].to_f, iq[(2 * i) + 1].to_f] }
    j = 0
    (1...n).each do |i|
      bit = n >> 1
      while j.anybits?(bit)
        j ^= bit
        bit >>= 1
      end
      j ^= bit
      bins[i], bins[j] = bins[j], bins[i] if i < j
    end
    length = 2
    while length <= n
      angle = -TWO_PI / length
      wr = Math.cos(angle)
      wi = Math.sin(angle)
      (0...n).step(length) do |start|
        ur = 1.0
        ui = 0.0
        (length / 2).times do |offset|
          a = start + offset
          b = a + (length / 2)
          br, bi = bins[b]
          tr = (br * ur) - (bi * ui)
          ti = (br * ui) + (bi * ur)
          ar, ai = bins[a]
          bins[a] = [ar + tr, ai + ti]
          bins[b] = [ar - tr, ai - ti]
          ur, ui = [(ur * wr) - (ui * wi), (ur * wi) + (ui * wr)]
        end
      end
      length *= 2
    end
    return bins
  end
  Array.new(n) do |k|
    re = 0.0
    im = 0.0
    j = 0
    while j < n
      ph = -TWO_PI * k * j / n
      c = Math.cos(ph)
      s = Math.sin(ph)
      xr = iq[j * 2].to_f
      xi = iq[(j * 2) + 1].to_f
      re += (xr * c) - (xi * s)
      im += (xr * s) + (xi * c)
      j += 1
    end
    [re, im]
  end
end

.diff_decode(opts = {}) ⇒ Object

Supported Method Parameters

bits = PWN::SDR::Decoder::DSP.diff_decode(bits: Array<0|1>) NRZ-I / DBPSK: output 1 on transition, 0 on hold.



756
757
758
759
760
761
762
763
764
765
766
767
# File 'lib/pwn/sdr/decoder/dsp.rb', line 756

public_class_method def self.diff_decode(opts = {})
  bits = opts[:bits]
  prev = bits.first || 0
  out  = Array.new(bits.length - 1)
  i = 1
  while i < bits.length
    out[i - 1] = bits[i] == prev ? 0 : 1
    prev = bits[i]
    i += 1
  end
  out
end

.envelope(opts = {}) ⇒ Object

Supported Method Parameters

env = PWN::SDR::Decoder::DSP.envelope( samples: 'required - Array', window: 'optional - moving-average window in samples (default 32)' )



160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/pwn/sdr/decoder/dsp.rb', line 160

public_class_method def self.envelope(opts = {})
  samples = opts[:samples]
  window  = (opts[:window] || 32).to_i
  window  = 1 if window < 1
  acc = 0.0
  buf = Array.new(window, 0.0)
  out = Array.new(samples.length)
  samples.each_with_index do |x, i|
    v = x.abs
    slot = i % window
    acc += v - buf[slot]
    buf[slot] = v
    out[i] = acc / window
  end
  out
end

.envelope_signed(opts = {}) ⇒ Object

Signed moving average (like envelope but keeps sign).

Supported Method Parameters

y = PWN::SDR::Decoder::DSP.envelope_signed(samples:, window:)



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/pwn/sdr/decoder/dsp.rb', line 255

public_class_method def self.envelope_signed(opts = {})
  samples = opts[:samples]
  window  = (opts[:window] || 8).to_i
  window  = 1 if window < 1
  acc = 0.0
  buf = Array.new(window, 0.0)
  out = Array.new(samples.length)
  samples.each_with_index do |x, i|
    slot = i % window
    acc += x - buf[slot]
    buf[slot] = x
    out[i] = acc / window
  end
  out
end

.even_parity_ok?(opts = {}) ⇒ Boolean

Supported Method Parameters

ok = PWN::SDR::Decoder::DSP.even_parity_ok?(word: Integer, width: 32)



356
357
358
359
360
361
362
# File 'lib/pwn/sdr/decoder/dsp.rb', line 356

public_class_method def self.even_parity_ok?(opts = {})
  word  = opts[:word].to_i
  width = (opts[:width] || 32).to_i
  p = 0
  width.times { |i| p ^= (word >> i) & 1 }
  p.zero?
end

.find_sync(opts = {}) ⇒ Object

Supported Method Parameters

idx = PWN::SDR::Decoder::DSP.find_sync( bits: 'required - Array<0|1>', pattern: 'required - Array<0|1> or Integer (MSB-first)', width: 'optional - bit-width when pattern is Integer', max_err: 'optional - allowed bit errors (default 0)', from: 'optional - start index (default 0)' )



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 312

public_class_method def self.find_sync(opts = {})
  bits    = opts[:bits]
  pattern = opts[:pattern]
  width   = opts[:width]
  max_err = (opts[:max_err] || 0).to_i
  from    = (opts[:from] || 0).to_i
  pat = if pattern.is_a?(Integer)
          w = width || pattern.bit_length
          Array.new(w) { |i| (pattern >> (w - 1 - i)) & 1 }
        else
          pattern
        end
  plen = pat.length
  upto = bits.length - plen
  i = from
  while i <= upto
    err = 0
    j = 0
    while j < plen
      err += 1 if bits[i + j] != pat[j]
      break if err > max_err

      j += 1
    end
    return i if err <= max_err

    i += 1
  end
  nil
end

.fm_demod_iq(opts = {}) ⇒ Object

Supported Method Parameters

audio = PWN::SDR::Decoder::DSP.fm_demod_iq( iq: 'required - interleaved Array [I0,Q0,…]', kf: 'optional - modulation index scale (default 1.0)' ) Polar-discriminant FM demod: atan2(cross, dot) * kf. Optional state: {} retains the previous IQ pair across calls; no leading zero.



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 497

public_class_method def self.fm_demod_iq(opts = {})
  iq = opts[:iq]
  kf = (opts[:kf] || 1.0).to_f
  n  = iq.length / 2
  return process_iq(data: iq.first(n * 2).pack('d*'), format: :f64, operation: :fm, kf: kf, state: opts[:state])[:samples] if opts[:state] || (native && PWN::FFI.available?(mod: :DSPNative))
  return [] if n < 2

  # Liquid uses a different scaling convention and emits n rather than
  # n-1 samples; it cannot substitute for this polar discriminator.
  out = Array.new(n - 1)
  prev_re = iq[0].to_f
  prev_im = iq[1].to_f
  i = 1
  while i < n
    re = iq[i * 2].to_f
    im = iq[(i * 2) + 1].to_f
    # arg(z * conj(z_prev)) = atan2 cross/dot
    dot   = (re * prev_re) + (im * prev_im)
    cross = (im * prev_re) - (re * prev_im)
    out[i - 1] = Math.atan2(cross, dot) * kf
    prev_re = re
    prev_im = im
    i += 1
  end
  out
end

.fsk_slice(opts = {}) ⇒ Object

Supported Method Parameters

bits = PWN::SDR::Decoder::DSP.fsk_slice( samples: 'required - Array', rate: 'required - sample rate (Hz)', baud: 'required - symbol rate', mark_hz: 'required - mark tone (bit=1)', space_hz:'required - space tone (bit=0)' ) Non-coherent 2-FSK: per-symbol Goertzel on mark/space, pick the winner.



281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/pwn/sdr/decoder/dsp.rb', line 281

public_class_method def self.fsk_slice(opts = {})
  samples  = opts[:samples]
  rate     = opts[:rate].to_f
  baud     = opts[:baud].to_f
  mark_hz  = opts[:mark_hz].to_f
  space_hz = opts[:space_hz].to_f
  spb      = rate / baud
  nsym     = (samples.length / spb).floor
  bits     = Array.new(nsym)
  i = 0
  while i < nsym
    a = (i * spb).floor
    b = ((i + 1) * spb).floor
    win = samples[a...b]
    pm = goertzel(samples: win, rate: rate, freq: mark_hz)
    ps = goertzel(samples: win, rate: rate, freq: space_hz)
    bits[i] = pm >= ps ? 1 : 0
    i += 1
  end
  bits
end

.gfsk_slice(opts = {}) ⇒ Object

Supported Method Parameters

bits = PWN::SDR::Decoder::DSP.gfsk_slice( iq: 'required - interleaved I/Q', rate:, baud:, bt: 'optional - Gaussian BT (default 0.35)', invert: false ) GFSK/GMSK/2-FSK: prefer liquid gmskdem at integer sps, else fm_demod_iq → nrz_slice.



668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
# File 'lib/pwn/sdr/decoder/dsp.rb', line 668

public_class_method def self.gfsk_slice(opts = {})
  iq   = opts[:iq]
  rate = opts[:rate].to_f
  baud = opts[:baud].to_f
  bt   = (opts[:bt] || 0.35).to_f
  inv  = opts[:invert]
  return [] if iq.empty? || baud <= 0

  sps = rate / baud
  if native && PWN::FFI.available?(mod: :Liquid) && sps >= 2.0
    begin
      k = sps.round
      riq = (sps - k).abs < 0.02 ? iq : resample_iq(iq: iq, src_rate: rate, dst_rate: baud * k)
      bits = PWN::FFI::Liquid.gmsk_demod(iq: riq, sps: k, bt: bt)
      return inv ? bits.map { |b| b ^ 1 } : bits
    rescue StandardError
      # fall through
    end
  end
  audio = fm_demod_iq(iq: iq)
  nrz_slice(samples: audio, rate: rate, baud: baud, invert: inv)
end

.goertzel(opts = {}) ⇒ Object

Supported Method Parameters

power = PWN::SDR::Decoder::DSP.goertzel( samples: 'required - Array', rate: 'required - sample rate (Hz)', freq: 'required - target tone frequency (Hz)' )



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/pwn/sdr/decoder/dsp.rb', line 134

public_class_method def self.goertzel(opts = {})
  samples = opts[:samples]
  rate    = opts[:rate].to_f
  freq    = opts[:freq].to_f
  n       = samples.length
  return 0.0 if n.zero?

  k     = (0.5 + ((n * freq) / rate)).floor
  w     = (TWO_PI * k) / n
  coeff = 2.0 * Math.cos(w)
  s1 = 0.0
  s2 = 0.0
  samples.each do |x|
    s0 = x + (coeff * s1) - s2
    s2 = s1
    s1 = s0
  end
  ((s1 * s1) + (s2 * s2) - (coeff * s1 * s2)) / n
end

.helpObject

Display Usage for this Module



1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
# File 'lib/pwn/sdr/decoder/dsp.rb', line 1098

public_class_method def self.help
  puts "USAGE:
    # Run unpack s16le and return its result
    #{self}.unpack_s16le(
      data: 'required - raw String of little-endian signed 16-bit PCM'
    )

    # Run resample and return its result
    #{self}.resample(
      samples: 'required - samples value consumed by #resample',
      src_rate: 'required - input sample rate (Hz)',
      dst_rate: 'required - output sample rate (Hz)'
    )

    # Run goertzel and return its result
    #{self}.goertzel(
      samples: 'required - samples value consumed by #goertzel',
      rate: 'required - sample rate (Hz)',
      freq: 'required - target tone frequency (Hz)'
    )

    # Run envelope and return its result
    #{self}.envelope(
      samples: 'required - samples value consumed by #envelope',
      window: 'optional - moving-average window in samples (default 32)'
    )

    # Run dc block and return its result
    #{self}.dc_block(
      samples: 'required - samples value consumed by #dc_block',
      alpha: 'optional - pole (default 0.995)',
      m: 'optional - m value consumed by #dc_block',
      as_db: 'optional - as db value consumed by #dc_block (defaults to 60.0)'
    )

    # Run nrz slice and return its result
    #{self}.nrz_slice(
      samples: 'required - Array<Float> (post-FM-discriminator baseband)',
      rate: 'required - sample rate (Hz)',
      baud: 'required - symbol rate',
      invert: 'optional - flip bit polarity (default false)'
    )

    # Signed moving average (like envelope but keeps sign)
    #{self}.envelope_signed(
      samples: 'optional - samples value consumed by #envelope_signed',
      window: 'optional - window value consumed by #envelope_signed'
    )

    # Run fsk slice and return its result
    #{self}.fsk_slice(
      samples: 'required - samples value consumed by #fsk_slice',
      rate: 'required - sample rate (Hz)',
      baud: 'required - symbol rate',
      mark_hz: 'required - mark tone (bit=1)',
      space_hz: 'required - space tone (bit=0)'
    )

    # Run find sync and return its result
    #{self}.find_sync(
      bits: 'required - bits value consumed by #find_sync',
      pattern: 'required - Array<0|1> or Integer (MSB-first)',
      width: 'optional - bit-width when pattern is Integer',
      max_err: 'optional - allowed bit errors (default 0)',
      from: 'optional - start index (default 0)'
    )

    # Run bits to int and return its result
    #{self}.bits_to_int(
      bits: 'optional - bits value consumed by #bits_to_int'
    )

    # Run even parity ok and return its result
    #{self}.even_parity_ok?(
      word: 'optional - word value consumed by #even_parity_ok?',
      width: 'optional - cyclic de Bruijn sequence width in bytes'
    )

    # BCH(31,21) syndrome — generator poly 0b11101101001 (0x769)
    #{self}.bch_31_21_syndrome(
      word: 'optional - word value consumed by #bch_31_21_syndrome'
    )

    # Run baudot decode and return its result
    #{self}.baudot_decode(
      bits: 'optional - bits value consumed by #baudot_decode'
    )

    # Run rms dbfs and return its result
    #{self}.rms_dbfs(
      samples: 'required - samples value consumed by #rms_dbfs'
    )

    # ── True-air I/Q primitives (used by Base.run_iq) ─────────────────
    #{self}.unpack_cs16le(
      data: 'required - raw String of interleaved little-endian s16 I/Q'
    )

    # Run unpack cu8 and return its result
    #{self}.unpack_cu8(
      data: 'required - raw String of interleaved u8 I/Q (RTL-SDR)'
    )

    # Run mag sq and return its result
    #{self}.mag_sq(
      iq: 'required - interleaved Array<Float> [I0,Q0,I1,Q1,…]'
    )

    # Run fm demod iq and return its result
    #{self}.fm_demod_iq(
      iq: 'required - interleaved Array<Float> [I0,Q0,…]',
      kf: 'optional - modulation index scale (default 1.0)',
      state: 'optional - caller-owned Hash preserving previous IQ pair'
    )

    # Run iq rms dbfs and return its result
    #{self}.iq_rms_dbfs(
      iq: 'required - interleaved Array<Float> [I0,Q0,…]'
    )

    # Correlate a real template against magnitude-squared energy for
    #{self}.correlate(
      samples: 'required - samples value consumed by #correlate',
      template: 'required - Array<Float> (same units)'
    )

    # ── True-air I/Q chain (all Decoder::* modules) ──────────────────
    #{self}.resample_iq(
      iq: 'required - interleaved [I0,Q0,…] Array<Float>',
      src_rate: 'required - Hz, dst_rate: required - Hz',
      dst_rate: 'optional - dst rate value consumed by #resample_iq'
    )

    # Run mix iq and return its result
    #{self}.mix_iq(
      iq: 'required - interleaved I/Q, rate: required - Hz',
      freq: 'required - offset Hz to shift DOWN by',
      rate: 'optional - rate value consumed by #mix_iq'
    )

    # Run gfsk slice and return its result
    #{self}.gfsk_slice(
      iq: 'required - interleaved I/Q, rate:, baud:',
      bt: 'optional - Gaussian BT (default 0.35), invert: false',
      rate: 'optional - rate value consumed by #gfsk_slice',
      baud: 'optional - baud value consumed by #gfsk_slice',
      invert: 'optional - invert value consumed by #gfsk_slice'
    )

    # Run slice 4fsk and return its result
    #{self}.slice_4fsk(
      samples: 'required - real FM-discriminator baseband',
      rate: 'optional - rate value consumed by #slice_4fsk',
      baud: 'optional - baud value consumed by #slice_4fsk'
    )

    # Run manchester decode and return its result
    #{self}.manchester_decode(
      bits: 'required - Array<0|1> at 2×data rate',
      ieee: 'optional - true = 01→1 10→0 (IEEE 802.3), else 10→1 01→0'
    )

    # Run diff decode and return its result
    #{self}.diff_decode(
      bits: 'optional - bits value consumed by #diff_decode'
    )

    # Run bytes from bits and return its result
    #{self}.bytes_from_bits(
      bits: 'optional - Array<0|1>, lsb_first: false',
      lsb_first: 'optional - lsb first value consumed by #bytes_from_bits'
    )

    # Run crc16 and return its result
    #{self}.crc16(
      bytes: 'optional - Array<Integer>, poly: 0x1021, init: 0xFFFF',
      refin: 'optional - false, refout: false, xorout: 0x0000',
      poly: 'optional - poly value consumed by #crc16',
      init: 'optional - init value consumed by #crc16',
      refout: 'optional - refout value consumed by #crc16',
      xorout: 'optional - xorout value consumed by #crc16'
    )

    # Run whiten lfsr and return its result
    #{self}.whiten_lfsr(
      bytes: 'optional - Array<Integer>, poly: Integer, init: Integer, width: 7',
      poly: 'optional - poly value consumed by #whiten_lfsr',
      init: 'optional - init value consumed by #whiten_lfsr',
      width: 'optional - cyclic de Bruijn sequence width in bytes'
    )

    # Run ook pulses and return its result
    #{self}.ook_pulses(
      iq: 'required - interleaved I/Q, rate:',
      min_us: 'optional - drop shorter pulses (default 20)',
      rate: 'optional - rate value consumed by #ook_pulses'
    )

    # Run cfft mag and return its result
    #{self}.cfft_mag(
      iq: 'required - interleaved I/Q, n: optional - FFT size',
      shift: 'optional - fftshift so DC is centred (default true)',
      n: 'optional - count, width, or size'
    )

    # Ruby radix-2 FFT for power-of-two sizes; O(n²) DFT otherwise
    #{self}.dft_naive(
      iq: 'optional - iq value consumed by #dft_naive',
      n: 'optional - count, width, or size'
    )

    # Run zadoff chu and return its result
    #{self}.zadoff_chu(
      root: 'optional - root value consumed by #zadoff_chu',
      n: 'optional - count, width, or size'
    )

    # Run ca code and return its result
    #{self}.ca_code(
      prn: 'required - prn value consumed by #ca_code'
    )

    # Run cmul and return its result
    #{self}.cmul(
      a: 'optional - a value consumed by #cmul',
      b: 'optional - b value consumed by #cmul',
      conj_b: 'optional - conj b value consumed by #cmul'
    )

    # Process packed IQ without allocating an intermediate IQ Array.
    # Returns samples plus :native or explicitly degraded :ruby backend.
    #{self}.process_iq(
      data: 'required - packed IQ bytes',
      format: 'optional - :cu8, :cs16le, or host-native :f64 (default :cu8)',
      operation: 'optional - :unpack, :mag, or :fm (default :fm)',
      state: 'optional - caller-owned Hash retaining byte remainder and previous pair',
      kf: 'optional - multiply FM phase radians (default 1.0)',
      native: 'optional - override native toggle (default DSP.native)'
    )

    # Print the AUTHOR(S) string for this module.
    #{self}.authors
  "
  constants.sort
end

.iq_rms_dbfs(opts = {}) ⇒ Object

Supported Method Parameters

power = PWN::SDR::Decoder::DSP.iq_rms_dbfs( iq: 'required - interleaved Array [I0,Q0,…]' )



529
530
531
532
533
534
535
536
537
# File 'lib/pwn/sdr/decoder/dsp.rb', line 529

public_class_method def self.iq_rms_dbfs(opts = {})
  m2 = mag_sq(iq: opts[:iq])
  return -120.0 if m2.empty?

  ms = m2.sum / m2.length
  return -120.0 if ms <= 0

  10.0 * Math.log10(ms)
end

.mag_sq(opts = {}) ⇒ Object

Supported Method Parameters

m2 = PWN::SDR::Decoder::DSP.mag_sq( iq: 'required - interleaved Array [I0,Q0,I1,Q1,…]' ) Returns Array of I²+Q² per sample (length = iq.length/2).



473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
# File 'lib/pwn/sdr/decoder/dsp.rb', line 473

public_class_method def self.mag_sq(opts = {})
  iq = opts[:iq]
  n  = iq.length / 2
  return process_iq(data: iq.first(n * 2).pack('d*'), format: :f64, operation: :mag)[:samples] if native && n >= 64 && PWN::FFI.available?(mod: :DSPNative)

  out = Array.new(n)
  i = 0
  while i < n
    re = iq[i * 2].to_f
    im = iq[(i * 2) + 1].to_f
    out[i] = (re * re) + (im * im)
    i += 1
  end
  out
end

.manchester_decode(opts = {}) ⇒ Object

Supported Method Parameters

bits = PWN::SDR::Decoder::DSP.manchester_decode( bits: 'required - Array<0|1> at 2×data rate', ieee: 'optional - true = 01→1 10→0 (IEEE 802.3), else 10→1 01→0' )



734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# File 'lib/pwn/sdr/decoder/dsp.rb', line 734

public_class_method def self.manchester_decode(opts = {})
  bits = opts[:bits]
  ieee = opts[:ieee]
  out  = []
  i = 0
  while i < bits.length - 1
    a = bits[i]
    b = bits[i + 1]
    if a == b
      i += 1 # phase slip — resync on next transition
      next
    end
    out << (ieee ? b : a)
    i += 2
  end
  out
end

.mix_iq(opts = {}) ⇒ Object

Supported Method Parameters

out = PWN::SDR::Decoder::DSP.mix_iq( iq: 'required - interleaved I/Q', rate: 'required - Hz', freq: 'required - offset Hz to shift DOWN by' )



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 630

public_class_method def self.mix_iq(opts = {})
  iq   = opts[:iq]
  rate = opts[:rate].to_f
  freq = opts[:freq].to_f
  return iq.dup if freq.abs < 1e-3 || iq.empty?

  if native && PWN::FFI.available?(mod: :Liquid)
    begin
      return PWN::FFI::Liquid.mix_down(iq: iq, freq: TWO_PI * freq / rate)
    rescue StandardError
      # fall through
    end
  end
  n = iq.length / 2
  w = TWO_PI * freq / rate
  out = Array.new(n * 2)
  i = 0
  while i < n
    ph = w * i
    c = Math.cos(ph)
    s = Math.sin(ph)
    re = iq[i * 2].to_f
    im = iq[(i * 2) + 1].to_f
    out[i * 2] = (re * c) + (im * s)
    out[(i * 2) + 1] = (im * c) - (re * s)
    i += 1
  end
  out
end

.nrz_slice(opts = {}) ⇒ Object

Supported Method Parameters

bits = PWN::SDR::Decoder::DSP.nrz_slice( samples: 'required - Array (post-FM-discriminator baseband)', rate: 'required - sample rate (Hz)', baud: 'required - symbol rate', invert: 'optional - flip bit polarity (default false)' ) Simple mid-bit sampler with zero-crossing resync. Returns Array<0|1>.



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 221

public_class_method def self.nrz_slice(opts = {})
  samples = opts[:samples]
  rate    = opts[:rate].to_f
  baud    = opts[:baud].to_f
  invert  = opts[:invert]
  spb     = rate / baud
  return [] if spb < 2.0 || samples.empty?

  # DC-block then low-pass via short moving average (~1/4 symbol).
  lp_win = [(spb / 4.0).round, 1].max
  filt   = envelope_signed(samples: dc_block(samples: samples), window: lp_win)

  bits  = []
  phase = spb / 2.0
  prev  = filt.first.to_f
  filt.each do |v|
    # zero-crossing → resync to mid-symbol
    phase = spb / 2.0 if (prev.negative? && v >= 0) || (prev.positive? && v.negative?)
    phase -= 1.0
    if phase <= 0
      b = v.negative? ? 0 : 1
      b ^= 1 if invert
      bits << b
      phase += spb
    end
    prev = v
  end
  bits
end

.ook_pulses(opts = {}) ⇒ Object

Supported Method Parameters

pulses = PWN::SDR::Decoder::DSP.ook_pulses( iq: 'required - interleaved I/Q', rate:, min_us: 'optional - drop shorter pulses (default 20)' ) → Array of { level: 0|1, us: Float, samples: Int } run-length list.



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 850

public_class_method def self.ook_pulses(opts = {})
  iq     = opts[:iq]
  rate   = opts[:rate].to_f
  min_us = (opts[:min_us] || 20).to_f
  m2     = mag_sq(iq: iq)
  return [] if m2.length < 32

  # Adaptive threshold: 0.5·(floor + peak) on power domain
  sorted = m2.sort
  floor  = sorted[m2.length / 10] || m2.min
  peak   = sorted[(m2.length * 9) / 10] || m2.max
  thr    = floor + ((peak - floor) * 0.5)
  us_per = 1_000_000.0 / rate
  runs = []
  state = m2.first >= thr ? 1 : 0
  cnt = 0
  m2.each do |v|
    s = v >= thr ? 1 : 0
    if s == state
      cnt += 1
    else
      runs << { level: state, us: cnt * us_per, samples: cnt } if (cnt * us_per) >= min_us
      state = s
      cnt = 1
    end
  end
  runs << { level: state, us: cnt * us_per, samples: cnt } if (cnt * us_per) >= min_us
  runs
end

.process_iq(opts = {}) ⇒ Object

Contiguous IQ kernel; state is caller-owned, never shared across streams.

Supported Method Parameters

result = PWN::SDR::Decoder::DSP.process_iq(data:, format: :cu8, operation: :fm, state: {}, kf: 1.0, native: true) Returns { samples:, backend: }; state retains incomplete bytes and last IQ.

Raises:

  • (ArgumentError)


1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
# File 'lib/pwn/sdr/decoder/dsp.rb', line 1048

public_class_method def self.process_iq(opts = {})
  format = opts.fetch(:format, :cu8).to_sym
  operation = opts.fetch(:operation, :fm).to_sym
  width = { cu8: 2, cs16le: 4, f64: 16 }.fetch(format)
  raise ArgumentError, 'operation must be unpack, mag or fm' unless i[unpack mag fm].include?(operation)

  state = opts[:state] || {}
  data = state.fetch(:remainder, ''.b) + opts[:data].to_s.b
  complete = data.bytesize / width * width
  payload = data.byteslice(0, complete)
  kf = opts.fetch(:kf, 1.0).to_f
  if opts.fetch(:native, native) && PWN::FFI.available?(mod: :DSPNative)
    begin
      result = PWN::FFI::DSPNative.process_iq(data: payload, format: format, operation: operation, previous: state[:previous], kf: kf)
      state[:previous] = result[:previous] if result[:previous]
      state[:remainder] = data.byteslice(complete, data.bytesize - complete)
      return { samples: result[:samples], backend: :native }
    rescue StandardError
      # Native failures leave caller state untouched; retry in Ruby.
    end
  end
  iq = case format
       when :cu8 then payload.unpack('C*').map { |v| (v - 127.5) / 128.0 }
       when :cs16le then payload.unpack('s<*').map { |v| v / 32_768.0 }
       when :f64 then payload.unpack('d*')
       end
  previous = state[:previous]
  samples = case operation
            when :unpack then iq
            when :mag then iq.each_slice(2).map { |re, im| (re * re) + (im * im) }
            when :fm
              iq.each_slice(2).filter_map do |re, im|
                value = Math.atan2((im * previous[0]) - (re * previous[1]), (re * previous[0]) + (im * previous[1])) * kf if previous
                previous = [re, im]
                value
              end
            end
  state[:previous] = iq.last(2) unless iq.empty?
  state[:remainder] = data.byteslice(complete, data.bytesize - complete)
  { samples: samples, backend: :ruby }
end

.resample(opts = {}) ⇒ Object

Supported Method Parameters

out = PWN::SDR::Decoder::DSP.resample( samples: 'required - Array', src_rate: 'required - input sample rate (Hz)', dst_rate: 'required - output sample rate (Hz)' )



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 93

public_class_method def self.resample(opts = {})
  samples  = opts[:samples]
  src_rate = opts[:src_rate].to_f
  dst_rate = opts[:dst_rate].to_f
  return samples.dup if (src_rate - dst_rate).abs < 1e-6

  if native && PWN::FFI.available?(mod: :Liquid)
    begin
      # liquid rate = output/input
      return PWN::FFI::Liquid.resample(
        samples: samples,
        rate: dst_rate / src_rate
      )
    rescue StandardError
      # fall through to pure Ruby
    end
  end

  ratio = src_rate / dst_rate
  out_len = (samples.length / ratio).floor
  out = Array.new(out_len)
  i = 0
  while i < out_len
    pos  = i * ratio
    idx  = pos.floor
    frac = pos - idx
    a = samples[idx] || 0.0
    b = samples[idx + 1] || a
    out[i] = a + ((b - a) * frac)
    i += 1
  end
  out
end

.resample_iq(opts = {}) ⇒ Object

Supported Method Parameters

out = PWN::SDR::Decoder::DSP.resample_iq( iq: 'required - interleaved [I0,Q0,…] Array', src_rate: 'required - Hz', dst_rate: 'required - Hz' )



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 592

public_class_method def self.resample_iq(opts = {})
  iq  = opts[:iq]
  src = opts[:src_rate].to_f
  dst = opts[:dst_rate].to_f
  return iq.dup if (src - dst).abs < 1.0 || iq.empty?

  if native && PWN::FFI.available?(mod: :Liquid)
    begin
      return PWN::FFI::Liquid.resample_iq(iq: iq, rate: dst / src)
    rescue StandardError
      # fall through
    end
  end
  n_in  = iq.length / 2
  ratio = src / dst
  n_out = (n_in / ratio).floor
  out = Array.new(n_out * 2)
  i = 0
  while i < n_out
    pos  = i * ratio
    idx  = pos.floor
    frac = pos - idx
    2.times do |c|
      a = iq[(idx * 2) + c] || 0.0
      b = iq[((idx + 1) * 2) + c] || a
      out[(i * 2) + c] = a + ((b - a) * frac)
    end
    i += 1
  end
  out
end

.rms_dbfs(opts = {}) ⇒ Object

Supported Method Parameters

dbfs = PWN::SDR::Decoder::DSP.rms_dbfs(samples: Array)



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
# File 'lib/pwn/sdr/decoder/dsp.rb', line 406

public_class_method def self.rms_dbfs(opts = {})
  samples = opts[:samples]
  return -120.0 if samples.nil? || samples.empty?

  if native && PWN::FFI.available?(mod: :Volk) && samples.length >= 64
    begin
      # Σ x² via volk: scale-square in Ruby is still the bottleneck for
      # tiny buffers so keep the pure-Ruby path under 64 samples.
      sq = samples.map { |v| v * v }
      ms = PWN::FFI::Volk.accumulate(samples: sq) / samples.length
      return -120.0 if ms <= 0

      return 10.0 * Math.log10(ms)
    rescue StandardError
      # fall through
    end
  end

  ms = samples.sum { |v| v * v } / samples.length
  return -120.0 if ms <= 0

  10.0 * Math.log10(ms)
end

.slice_4fsk(opts = {}) ⇒ Object

Supported Method Parameters

dibits = PWN::SDR::Decoder::DSP.slice_4fsk( samples: 'required - real FM-discriminator baseband', rate:, baud: ) → Array<0..3> per symbol (4-level decision, adaptive thresholds). C4FM/4-GFSK maps +3 → 01, +1 → 00, −1 → 10, −3 → 11 in P25/DMR.



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
# File 'lib/pwn/sdr/decoder/dsp.rb', line 699

public_class_method def self.slice_4fsk(opts = {})
  samples = opts[:samples]
  rate    = opts[:rate].to_f
  baud    = opts[:baud].to_f
  spb     = rate / baud
  return [] if spb < 2.0 || samples.empty?

  lp   = envelope_signed(samples: dc_block(samples: samples), window: [(spb / 4.0).round, 1].max)
  nsym = (lp.length / spb).floor
  # sample mid-symbol values, then quantise into 4 levels
  vals = Array.new(nsym) { |i| lp[((i + 0.5) * spb).floor] || 0.0 }
  return [] if vals.empty?

  sorted = vals.sort
  lo = sorted[(nsym * 0.1).floor] || vals.min
  hi = sorted[(nsym * 0.9).floor] || vals.max
  step = (hi - lo) / 3.0
  step = 1e-9 if step.abs < 1e-9
  t_lo = lo + step
  t_hi = hi - step
  vals.map do |v|
    if v >= t_hi then 1        # +3
    elsif v >= 0 then 0        # +1
    elsif v >= t_lo then 2     # −1
    else 3                     # −3
    end
  end
end

.unpack_cs16le(opts = {}) ⇒ Object

Supported Method Parameters

iq = PWN::SDR::Decoder::DSP.unpack_cs16le( data: 'required - raw String of interleaved little-endian s16 I/Q' ) Returns interleaved Array [I0,Q0,I1,Q1,…] normalised ±1.0.



438
439
440
441
442
443
444
445
446
447
448
449
450
451
# File 'lib/pwn/sdr/decoder/dsp.rb', line 438

public_class_method def self.unpack_cs16le(opts = {})
  data = opts[:data].to_s
  return process_iq(data: data, format: :cs16le, operation: :unpack)[:samples] if native && (data.bytesize % 4).zero? && PWN::FFI.available?(mod: :DSPNative)

  if native && PWN::FFI.available?(mod: :Volk)
    begin
      return PWN::FFI::Volk.unpack_s16le(data: data)
    rescue StandardError
      # fall through
    end
  end
  norm = 1.0 / 32_768.0
  data.unpack('s<*').map { |v| v * norm }
end

.unpack_cu8(opts = {}) ⇒ Object

Supported Method Parameters

iq = PWN::SDR::Decoder::DSP.unpack_cu8( data: 'required - raw String of interleaved u8 I/Q (RTL-SDR)' ) Returns interleaved Array [I0,Q0,…] centred & normalised ±1.0.



459
460
461
462
463
464
465
# File 'lib/pwn/sdr/decoder/dsp.rb', line 459

public_class_method def self.unpack_cu8(opts = {})
  data = opts[:data].to_s
  return process_iq(data: data, format: :cu8, operation: :unpack)[:samples] if native && data.bytesize.even? && PWN::FFI.available?(mod: :DSPNative)

  norm = 1.0 / 128.0
  data.unpack('C*').map { |v| (v - 127.5) * norm }
end

.unpack_s16le(opts = {}) ⇒ Object

Supported Method Parameters

samples = PWN::SDR::Decoder::DSP.unpack_s16le( data: 'required - raw String of little-endian signed 16-bit PCM' )



73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/pwn/sdr/decoder/dsp.rb', line 73

public_class_method def self.unpack_s16le(opts = {})
  data = opts[:data].to_s
  if native && PWN::FFI.available?(mod: :Volk)
    begin
      return PWN::FFI::Volk.unpack_s16le(data: data)
    rescue StandardError
      # fall through to pure Ruby
    end
  end
  norm = 1.0 / 32_768.0
  data.unpack('s<*').map { |v| v * norm }
end

.whiten_lfsr(opts = {}) ⇒ Object

Supported Method Parameters

out = PWN::SDR::Decoder::DSP.whiten_lfsr( bytes: Array, poly: Integer, init: Integer, width: 7 ) Galois LFSR (MSB-first). BLE: poly 0x11 (x^7+x^4+1), init (ch|0x40).



823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
# File 'lib/pwn/sdr/decoder/dsp.rb', line 823

public_class_method def self.whiten_lfsr(opts = {})
  bytes = opts[:bytes]
  poly  = opts[:poly].to_i
  reg   = opts[:init].to_i
  w     = (opts[:width] || 7).to_i
  top   = 1 << (w - 1)
  out   = Array.new(bytes.length)
  bytes.each_with_index do |byte, bi|
    v = byte & 0xFF
    8.times do |i|
      msb = reg.anybits?(top) ? 1 : 0
      reg = ((reg << 1) & ((1 << w) - 1))
      reg ^= poly if msb == 1
      v ^= (msb << i)
    end
    out[bi] = v
  end
  out
end

.zadoff_chu(opts = {}) ⇒ Object

Supported Method Parameters

zc = PWN::SDR::Decoder::DSP.zadoff_chu(root:, n: 63) Returns interleaved [I0,Q0,…] Array. LTE PSS uses roots 25/29/34.



981
982
983
984
985
986
987
988
989
990
991
# File 'lib/pwn/sdr/decoder/dsp.rb', line 981

public_class_method def self.zadoff_chu(opts = {})
  u = opts[:root].to_i
  n = (opts[:n] || 63).to_i
  out = Array.new(n * 2)
  n.times do |k|
    ph = -Math::PI * u * k * (k + 1) / n
    out[k * 2]       = Math.cos(ph)
    out[(k * 2) + 1] = Math.sin(ph)
  end
  out
end