File
pysdrlib.file ¶
Sample files: read them like a device, write them from one, play a recording back as a radio.
Both directions use the formats in pysdrlib.Formats (pysdrlib.Formats.ls() lists them; reference: pysdrlib.base.formats).
The walkthrough, with code, is the Sample files guide.
| Class | |
|---|---|
File(path, fmt) |
Reads samples from a file, forward or back, in blocks |
FileSink(path, fmt) |
Writes samples to a file |
pysdrlib.open("file", path=..., tx_path=...) |
Plays a recording back as a receiving device, and/or records what it transmits (Replay) |
Any of them can be a SigMF recording: name.sigmf-data with name.sigmf-meta beside it.
Format names follow SigMF: the number is the bits of one value (I or Q), so a GNU Radio .cfile (two float32) is
cf32, an RTL-SDR .cu8 is cui8, and ci16 is two int16. Before pysdrlib 0.5 the number was the bits of the whole
sample (cf64 was two float32): check old code.
File has get_samples(), so code that processes a device's samples can be pointed at a recording (for the whole
Device interface, replay it). Neither class scales: integer formats are read and written as stored, not divided by
full scale.
Reading¶
| Call | |
|---|---|
next(count, partial=False) |
The next count samples. Past the end it raises err.Overflow, unless partial=True, which returns what is left (an empty array at EOF) |
forward(count, partial=False) |
Yield blocks until EOF. File(...)(count) is the same |
prev(count), reverse(count) |
Step back, returning the samples just passed (reverse yields block after block to the start) |
seek(sample), reset() |
Move to a sample index / the start. seek outside the file raises err.Overflow |
percent(fraction=True) |
How much of the file has been read |
get_samples() |
next(count) with count from set_sample_count (default 8192) |
Positions and lengths are in samples, not bytes (f.cur_samp, f.max_samp). A trailing partial sample in the
file is ignored.
Writing¶
FileSink(path, fmt, append=False, open=False, clip=False)truncates an existing file unlessappend=True. The format of an existing file is not checked when appending.- Opening a sink again after closing it starts the file over (
count, captures and annotations too), unlessappend=True. write()takes 1-D samples (other shapes raiseValueError: flatten, or write each channel to its own file) and needs the sink open (open(),open=Trueorwith).- A value outside the format's range (including NaN or infinity in an integer format) raises
ValueError; nothing wraps. Withclip=Truevalues saturate instead (each I/Q component on its own), NaN is stored as 0, and one warning, "N samples clipped", is logged when the sink closes.FileSink.clippedholds the running count.
SigMF¶
- A path ending in
.sigmf(or.sigmf-data/.sigmf-meta) makesFileSinkwrite SigMF;sigmf=Truedoes it for any name. The.sigmf-metafile is written when the sink opens, and brought up to date byflush()andclose(). write(x, meta=m)with theRxMetaofsdr.read(..., meta=True)records the stream as the device saw it: the sample rate and frequency (when not given), a capture at every retune, and an annotation wherever samples were lost or skipped by a flush.- From a radio whose clock holds a date (UHD set from GPS or
set_time_now, a replay),core:datetimeis the radio's time of the first sample (RxMeta.hw_time), not the computer's when the file was opened. Filetakes the format from the metadata (afmtgiven wins), and hasrate,freqandmeta(asigmf.Meta).- Datatypes: every format with a SigMF name (
Formats.cf32.sigmf == "cf32_le";Formats.get("cu8")works too). Not supported: big-endian, multi-channel recordings, and formats SigMF has no name for (4-bit, one's complement, float16). Appending to a SigMF recording isn't supported. - Reading, sample numbers count from the data file's first sample (
core:offsetis taken off), andmeta.datetimeis that sample's time.
Replay¶
- Samples are delivered in blocks on a thread, paced to the sample rate;
realtime=Falsedelivers them as fast as they are read (nothing is dropped: playback waits for the reader). - The frequency follows the recording: each SigMF capture is a retune, an
EventinRxMeta.set_rx_freqonly relabels the stream, and the sample rate is fixed at the recording's. - At the end it starts again with
loop=True; otherwise delivery stops,sdr.eofis True, andreadtimes out. - A recording that can't be read while it plays (cut short, a disk error) ends the stream:
readraiseserr.Lost. sdr.seek(sample),sdr.positionandsdr.lengthmove around the recording.RxMeta.hw_timeis when the recording took each sample (from the SigMFcore:datetime), across loops and seeks.- A server hosts it like any radio:
pysdrlib.device("remote", address, "file").open(path=..., loop=True), orpysdrlib server --open file:path=cap.sigmf,loop=true.
Transmitting to a file¶
- What is written goes to
tx_pathintx_format(defaultcf32; SigMF for a.sigmfname), scaled to the format's full scale and saturated there. - With
realtime(the default) it goes out at the transmit rate like a radio's:writeblocks while more thanTX_BUFFER_SECONDSis queued ahead of the clock, andget_tx_stats()countssent,pendingandunderruns(a write that came after everything had gone out).realtime=Falsetakes it as fast as it is written. tx_pathcan't be the recording being played (ValueError).- With
pathtoo, it plays a recording and records what is transmitted at once (a loopback for testing); without, it only transmits.
Errors¶
pysdrlib.file.err defines Overflow (asking for samples past either end of the file) and Underflow (the file had
fewer samples than its size promised, e.g. it was truncated while being read). Using a File or FileSink that is not
open raises pysdrlib.err.NotOpen.
Tests are in tests/test_file.py.
Modules:
| Name | Description |
|---|---|
err |
The file errors, now |
file |
Wrapper for processing files |
play |
|
replay |
A recording played back as a receiving device, and a file that what is transmitted is recorded to: |
sigmf |
SigMF recordings (https://sigmf.org): samples in |
sink |
Write samples to a file in any of the Formats |
err ¶
The file errors, now pysdrlib.err.Overflow and pysdrlib.err.Underflow (kept here under their old names)
Classes:
| Name | Description |
|---|---|
Overflow |
Error thrown by |
Underflow |
Error thrown by |
file ¶
Wrapper for processing files
Classes:
| Name | Description |
|---|---|
File |
Read samples from a file like a device: |
File ¶
Read samples from a file like a device: File(path, fmt), then next, forward, seek...
fmt names one of pysdrlib.Formats (e.g. "cf32", "ci8"; see pysdrlib.base.formats). Samples are returned as stored,
unless scale=True: then complex64 (or float32) with full scale at +-1, like a device's (see Formats.scale).
Usable as a context manager, which opens and closes it:
with File("capture.cfile", "cf32") as f: # cf32: two float32 per sample
for block in f.forward(8192, partial=True):
...
A SigMF recording ("x.sigmf-meta", "x.sigmf-data", "x.sigmf", or just "x") needs no fmt: it comes from the metadata, with rate, freq and the rest in meta.
Nor does a file whose extension names its format (".cfile", ".cf32", ".cs16", ".cu8"...; see Formats.from_extension).
Reading past the end raises pysdrlib.err.Overflow (or, with partial=True, returns what is left). Reading opens the
file if it isn't open yet.
A File can be pickled (to hand to a worker process) and copied. The new one has the same position and its own
handle, and starts closed: it opens at its first read, which is where a missing file raises. A relative path is
relative to the reader's working directory.
Methods:
| Name | Description |
|---|---|
open |
Open the file for reading, at the current position |
close |
Close the file; the position is kept |
get_samples |
The next |
set_sample_count |
Samples returned by |
set_fmt |
Set the sample format by name (a |
get_fmt |
The sample format (a |
set_path |
Set the file to read, from its first sample. Raises |
get_path |
The file being read (a |
reset |
Go back to the first sample |
seek |
Move to sample index |
next |
Return the next |
prev |
Move back |
forward |
Yield blocks of |
reverse |
Yield blocks of |
percent |
Return how much of the file has been read: 0.0-1.0 by default, 0-100 with |
Attributes:
| Name | Type | Description |
|---|---|---|
rate |
Sample rate of a SigMF recording (None: not recorded, or not SigMF) |
|
freq |
Centre frequency of the first sample of a SigMF recording (None: not recorded, or not SigMF) |
|
is_open |
bool
|
Whether the file is open ( |
Source code in src/pysdrlib/file/file.py
freq
property
¶
Centre frequency of the first sample of a SigMF recording (None: not recorded, or not SigMF)
is_open
property
¶
Whether the file is open (open, or the first read); close keeps the position for the next
open ¶
Open the file for reading, at the current position
Source code in src/pysdrlib/file/file.py
close ¶
get_samples ¶
set_sample_count ¶
set_fmt ¶
Set the sample format by name (a pysdrlib.Formats member); the file length in samples follows
Source code in src/pysdrlib/file/file.py
get_fmt ¶
set_path ¶
Set the file to read, from its first sample. Raises FileNotFoundError if it doesn't exist (the file read
before then stays). A SigMF recording's metadata is read. The format is the one given (fmt, set_fmt) if one
was; else this file's own, from its metadata or extension (None: neither says, so set_fmt it before reading).
An open File stays open, on the new file
Source code in src/pysdrlib/file/file.py
get_path ¶
reset ¶
seek ¶
Move to sample index samp
Source code in src/pysdrlib/file/file.py
next ¶
Return the next
With partial=True, a request running past EOF returns the remaining
samples (possibly an empty array) instead of raising Overflow.
Source code in src/pysdrlib/file/file.py
prev ¶
Move back
Source code in src/pysdrlib/file/file.py
forward ¶
Yield blocks of
With partial=True, a short final block is yielded too.
Source code in src/pysdrlib/file/file.py
reverse ¶
Yield blocks of count samples from the current position back toward the start, each one before the last
percent ¶
Return how much of the file has been read: 0.0-1.0 by default, 0-100 with fraction=False
Source code in src/pysdrlib/file/file.py
play ¶
pysdrlib play: look at a recording, play it in real time, or serve it like a radio
pysdrlib play capture.sigmf what it is, then its power second by second as it plays
pysdrlib play capture.cfile --fmt cf32 --rate 2e6 --freq 100e6 --loop
pysdrlib play capture.sigmf --info just what it is
pysdrlib play capture.sigmf --serve tcp://0.0.0.0:5555 --loop host it: clients open device file-0
Serving needs pyzmq (pip install pysdrlib[remote]); the rest needs nothing more.
Functions:
| Name | Description |
|---|---|
add_arguments |
Add the |
describe |
Lines saying what a |
run |
|
add_arguments ¶
Add the play command to the pysdrlib command's subparsers
Source code in src/pysdrlib/file/play.py
describe ¶
Lines saying what a File is
Source code in src/pysdrlib/file/play.py
run ¶
pysdrlib play: returns the exit status
Source code in src/pysdrlib/file/play.py
replay ¶
A recording played back as a receiving device, and a file that what is transmitted is recorded to:
pysdrlib.open("file", path=..., tx_path=...)
Classes:
| Name | Description |
|---|---|
Replay |
A recording, received like a radio: the same |
Replay ¶
Bases: NativeDevice
A recording, received like a radio: the same read, stream, RxMeta and drop reporting, from a thread that
delivers it in blocks at its sample rate (or as fast as it is read, realtime=False).
sdr = pysdrlib.open("file", path="capture.sigmf") # SigMF: format, rate, frequency
sdr = pysdrlib.open("file", path="capture.cfile", fmt="cf32", rate=2e6, freq=100e6, loop=True)
sdr.initialize() # the recording's rate and frequency
sdr.start_rx()
The frequency follows the recording: each SigMF capture is a retune (an Event in RxMeta, and get_rx_freq).
set_rx_freq only relabels the stream (a recording can't be retuned), and the rate is the recording's. At the end,
loop starts it again; otherwise delivery stops and eof is True (read then times out). If the recording can't
be read (cut short while it plays, a disk error), read raises err.Lost once what was read before it is read.
With tx_path (not the recording itself) it also transmits, into a file: start_tx and write as on a radio, at the transmit rate when
realtime (a write blocks while more than TX_BUFFER_SECONDS are ahead of the clock; written late, an underrun is
counted), the transmit frequency recorded as SigMF captures. Without path it only transmits.
sdr = pysdrlib.open("file", tx_path="sent.sigmf", rate=2e6)
sdr.initialize(cf=915e6, Fs=2e6); sdr.start_tx(); sdr.write(samples)
Methods:
| Name | Description |
|---|---|
seek |
Continue playback from |
get_rx_context |
How the recording was received (its |
Attributes:
| Name | Type | Description |
|---|---|---|
eof |
Playback reached the end of the recording (and |
|
position |
The sample of the recording delivered next |
|
length |
Samples in the recording |
Source code in src/pysdrlib/file/replay.py
seek ¶
Continue playback from sample of the recording (a jump in what is received, not a gap in the stream:
flush() to drop what was queued before it)
Source code in src/pysdrlib/file/replay.py
get_rx_context ¶
How the recording was received (its pysdrlib:rx), at the playback position's frequency; a recording that
doesn't say: this replay's own (no chain)
Source code in src/pysdrlib/file/replay.py
sigmf ¶
SigMF recordings (https://sigmf.org): samples in <name>.sigmf-data, what they are in <name>.sigmf-meta (JSON)
pysdrlib reads and writes the core namespace: the datatype, sample rate, the captures (the centre frequency from each
sample on, and when the recording started), and annotations (pysdrlib marks samples lost while recording with one).
How the radio received is its own extension, pysdrlib:rx in the global object (an RxContext: the chain between the
radio and the air with its LO and whether it inverts the spectrum, the reference correction and clock source, gains,
antenna port), declared in core:extensions as optional: other readers skip it, Meta.context gives it back.
Sample numbers are counted from the first sample of the data file: core:offset (a recording split over files) is
taken off the captures' and annotations' core:sample_start, in Meta (Meta.raw is the file as it is). When the
first capture has no core:datetime but a later one does, the first sample's time is worked back from it at the sample
rate.
Only single-channel, little-endian recordings in a datatype Formats has (see Formats.sigmf).
Classes:
| Name | Description |
|---|---|
Meta |
What a |
Functions:
| Name | Description |
|---|---|
is_sigmf |
|
paths |
(data path, meta path) of the recording |
iso |
Seconds since the epoch, as SigMF writes a time (ISO 8601, UTC) |
now |
The current time, as SigMF writes it |
read |
The metadata of the recording |
write |
Write the |
Meta
dataclass
¶
Meta(fmt: Formats, rate: Optional[float] = None, captures: list = list(), datetime: Optional[str] = None, annotations: list = list(), raw: dict = dict())
What a .sigmf-meta says, as pysdrlib uses it. captures: [(first sample, frequency or None)], in order;
datetime: when the first sample was taken. Sample numbers (captures, annotations) count from the data file's first;
raw: the whole JSON, as it is, for any other field
Methods:
| Name | Description |
|---|---|
freq_at |
Centre frequency at |
Attributes:
| Name | Type | Description |
|---|---|---|
start_time |
When the first sample was taken, in seconds since the epoch (from |
|
context |
How the radio received ( |
|
freq |
Centre frequency of the first sample (None: not recorded) |
start_time
property
¶
When the first sample was taken, in seconds since the epoch (from datetime; None if not recorded)
context
property
¶
How the radio received (RxContext), when the recording says (pysdrlib:rx); None otherwise
freq_at ¶
Centre frequency at sample: the one of the last capture that starts at or before it
Source code in src/pysdrlib/file/sigmf.py
is_sigmf ¶
path names a SigMF recording: one of its files (".sigmf-data", ".sigmf-meta"), or ".sigmf" for both
paths ¶
(data path, meta path) of the recording path names (any of its files, ".sigmf", or the name without a suffix)
Source code in src/pysdrlib/file/sigmf.py
iso ¶
now ¶
read ¶
The metadata of the recording path names. Raises ValueError for one pysdrlib can't read
Source code in src/pysdrlib/file/sigmf.py
write ¶
Write the .sigmf-meta of the recording path names. captures: [(first sample, frequency)]; extra: more
global fields ({"core:hw": ...}); context: how the radio received (an RxContext, stored as pysdrlib:rx). Written
to a temporary file and renamed, so a reader never sees half of it
Source code in src/pysdrlib/file/sigmf.py
sink ¶
Write samples to a file in any of the Formats
Classes:
| Name | Description |
|---|---|
FileSink |
Counterpart of File: |
FileSink ¶
FileSink(path, fmt: str | None = None, append: bool = False, open: bool = False, clip: bool = False, scale: bool = False, sigmf: bool | None = None, rate: float | None = None, freq: float | None = None, hw: str | None = None, context=None)
Counterpart of File: FileSink(path, fmt), then write(samples). fmt left out: the one the extension names
(".cs16" -> ci16t...; see Formats.from_extension), else cf32.
Truncates an existing file unless append=True (the format of an existing file is not checked). So opening a sink
again after close starts the file over: count, clipped, the captures and the annotations start over with it.
open=True opens it on construction.
scale=True takes samples as a device gives them (full scale at +-1) and stores them at the format's full scale, the
inverse of File(..., scale=True). clip=True saturates values outside the format's range (and stores NaN as 0 in integer formats)
instead of raising ValueError, and logs one warning
("N samples clipped") when the sink closes. clipped holds the running count. Usable as a context manager.
A SigMF recording is written for a path ending in ".sigmf" (or ".sigmf-data"/".sigmf-meta"), or with sigmf=True:
the samples in <name>.sigmf-data, and <name>.sigmf-meta with the format, rate, freq, hw (a description
of the radio) and context (how it received: Device.get_rx_context(), kept as pysdrlib:rx; its rate, frequency
and radio fill in those not given). The meta file is written on open and kept up to date by flush and close. write(samples, meta=m)
with a device's RxMeta fills in the rate and frequency, starts a new capture at each retune, and annotates where
samples were lost; retune(freq) starts a capture by hand.
Methods:
| Name | Description |
|---|---|
open |
Open the file for writing (truncating it unless |
close |
Close the file (writing the SigMF metadata), logging a warning if |
retune |
The samples written from now on are at |
write |
Append samples (a 1-D array-like) in the sink's format. |
flush |
Write buffered samples to disk (and the SigMF metadata so far) |
Attributes:
| Name | Type | Description |
|---|---|---|
freq |
The frequency of the samples being written now (SigMF: the last capture's) |
Source code in src/pysdrlib/file/sink.py
open ¶
Open the file for writing (truncating it unless append=True)
Source code in src/pysdrlib/file/sink.py
close ¶
Close the file (writing the SigMF metadata), logging a warning if clip=True saturated any samples
Source code in src/pysdrlib/file/sink.py
retune ¶
write ¶
Append samples (a 1-D array-like) in the sink's format.
meta: the RxMeta a device's read(..., meta=True) returned with them: the rate, frequency, retunes and lost
samples are recorded (in the SigMF metadata).
Values outside the format's range raise ValueError unless the sink was made with clip=True.