diff --git a/src/main/java/io/github/dsheirer/gui/preference/record/RecordPreferenceEditor.java b/src/main/java/io/github/dsheirer/gui/preference/record/RecordPreferenceEditor.java index 4f11862d..3df5c362 100644 --- a/src/main/java/io/github/dsheirer/gui/preference/record/RecordPreferenceEditor.java +++ b/src/main/java/io/github/dsheirer/gui/preference/record/RecordPreferenceEditor.java @@ -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 mRecordFormatComboBox; + private ComboBox 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 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 getRecordFormatComboBox() { if(mRecordFormatComboBox == null) diff --git a/src/main/java/io/github/dsheirer/preference/record/RecordPreference.java b/src/main/java/io/github/dsheirer/preference/record/RecordPreference.java index 51cd2d70..f813ecc0 100644 --- a/src/main/java/io/github/dsheirer/preference/record/RecordPreference.java +++ b/src/main/java/io/github/dsheirer/preference/record/RecordPreference.java @@ -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(); + } } diff --git a/src/main/java/io/github/dsheirer/record/BasebandRecordFormat.java b/src/main/java/io/github/dsheirer/record/BasebandRecordFormat.java new file mode 100644 index 00000000..2e118253 --- /dev/null +++ b/src/main/java/io/github/dsheirer/record/BasebandRecordFormat.java @@ -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 + * **************************************************************************** + */ + +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; + } +} diff --git a/src/main/java/io/github/dsheirer/record/RecorderFactory.java b/src/main/java/io/github/dsheirer/record/RecorderFactory.java index dbb637b2..c9730c1f 100644 --- a/src/main/java/io/github/dsheirer/record/RecorderFactory.java +++ b/src/main/java/io/github/dsheirer/record/RecorderFactory.java @@ -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; + } } diff --git a/src/main/java/io/github/dsheirer/record/wave/ComplexSamplesWaveRecorder.java b/src/main/java/io/github/dsheirer/record/wave/ComplexSamplesWaveRecorder.java index e8864b37..1cc41fbe 100644 --- a/src/main/java/io/github/dsheirer/record/wave/ComplexSamplesWaveRecorder.java +++ b/src/main/java/io/github/dsheirer/record/wave/ComplexSamplesWaveRecorder.java @@ -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, ISourceEventListener { private final static Logger mLog = LoggerFactory.getLogger(ComplexSamplesWaveRecorder.class); - private Dispatcher mBufferProcessor = new Dispatcher<>("sdrtrunk complex wave recorder", 250); + private Dispatcher 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 getSourceEventListener() { - return new Listener() + 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 - { - 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(); - } - } - } - } } diff --git a/src/main/java/io/github/dsheirer/record/wave/IBasebandRecordingWriter.java b/src/main/java/io/github/dsheirer/record/wave/IBasebandRecordingWriter.java new file mode 100644 index 00000000..7f8e8cd3 --- /dev/null +++ b/src/main/java/io/github/dsheirer/record/wave/IBasebandRecordingWriter.java @@ -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 + * **************************************************************************** + */ +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); + }; + } +} diff --git a/src/main/java/io/github/dsheirer/record/wave/IQWriter.java b/src/main/java/io/github/dsheirer/record/wave/IQWriter.java new file mode 100644 index 00000000..0bb61316 --- /dev/null +++ b/src/main/java/io/github/dsheirer/record/wave/IQWriter.java @@ -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 + * **************************************************************************** + */ +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(); + } + } +} diff --git a/src/main/java/io/github/dsheirer/record/wave/IRecordingPathProvider.java b/src/main/java/io/github/dsheirer/record/wave/IRecordingPathProvider.java new file mode 100644 index 00000000..f2cb433f --- /dev/null +++ b/src/main/java/io/github/dsheirer/record/wave/IRecordingPathProvider.java @@ -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 + * **************************************************************************** + */ +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; +} diff --git a/src/main/java/io/github/dsheirer/record/wave/NativeBufferWaveRecorder.java b/src/main/java/io/github/dsheirer/record/wave/NativeBufferWaveRecorder.java index abb6d9d5..0048e2fd 100644 --- a/src/main/java/io/github/dsheirer/record/wave/NativeBufferWaveRecorder.java +++ b/src/main/java/io/github/dsheirer/record/wave/NativeBufferWaveRecorder.java @@ -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 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 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 + public class NativeBufferWriter implements Listener, 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 (mLastReportedSize + STATUS_UPDATE_BYTE_INTERVAL)) diff --git a/src/main/java/io/github/dsheirer/record/wave/WaveWriter.java b/src/main/java/io/github/dsheirer/record/wave/WaveWriter.java index f05a69e0..503f08fb 100644 --- a/src/main/java/io/github/dsheirer/record/wave/WaveWriter.java +++ b/src/main/java/io/github/dsheirer/record/wave/WaveWriter.java @@ -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); diff --git a/src/main/java/io/github/dsheirer/source/tuner/TunerController.java b/src/main/java/io/github/dsheirer/source/tuner/TunerController.java index 0ce74a86..73e0ce5f 100644 --- a/src/main/java/io/github/dsheirer/source/tuner/TunerController.java +++ b/src/main/java/io/github/dsheirer/source/tuner/TunerController.java @@ -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); diff --git a/src/main/java/io/github/dsheirer/source/tuner/recording/AddRecordingTunerDialog.java b/src/main/java/io/github/dsheirer/source/tuner/recording/AddRecordingTunerDialog.java index cb7f9b7f..038dbd15 100644 --- a/src/main/java/io/github/dsheirer/source/tuner/recording/AddRecordingTunerDialog.java +++ b/src/main/java/io/github/dsheirer/source/tuner/recording/AddRecordingTunerDialog.java @@ -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, + "Unable to determine the sample rate and center frequency from the I/Q recording " + + "file name.
Expected format: yyyyMMdd-HHmmss_label_TUNER_123456789Hz_10MSps.iq", + "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 { diff --git a/src/main/java/io/github/dsheirer/source/wave/ComplexWaveSource.java b/src/main/java/io/github/dsheirer/source/wave/ComplexWaveSource.java index 620a2c4e..00924a77 100644 --- a/src/main/java/io/github/dsheirer/source/wave/ComplexWaveSource.java +++ b/src/main/java/io/github/dsheirer/source/wave/ComplexWaveSource.java @@ -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 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; diff --git a/src/main/java/io/github/dsheirer/source/wave/SDRSharpIQRecording.java b/src/main/java/io/github/dsheirer/source/wave/SDRSharpIQRecording.java new file mode 100644 index 00000000..66dceb5d --- /dev/null +++ b/src/main/java/io/github/dsheirer/source/wave/SDRSharpIQRecording.java @@ -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 + * **************************************************************************** + */ +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 : ""); + } +} diff --git a/src/test/java/io/github/dsheirer/record/wave/IQWriterTest.java b/src/test/java/io/github/dsheirer/record/wave/IQWriterTest.java new file mode 100644 index 00000000..11b716bf --- /dev/null +++ b/src/test/java/io/github/dsheirer/record/wave/IQWriterTest.java @@ -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 + * **************************************************************************** + */ +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 received = new ArrayList<>(); + + try(ComplexWaveSource source = new ComplexWaveSource(path.toFile())) + { + source.setListener((INativeBuffer buffer) -> { + Iterator 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)); + } +} diff --git a/src/test/java/io/github/dsheirer/source/wave/SDRSharpIQRecordingTest.java b/src/test/java/io/github/dsheirer/source/wave/SDRSharpIQRecordingTest.java new file mode 100644 index 00000000..99e8cb60 --- /dev/null +++ b/src/test/java/io/github/dsheirer/source/wave/SDRSharpIQRecordingTest.java @@ -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 + * **************************************************************************** + */ +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)); + } +}