Compare commits

...

3 Commits

21 changed files with 2171 additions and 157 deletions

View File

@@ -0,0 +1,779 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*
* The transform kernels in this class are ported from the mixed radix complex FFT (cffti, cfftf and passf2/3/4/5)
* in JTransforms org.jtransforms.fft.FloatFFT_1D, which carries the following license:
*
* JTransforms
* Copyright (c) 2007 onward, Piotr Wendykier
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.github.dsheirer.dsp.fft;
/**
* Allocation-free mixed radix complex FFT for sizes that factor into 2, 3 and 5 only.
*
* This is a port of the JTransforms FloatFFT_1D mixed radix complex transform path. JTransforms allocates a new
* 2N float scratch array on every mixed radix transform, which creates significant garbage collection pressure when
* the transform runs at block rate (e.g. the polyphase channelizer IFFT). This implementation pre-allocates the
* scratch buffer once and reuses it for each transform.
*
* Results match JTransforms FloatFFT_1D complexForward() and complexInverse(): the forward transform uses the
* exp(-j...) kernel, the inverse uses exp(+j...), and the inverse optionally scales by 1/N. Twiddle factors are
* calculated in double precision, so results can differ from JTransforms in the least significant bits.
*
* Samples are interleaved complex: a[offset + 2k] = Re[k] and a[offset + 2k + 1] = Im[k] for 0 <= k < N.
*
* Note: this class is NOT thread-safe since it reuses an internal scratch buffer. Use one instance per thread.
*/
public class MixedRadixComplexFFT
{
private static final int[] FACTORS = {4, 2, 3, 5};
private static final int FORWARD = -1;
private static final int INVERSE = 1;
private final int mSize;
private final int[] mFactors;
private final float[] mTwiddles;
private final float[] mScratch;
private final float mScale;
/**
* Constructs an instance
* @param size of the transform in complex samples. Must be a positive value with no prime factors other than
* 2, 3 and 5.
* @throws IllegalArgumentException if the size is not supported
*/
public MixedRadixComplexFFT(int size)
{
if(!isSupported(size))
{
throw new IllegalArgumentException("Unsupported FFT size [" + size +
"] - size must be positive and have no prime factors other than 2, 3 and 5");
}
mSize = size;
mFactors = factorize(size);
mTwiddles = new float[2 * size + 2];
mScratch = new float[2 * size];
mScale = 1.0f / size;
calculateTwiddles();
}
/**
* Indicates if the size can be transformed by this class.
* @param size in complex samples
* @return true if the size is positive and has no prime factors other than 2, 3 and 5.
*/
public static boolean isSupported(int size)
{
if(size < 1)
{
return false;
}
int remainder = size;
for(int factor: new int[]{2, 3, 5})
{
while(remainder % factor == 0)
{
remainder /= factor;
}
}
return remainder == 1;
}
/**
* Size of this transform
* @return size in complex samples
*/
public int getSize()
{
return mSize;
}
/**
* Computes the forward DFT of the interleaved complex samples, in place. Equivalent to JTransforms
* FloatFFT_1D.complexForward(samples, offset).
* @param samples interleaved complex, with at least 2N values from the offset
* @param offset to the first sample
*/
public void forward(float[] samples, int offset)
{
transform(samples, offset, FORWARD);
}
/**
* Computes the forward DFT of the interleaved complex samples, in place.
* @param samples interleaved complex, with at least 2N values
*/
public void forward(float[] samples)
{
forward(samples, 0);
}
/**
* Computes the inverse DFT of the interleaved complex samples, in place. Equivalent to JTransforms
* FloatFFT_1D.complexInverse(samples, offset, scale).
* @param samples interleaved complex, with at least 2N values from the offset
* @param offset to the first sample
* @param scale true to scale the results by 1/N
*/
public void inverse(float[] samples, int offset, boolean scale)
{
transform(samples, offset, INVERSE);
if(scale && mSize > 1)
{
int end = offset + 2 * mSize;
for(int x = offset; x < end; x++)
{
samples[x] *= mScale;
}
}
}
/**
* Computes the inverse DFT of the interleaved complex samples, in place.
* @param samples interleaved complex, with at least 2N values
* @param scale true to scale the results by 1/N
*/
public void inverse(float[] samples, boolean scale)
{
inverse(samples, 0, scale);
}
/**
* Factors the size into the radix sequence used by the transform, ported from JTransforms cffti(). Radix 4 is
* preferred, then 2, 3 and 5, and a radix 2 factor is moved to the front of the sequence.
*/
private static int[] factorize(int size)
{
if(size == 1)
{
return new int[0];
}
int[] factors = new int[32];
int count = 0;
int remainder = size;
for(int factor: FACTORS)
{
while(remainder % factor == 0)
{
factors[count++] = factor;
remainder /= factor;
if(factor == 2 && count != 1)
{
System.arraycopy(factors, 0, factors, 1, count - 1);
factors[0] = 2;
}
}
}
if(remainder != 1)
{
throw new IllegalArgumentException("Unsupported FFT size [" + size + "]");
}
int[] result = new int[count];
System.arraycopy(factors, 0, result, 0, count);
return result;
}
/**
* Calculates the twiddle factor table, ported from JTransforms cffti() with the table offset removed and the
* angles calculated in double precision.
*/
private void calculateTwiddles()
{
if(mSize == 1)
{
return;
}
double angleIncrement = 2.0 * Math.PI / mSize;
int i = 1;
int l1 = 1;
for(int factor: mFactors)
{
int ld = 0;
int l2 = l1 * factor;
int ido = mSize / l2;
int idot = ido + ido + 2;
for(int j = 1; j < factor; j++)
{
mTwiddles[i - 1] = 1;
mTwiddles[i] = 0;
ld += l1;
int fi = 0;
double argld = ld * angleIncrement;
for(int ii = 4; ii <= idot; ii += 2)
{
i += 2;
fi++;
double arg = fi * argld;
mTwiddles[i - 1] = (float)Math.cos(arg);
mTwiddles[i] = (float)Math.sin(arg);
}
}
l1 = l2;
}
}
/**
* Performs the transform, ported from JTransforms cfftf() using the reusable scratch buffer.
* @param a samples
* @param offa offset to first sample
* @param isign -1 for forward and +1 for inverse
*/
private void transform(float[] a, int offa, int isign)
{
if(mSize == 1)
{
return;
}
float[] ch = mScratch;
int twon = 2 * mSize;
boolean inScratch = false;
int l1 = 1;
int iw = 0;
for(int factor: mFactors)
{
int l2 = factor * l1;
int idot = 2 * (mSize / l2);
switch(factor)
{
case 4:
if(inScratch)
{
passf4(idot, l1, ch, 0, a, offa, iw, isign);
}
else
{
passf4(idot, l1, a, offa, ch, 0, iw, isign);
}
break;
case 2:
if(inScratch)
{
passf2(idot, l1, ch, 0, a, offa, iw, isign);
}
else
{
passf2(idot, l1, a, offa, ch, 0, iw, isign);
}
break;
case 3:
if(inScratch)
{
passf3(idot, l1, ch, 0, a, offa, iw, isign);
}
else
{
passf3(idot, l1, a, offa, ch, 0, iw, isign);
}
break;
case 5:
if(inScratch)
{
passf5(idot, l1, ch, 0, a, offa, iw, isign);
}
else
{
passf5(idot, l1, a, offa, ch, 0, iw, isign);
}
break;
default:
throw new IllegalStateException("Unsupported radix: " + factor);
}
inScratch = !inScratch;
l1 = l2;
iw += (factor - 1) * idot;
}
if(inScratch)
{
System.arraycopy(ch, 0, a, offa, twon);
}
}
/**
* Radix 2 butterfly, ported from JTransforms passf2().
*/
private void passf2(final int ido, final int l1, final float[] in, final int in_off, final float[] out,
final int out_off, final int offset, final int isign)
{
final float[] wtable = mTwiddles;
int iw1 = offset;
int idx = ido * l1;
if(ido <= 2)
{
for(int k = 0; k < l1; k++)
{
int idx0 = k * ido;
int iidx1 = in_off + 2 * idx0;
int iidx2 = iidx1 + ido;
float a1r = in[iidx1];
float a1i = in[iidx1 + 1];
float a2r = in[iidx2];
float a2i = in[iidx2 + 1];
int oidx1 = out_off + idx0;
int oidx2 = oidx1 + idx;
out[oidx1] = a1r + a2r;
out[oidx1 + 1] = a1i + a2i;
out[oidx2] = a1r - a2r;
out[oidx2 + 1] = a1i - a2i;
}
}
else
{
for(int k = 0; k < l1; k++)
{
for(int i = 0; i < ido - 1; i += 2)
{
int idx0 = k * ido;
int iidx1 = in_off + i + 2 * idx0;
int iidx2 = iidx1 + ido;
float i1r = in[iidx1];
float i1i = in[iidx1 + 1];
float i2r = in[iidx2];
float i2i = in[iidx2 + 1];
int widx1 = i + iw1;
float w1r = wtable[widx1];
float w1i = isign * wtable[widx1 + 1];
float t1r = i1r - i2r;
float t1i = i1i - i2i;
int oidx1 = out_off + i + idx0;
int oidx2 = oidx1 + idx;
out[oidx1] = i1r + i2r;
out[oidx1 + 1] = i1i + i2i;
out[oidx2] = w1r * t1r - w1i * t1i;
out[oidx2 + 1] = w1r * t1i + w1i * t1r;
}
}
}
}
/**
* Radix 3 butterfly, ported from JTransforms passf3().
*/
private void passf3(final int ido, final int l1, final float[] in, final int in_off, final float[] out,
final int out_off, final int offset, final int isign)
{
final float taur = -0.5f;
final float taui = 0.866025403784438707610604524234076962f;
final float[] wtable = mTwiddles;
int iw1 = offset;
int iw2 = iw1 + ido;
final int idxt = l1 * ido;
if(ido == 2)
{
for(int k = 1; k <= l1; k++)
{
int iidx1 = in_off + (3 * k - 2) * ido;
int iidx2 = iidx1 + ido;
int iidx3 = iidx1 - ido;
float i1r = in[iidx1];
float i1i = in[iidx1 + 1];
float i2r = in[iidx2];
float i2i = in[iidx2 + 1];
float i3r = in[iidx3];
float i3i = in[iidx3 + 1];
float tr2 = i1r + i2r;
float cr2 = i3r + taur * tr2;
float ti2 = i1i + i2i;
float ci2 = i3i + taur * ti2;
float cr3 = isign * taui * (i1r - i2r);
float ci3 = isign * taui * (i1i - i2i);
int oidx1 = out_off + (k - 1) * ido;
int oidx2 = oidx1 + idxt;
int oidx3 = oidx2 + idxt;
out[oidx1] = i3r + tr2;
out[oidx1 + 1] = i3i + ti2;
out[oidx2] = cr2 - ci3;
out[oidx2 + 1] = ci2 + cr3;
out[oidx3] = cr2 + ci3;
out[oidx3 + 1] = ci2 - cr3;
}
}
else
{
for(int k = 1; k <= l1; k++)
{
int idx1 = in_off + (3 * k - 2) * ido;
int idx2 = out_off + (k - 1) * ido;
for(int i = 0; i < ido - 1; i += 2)
{
int iidx1 = i + idx1;
int iidx2 = iidx1 + ido;
int iidx3 = iidx1 - ido;
float a1r = in[iidx1];
float a1i = in[iidx1 + 1];
float a2r = in[iidx2];
float a2i = in[iidx2 + 1];
float a3r = in[iidx3];
float a3i = in[iidx3 + 1];
float tr2 = a1r + a2r;
float cr2 = a3r + taur * tr2;
float ti2 = a1i + a2i;
float ci2 = a3i + taur * ti2;
float cr3 = isign * taui * (a1r - a2r);
float ci3 = isign * taui * (a1i - a2i);
float dr2 = cr2 - ci3;
float dr3 = cr2 + ci3;
float di2 = ci2 + cr3;
float di3 = ci2 - cr3;
int widx1 = i + iw1;
int widx2 = i + iw2;
float w1r = wtable[widx1];
float w1i = isign * wtable[widx1 + 1];
float w2r = wtable[widx2];
float w2i = isign * wtable[widx2 + 1];
int oidx1 = i + idx2;
int oidx2 = oidx1 + idxt;
int oidx3 = oidx2 + idxt;
out[oidx1] = a3r + tr2;
out[oidx1 + 1] = a3i + ti2;
out[oidx2] = w1r * dr2 - w1i * di2;
out[oidx2 + 1] = w1r * di2 + w1i * dr2;
out[oidx3] = w2r * dr3 - w2i * di3;
out[oidx3 + 1] = w2r * di3 + w2i * dr3;
}
}
}
}
/**
* Radix 4 butterfly, ported from JTransforms passf4().
*/
private void passf4(final int ido, final int l1, final float[] in, final int in_off, final float[] out,
final int out_off, final int offset, final int isign)
{
final float[] wtable = mTwiddles;
int iw1 = offset;
int iw2 = iw1 + ido;
int iw3 = iw2 + ido;
int idx0 = l1 * ido;
if(ido == 2)
{
for(int k = 0; k < l1; k++)
{
int idxt1 = k * ido;
int iidx1 = in_off + 4 * idxt1 + 1;
int iidx2 = iidx1 + ido;
int iidx3 = iidx2 + ido;
int iidx4 = iidx3 + ido;
float i1i = in[iidx1 - 1];
float i1r = in[iidx1];
float i2i = in[iidx2 - 1];
float i2r = in[iidx2];
float i3i = in[iidx3 - 1];
float i3r = in[iidx3];
float i4i = in[iidx4 - 1];
float i4r = in[iidx4];
float ti1 = i1r - i3r;
float ti2 = i1r + i3r;
float tr4 = i4r - i2r;
float ti3 = i2r + i4r;
float tr1 = i1i - i3i;
float tr2 = i1i + i3i;
float ti4 = i2i - i4i;
float tr3 = i2i + i4i;
int oidx1 = out_off + idxt1;
int oidx2 = oidx1 + idx0;
int oidx3 = oidx2 + idx0;
int oidx4 = oidx3 + idx0;
out[oidx1] = tr2 + tr3;
out[oidx1 + 1] = ti2 + ti3;
out[oidx2] = tr1 + isign * tr4;
out[oidx2 + 1] = ti1 + isign * ti4;
out[oidx3] = tr2 - tr3;
out[oidx3 + 1] = ti2 - ti3;
out[oidx4] = tr1 - isign * tr4;
out[oidx4 + 1] = ti1 - isign * ti4;
}
}
else
{
for(int k = 0; k < l1; k++)
{
int idx1 = k * ido;
int idx2 = in_off + 1 + 4 * idx1;
for(int i = 0; i < ido - 1; i += 2)
{
int iidx1 = i + idx2;
int iidx2 = iidx1 + ido;
int iidx3 = iidx2 + ido;
int iidx4 = iidx3 + ido;
float i1i = in[iidx1 - 1];
float i1r = in[iidx1];
float i2i = in[iidx2 - 1];
float i2r = in[iidx2];
float i3i = in[iidx3 - 1];
float i3r = in[iidx3];
float i4i = in[iidx4 - 1];
float i4r = in[iidx4];
float ti1 = i1r - i3r;
float ti2 = i1r + i3r;
float ti3 = i2r + i4r;
float tr4 = i4r - i2r;
float tr1 = i1i - i3i;
float tr2 = i1i + i3i;
float ti4 = i2i - i4i;
float tr3 = i2i + i4i;
float cr3 = tr2 - tr3;
float ci3 = ti2 - ti3;
float cr2 = tr1 + isign * tr4;
float cr4 = tr1 - isign * tr4;
float ci2 = ti1 + isign * ti4;
float ci4 = ti1 - isign * ti4;
int widx1 = i + iw1;
int widx2 = i + iw2;
int widx3 = i + iw3;
float w1r = wtable[widx1];
float w1i = isign * wtable[widx1 + 1];
float w2r = wtable[widx2];
float w2i = isign * wtable[widx2 + 1];
float w3r = wtable[widx3];
float w3i = isign * wtable[widx3 + 1];
int oidx1 = out_off + i + idx1;
int oidx2 = oidx1 + idx0;
int oidx3 = oidx2 + idx0;
int oidx4 = oidx3 + idx0;
out[oidx1] = tr2 + tr3;
out[oidx1 + 1] = ti2 + ti3;
out[oidx2] = w1r * cr2 - w1i * ci2;
out[oidx2 + 1] = w1r * ci2 + w1i * cr2;
out[oidx3] = w2r * cr3 - w2i * ci3;
out[oidx3 + 1] = w2r * ci3 + w2i * cr3;
out[oidx4] = w3r * cr4 - w3i * ci4;
out[oidx4 + 1] = w3r * ci4 + w3i * cr4;
}
}
}
}
/**
* Radix 5 butterfly, ported from JTransforms passf5().
*/
private void passf5(final int ido, final int l1, final float[] in, final int in_off, final float[] out,
final int out_off, final int offset, final int isign)
{
final float tr11 = 0.309016994374947451262869435595348477f;
final float ti11 = 0.951056516295153531181938433292089030f;
final float tr12 = -0.809016994374947340240566973079694435f;
final float ti12 = 0.587785252292473248125759255344746634f;
final float[] wtable = mTwiddles;
int iw1 = offset;
int iw2 = iw1 + ido;
int iw3 = iw2 + ido;
int iw4 = iw3 + ido;
int idx0 = l1 * ido;
if(ido == 2)
{
for(int k = 1; k <= l1; ++k)
{
int iidx1 = in_off + (5 * k - 4) * ido + 1;
int iidx2 = iidx1 + ido;
int iidx3 = iidx1 - ido;
int iidx4 = iidx2 + ido;
int iidx5 = iidx4 + ido;
float i1i = in[iidx1 - 1];
float i1r = in[iidx1];
float i2i = in[iidx2 - 1];
float i2r = in[iidx2];
float i3i = in[iidx3 - 1];
float i3r = in[iidx3];
float i4i = in[iidx4 - 1];
float i4r = in[iidx4];
float i5i = in[iidx5 - 1];
float i5r = in[iidx5];
float ti5 = i1r - i5r;
float ti2 = i1r + i5r;
float ti4 = i2r - i4r;
float ti3 = i2r + i4r;
float tr5 = i1i - i5i;
float tr2 = i1i + i5i;
float tr4 = i2i - i4i;
float tr3 = i2i + i4i;
float cr2 = i3i + tr11 * tr2 + tr12 * tr3;
float ci2 = i3r + tr11 * ti2 + tr12 * ti3;
float cr3 = i3i + tr12 * tr2 + tr11 * tr3;
float ci3 = i3r + tr12 * ti2 + tr11 * ti3;
float cr5 = isign * (ti11 * tr5 + ti12 * tr4);
float ci5 = isign * (ti11 * ti5 + ti12 * ti4);
float cr4 = isign * (ti12 * tr5 - ti11 * tr4);
float ci4 = isign * (ti12 * ti5 - ti11 * ti4);
int oidx1 = out_off + (k - 1) * ido;
int oidx2 = oidx1 + idx0;
int oidx3 = oidx2 + idx0;
int oidx4 = oidx3 + idx0;
int oidx5 = oidx4 + idx0;
out[oidx1] = i3i + tr2 + tr3;
out[oidx1 + 1] = i3r + ti2 + ti3;
out[oidx2] = cr2 - ci5;
out[oidx2 + 1] = ci2 + cr5;
out[oidx3] = cr3 - ci4;
out[oidx3 + 1] = ci3 + cr4;
out[oidx4] = cr3 + ci4;
out[oidx4 + 1] = ci3 - cr4;
out[oidx5] = cr2 + ci5;
out[oidx5 + 1] = ci2 - cr5;
}
}
else
{
for(int k = 1; k <= l1; k++)
{
int idx1 = in_off + 1 + (k * 5 - 4) * ido;
int idx2 = out_off + (k - 1) * ido;
for(int i = 0; i < ido - 1; i += 2)
{
int iidx1 = i + idx1;
int iidx2 = iidx1 + ido;
int iidx3 = iidx1 - ido;
int iidx4 = iidx2 + ido;
int iidx5 = iidx4 + ido;
float i1i = in[iidx1 - 1];
float i1r = in[iidx1];
float i2i = in[iidx2 - 1];
float i2r = in[iidx2];
float i3i = in[iidx3 - 1];
float i3r = in[iidx3];
float i4i = in[iidx4 - 1];
float i4r = in[iidx4];
float i5i = in[iidx5 - 1];
float i5r = in[iidx5];
float ti5 = i1r - i5r;
float ti2 = i1r + i5r;
float ti4 = i2r - i4r;
float ti3 = i2r + i4r;
float tr5 = i1i - i5i;
float tr2 = i1i + i5i;
float tr4 = i2i - i4i;
float tr3 = i2i + i4i;
float cr2 = i3i + tr11 * tr2 + tr12 * tr3;
float ci2 = i3r + tr11 * ti2 + tr12 * ti3;
float cr3 = i3i + tr12 * tr2 + tr11 * tr3;
float ci3 = i3r + tr12 * ti2 + tr11 * ti3;
float cr5 = isign * (ti11 * tr5 + ti12 * tr4);
float ci5 = isign * (ti11 * ti5 + ti12 * ti4);
float cr4 = isign * (ti12 * tr5 - ti11 * tr4);
float ci4 = isign * (ti12 * ti5 - ti11 * ti4);
float dr3 = cr3 - ci4;
float dr4 = cr3 + ci4;
float di3 = ci3 + cr4;
float di4 = ci3 - cr4;
float dr5 = cr2 + ci5;
float dr2 = cr2 - ci5;
float di5 = ci2 - cr5;
float di2 = ci2 + cr5;
int widx1 = i + iw1;
int widx2 = i + iw2;
int widx3 = i + iw3;
int widx4 = i + iw4;
float w1r = wtable[widx1];
float w1i = isign * wtable[widx1 + 1];
float w2r = wtable[widx2];
float w2i = isign * wtable[widx2 + 1];
float w3r = wtable[widx3];
float w3i = isign * wtable[widx3 + 1];
float w4r = wtable[widx4];
float w4i = isign * wtable[widx4 + 1];
int oidx1 = i + idx2;
int oidx2 = oidx1 + idx0;
int oidx3 = oidx2 + idx0;
int oidx4 = oidx3 + idx0;
int oidx5 = oidx4 + idx0;
out[oidx1] = i3i + tr2 + tr3;
out[oidx1 + 1] = i3r + ti2 + ti3;
out[oidx2] = w1r * dr2 - w1i * di2;
out[oidx2 + 1] = w1r * di2 + w1i * dr2;
out[oidx3] = w2r * dr3 - w2i * di3;
out[oidx3 + 1] = w2r * di3 + w2i * dr3;
out[oidx4] = w3r * dr4 - w3i * di4;
out[oidx4 + 1] = w3r * di4 + w3i * dr4;
out[oidx5] = w4r * dr5 - w4i * di5;
out[oidx5 + 1] = w4r * di5 + w4i * dr5;
}
}
}
}
}

View File

@@ -18,6 +18,7 @@
*/
package io.github.dsheirer.dsp.filter.channelizer;
import io.github.dsheirer.dsp.fft.MixedRadixComplexFFT;
import io.github.dsheirer.dsp.filter.FilterFactory;
import io.github.dsheirer.dsp.filter.design.FilterDesignException;
import io.github.dsheirer.sample.complex.InterleavedComplexSamples;
@@ -27,7 +28,6 @@ import java.util.Arrays;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import org.apache.commons.math3.util.FastMath;
import org.jtransforms.fft.FloatFFT_1D;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -85,7 +85,8 @@ public class ComplexPolyphaseChannelizerM2 extends AbstractComplexPolyphaseChann
//Sized to process 40 times per second
private IFFTProcessorDispatcher mIFFTProcessorDispatcher = new IFFTProcessorDispatcher(25);
private FloatFFT_1D mFFT;
//Allocation-free IFFT. Only used by the IFFT processor dispatcher thread since it reuses a scratch buffer.
private MixedRadixComplexFFT mFFT;
private ChannelDFT mChannelDFT;
private float[] mInlineSamples;
private float[] mInlineFilter;
@@ -453,7 +454,7 @@ public class ComplexPolyphaseChannelizerM2 extends AbstractComplexPolyphaseChann
private void init(float[] coefficients)
{
int channelCount = getChannelCount();
mFFT = new FloatFFT_1D(channelCount);
mFFT = new MixedRadixComplexFFT(channelCount);
mChannelDFT = ChannelDFTFactory.getChannelDFT(channelCount);
int bufferLength = getSubChannelCount() * mTapsPerChannel;
mSamplesPerBlock = channelCount; //Same as subChannelCount / 2
@@ -505,7 +506,7 @@ public class ComplexPolyphaseChannelizerM2 extends AbstractComplexPolyphaseChann
for(int offset = 0; offset < samples.length; offset += blockLength)
{
//Rotate each of the channels to the correct phase using the IFFT
mFFT.complexInverse(samples, offset, true);
mFFT.inverse(samples, offset, true);
}
}

View File

@@ -21,12 +21,14 @@ package io.github.dsheirer.gui.preference.record;
import io.github.dsheirer.preference.UserPreferences;
import io.github.dsheirer.preference.record.RecordPreference;
import io.github.dsheirer.record.BasebandRecordFormat;
import io.github.dsheirer.record.RecordFormat;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
@@ -43,6 +45,7 @@ public class RecordPreferenceEditor extends HBox
private RecordPreference mRecordPreference;
private GridPane mEditorPane;
private ComboBox<RecordFormat> mRecordFormatComboBox;
private ComboBox<BasebandRecordFormat> mBasebandRecordFormatComboBox;
public RecordPreferenceEditor(UserPreferences userPreferences)
{
@@ -64,11 +67,39 @@ public class RecordPreferenceEditor extends HBox
mEditorPane.add(label, 0, 0);
mEditorPane.add(getRecordFormatComboBox(), 1, 0);
Label basebandLabel = new Label("Baseband I/Q Recording Format:");
mEditorPane.add(basebandLabel, 0, 1);
mEditorPane.add(getBasebandRecordFormatComboBox(), 1, 1);
}
return mEditorPane;
}
/**
* Baseband (tuner and channel I/Q) recording file format selector
*/
private ComboBox<BasebandRecordFormat> getBasebandRecordFormatComboBox()
{
if(mBasebandRecordFormatComboBox == null)
{
mBasebandRecordFormatComboBox = new ComboBox<>();
mBasebandRecordFormatComboBox.getItems().addAll(BasebandRecordFormat.values());
mBasebandRecordFormatComboBox.getSelectionModel().select(mRecordPreference.getBasebandRecordFormat());
mBasebandRecordFormatComboBox.setTooltip(new Tooltip("File format for tuner and channel baseband " +
"I/Q recordings. Applies to recordings started after the change."));
mBasebandRecordFormatComboBox.getSelectionModel().selectedItemProperty()
.addListener((observable, oldValue, newValue) -> {
if(newValue != null)
{
mRecordPreference.setBasebandRecordFormat(newValue);
}
});
}
return mBasebandRecordFormatComboBox;
}
private ComboBox<RecordFormat> getRecordFormatComboBox()
{
if(mRecordFormatComboBox == null)

View File

@@ -50,6 +50,13 @@ public class NXDNTalkgroupIdentifier extends TalkgroupIdentifier
return Protocol.NXDN;
}
@Override
public boolean isValid()
{
//NXDN conventional repeaters use a value of zero for the TO talkgroup value.
return getValue() >= 0;
}
/**
* Indicates if the identifier is for a Type-D system.
*/

View File

@@ -21,6 +21,7 @@ package io.github.dsheirer.preference.record;
import io.github.dsheirer.preference.Preference;
import io.github.dsheirer.preference.PreferenceType;
import io.github.dsheirer.record.BasebandRecordFormat;
import io.github.dsheirer.record.RecordFormat;
import io.github.dsheirer.sample.Listener;
import org.slf4j.Logger;
@@ -35,9 +36,12 @@ public class RecordPreference extends Preference
{
private static final String PREFERENCE_KEY_AUDIO_RECORD_FORMAT = "audio.record.format";
private static final RecordFormat DEFAULT_RECORD_FORMAT = RecordFormat.MP3;
private static final String PREFERENCE_KEY_BASEBAND_RECORD_FORMAT = "baseband.record.format";
private static final BasebandRecordFormat DEFAULT_BASEBAND_RECORD_FORMAT = BasebandRecordFormat.WAVE;
private final static Logger mLog = LoggerFactory.getLogger(RecordPreference.class);
private Preferences mPreferences = Preferences.userNodeForPackage(RecordPreference.class);
private RecordFormat mAudioRecordFormat;
private BasebandRecordFormat mBasebandRecordFormat;
/**
* Constructs this preference with an update listener
@@ -90,4 +94,41 @@ public class RecordPreference extends Preference
mPreferences.put(PREFERENCE_KEY_AUDIO_RECORD_FORMAT, audioRecordFormat.name());
notifyPreferenceUpdated();
}
/**
* Baseband (complex I/Q) recording file format for tuner and channel baseband recordings.
*/
public BasebandRecordFormat getBasebandRecordFormat()
{
if(mBasebandRecordFormat == null)
{
try
{
String format = mPreferences.get(PREFERENCE_KEY_BASEBAND_RECORD_FORMAT,
DEFAULT_BASEBAND_RECORD_FORMAT.name());
mBasebandRecordFormat = BasebandRecordFormat.valueOf(format);
}
catch(Exception e)
{
mLog.error("Error parsing baseband record format preference", e);
}
if(mBasebandRecordFormat == null)
{
mBasebandRecordFormat = DEFAULT_BASEBAND_RECORD_FORMAT;
}
}
return mBasebandRecordFormat;
}
/**
* Sets the baseband (complex I/Q) recording file format
*/
public void setBasebandRecordFormat(BasebandRecordFormat basebandRecordFormat)
{
mBasebandRecordFormat = basebandRecordFormat;
mPreferences.put(PREFERENCE_KEY_BASEBAND_RECORD_FORMAT, basebandRecordFormat.name());
notifyPreferenceUpdated();
}
}

View File

@@ -0,0 +1,60 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.record;
/**
* File formats for baseband (complex I/Q sample) recordings.
*/
public enum BasebandRecordFormat
{
/**
* sdrtrunk wave format: 2-channel, 16-bit PCM wave file with frequency in the file name.
*/
WAVE("sdrtrunk (.wav)", ".wav"),
/**
* SDRSharp raw I/Q format: headerless, interleaved 16-bit little-endian I/Q samples with the start time,
* tuner type, center frequency and sample rate encoded in the file name.
*/
SDRSHARP_IQ("SDRSharp (.iq)", ".iq");
private final String mLabel;
private final String mExtension;
BasebandRecordFormat(String label, String extension)
{
mLabel = label;
mExtension = extension;
}
/**
* File extension, including the leading period.
*/
public String getExtension()
{
return mExtension;
}
@Override
public String toString()
{
return mLabel;
}
}

View File

@@ -32,10 +32,14 @@ import io.github.dsheirer.record.wave.IRecordingStatusListener;
import io.github.dsheirer.record.wave.NativeBufferWaveRecorder;
import io.github.dsheirer.source.config.SourceConfigTuner;
import io.github.dsheirer.source.config.SourceConfigTunerMultipleFrequency;
import io.github.dsheirer.source.wave.SDRSharpIQRecording;
import io.github.dsheirer.util.StringUtils;
import io.github.dsheirer.util.TimeStamp;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@@ -46,6 +50,12 @@ public class RecorderFactory
{
public static final float BASEBAND_SAMPLE_RATE = 25000.0f; //Default sample rate - source can override
/**
* Tuner type token used in SDRSharp (.iq) file names for channel baseband recordings, since a channel is a
* down-converted (decimated) slice of a tuner's spectrum rather than a tuner's raw output.
*/
public static final String CHANNEL_TUNER_TYPE = "SDRTRUNK";
/**
* Creates recorder modules based on the channel configuration details
* @param userPreferences
@@ -177,31 +187,92 @@ public class RecorderFactory
}
/**
* Constructs a baseband recorder for use in a processing chain.
* Constructs a channel baseband recorder for use in a processing chain, using the user's preferred baseband
* recording format.
* @param channelName for the file name
* @param frequency of the channel
* @param userPreferences for the recording directory and baseband record format
*/
public static ComplexSamplesWaveRecorder getBasebandRecorder(String channelName, long frequency, UserPreferences userPreferences)
{
BasebandRecordFormat format = userPreferences.getRecordPreference().getBasebandRecordFormat();
Path directory = getRecordingBasePath(userPreferences);
String label = StringUtils.replaceIllegalCharacters(channelName);
if(format == BasebandRecordFormat.SDRSHARP_IQ)
{
return new ComplexSamplesWaveRecorder(BASEBAND_SAMPLE_RATE, format,
sampleRate -> getIQRecordingPath(directory, label, CHANNEL_TUNER_TYPE, frequency, sampleRate));
}
StringBuilder sb = new StringBuilder();
sb.append(getRecordingBasePath(userPreferences));
sb.append(directory);
sb.append(File.separator);
sb.append(TimeStamp.getTimeStamp("_"));
sb.append("_");
sb.append(frequency);
sb.append("_");
sb.append(StringUtils.replaceIllegalCharacters(channelName)).append("_baseband");
sb.append(label).append("_baseband");
return new ComplexSamplesWaveRecorder(BASEBAND_SAMPLE_RATE, sb.toString());
}
/**
* Constructs a baseband recorder for use in a processing chain.
* Constructs a tuner baseband recorder, using the user's preferred baseband recording format.
* @param tunerName (e.g. tuner class AIRSPY) used in the file name
* @param frequency tuner center frequency
* @param userPreferences for the recording directory and baseband record format
* @param statusListener to receive recording status updates
*/
public static NativeBufferWaveRecorder getTunerRecorder(String channelName, UserPreferences userPreferences,
public static NativeBufferWaveRecorder getTunerRecorder(String tunerName, long frequency,
UserPreferences userPreferences,
IRecordingStatusListener statusListener)
{
BasebandRecordFormat format = userPreferences.getRecordPreference().getBasebandRecordFormat();
Path directory = getRecordingBasePath(userPreferences);
String tuner = StringUtils.replaceIllegalCharacters(tunerName);
if(format == BasebandRecordFormat.SDRSHARP_IQ)
{
return new NativeBufferWaveRecorder(BASEBAND_SAMPLE_RATE, format,
sampleRate -> getIQRecordingPath(directory, null, tuner, frequency, sampleRate), statusListener);
}
StringBuilder sb = new StringBuilder();
sb.append(getRecordingBasePath(userPreferences));
sb.append(File.separator).append(StringUtils.replaceIllegalCharacters(channelName)).append("_baseband");
sb.append(directory);
sb.append(File.separator).append(tuner).append("_").append(frequency).append("_baseband");
return new NativeBufferWaveRecorder(BASEBAND_SAMPLE_RATE, sb.toString(), statusListener);
}
/**
* Creates a unique SDRSharp compatible (.iq) recording file path, time stamped with the current time. If the
* file already exists, a version suffix is appended to the label to keep the file name parseable.
* @param directory for the recording
* @param label optional label (e.g. channel name)
* @param tunerType for the file name
* @param frequency center frequency
* @param sampleRate of the recording
* @return unique path
* @throws IOException if a unique path can't be created
*/
static Path getIQRecordingPath(Path directory, String label, String tunerType, long frequency, double sampleRate)
throws IOException
{
LocalDateTime now = LocalDateTime.now();
Path path = directory.resolve(SDRSharpIQRecording.createFileName(now, label, tunerType, frequency, sampleRate));
for(int version = 2; Files.exists(path); version++)
{
if(version > 20)
{
throw new IOException("Unable to create a unique file name for recording - exceeded 20 versioning attempts");
}
String versionedLabel = (label == null || label.isBlank()) ? "v" + version : label + "-v" + version;
path = directory.resolve(SDRSharpIQRecording.createFileName(now, versionedLabel, tunerType, frequency,
sampleRate));
}
return path;
}
}

View File

@@ -1,6 +1,6 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2025 Dennis Sheirer
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
@@ -19,6 +19,7 @@
package io.github.dsheirer.record.wave;
import io.github.dsheirer.module.Module;
import io.github.dsheirer.record.BasebandRecordFormat;
import io.github.dsheirer.sample.ConversionUtils;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.ComplexSamples;
@@ -37,23 +38,46 @@ import org.slf4j.LoggerFactory;
import javax.sound.sampled.AudioFormat;
/**
* WAVE audio recorder module for recording complex (I&Q) samples to a wave file
* Baseband recorder module for recording complex (I&Q) samples to a wave (.wav) or SDRSharp raw I/Q (.iq) file.
*
* The recording file is created when the first sample buffer arrives so that the file name reflects the current
* sample rate and no empty file is left behind when a sample rate change restarts the recorder.
*/
public class ComplexSamplesWaveRecorder extends Module implements IComplexSamplesListener,
Listener<ComplexSamples>, ISourceEventListener
{
private final static Logger mLog = LoggerFactory.getLogger(ComplexSamplesWaveRecorder.class);
private Dispatcher<ComplexSamples> mBufferProcessor = new Dispatcher<>("sdrtrunk complex wave recorder", 250);
private Dispatcher<ComplexSamples> mBufferProcessor = new Dispatcher<>("sdrtrunk complex baseband recorder", 250);
private AtomicBoolean mRunning = new AtomicBoolean();
private BufferWaveWriter mWriter;
private String mFilePrefix;
private final Object mWriterLock = new Object();
private final BasebandRecordFormat mRecordFormat;
private final IRecordingPathProvider mPathProvider;
private IBasebandRecordingWriter mWriter;
private Path mFile;
private AudioFormat mAudioFormat;
/**
* Constructs a wave format recorder.
* @param sampleRate initial sample rate
* @param filePrefix full path and file name, without the .wav extension
*/
public ComplexSamplesWaveRecorder(float sampleRate, String filePrefix)
{
mFilePrefix = filePrefix;
this(sampleRate, BasebandRecordFormat.WAVE, rate -> Paths.get(filePrefix + BasebandRecordFormat.WAVE.getExtension()));
}
/**
* Constructs an instance
* @param sampleRate initial sample rate
* @param recordFormat for the recording file
* @param pathProvider to provide the recording file path each time a new recording file is created.
*/
public ComplexSamplesWaveRecorder(float sampleRate, BasebandRecordFormat recordFormat,
IRecordingPathProvider pathProvider)
{
mRecordFormat = recordFormat;
mPathProvider = pathProvider;
setSampleRate(sampleRate);
}
@@ -71,6 +95,9 @@ public class ComplexSamplesWaveRecorder extends Module implements IComplexSample
}
}
/**
* Current recording file or null if a recording file has not yet been created.
*/
public Path getFile()
{
return mFile;
@@ -80,22 +107,8 @@ public class ComplexSamplesWaveRecorder extends Module implements IComplexSample
{
if(mRunning.compareAndSet(false, true))
{
try
{
StringBuilder sb = new StringBuilder();
sb.append(mFilePrefix);
sb.append(".wav");
mFile = Paths.get(sb.toString());
mWriter = new BufferWaveWriter(mAudioFormat, mFile);
mBufferProcessor.setListener(mWriter);
mBufferProcessor.start();
}
catch(IOException io)
{
mLog.error("Error starting complex baseband recorder", io);
}
mBufferProcessor.setListener(this::write);
mBufferProcessor.start();
}
}
@@ -109,26 +122,7 @@ public class ComplexSamplesWaveRecorder extends Module implements IComplexSample
mBufferProcessor.setListener(null);
}
if(mWriter != null)
{
//Thread this operation so that it doesn't tie up the calling thread. The wave writer
//close method will also rename the file and this can sometimes take a few seconds.
ThreadPool.CACHED.submit(new Runnable()
{
@Override
public void run()
{
try
{
mWriter.close();
}
catch(IOException ioe)
{
mLog.error("Error closing baseband I/Q recorder", ioe);
}
}
});
}
closeWriter();
}
}
@@ -142,26 +136,75 @@ public class ComplexSamplesWaveRecorder extends Module implements IComplexSample
mBufferProcessor.setListener(null);
}
if(mWriter != null)
closeWriter();
}
}
/**
* Closes the current writer on a separate thread so that it doesn't tie up the calling thread.
*/
private void closeWriter()
{
IBasebandRecordingWriter writer;
synchronized(mWriterLock)
{
writer = mWriter;
mWriter = null;
}
if(writer != null)
{
ThreadPool.CACHED.submit(() ->
{
//Thread this operation so that it doesn't tie up the calling thread. The wave writer
//close method will also rename the file and this can sometimes take a few seconds.
ThreadPool.CACHED.submit(new Runnable()
try
{
@Override
public void run()
{
try
{
mWriter.close();
}
catch(IOException ioe)
{
mLog.error("Error closing baseband I/Q recorder", ioe);
}
}
});
writer.close();
}
catch(IOException ioe)
{
mLog.error("Error closing baseband I/Q recorder", ioe);
}
});
}
}
/**
* Writes the samples to the recording, creating the recording file on first use. Invoked on the dispatcher
* thread.
*/
private void write(ComplexSamples complexSamples)
{
boolean error = false;
synchronized(mWriterLock)
{
if(!mRunning.get())
{
return;
}
try
{
if(mWriter == null)
{
mFile = mPathProvider.getPath(mAudioFormat.getSampleRate());
mWriter = IBasebandRecordingWriter.create(mRecordFormat, mAudioFormat, mFile);
}
mWriter.writeData(ConversionUtils.convertToSigned16BitSamples(complexSamples));
}
catch(IOException ioe)
{
mLog.error("IOException while writing I/Q buffers to baseband recorder [" + mFile +
"] - stopping recorder", ioe);
error = true;
}
}
if(error)
{
stop();
}
}
@@ -186,49 +229,14 @@ public class ComplexSamplesWaveRecorder extends Module implements IComplexSample
@Override
public Listener<SourceEvent> getSourceEventListener()
{
return new Listener<SourceEvent>()
return sourceEvent ->
{
@Override
public void receive(SourceEvent sourceEvent)
switch(sourceEvent.getEvent())
{
switch(sourceEvent.getEvent())
{
case NOTIFICATION_SAMPLE_RATE_CHANGE:
setSampleRate(sourceEvent.getValue().floatValue());
break;
}
case NOTIFICATION_SAMPLE_RATE_CHANGE:
setSampleRate(sourceEvent.getValue().floatValue());
break;
}
};
}
/**
* Wave writer implementation for complex buffers delivered from buffer processor
*/
public class BufferWaveWriter extends WaveWriter implements Listener<ComplexSamples>
{
public BufferWaveWriter(AudioFormat format, Path file) throws IOException
{
super(format, file);
}
@Override
public void receive(ComplexSamples complexSamples)
{
boolean error = false;
if(!error)
{
try
{
mWriter.writeData(ConversionUtils.convertToSigned16BitSamples(complexSamples));
}
catch(IOException ioe)
{
mLog.error("IOException while writing I/Q buffers to wave recorder - stopping recorder", ioe);
error = true;
stop();
}
}
}
}
}

View File

@@ -0,0 +1,62 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.record.wave;
import io.github.dsheirer.record.BasebandRecordFormat;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.file.Path;
import javax.sound.sampled.AudioFormat;
/**
* Writer for baseband (complex I/Q) sample recordings.
*/
public interface IBasebandRecordingWriter extends AutoCloseable
{
/**
* Writes the buffer contents to the recording. Assumes the buffer is full, with the first byte at position 0
* and samples are interleaved, signed 16-bit little-endian I/Q.
*/
void writeData(ByteBuffer buffer) throws IOException;
/**
* Closes the recording.
*/
@Override
void close() throws IOException;
/**
* Creates a writer for the specified format.
* @param format of the recording file
* @param audioFormat describing the sample rate and sample size (2-channel, 16-bit)
* @param path for the recording file
* @return opened writer
* @throws IOException if the file can't be created
*/
static IBasebandRecordingWriter create(BasebandRecordFormat format, AudioFormat audioFormat, Path path)
throws IOException
{
return switch(format)
{
case SDRSHARP_IQ -> new IQWriter(path);
case WAVE -> new WaveWriter(audioFormat, path);
};
}
}

View File

@@ -0,0 +1,76 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.record.wave;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import org.apache.commons.lang3.Validate;
/**
* Writer for SDRSharp compatible raw I/Q (.iq) recordings: headerless, interleaved, signed 16-bit little-endian
* I/Q samples. Recording metadata (start time, tuner, frequency and sample rate) is carried in the file name.
*
* @see io.github.dsheirer.source.wave.SDRSharpIQRecording
*/
public class IQWriter implements IBasebandRecordingWriter
{
private final Path mFile;
private final FileChannel mFileChannel;
/**
* Constructs an instance and creates the (new) file.
* @param file to create
* @throws IOException if the file already exists or can't be created
*/
public IQWriter(Path file) throws IOException
{
Validate.notNull(file, "File cannot be null");
mFile = file;
mFileChannel = FileChannel.open(file, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW);
}
public Path getFile()
{
return mFile;
}
@Override
public void writeData(ByteBuffer buffer) throws IOException
{
buffer.position(0);
while(buffer.hasRemaining())
{
mFileChannel.write(buffer);
}
}
@Override
public void close() throws IOException
{
if(mFileChannel.isOpen())
{
mFileChannel.force(true);
mFileChannel.close();
}
}
}

View File

@@ -0,0 +1,38 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.record.wave;
import java.io.IOException;
import java.nio.file.Path;
/**
* Provides the file path for a new baseband recording file. Invoked each time a recorder creates a new file
* (start, sample rate change, or file size rollover) so that time-stamped and sample-rate-bearing file names are
* current.
*/
@FunctionalInterface
public interface IRecordingPathProvider
{
/**
* @param sampleRate of the recording
* @return path for the new recording file
* @throws IOException if a unique path can't be determined
*/
Path getPath(float sampleRate) throws IOException;
}

View File

@@ -20,6 +20,7 @@ package io.github.dsheirer.record.wave;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.module.Module;
import io.github.dsheirer.record.BasebandRecordFormat;
import io.github.dsheirer.sample.ConversionUtils;
import io.github.dsheirer.sample.Listener;
import io.github.dsheirer.sample.complex.InterleavedComplexSamples;
@@ -50,8 +51,9 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
private Dispatcher<INativeBuffer> mBufferProcessor = new Dispatcher<>("sdrtrunk native buffer wave recorder", 250);
private AtomicBoolean mRunning = new AtomicBoolean();
private NativeBufferWaveWriter mWriter;
private String mFilePrefix;
private NativeBufferWriter mWriter;
private final BasebandRecordFormat mRecordFormat;
private final IRecordingPathProvider mPathProvider;
private AudioFormat mAudioFormat;
private IRecordingStatusListener mStatusListener;
private String mFilePath;
@@ -59,9 +61,30 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
private long mLastReportedSize = 0;
private int mRecordingCount = 0;
/**
* Constructs a wave format recorder.
* @param sampleRate initial sample rate
* @param filePrefix full path and file name prefix. A timestamp and .wav extension are appended to each file.
* @param statusListener to receive recording status updates
*/
public NativeBufferWaveRecorder(float sampleRate, String filePrefix, IRecordingStatusListener statusListener)
{
mFilePrefix = filePrefix;
this(sampleRate, BasebandRecordFormat.WAVE, rate -> Paths.get(filePrefix + "_" +
TimeStamp.getTimeStamp("_") + BasebandRecordFormat.WAVE.getExtension()), statusListener);
}
/**
* Constructs an instance
* @param sampleRate initial sample rate
* @param recordFormat for the recording files
* @param pathProvider to provide the file path each time a new recording file is created (start or rollover)
* @param statusListener to receive recording status updates
*/
public NativeBufferWaveRecorder(float sampleRate, BasebandRecordFormat recordFormat,
IRecordingPathProvider pathProvider, IRecordingStatusListener statusListener)
{
mRecordFormat = recordFormat;
mPathProvider = pathProvider;
mStatusListener = statusListener;
setSampleRate(sampleRate);
}
@@ -80,14 +103,14 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
}
}
private String getFileName()
/**
* Creates a new writer for the next recording file and updates the current file path.
*/
private NativeBufferWriter createWriter() throws IOException
{
StringBuilder sb = new StringBuilder();
sb.append(mFilePrefix);
sb.append("_");
sb.append(TimeStamp.getTimeStamp("_"));
sb.append(".wav");
return sb.toString();
Path path = mPathProvider.getPath(mAudioFormat.getSampleRate());
mFilePath = path.toString();
return new NativeBufferWriter(IBasebandRecordingWriter.create(mRecordFormat, mAudioFormat, path));
}
public void start()
@@ -100,8 +123,7 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
try
{
mFilePath = getFileName();
mWriter = new NativeBufferWaveWriter(mAudioFormat, Paths.get(mFilePath));
mWriter = createWriter();
mBufferProcessor.setListener(mWriter);
mStatusListener.update(mRecordingCount, mFilePath, 0);
mBufferProcessor.start();
@@ -135,8 +157,7 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
try
{
mFilePath = getFileName();
mWriter = new NativeBufferWaveWriter(mAudioFormat, Paths.get(mFilePath));
mWriter = createWriter();
mBufferProcessor.setListener(mWriter);
mStatusListener.update(++mRecordingCount, mFilePath, 0);
}
@@ -158,7 +179,9 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
mBufferProcessor.setListener(null);
}
if(mWriter != null)
NativeBufferWriter writer = mWriter;
if(writer != null)
{
//Thread this operation so that it doesn't tie up the calling thread. The wave writer
//close method will also rename the file and this can sometimes take a few seconds.
@@ -166,7 +189,7 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
{
try
{
mWriter.close();
writer.close();
}
catch(IOException ioe)
{
@@ -212,13 +235,21 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
}
/**
* Wave writer implementation for complex samples delivered from buffer processor
* Writer for complex samples delivered from buffer processor
*/
public class NativeBufferWaveWriter extends WaveWriter implements Listener<INativeBuffer>
public class NativeBufferWriter implements Listener<INativeBuffer>, AutoCloseable
{
public NativeBufferWaveWriter(AudioFormat format, Path file) throws IOException
private final IBasebandRecordingWriter mBasebandWriter;
public NativeBufferWriter(IBasebandRecordingWriter basebandWriter)
{
super(format, file);
mBasebandWriter = basebandWriter;
}
@Override
public void close() throws IOException
{
mBasebandWriter.close();
}
@Override
@@ -239,7 +270,8 @@ public class NativeBufferWaveRecorder extends Module implements Listener<INative
rollRecording();
}
mWriter.writeData(data);
//Write to the current writer, which changes after a rollover
mWriter.mBasebandWriter.writeData(data);
mCurrentSize += data.array().length;
if(mCurrentSize > (mLastReportedSize + STATUS_UPDATE_BYTE_INTERVAL))

View File

@@ -35,7 +35,7 @@ import org.slf4j.LoggerFactory;
import javax.sound.sampled.AudioFormat;
public class WaveWriter implements AutoCloseable
public class WaveWriter implements IBasebandRecordingWriter
{
private final static Logger mLog = LoggerFactory.getLogger(WaveWriter.class);

View File

@@ -749,7 +749,7 @@ public abstract class TunerController implements Tunable, ISourceEventProcessor,
{
if(!isRecording())
{
mRecorder = RecorderFactory.getTunerRecorder(prefix + "_" + getFrequency(), userPreferences, statusListener);
mRecorder = RecorderFactory.getTunerRecorder(prefix, getFrequency(), userPreferences, statusListener);
mRecorder.setSampleRate((float)getSampleRate());
mRecorder.start();
addBufferListener(mRecorder);

View File

@@ -24,6 +24,7 @@ import io.github.dsheirer.properties.SystemProperties;
import io.github.dsheirer.source.tuner.configuration.TunerConfigurationManager;
import io.github.dsheirer.source.tuner.manager.DiscoveredRecordingTuner;
import io.github.dsheirer.source.tuner.ui.DiscoveredTunerModel;
import io.github.dsheirer.source.wave.SDRSharpIQRecording;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@@ -42,7 +43,7 @@ import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
/**
* Dialog to select a recording and specify a center frequency for use in adding a Recording Tuner
@@ -100,20 +101,13 @@ public class AddRecordingTunerDialog extends JFrame
fileChooser.setCurrentDirectory(browseDirectory);
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setFileFilter(new FileFilter()
{
@Override
public boolean accept(File f)
{
return f.getAbsolutePath().endsWith(".wav") || f.isDirectory();
}
@Override
public String getDescription()
{
return "Recordings (*.wav)";
}
});
FileNameExtensionFilter basebandFilter = new FileNameExtensionFilter("Baseband Recordings (*.wav, *.iq)",
"wav", SDRSharpIQRecording.FILE_EXTENSION);
fileChooser.addChoosableFileFilter(basebandFilter);
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("Wave Recordings (*.wav)", "wav"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("SDRSharp I/Q Recordings (*.iq)",
SDRSharpIQRecording.FILE_EXTENSION));
fileChooser.setFileFilter(basebandFilter);
int returnVal = fileChooser.showOpenDialog(AddRecordingTunerDialog.this);
@@ -128,9 +122,30 @@ public class AddRecordingTunerDialog extends JFrame
{
mSelectedRecording = fileChooser.getSelectedFile();
mAddButton.setEnabled(mSelectedRecording != null);
if(SDRSharpIQRecording.hasIQExtension(mSelectedRecording))
{
SDRSharpIQRecording iqRecording = SDRSharpIQRecording.parse(mSelectedRecording);
if(mSelectedRecording != null &&
if(iqRecording == null)
{
JOptionPane.showMessageDialog(AddRecordingTunerDialog.this,
"<html>Unable to determine the sample rate and center frequency from the I/Q recording " +
"file name.<br>Expected format: <i>yyyyMMdd-HHmmss_label_TUNER_123456789Hz_10MSps.iq</i></html>",
"Unsupported I/Q Recording",
JOptionPane.ERROR_MESSAGE);
mSelectedRecording = null;
}
else
{
mLog.info("Selected " + iqRecording);
if(mFrequencyTextField.getText() == null || mFrequencyTextField.getText().isEmpty())
{
mFrequencyTextField.setText(String.valueOf(iqRecording.getCenterFrequency()));
}
}
}
else if(mSelectedRecording != null &&
(mFrequencyTextField.getText() == null || mFrequencyTextField.getText().isEmpty()))
{
Matcher m = TUNER_RECORDING_PATTERN.matcher(mSelectedRecording.getName());
@@ -140,6 +155,8 @@ public class AddRecordingTunerDialog extends JFrame
mFrequencyTextField.setText(m.group(1));
}
}
mAddButton.setEnabled(mSelectedRecording != null);
}
else
{

View File

@@ -28,7 +28,9 @@ import io.github.dsheirer.source.IFrameLocationListener;
import io.github.dsheirer.source.Source;
import io.github.dsheirer.source.SourceEvent;
import io.github.dsheirer.util.ThreadPool;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ScheduledFuture;
@@ -49,7 +51,7 @@ public class ComplexWaveSource extends Source implements IControllableFileSource
private IFrameLocationListener mFrameLocationListener;
private int mBufferSampleCount = 65536; //Complex samples per buffer
private int mBytesPerFrame;
private int mFrameCounter = 0;
private long mFrameCounter = 0; //Bytes read - long to support recordings larger than 2 GB
private long mFrequency = 0;
private Listener<INativeBuffer> mListener;
private AudioInputStream mInputStream;
@@ -234,7 +236,7 @@ public class ComplexWaveSource extends Source implements IControllableFileSource
{
if(mInputStream == null)
{
mInputStream = AudioSystem.getAudioInputStream(mFile);
mInputStream = getAudioInputStream(mFile);
AudioFormat format = mInputStream.getFormat();
@@ -320,7 +322,7 @@ public class ComplexWaveSource extends Source implements IControllableFileSource
return mFile;
}
private void broadcast(int byteLocation)
private void broadcast(long byteLocation)
{
int frameLocation = (int)(byteLocation / mBytesPerFrame);
@@ -347,7 +349,7 @@ public class ComplexWaveSource extends Source implements IControllableFileSource
*/
public static boolean supports(File file)
{
try(AudioInputStream ais = AudioSystem.getAudioInputStream(file))
try(AudioInputStream ais = getAudioInputStream(file))
{
AudioFormat format = ais.getFormat();
@@ -364,6 +366,38 @@ public class ComplexWaveSource extends Source implements IControllableFileSource
return false;
}
/**
* Creates an audio input stream for the file. Wave files are opened via the Java audio system. SDRSharp raw
* I/Q (.iq) recordings are opened as headerless signed 16-bit little-endian stereo PCM, using the sample rate
* parsed from the file name.
* @param file to open
* @return audio input stream
* @throws IOException if the file can't be opened or (.iq) the file name can't be parsed
* @throws UnsupportedAudioFileException if the file is not a supported audio file
*/
private static AudioInputStream getAudioInputStream(File file) throws IOException, UnsupportedAudioFileException
{
if(SDRSharpIQRecording.hasIQExtension(file))
{
SDRSharpIQRecording recording = SDRSharpIQRecording.parse(file);
if(recording == null)
{
throw new IOException("Unable to parse sample rate from SDRSharp I/Q recording file name: " +
file.getName());
}
float sampleRate = (float)recording.getSampleRate();
AudioFormat format = new AudioFormat(AudioFormat.Encoding.PCM_SIGNED, sampleRate,
SDRSharpIQRecording.BITS_PER_SAMPLE, SDRSharpIQRecording.CHANNELS, SDRSharpIQRecording.BYTES_PER_FRAME,
sampleRate, false);
long frameLength = file.length() / SDRSharpIQRecording.BYTES_PER_FRAME;
return new AudioInputStream(new BufferedInputStream(new FileInputStream(file)), format, frameLength);
}
return AudioSystem.getAudioInputStream(file);
}
public class ReplayController implements Runnable
{
private double mFramesPerInterval;

View File

@@ -0,0 +1,237 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.wave;
import java.io.File;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Metadata for an SDRSharp raw I/Q baseband recording (.iq file extension).
*
* These recordings contain headerless, interleaved, signed 16-bit little-endian I/Q samples. The recording metadata
* is encoded in the file name using the format:
*
* yyyyMMdd-HHmmss_[label_]TUNER_[frequency][Hz|kHz|MHz|GHz]_[rate][Sps|kSps|MSps]
*
* Example: 20261102-071525_toronto_AIRSPY_424461724Hz_10MSps.iq
*/
public class SDRSharpIQRecording
{
public static final String FILE_EXTENSION = "iq";
public static final int BYTES_PER_FRAME = 4; //16-bit I + 16-bit Q
public static final int BITS_PER_SAMPLE = 16;
public static final int CHANNELS = 2;
private static final DateTimeFormatter TIMESTAMP_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd-HHmmss");
private static final Pattern FILE_NAME_PATTERN = Pattern.compile(
"^(\\d{8}-\\d{6})_(?:(.*)_)?([^_]+)_(\\d+(?:\\.\\d+)?)([kKMG]?)Hz_(\\d+(?:\\.\\d+)?)([kKMG]?)(?:S(?:ps|PS)|sps)?\\.iq$",
Pattern.CASE_INSENSITIVE);
private final File mFile;
private final LocalDateTime mStartTime;
private final String mLabel;
private final String mTunerType;
private final long mCenterFrequency;
private final double mSampleRate;
private SDRSharpIQRecording(File file, LocalDateTime startTime, String label, String tunerType,
long centerFrequency, double sampleRate)
{
mFile = file;
mStartTime = startTime;
mLabel = label;
mTunerType = tunerType;
mCenterFrequency = centerFrequency;
mSampleRate = sampleRate;
}
/**
* Indicates if the file has the SDRSharp .iq file extension.
*/
public static boolean hasIQExtension(File file)
{
return file != null && file.getName().toLowerCase().endsWith("." + FILE_EXTENSION);
}
/**
* Parses the recording metadata from the file name.
* @param file to parse
* @return parsed recording or null if the file name does not match the SDRSharp .iq file naming format.
*/
public static SDRSharpIQRecording parse(File file)
{
if(file == null)
{
return null;
}
Matcher m = FILE_NAME_PATTERN.matcher(file.getName());
if(!m.matches())
{
return null;
}
try
{
LocalDateTime startTime = LocalDateTime.parse(m.group(1), TIMESTAMP_FORMATTER);
String label = m.group(2);
String tunerType = m.group(3);
long frequency = scale(m.group(4), m.group(5)).longValue();
double sampleRate = scale(m.group(6), m.group(7)).doubleValue();
if(frequency <= 0 || sampleRate <= 0)
{
return null;
}
return new SDRSharpIQRecording(file, startTime, label, tunerType, frequency, sampleRate);
}
catch(DateTimeParseException | NumberFormatException | ArithmeticException e)
{
return null;
}
}
/**
* Creates an SDRSharp compatible recording file name.
* @param startTime of the recording
* @param label optional (nullable) label (e.g. channel name)
* @param tunerType tuner type (e.g. AIRSPY). Underscores are replaced with hyphens since the underscore is the
* file name field delimiter.
* @param frequency center frequency in Hertz
* @param sampleRate in samples per second
* @return file name, including the .iq extension
*/
public static String createFileName(LocalDateTime startTime, String label, String tunerType, long frequency,
double sampleRate)
{
StringBuilder sb = new StringBuilder();
sb.append(TIMESTAMP_FORMATTER.format(startTime)).append("_");
if(label != null && !label.isBlank())
{
sb.append(label.trim()).append("_");
}
String tuner = (tunerType == null || tunerType.isBlank()) ? "UNKNOWN" : tunerType.trim();
sb.append(tuner.replace("_", "-")).append("_");
sb.append(frequency).append("Hz_");
sb.append(formatSampleRate(sampleRate)).append(".").append(FILE_EXTENSION);
return sb.toString();
}
/**
* Formats the sample rate using the largest metric unit prefix (e.g. 10000000 = 10MSps, 2500000 = 2.5MSps,
* 25000 = 25kSps). The rate is rounded to the nearest whole sample per second.
*/
public static String formatSampleRate(double sampleRate)
{
BigDecimal rate = BigDecimal.valueOf(Math.round(sampleRate));
String prefix = "";
if(rate.compareTo(BigDecimal.valueOf(1_000_000)) >= 0)
{
rate = rate.movePointLeft(6);
prefix = "M";
}
else if(rate.compareTo(BigDecimal.valueOf(1_000)) >= 0)
{
rate = rate.movePointLeft(3);
prefix = "k";
}
return rate.stripTrailingZeros().toPlainString() + prefix + "Sps";
}
/**
* Applies the metric unit prefix (k, M, G) to the value.
*/
private static BigDecimal scale(String value, String prefix)
{
BigDecimal decimal = new BigDecimal(value);
return switch(prefix)
{
case "k", "K" -> decimal.movePointRight(3);
case "M" -> decimal.movePointRight(6);
case "G", "g" -> decimal.movePointRight(9);
//Lower-case 'm' (milli) makes no sense for frequency or sample rate - treat as mega.
case "m" -> decimal.movePointRight(6);
default -> decimal;
};
}
public File getFile()
{
return mFile;
}
/**
* Recording start time (local time of the recording computer).
*/
public LocalDateTime getStartTime()
{
return mStartTime;
}
/**
* Optional user label, or null.
*/
public String getLabel()
{
return mLabel;
}
/**
* Tuner type text from the file name (e.g. AIRSPY)
*/
public String getTunerType()
{
return mTunerType;
}
/**
* Center frequency in Hertz
*/
public long getCenterFrequency()
{
return mCenterFrequency;
}
/**
* Sample rate in samples per second
*/
public double getSampleRate()
{
return mSampleRate;
}
@Override
public String toString()
{
return "SDRSharp I/Q Recording - Tuner:" + mTunerType + " Start:" + mStartTime + " Frequency:" +
mCenterFrequency + " Sample Rate:" + mSampleRate + (mLabel != null ? " Label:" + mLabel : "");
}
}

View File

@@ -0,0 +1,286 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.dsp.fft;
import io.github.dsheirer.dsp.filter.channelizer.ComplexPolyphaseChannelizerM2;
import java.lang.management.ManagementFactory;
import java.util.Random;
import org.jtransforms.fft.FloatFFT_1D;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assumptions.assumeTrue;
/**
* Verifies that the MixedRadixComplexFFT produces the same results as JTransforms FloatFFT_1D and does not allocate
* memory per transform.
*/
public class MixedRadixComplexFFTTest
{
/**
* Maximum error relative to the largest output magnitude.
*/
private static final double RELATIVE_TOLERANCE = 2e-6;
/**
* Sizes covering each radix (2, 3, 4, 5), mixed factorizations, powers of two and the channelizer channel counts.
*/
private static final int[] SIZES = {1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 25, 27, 30, 32, 40, 45, 50, 60, 64, 72,
80, 90, 96, 100, 120, 125, 128, 150, 160, 180, 192, 200, 240, 250, 256, 270, 300, 320, 360, 384, 400, 450, 480,
500, 512, 600, 640, 720, 750, 768, 800, 900, 960, 1000, 1024, 1080, 1200, 1500, 2000, 2400, 3000, 4096, 6000};
private static float[] randomSamples(int length, Random random)
{
float[] samples = new float[length];
for(int x = 0; x < samples.length; x++)
{
samples[x] = random.nextFloat() * 2.0f - 1.0f;
}
return samples;
}
/**
* Asserts that the actual values match the expected values within a tolerance relative to the largest expected
* magnitude.
*/
private static void assertClose(float[] expected, float[] actual, String message)
{
assertEquals(expected.length, actual.length, message + " length");
double maxMagnitude = 1e-30;
double maxError = 0;
for(int x = 0; x < expected.length; x++)
{
maxMagnitude = Math.max(maxMagnitude, Math.abs(expected[x]));
maxError = Math.max(maxError, Math.abs(expected[x] - actual[x]));
}
double relativeError = maxError / maxMagnitude;
assertTrue(relativeError <= RELATIVE_TOLERANCE, message + " relative error " + relativeError +
" exceeds " + RELATIVE_TOLERANCE);
}
/**
* Double precision brute force DFT reference.
* @param samples interleaved complex
* @param sign -1 forward, +1 inverse
*/
private static float[] referenceDFT(float[] samples, int sign)
{
int n = samples.length / 2;
float[] result = new float[samples.length];
for(int k = 0; k < n; k++)
{
double re = 0;
double im = 0;
for(int t = 0; t < n; t++)
{
double angle = sign * 2.0 * Math.PI * ((long)k * t % n) / n;
double cos = Math.cos(angle);
double sin = Math.sin(angle);
re += samples[2 * t] * cos - samples[2 * t + 1] * sin;
im += samples[2 * t] * sin + samples[2 * t + 1] * cos;
}
result[2 * k] = (float)re;
result[2 * k + 1] = (float)im;
}
return result;
}
@Test
public void forwardMatchesJTransforms()
{
Random random = new Random(1);
for(int size : SIZES)
{
float[] input = randomSamples(2 * size, random);
float[] expected = input.clone();
new FloatFFT_1D(size).complexForward(expected);
float[] actual = input.clone();
new MixedRadixComplexFFT(size).forward(actual);
assertClose(expected, actual, "Forward size " + size);
}
}
@Test
public void inverseMatchesJTransforms()
{
Random random = new Random(2);
for(int size : SIZES)
{
for(boolean scale : new boolean[]{true, false})
{
float[] input = randomSamples(2 * size, random);
float[] expected = input.clone();
new FloatFFT_1D(size).complexInverse(expected, scale);
float[] actual = input.clone();
new MixedRadixComplexFFT(size).inverse(actual, scale);
assertClose(expected, actual, "Inverse size " + size + " scale " + scale);
}
}
}
@Test
public void matchesDoublePrecisionReference()
{
Random random = new Random(3);
for(int size : SIZES)
{
if(size > 1200)
{
continue; //Brute force reference is O(N^2)
}
MixedRadixComplexFFT fft = new MixedRadixComplexFFT(size);
float[] input = randomSamples(2 * size, random);
float[] forward = input.clone();
fft.forward(forward);
assertClose(referenceDFT(input, -1), forward, "Forward reference size " + size);
float[] inverse = input.clone();
fft.inverse(inverse, false);
assertClose(referenceDFT(input, 1), inverse, "Inverse reference size " + size);
}
}
/**
* Mirrors the channelizer usage: repeated in-place inverse transforms of consecutive blocks in a larger array,
* reusing a single instance and its scratch buffer. Also verifies that data outside each block is not modified.
*/
@Test
public void offsetBlocksMatchJTransforms()
{
Random random = new Random(4);
int blocks = 7;
for(int size : new int[]{2, 72, 96, 100, 128, 240, 400, 480, 600})
{
int blockLength = 2 * size;
int guard = 3;
float[] input = randomSamples(blocks * blockLength + 2 * guard, random);
float[] expected = input.clone();
FloatFFT_1D jtransforms = new FloatFFT_1D(size);
float[] actual = input.clone();
MixedRadixComplexFFT fft = new MixedRadixComplexFFT(size);
for(int offset = guard; offset < guard + blocks * blockLength; offset += blockLength)
{
jtransforms.complexInverse(expected, offset, true);
fft.inverse(actual, offset, true);
}
assertClose(expected, actual, "Offset blocks size " + size);
for(int x = 0; x < guard; x++)
{
assertEquals(input[x], actual[x], "Leading guard modified size " + size);
assertEquals(input[input.length - 1 - x], actual[actual.length - 1 - x],
"Trailing guard modified size " + size);
}
}
}
@Test
public void roundTripRestoresInput()
{
Random random = new Random(5);
for(int size : SIZES)
{
MixedRadixComplexFFT fft = new MixedRadixComplexFFT(size);
float[] input = randomSamples(2 * size, random);
float[] samples = input.clone();
fft.forward(samples);
fft.inverse(samples, true);
assertArrayEquals(input, samples, 1e-5f, "Round trip size " + size);
}
}
@Test
public void supportsAllChannelizerChannelCounts()
{
for(double sampleRate = 50_000; sampleRate <= 61_440_000; sampleRate += 25_000)
{
int channelCount = ComplexPolyphaseChannelizerM2.getChannelCount(sampleRate);
assertTrue(MixedRadixComplexFFT.isSupported(channelCount), "Channel count " + channelCount +
" for sample rate " + sampleRate);
}
}
@Test
public void rejectsUnsupportedSizes()
{
for(int size : new int[]{0, -4, 7, 14, 49, 244, 1001})
{
assertFalse(MixedRadixComplexFFT.isSupported(size), "Size " + size);
assertThrows(IllegalArgumentException.class, () -> new MixedRadixComplexFFT(size), "Size " + size);
}
}
/**
* Verifies that repeated transforms do not allocate memory, which is the reason this class exists.
*/
@Test
public void doesNotAllocatePerTransform()
{
assumeTrue(ManagementFactory.getThreadMXBean() instanceof com.sun.management.ThreadMXBean);
com.sun.management.ThreadMXBean threadMXBean = (com.sun.management.ThreadMXBean)ManagementFactory.getThreadMXBean();
assumeTrue(threadMXBean.isThreadAllocatedMemorySupported() && threadMXBean.isThreadAllocatedMemoryEnabled());
int size = 400;
int iterations = 10_000;
MixedRadixComplexFFT fft = new MixedRadixComplexFFT(size);
float[] samples = randomSamples(2 * size, new Random(6));
//Warm up so that class loading and JIT compilation are complete before measuring
for(int x = 0; x < iterations; x++)
{
fft.inverse(samples, 0, true);
}
long threadId = Thread.currentThread().threadId();
long before = threadMXBean.getThreadAllocatedBytes(threadId);
for(int x = 0; x < iterations; x++)
{
fft.inverse(samples, 0, true);
}
long allocated = threadMXBean.getThreadAllocatedBytes(threadId) - before;
//JTransforms allocates 2N floats (3200 bytes at N=400) per call, about 32 MB for these iterations
assertTrue(allocated < 64 * 1024, "Allocated " + allocated + " bytes over " + iterations + " transforms");
}
}

View File

@@ -19,12 +19,12 @@
package io.github.dsheirer.dsp.filter.channelizer;
import io.github.dsheirer.dsp.fft.MixedRadixComplexFFT;
import io.github.dsheirer.sample.complex.InterleavedComplexSamples;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;
import org.jtransforms.fft.FloatFFT_1D;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
@@ -142,7 +142,9 @@ public class ComplexPolyphaseChannelizerM2Test
channelizer.stop();
assertEquals(batchCount, batches.size(), "Batches (channelCount=" + channelCount + ")");
FloatFFT_1D fft = new FloatFFT_1D(channelCount);
//Use the same IFFT as the channelizer so the comparison remains bit-exact. Equivalence of this IFFT with
//JTransforms is verified separately in MixedRadixComplexFFTTest.
MixedRadixComplexFFT fft = new MixedRadixComplexFFT(channelCount);
int blockLength = channelCount * 2;
boolean topBlock = TAPS_PER_CHANNEL % 2 == 0;
@@ -152,7 +154,7 @@ public class ComplexPolyphaseChannelizerM2Test
float[] expected = harness.processFused(topBlock);
topBlock = !topBlock;
harness.shift(channelCount);
fft.complexInverse(expected, true);
fft.inverse(expected, true);
float[] batch = batches.get(block / blocksPerBatch);
int offset = (block % blocksPerBatch) * blockLength;

View File

@@ -0,0 +1,107 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.record.wave;
import io.github.dsheirer.buffer.INativeBuffer;
import io.github.dsheirer.sample.ConversionUtils;
import io.github.dsheirer.sample.complex.InterleavedComplexSamples;
import io.github.dsheirer.source.wave.ComplexWaveSource;
import io.github.dsheirer.source.wave.SDRSharpIQRecording;
import java.nio.ByteBuffer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class IQWriterTest
{
@TempDir
Path mTempDir;
@Test
void writesHeaderlessSamplesReadableByComplexWaveSource() throws Exception
{
float[] samples = new float[]{0.5f, -0.25f, 0.125f, -1.0f, 0.0f, 0.75f};
String name = SDRSharpIQRecording.createFileName(LocalDateTime.now(), "test", "AIRSPY", 851_000_000L, 25_000);
Path path = mTempDir.resolve(name);
try(IQWriter writer = new IQWriter(path))
{
writer.writeData(ConversionUtils.convertToSigned16BitSamples(new InterleavedComplexSamples(samples, 0)));
}
//Headerless: 3 complex samples x 4 bytes
assertEquals(12, Files.size(path));
assertTrue(ComplexWaveSource.supports(path.toFile()));
List<float[]> received = new ArrayList<>();
try(ComplexWaveSource source = new ComplexWaveSource(path.toFile()))
{
source.setListener((INativeBuffer buffer) -> {
Iterator<InterleavedComplexSamples> it = buffer.iteratorInterleaved();
while(it.hasNext())
{
received.add(it.next().samples());
}
});
source.open();
assertEquals(25_000d, source.getSampleRate());
source.next(3);
}
float[] readBack = received.get(0);
assertEquals(samples.length, readBack.length);
assertArrayEquals(samples, readBack, 0.0001f);
}
@Test
void refusesToOverwriteExistingFile() throws Exception
{
Path path = mTempDir.resolve("existing.iq");
Files.write(path, new byte[]{1, 2, 3, 4});
assertThrows(java.nio.file.FileAlreadyExistsException.class, () -> new IQWriter(path));
assertArrayEquals(new byte[]{1, 2, 3, 4}, Files.readAllBytes(path));
}
@Test
void writesFullBuffer() throws Exception
{
Path path = mTempDir.resolve("full.iq");
ByteBuffer buffer = ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7, 8});
buffer.position(8); //Writer must rewind
try(IQWriter writer = new IQWriter(path))
{
writer.writeData(buffer);
}
assertArrayEquals(new byte[]{1, 2, 3, 4, 5, 6, 7, 8}, Files.readAllBytes(path));
}
}

View File

@@ -0,0 +1,125 @@
/*
* *****************************************************************************
* Copyright (C) 2014-2026 Dennis Sheirer
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
* ****************************************************************************
*/
package io.github.dsheirer.source.wave;
import java.io.File;
import java.time.LocalDateTime;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class SDRSharpIQRecordingTest
{
private static SDRSharpIQRecording parse(String name)
{
return SDRSharpIQRecording.parse(new File(name));
}
@Test
void parsesHertzFrequency()
{
SDRSharpIQRecording r = parse("20261102-071525_toronto_AIRSPY_424461724Hz_10MSps.iq");
assertNotNull(r);
assertEquals(LocalDateTime.of(2026, 11, 2, 7, 15, 25), r.getStartTime());
assertEquals("toronto", r.getLabel());
assertEquals("AIRSPY", r.getTunerType());
assertEquals(424461724L, r.getCenterFrequency());
assertEquals(10_000_000d, r.getSampleRate());
}
@Test
void parsesKilohertzAndMegahertzFrequency()
{
assertEquals(855_125_000L, parse("20261102-072949_toronto_AIRSPY_855125kHz_10MSps.iq").getCenterFrequency());
assertEquals(412_000_000L, parse("20261102-071621_toronto_AIRSPY_412MHz_10MSps.iq").getCenterFrequency());
assertEquals(860_880_000L, parse("20261102-071621_toronto_AIRSPY_860.88MHz_10MSps.iq").getCenterFrequency());
}
@Test
void parsesOptionalAndUnderscoredLabels()
{
SDRSharpIQRecording noLabel = parse("20261102-071525_AIRSPY_424461724Hz_10MSps.iq");
assertNotNull(noLabel);
assertNull(noLabel.getLabel());
assertEquals("AIRSPY", noLabel.getTunerType());
SDRSharpIQRecording underscored = parse("20261102-071525_toronto_north_AIRSPY_424461724Hz_2.5MSps.iq");
assertNotNull(underscored);
assertEquals("toronto_north", underscored.getLabel());
assertEquals("AIRSPY", underscored.getTunerType());
assertEquals(2_500_000d, underscored.getSampleRate());
}
@Test
void rejectsUnparseableNames()
{
assertNull(parse("recording.iq"));
assertNull(parse("20261102-071525_toronto_AIRSPY_424461724Hz_10MSps.wav"));
assertNull(parse("20261302-071525_toronto_AIRSPY_424461724Hz_10MSps.iq")); //Invalid month
}
@Test
void formatsSampleRate()
{
assertEquals("10MSps", SDRSharpIQRecording.formatSampleRate(10_000_000));
assertEquals("2.5MSps", SDRSharpIQRecording.formatSampleRate(2_500_000));
assertEquals("2.048MSps", SDRSharpIQRecording.formatSampleRate(2_048_000));
assertEquals("25kSps", SDRSharpIQRecording.formatSampleRate(25_000));
assertEquals("12.5kSps", SDRSharpIQRecording.formatSampleRate(12_500));
assertEquals("26.042kSps", SDRSharpIQRecording.formatSampleRate(26_041.666));
assertEquals("800Sps", SDRSharpIQRecording.formatSampleRate(800));
}
@Test
void createdFileNamesRoundTrip()
{
LocalDateTime start = LocalDateTime.of(2026, 11, 3, 14, 5, 9);
String name = SDRSharpIQRecording.createFileName(start, null, "AIRSPY", 851_012_500L, 10_000_000);
assertEquals("20261103-140509_AIRSPY_851012500Hz_10MSps.iq", name);
String channel = SDRSharpIQRecording.createFileName(start, "Site 1_Control", "SDRTRUNK", 851_012_500L, 25_000);
assertEquals("20261103-140509_Site 1_Control_SDRTRUNK_851012500Hz_25kSps.iq", channel);
SDRSharpIQRecording parsed = parse(channel);
assertNotNull(parsed);
assertEquals(start, parsed.getStartTime());
assertEquals("Site 1_Control", parsed.getLabel());
assertEquals("SDRTRUNK", parsed.getTunerType());
assertEquals(851_012_500L, parsed.getCenterFrequency());
assertEquals(25_000d, parsed.getSampleRate());
//Underscores in the tuner type would break parsing - they're replaced with hyphens
SDRSharpIQRecording hf = parse(SDRSharpIQRecording.createFileName(start, null, "AIRSPY_HF", 7_200_000L, 768_000));
assertNotNull(hf);
assertEquals("AIRSPY-HF", hf.getTunerType());
assertEquals(768_000d, hf.getSampleRate());
}
@Test
void detectsExtension()
{
assertTrue(SDRSharpIQRecording.hasIQExtension(new File("a.IQ")));
assertFalse(SDRSharpIQRecording.hasIQExtension(new File("a.wav")));
assertFalse(SDRSharpIQRecording.hasIQExtension(null));
}
}