27. IQ Files Without Copies, and SigMF¶
PySDR’s IQ Files and SigMF chapter covers the practical side of recordings: raw binary files of interleaved samples, the np.fromfile call that reads them (and the classic mistake of forgetting the dtype), integer formats from SDR hardware, and SigMF, the open standard that puts a JSON metadata file next to the samples. Reading a file in NumPy is one line, and it copies the whole file into memory.
For a 10 ms GPS snippet that is fine. For the recordings you make in practice (a few minutes at 20 MS/s are gigabytes) it is not, and it is also unnecessary: the operating system can make the file look like memory, loading pages only when they are touched. In this chapter we build a small SigMF reader in C++ around that idea, and use it to show four language features that fit file handling particularly well: RAII for the mapping, std::span views into it, std::expected for the many ways a recording can be broken, and a template trick that turns the format string from the metadata into a C++ type. At the end, the GPS acquisition from Spreading Codes: GPS C/A Codes at Compile Time runs directly on a mapped recording without copying a single sample.
Mapping a File, the RAII Way¶
On POSIX systems, mmap maps a file into the address space of the process. Reading from the returned pointer reads the file; pages that are never touched are never loaded, and pages that were read can be dropped by the OS again under memory pressure, because it knows where to reload them from. The mapping must be released with munmap, exactly once, on every path out of the code. That is what RAII (resource acquisition is initialization) is for: an object that owns the mapping and releases it in its destructor (code/include/cppsdr/iq_file.hpp):
class mapped_file {
public:
static std::expected<mapped_file, std::string> open(std::filesystem::path const& path);
mapped_file(mapped_file&& o) noexcept
: data_(std::exchange(o.data_, nullptr)), size_(std::exchange(o.size_, 0)) {}
mapped_file(mapped_file const&) = delete; // one mapping, one owner
mapped_file& operator=(mapped_file const&) = delete;
~mapped_file() { if (data_) ::munmap(const_cast<std::byte*>(data_), size_); }
std::span<const std::byte> bytes() const { return {data_, size_}; }
private:
const std::byte* data_ = nullptr;
std::size_t size_ = 0;
};
The copy operations are deleted, because two objects unmapping the same memory would be a bug; the move constructor transfers ownership with std::exchange, leaving the source empty. The contents are exposed as std::span<const std::byte>: a view that knows its size, and through which nothing can be written. The class is the same shape as std::unique_ptr, and in fact a unique_ptr with a custom deleter would do the job too; Kormanyos recommends the same pattern for wrapping C driver APIs in Real-Time C++ (4th ed., chapter 17).
Errors as Values: std::expected¶
A recording can be broken in many ways: the metadata file is missing, is not valid JSON, has no core:datatype, names a datatype we do not support, or the data file size is not a whole number of samples. None of these is exceptional in a tool that reads files people send you; they are ordinary outcomes that the caller must handle. C++23’s std::expected<T, E> holds either a value or an error, and makes that explicit in the type:
static std::expected<recording, std::string> open(std::filesystem::path base)
{
...
auto meta = parse_metadata(text.str());
if (!meta) return std::unexpected(meta.error());
auto file = mapped_file::open(base.string() + ".sigmf-data");
if (!file) return std::unexpected(file.error());
if (file->bytes().size() % meta->format.bytes_per_sample() != 0)
return std::unexpected("data size is not a whole number of samples");
return recording(std::move(*meta), std::move(*file));
}
The caller cannot use the recording without checking (if (!rec)), and the error carries a message. Unlike exceptions, std::expected also works in code compiled with -fno-exceptions, which is common in embedded and real-time projects. The test opens five deliberately broken recordings and checks each message, for example “core:datatype: unsupported number of bits” for a file that claims to be cf33_le.
The JSON itself is parsed with the widely used nlohmann/json library, in its non-throwing mode (json::parse(text, nullptr, false)), and copied into a plain struct with named fields:
struct metadata {
sample_format format{};
double sample_rate = 0;
std::string description, hw, author;
std::vector<capture> captures; // core:sample_start, core:frequency
std::vector<annotation> annotations; // core:sample_start, core:sample_count, core:label, ...
};
After parsing, the rest of the program never touches JSON keys again; a typo in a field name is a compile error rather than a silent default.
The Datatype Is a Type¶
SigMF describes the sample format with a short string: cf32_le is complex 32-bit float, little-endian (np.complex64); ci16_be is complex 16-bit signed integers, big-endian; cu8 is complex unsigned bytes, what an RTL-SDR delivers. We parse it into a struct, with a constexpr function that returns std::expected, so the parser can be tested at compile time:
static_assert(parse_datatype("cf32_le") == sample_format{true, number::floating, 32, std::endian::little});
static_assert(parse_datatype("ci16_be") == sample_format{true, number::signed_int, 16, std::endian::big});
static_assert(!parse_datatype("cf33_le").has_value() && !parse_datatype("ci16").has_value());
std::endian (C++20) names the byte order, and std::endian::native tells us the byte order of the machine we are compiled for.
Now the interesting step. The format is known only at run time, when the metadata has been read, but the conversion loop should be written once, as a template on the C++ value type, and compiled separately for each type. A small dispatch function bridges the two:
template <class F>
decltype(auto) with_value_type(sample_format const& fmt, F&& f)
{
switch (fmt.kind) {
case number::floating:
if (fmt.bits == 32) return f.template operator()<float>();
return f.template operator()<double>();
case number::signed_int:
if (fmt.bits == 8) return f.template operator()<std::int8_t>();
if (fmt.bits == 16) return f.template operator()<std::int16_t>();
return f.template operator()<std::int32_t>();
...
}
}
It calls a template lambda (C++20) with the type that matches the format. The converting read is then written once, for any T:
with_value_type(f, [&]<class T>() {
for (std::size_t i = 0; i < n; ++i, p += f.bytes_per_sample()) {
const float re = to_float(load<T>(p, f.order));
const float im = f.is_complex ? to_float(load<T>(p + sizeof(T), f.order)) : 0.0f;
out[i] = cf32(re, im);
}
});
The switch runs once per call, the loop inside runs specialized for std::int16_t or float or whatever the file holds. This run-time to compile-time dispatch is a pattern worth knowing; it shows up wherever data formats are described by metadata.
The two helpers carry the format details. load<T> reads a value from raw bytes and swaps the byte order if the file’s differs from the machine’s:
template <class T>
T load(const std::byte* p, std::endian order)
{
...
U u; // unsigned integer of the same size as T
std::memcpy(&u, p, sizeof u); // the portable way to reinterpret bytes
if (order != std::endian::native) u = std::byteswap(u); // C++23
return std::bit_cast<T>(u); // C++20
}
std::memcpy into a local variable is the portable, well-defined way to read a value from a byte buffer (a reinterpret_cast of an arbitrary byte pointer can violate alignment and aliasing rules), and compilers turn it into a single load. std::byteswap and std::bit_cast make the byte-order handling work for floats as well as integers. to_float<T> then scales integers to \([-1, 1)\), removing the offset of unsigned formats (an RTL-SDR’s cu8 is centred at 127.5). PySDR’s int16 example converts with astype(np.float32) without scaling; SigMF does not prescribe a scale, so pick one convention and write it down.
The test writes the same QPSK signal (PySDR’s example) as cf32_le, ci16_le, ci16_be and cu8 recordings and checks that every one of them converts bit-exactly to what NumPy computes, read in odd-sized blocks as a streaming reader would.
Zero Copies¶
When the file holds cf32 in the machine’s byte order, which is the common case, no conversion is needed at all. The recording then offers a view of type std::span<const std::complex<float>> directly over the mapped memory:
std::optional<std::span<const cf32>> view_cf32() const
{
constexpr sample_format native_cf32{true, number::floating, 32, std::endian::native};
const auto b = file_.bytes();
if (meta_.format != native_cf32 || reinterpret_cast<std::uintptr_t>(b.data()) % alignof(cf32) != 0)
return std::nullopt;
return std::span<const cf32>(reinterpret_cast<const cf32*>(b.data()), size());
}
The return type std::optional says that the view is not always possible; the caller falls back to read() for integer formats. The layout guarantee from Samples in Memory (std::complex<float> is two floats) is what makes the view meaningful. Whether the cast is formally well-defined is a subtle question: C++20 made objects of implicit-lifetime types such as float spring into existence in memory obtained from allocation functions (paper P0593), but the standard knows nothing about mmap. This pattern is universal in practice, and C++23 adds std::start_lifetime_as_array precisely to state it explicitly; libc++ does not have it yet.
Annotations become views too. A SigMF annotation marks a range of samples (core:sample_start, core:sample_count) with a label; the matching samples are just a subspan of the mapping:
std::optional<std::span<const cf32>> view(annotation const& a) const
{
auto all = view_cf32();
if (!all || a.sample_start + a.sample_count > all->size()) return std::nullopt;
return all->subspan(a.sample_start, a.sample_count);
}
The test checks that the annotated burst’s data pointer points straight into the mapping, 1000 samples from its start.
Putting the chapters together: we stored PySDR’s GPS recording as a SigMF recording, with the first 10 ms annotated, and handed the annotation’s view to the acquisition from Spreading Codes: GPS C/A Codes at Compile Time:
auto rec = iq::recording::open("testdata/sigmf/gps_l1"); // std::expected
auto samples = rec->view(rec->meta().annotations.at(0)); // std::span, no copy
gps::acquisition acq({.sample_rate = rec->meta().sample_rate}); // sample rate from the metadata
for (unsigned prn = 1; prn <= 32; ++prn)
if (acq.search(prn, *samples).detected) ...
It finds the same six satellites (11, 12, 22, 25, 31 and 32), reading the samples straight from the page cache. The sample rate comes from the metadata, so the code cannot be run with the wrong rate by accident; the designated initializer {.sample_rate = ...} leaves every other setting at its default.
Key Takeaways¶
Map large recordings instead of reading them: the OS loads only the pages you touch, and an RAII class makes the mapping impossible to leak.
Hand out
std::spanviews (of bytes, of samples, of annotated ranges) instead of copies;std::optionalsays when a view is not possible.Return
std::expectedfor errors that are ordinary outcomes, such as a broken file; it is explicit, carries a message, and works without exceptions.Parse format strings into types, and bridge from run-time formats to compiled code with a template lambda dispatch.
Use
std::memcpy,std::byteswapandstd::bit_castto read binary data portably, in any byte order.