From 972a6d3e4d3b684fbadeb5cd046a8634ec24eb8c Mon Sep 17 00:00:00 2001 From: Arturs Artamonovs Date: Mon, 3 Feb 2025 22:31:45 +0000 Subject: iqconvert: converts from u8 to f32 without issues --- IQ/IQUtils.swift | 88 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 88 insertions(+) create mode 100644 IQ/IQUtils.swift (limited to 'IQ/IQUtils.swift') diff --git a/IQ/IQUtils.swift b/IQ/IQUtils.swift new file mode 100644 index 0000000..9d1b048 --- /dev/null +++ b/IQ/IQUtils.swift @@ -0,0 +1,88 @@ +// +// IQUtils.swift +// PrySDR +// +// Created by Jacky Jack on 21/01/2025. +// + +import Accelerate + +/// Convert from UInt8 to Float, naive implementation +/// - Parameters: +/// - arr: array of UInt8 +/// - Returns: Return floats -0.996...0.996 +/// +func cnvU8toFloat32(_ arr: [UInt8]) -> [Float32] { + + //let iq = IQ(size: 8, bits: 8, sign: false, complex: true) + + var out: [Float32] = .init(repeating: 0.0, count: arr.count) + + // 0..255 -> -0.996 ... 0.996 + // 0..127 -> -0.996 ... 0.0039 + // 128...255 -> 0.0039 ... 0.996 + for i in 0..= 128 { + out[i] = Float(arr[i]-128)/128.0 + } else { // + out[i] = Float(Int(arr[i])-128)/128.0 + }*/ + out[i] = (Float(arr[i])-127.5)/128.0 + } + + return out +} + +/// Convert from UInt8 to Float, naive implementation rtlsdr specfic +/// https://cgit.osmocom.org/gr-osmosdr/tree/lib/rtl/rtl_source_c.cc#n179 +/// - Parameters: +/// - arr: array of UInt8 +/// - Returns: Return floats -0.996...0.996 +/// +func cnvU8toFloat32_rtlsdr(_ arr: [UInt8]) -> [Float32] { + + //let iq = IQ(size: 8, bits: 8, sign: false, complex: true) + + var out: [Float32] = .init(repeating: 0.0, count: arr.count) + + // 0..255 -> -1.0 ... 1.0 + for i in 0..= 128 { + out[i] = Float(arr[i]-128)/128.0 + } else { // + out[i] = Float(Int(arr[i])-128)/128.0 + }*/ + out[i] = (Float(arr[i])-127.4)/128.0 + } + + return out +} + + +/// Convert from UInt8 to Float, using Accel framework +/// - Parameters: +/// - arr: array of UInt8 +/// - Returns: Return floats -1.0...1.0 +/// +func cnvU8toFloat32_accel(_ arr: [UInt8]) -> [Float32] { + var out: [Float32] = .init(repeating: 0.0, count: arr.count) + vDSP.convertElements(of: arr, to: &out) + out = vDSP.add(-127.5, out) + out = vDSP.divide(out, 128) + return out +} + +/// Convert from UInt8 to Float, using Accel framework specific to rtlsdr +/// - Parameters: +/// - arr: array of UInt8 +/// - Returns: Return floats -1.0...1.0 +/// +func cnvU8toFloat32_accel_rtlsdr(_ arr: [UInt8]) -> [Float32] { + var out: [Float32] = .init(repeating: 0.0, count: arr.count) + vDSP.convertElements(of: arr, to: &out) + out = vDSP.add(-127.4, out) + out = vDSP.divide(out, 128) + return out +} -- cgit v1.2.3