Skip to content

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 unless append=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), unless append=True.
  • write() takes 1-D samples (other shapes raise ValueError: flatten, or write each channel to its own file) and needs the sink open (open(), open=True or with).
  • A value outside the format's range (including NaN or infinity in an integer format) raises ValueError; nothing wraps. With clip=True values 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.clipped holds the running count.

SigMF

  • A path ending in .sigmf (or .sigmf-data/.sigmf-meta) makes FileSink write SigMF; sigmf=True does it for any name. The .sigmf-meta file is written when the sink opens, and brought up to date by flush() and close().
  • write(x, meta=m) with the RxMeta of sdr.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:datetime is the radio's time of the first sample (RxMeta.hw_time), not the computer's when the file was opened.
  • File takes the format from the metadata (a fmt given wins), and has rate, freq and meta (a sigmf.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:offset is taken off), and meta.datetime is that sample's time.

Replay

  • Samples are delivered in blocks on a thread, paced to the sample rate; realtime=False delivers 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 Event in RxMeta. set_rx_freq only 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.eof is True, and read times out.
  • A recording that can't be read while it plays (cut short, a disk error) ends the stream: read raises err.Lost.
  • sdr.seek(sample), sdr.position and sdr.length move around the recording.
  • RxMeta.hw_time is when the recording took each sample (from the SigMF core:datetime), across loops and seeks.
  • A server hosts it like any radio: pysdrlib.device("remote", address, "file").open(path=..., loop=True), or pysdrlib server --open file:path=cap.sigmf,loop=true.

Transmitting to a file

  • What is written goes to tx_path in tx_format (default cf32; SigMF for a .sigmf name), 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: write blocks while more than TX_BUFFER_SECONDS is queued ahead of the clock, and get_tx_stats() counts sent, pending and underruns (a write that came after everything had gone out). realtime=False takes it as fast as it is written.
  • tx_path can't be the recording being played (ValueError).
  • With path too, 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 pysdrlib.err.Overflow and pysdrlib.err.Underflow (kept here under their old names)

file

Wrapper for processing files

play

pysdrlib play: look at a recording, play it in real time, or serve it like a radio

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 <name>.sigmf-data, what they are in <name>.sigmf-meta (JSON)

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 File when asked for samples past the end of the file (or before its start)

Underflow

Error thrown by File when the file held fewer samples than its size says, e.g. it was truncated while being read

Overflow

Bases: _Error, EOFError

Error thrown by File when asked for samples past the end of the file (or before its start)

Underflow

Bases: _Error

Error thrown by File when the file held fewer samples than its size says, e.g. it was truncated while being read

file

Wrapper for processing files

Classes:

Name Description
File

Read samples from a file like a device: File(path, fmt), then next, forward, seek...

File

File(path=None, fmt: str | None = None, scale: bool = False)

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 count samples (see set_sample_count), as a device's get_samples would

set_sample_count

Samples returned by get_samples (default 8192)

set_fmt

Set the sample format by name (a pysdrlib.Formats member); the file length in samples follows

get_fmt

The sample format (a pysdrlib.Formats member)

set_path

Set the file to read, from its first sample. Raises FileNotFoundError if it doesn't exist (the file read

get_path

The file being read (a pathlib.Path)

reset

Go back to the first sample

seek

Move to sample index samp

next

Return the next samples and move forward.

prev

Move back samples and return them (the samples just before the old position)

forward

Yield blocks of samples until EOF.

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

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 (open, or the first read); close keeps the position for the next

Source code in src/pysdrlib/file/file.py
def __init__(self, path=None, fmt: str | None = None, scale: bool = False):
    self.log = logger.new("device.File")
    self.scale = scale   # return samples scaled to +-1, like a device (otherwise as stored)
    self.fmt: Formats = None # type: ignore
    self.path: Path = None # type: ignore
    self.meta: _sigmf.Meta | None = None   # a SigMF recording's metadata
    self.count = 8192
    self.cur_samp = 0
    self.max_samp = 0
    self._fsize = 0
    self.f = None
    self._fmt_given = False   # `fmt` was given (it stays), not derived from a file (the next one has its own)
    if fmt is not None:
        self.set_fmt(fmt)
    if path is not None:
        self.set_path(path)
    if self.fmt is None and path is not None:
        raise err.UnknownFormat(f"{path}: give the sample format (fmt=...): its extension doesn't name one, and it isn't SigMF")
rate property
rate

Sample rate of a SigMF recording (None: not recorded, or not SigMF)

freq property
freq

Centre frequency of the first sample of a SigMF recording (None: not recorded, or not SigMF)

is_open property
is_open: bool

Whether the file is open (open, or the first read); close keeps the position for the next

open
open()

Open the file for reading, at the current position

Source code in src/pysdrlib/file/file.py
def open(self):
    """Open the file for reading, at the current position"""
    self.log.trace("open()")
    if self.f is not None:
        self.log.warning("File is already open!")
    else:
        self.f = open(self.path, "rb")
        if self.fmt is not None:
            self._seek(self.cur_samp)
close
close()

Close the file; the position is kept

Source code in src/pysdrlib/file/file.py
def close(self):
    """Close the file; the position is kept"""
    self.log.trace("close()")
    if self.f is None:
        self.log.warning("File is already closed!")
    else:
        self.f.close()
        self.f = None
get_samples
get_samples()

The next count samples (see set_sample_count), as a device's get_samples would

Source code in src/pysdrlib/file/file.py
def get_samples(self):
    """The next `count` samples (see `set_sample_count`), as a device's `get_samples` would"""
    return self.next(self.count)
set_sample_count
set_sample_count(count: int)

Samples returned by get_samples (default 8192)

Source code in src/pysdrlib/file/file.py
def set_sample_count(self, count: int):
    """Samples returned by `get_samples` (default 8192)"""
    self.log.trace("set_sample_count(%s)", count)
    self.count = count
set_fmt
set_fmt(fmt: str)

Set the sample format by name (a pysdrlib.Formats member); the file length in samples follows

Source code in src/pysdrlib/file/file.py
def set_fmt(self, fmt: str):
    """Set the sample format by name (a `pysdrlib.Formats` member); the file length in samples follows"""
    self.log.trace("set_fmt(%s)", fmt)
    self.fmt = Formats.get(fmt)
    self._fmt_given = True
    if not self._fsize == 0:
        self.max_samp = self._fsize // self.fmt.bytes
get_fmt
get_fmt()

The sample format (a pysdrlib.Formats member)

Source code in src/pysdrlib/file/file.py
def get_fmt(self):
    """The sample format (a `pysdrlib.Formats` member)"""
    return self.fmt
set_path
set_path(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
def set_path(self, 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"""
    self.log.trace("set_path(%s)", path)
    path = Path(path)
    data, meta_path = _sigmf.paths(path)
    meta = None
    if _sigmf.is_sigmf(path) or (not path.exists() and meta_path.is_file()):
        path = data
        meta = _sigmf.read(meta_path)
    fmt = self.fmt if self._fmt_given else (meta.fmt if meta is not None else Formats.from_extension(path))
    size = path.stat().st_size
    handle = open(path, "rb") if self.f is not None else None
    if self.f is not None:
        self.f.close()
    self.f, self.path, self.meta, self.fmt, self._fsize = handle, path, meta, fmt, size
    self.cur_samp = 0
    self.max_samp = size // fmt.bytes if fmt is not None else 0
get_path
get_path()

The file being read (a pathlib.Path)

Source code in src/pysdrlib/file/file.py
def get_path(self):
    """The file being read (a `pathlib.Path`)"""
    return self.path
reset
reset()

Go back to the first sample

Source code in src/pysdrlib/file/file.py
def reset(self):
    """Go back to the first sample"""
    self.log.trace("reset()")
    self.cur_samp = 0
    if self.f is not None:
        self._seek(0)
seek
seek(samp: int)

Move to sample index samp

Source code in src/pysdrlib/file/file.py
def seek(self, samp: int):
    """Move to sample index `samp`"""
    self.log.trace("seek(%s)", samp)
    if samp < 0 or samp > self.max_samp:
        raise err.Overflow(f"seek({samp}) outside 0..{self.max_samp}")
    self.cur_samp = samp
    if self.f is not None:
        self._seek(samp)
next
next(count: int, partial: bool = False)

Return the next samples and move forward.

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
def next(self, count: int, partial: bool = False):
    """Return the next <count> samples and move forward.

    With `partial=True`, a request running past EOF returns the remaining
    samples (possibly an empty array) instead of raising Overflow.
    """
    self.log.trace("next()")
    self._ensure_open("next")
    self._need_fmt()
    if partial:
        count = max(0, min(count, self.max_samp - self.cur_samp))
    if self.cur_samp + count > self.max_samp:
        raise err.Overflow(f"{self.cur_samp}+{count} > {self.max_samp}")
    samps = self._read(count)
    if len(samps) < count:
        raise err.Underflow(f"self._read({count}) at idx {self.cur_samp}, got {len(samps)}")
    self.cur_samp += count
    return samps
prev
prev(count: int)

Move back samples and return them (the samples just before the old position)

Source code in src/pysdrlib/file/file.py
def prev(self, count: int):
    """Move back <count> samples and return them (the samples just before the old position)"""
    self.log.trace("prev()")
    self._ensure_open("prev")
    self._need_fmt()
    if self.cur_samp - count < 0:
        raise err.Overflow(f"{self.cur_samp}-{count} < 0")
    self.cur_samp -= count
    self._seek(self.cur_samp)
    samps = self._read(count)
    self._seek(self.cur_samp)  # reading advanced the file; stay at cur_samp
    if len(samps) < count:
        raise err.Underflow(f"self._read({count}) at idx {self.cur_samp}, got {len(samps)}")
    return samps
forward
forward(count: int, partial: bool = False)

Yield blocks of samples until EOF.

With partial=True, a short final block is yielded too.

Source code in src/pysdrlib/file/file.py
def forward(self, count: int, partial: bool = False):
    """Yield blocks of <count> samples until EOF.

    With `partial=True`, a short final block is yielded too.
    """
    while self.cur_samp + count <= self.max_samp:
        yield self.next(count)
    if partial and self.cur_samp < self.max_samp:
        yield self.next(count, partial=True)
reverse
reverse(count: int)

Yield blocks of count samples from the current position back toward the start, each one before the last

Source code in src/pysdrlib/file/file.py
def reverse(self, count: int):
    """Yield blocks of `count` samples from the current position back toward the start, each one before the last"""
    while self.cur_samp - count >= 0:
        # return self.prev(count)
        yield self.prev(count)
percent
percent(fraction: bool = True)

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
def percent(self, fraction: bool = True):
    """Return how much of the file has been read: 0.0-1.0 by default, 0-100 with `fraction=False`"""
    if self.max_samp == 0:
        return 0.0
    done = float(self.cur_samp/self.max_samp)
    return done if fraction else done * 100

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 play command to the pysdrlib command's subparsers

describe

Lines saying what a File is

run

pysdrlib play: returns the exit status

add_arguments

add_arguments(sub)

Add the play command to the pysdrlib command's subparsers

Source code in src/pysdrlib/file/play.py
def add_arguments(sub):
    """Add the `play` command to the `pysdrlib` command's subparsers"""
    p = sub.add_parser("play", help="look at a recording, play it in real time, or serve it like a radio",
                       description=__doc__.split("\n\n")[0])
    p.add_argument("path", help="the recording: a SigMF one (NAME.sigmf, or either of its files), or a raw file")
    p.add_argument("--fmt", help="its sample format, for a raw file whose extension doesn't name one (see pysdrlib.Formats: cf32, ci16t, cui8...)")
    p.add_argument("--rate", type=float, help="its sample rate, for a raw file (Hz)")
    p.add_argument("--freq", type=float, help="its centre frequency (Hz; for SigMF: overrides the recording's)")
    p.add_argument("--loop", action="store_true", help="start again at the end")
    p.add_argument("--info", action="store_true", help="say what the recording is, and don't play it")
    p.add_argument("--interval", type=float, default=1.0, metavar="S", help="seconds between lines while playing (default %(default)s)")
    p.add_argument("--fast", action="store_true", help="as fast as it can be read, not at the sample rate")
    p.add_argument("--serve", metavar="ENDPOINT", help="host it like a radio at this C2 endpoint (e.g. tcp://0.0.0.0:5555) until Ctrl+C")
    return p

describe

describe(f, rate)

Lines saying what a File is

Source code in src/pysdrlib/file/play.py
def describe(f, rate):
    """Lines saying what a `File` is"""
    lines = [f"{f.path}", f"  format {f.fmt.name}" + (f" (SigMF {f.fmt.sigmf})" if f.fmt.sigmf else "") +
             f", {f.max_samp:,} samples" + (f", {f.max_samp / rate:.3f} s at {_hz(rate)}" if rate else ", rate unknown")]
    meta = f.meta
    if meta is not None:
        glob = meta.raw.get("global", {})
        if meta.datetime:
            lines.append(f"  recorded {meta.datetime}" + (f" on {glob['core:hw']}" if glob.get("core:hw") else ""))
        lines.append(f"  {len(meta.captures)} capture(s): " + ", ".join(
            f"{_hz(fr)} from {start:,}" for start, fr in meta.captures[:8]) + (" ..." if len(meta.captures) > 8 else ""))
        if meta.context is not None:
            lines.append("  received " + _received(meta.context))
        if meta.annotations:
            lines.append(f"  {len(meta.annotations)} annotation(s): " + "; ".join(
                f"{a.get('core:sample_start', '?'):,}: {a.get('core:comment') or a.get('core:label') or ''}".strip()
                for a in meta.annotations[:4]) + (" ..." if len(meta.annotations) > 4 else ""))
    return lines

run

run(args) -> int

pysdrlib play: returns the exit status

Source code in src/pysdrlib/file/play.py
def run(args) -> int:
    """`pysdrlib play`: returns the exit status"""
    import pysdrlib
    from .file import File
    try:
        f = File(args.path, args.fmt)
    except (OSError, ValueError, KeyError) as e:
        raise SystemExit(f"error: {e}")
    rate = args.rate or f.rate
    for line in describe(f, rate):
        print(line)
    if args.info:
        return 0
    if not f.fmt.is_complex:
        raise SystemExit(f"error: {f.fmt.name} is a real format: only I/Q recordings can be played")
    if rate is None:
        raise SystemExit("error: the recording doesn't say its sample rate: give --rate")
    open_args = {"path": str(args.path), "fmt": args.fmt, "rate": args.rate, "freq": args.freq, "loop": args.loop,
                 "realtime": not args.fast}
    if args.serve:
        return _serve(args, open_args)
    sdr = pysdrlib.open("file", **open_args)
    sdr.on_drop = "ignore"   # a terminal that can't keep up only skips lines' worth
    try:
        sdr.initialize()
        block = max(1, int(rate * min(args.interval, 1.0) / 4))
        per_line = max(1, int(round(args.interval * rate / block)))
        print(f"playing{' (looping)' if args.loop else ''}: Ctrl+C to stop")
        with sdr.stream(block, meta=True, timeout=1.0) as s:
            acc = peak = 0.0
            n = 0
            for k, (x, m) in enumerate(s, 1):
                p = np.abs(x) ** 2
                acc, peak, n = acc + float(p.sum()), max(peak, float(p.max())), n + len(x)
                if k % per_line == 0:
                    print(f"  {(m.index + len(x)) / rate:8.2f} s  {_hz(m.freq):>12}  power {_db(acc / n):6.1f} dBFS  "
                          f"peak {_db(peak):6.1f} dBFS" + (f"  [{100 * sdr.position / max(1, sdr.length):3.0f}%]"))
                    acc = peak = 0.0
                    n = 0
    except pysdrlib.err.Timeout:
        if not sdr.eof:
            raise
        print("end of the recording")
    except KeyboardInterrupt:
        pass
    finally:
        sdr.close()
    return 0

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 read, stream, RxMeta and drop reporting, from a thread that

Replay

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 sample of the recording (a jump in what is received, not a gap in the stream:

get_rx_context

How the recording was received (its pysdrlib:rx), at the playback position's frequency; a recording that

Attributes:

Name Type Description
eof

Playback reached the end of the recording (and loop is off)

position

The sample of the recording delivered next

length

Samples in the recording

Source code in src/pysdrlib/file/replay.py
def __init__(self):
    super().__init__()
    self.file: File = None  # type: ignore
    self.loop = False
    self.realtime = True
    self.block_samples = 65536
    self._eof = False
    self._failed = None            # why playback stopped, when the recording couldn't be read
    self._seek_to = None
    self._next_samp = None         # the recording's sample after the last block delivered
    self._freq = None              # the recording's frequency at the playback position
    self._retunes = collections.deque()   # (stream index, freq) from the playback thread, for the reader's
    self._thread = None
    self._stop = threading.Event()
    self._lock = threading.Lock()   # the file, between the playback thread and seek
    self.sink: FileSink = None  # type: ignore   # what is transmitted goes here (tx_path)
    self._tx = {"written": 0, "underruns": 0, "t0": None, "sent0": 0}
eof property
eof

Playback reached the end of the recording (and loop is off)

position property
position

The sample of the recording delivered next

length property
length

Samples in the recording

seek
seek(sample)

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
def seek(self, sample):
    """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)"""
    self._ensure_open("seek")
    self._need_recording("seek")
    if not 0 <= sample <= self.length:
        raise ValueError(f"seek({sample}) outside 0..{self.length}")
    with self._lock:
        self._seek_to = int(sample)
        self._eof = False
    if not self.state["rx"]:
        self._apply_seek(0)
get_rx_context
get_rx_context(channel=0)

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
def get_rx_context(self, channel=0):
    """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)"""
    rec = self.file.meta.context if self.file is not None and self.file.meta is not None else None
    if rec is None:
        return super().get_rx_context(channel)
    return dataclasses.replace(rec, freq=self.get_rx_freq(channel), rate=self._rate if self._rate is not None else rec.rate)

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 .sigmf-meta says, as pysdrlib uses it. captures: [(first sample, frequency or None)], in order;

Functions:

Name Description
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)

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 path names. Raises ValueError for one pysdrlib can't read

write

Write the .sigmf-meta of the recording path names. captures: [(first sample, frequency)]; extra: more

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 sample: the one of the last capture that starts at or before it

Attributes:

Name Type Description
start_time

When the first sample was taken, in seconds since the epoch (from datetime; None if not recorded)

context

How the radio received (RxContext), when the recording says (pysdrlib:rx); None otherwise

freq

Centre frequency of the first sample (None: not recorded)

start_time property
start_time

When the first sample was taken, in seconds since the epoch (from datetime; None if not recorded)

context property
context

How the radio received (RxContext), when the recording says (pysdrlib:rx); None otherwise

freq property
freq

Centre frequency of the first sample (None: not recorded)

freq_at
freq_at(sample)

Centre frequency at sample: the one of the last capture that starts at or before it

Source code in src/pysdrlib/file/sigmf.py
def freq_at(self, sample):
    """Centre frequency at `sample`: the one of the last capture that starts at or before it"""
    freq = self.freq
    for start, f in self.captures:
        if start > sample:
            break
        freq = f if f is not None else freq
    return freq

is_sigmf

is_sigmf(path) -> bool

path names a SigMF recording: one of its files (".sigmf-data", ".sigmf-meta"), or ".sigmf" for both

Source code in src/pysdrlib/file/sigmf.py
def is_sigmf(path) -> bool:
    """`path` names a SigMF recording: one of its files (".sigmf-data", ".sigmf-meta"), or ".sigmf" for both"""
    return Path(path).suffix in _SUFFIXES

paths

paths(path)

(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
def paths(path):
    """(data path, meta path) of the recording `path` names (any of its files, ".sigmf", or the name without a suffix)"""
    p = Path(path)
    base = p.with_suffix("") if p.suffix in _SUFFIXES else p
    return base.with_name(base.name + ".sigmf-data"), base.with_name(base.name + ".sigmf-meta")

iso

iso(seconds)

Seconds since the epoch, as SigMF writes a time (ISO 8601, UTC)

Source code in src/pysdrlib/file/sigmf.py
def iso(seconds):
    """Seconds since the epoch, as SigMF writes a time (ISO 8601, UTC)"""
    return _dt.datetime.fromtimestamp(seconds, _dt.timezone.utc).isoformat().replace("+00:00", "Z")

now

now()

The current time, as SigMF writes it

Source code in src/pysdrlib/file/sigmf.py
def now():
    """The current time, as SigMF writes it"""
    return iso(_dt.datetime.now(_dt.timezone.utc).timestamp())

read

read(path) -> Meta

The metadata of the recording path names. Raises ValueError for one pysdrlib can't read

Source code in src/pysdrlib/file/sigmf.py
def read(path) -> Meta:
    """The metadata of the recording `path` names. Raises ValueError for one pysdrlib can't read"""
    _, meta_path = paths(path)
    with retry_busy(open, meta_path, encoding="utf-8") as f:
        raw = json.load(f)
    glob = raw.get("global", {})
    datatype = glob.get("core:datatype")
    try:
        fmt = Formats.get(datatype)
    except KeyError as e:
        raise _err.UnknownFormat(f"{meta_path}: datatype {datatype!r} is not supported: {e}") from None
    if int(glob.get("core:num_channels", 1)) != 1:
        raise ValueError(f"{meta_path}: {glob['core:num_channels']} channels; only single-channel recordings are supported")
    caps = sorted(raw.get("captures", []), key=lambda c: c.get("core:sample_start", 0))
    offset = int(glob.get("core:offset", 0) or 0)
    starts = [int(c.get("core:sample_start", 0)) - offset for c in caps]
    captures = [(max(0, start), c.get("core:frequency")) for k, (start, c) in enumerate(zip(starts, caps))
                if not (k + 1 < len(starts) and start < 0 and starts[k + 1] <= 0)]   # (superseded before the file starts)
    rate = glob.get("core:sample_rate")
    rate = float(rate) if rate is not None else None
    when = next(((start, c["core:datetime"]) for start, c in zip(starts, caps) if "core:datetime" in c), None)
    if when is not None:
        when = _first_sample_time(*when, rate)
    annotations = raw.get("annotations", [])
    if offset:
        annotations = [a for a in (_shifted(a, offset) for a in annotations) if a is not None]
    return Meta(fmt, rate, captures, when, annotations, raw)

write

write(path, fmt, rate=None, captures=(), datetime=None, annotations=(), extra=None, context=None)

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
def write(path, fmt, rate=None, captures=(), datetime=None, annotations=(), extra=None, context=None):
    """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"""
    fmt = Formats.get(fmt)
    if fmt.sigmf is None:
        raise ValueError(f"SigMF has no datatype for {fmt.name}: use one of "
                         f"{', '.join(f.name for f in Formats if f.sigmf)}")
    _, meta_path = paths(path)
    from .. import __version__
    glob = {"core:datatype": fmt.sigmf, "core:version": VERSION, "core:recorder": f"pysdrlib {__version__}"}
    if rate is not None:
        glob["core:sample_rate"] = float(rate)
    glob.update(extra or {})
    if context is not None:
        glob["core:extensions"] = [*(e for e in glob.get("core:extensions", []) if e.get("name") != EXTENSION),
                                   {"name": EXTENSION, "version": EXTENSION_VERSION, "optional": True}]
        glob[EXTENSION + ":rx"] = context.json()
    caps = []
    for k, (start, freq) in enumerate(captures or [(0, None)]):
        c = {"core:sample_start": int(start)}
        if freq is not None:
            c["core:frequency"] = float(freq)
        if k == 0 and datetime is not None:
            c["core:datetime"] = datetime
        caps.append(c)
    doc = {"global": glob, "captures": caps, "annotations": list(annotations)}
    tmp = meta_path.with_name(meta_path.name + ".tmp")
    with open(tmp, "w", encoding="utf-8") as f:
        json.dump(doc, f, indent=2, default=_plain)
    retry_busy(os.replace, tmp, meta_path)

sink

Write samples to a file in any of the Formats

Classes:

Name Description
FileSink

Counterpart of File: FileSink(path, fmt), then write(samples). fmt left out: the one the extension names

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 append=True)

close

Close the file (writing the SigMF metadata), logging a warning if clip=True saturated any samples

retune

The samples written from now on are at freq (a new SigMF capture)

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
def __init__(self, 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):
    self.log = logger.new("device.FileSink")
    self.sigmf = _sigmf.is_sigmf(path) if sigmf is None else bool(sigmf)
    self.path = _sigmf.paths(path)[0] if self.sigmf else Path(path)
    self.fmt: Formats = Formats.get(fmt) if fmt is not None else (Formats.from_extension(self.path) or Formats.cf32)
    if self.sigmf and self.fmt.sigmf is None:
        raise ValueError(f"SigMF has no datatype for {self.fmt.name}")
    if self.sigmf and append:
        raise ValueError("appending to a SigMF recording is not supported")
    self.append = append
    self.clip = clip
    self.scale = scale   # samples come with full scale at +-1, like a device's (see Formats.unscale)
    self.count = 0    # samples written through this sink
    self.clipped = 0  # samples that were saturated (clip=True only)
    self.context = context   # how the radio received (RxContext), for SigMF
    if context is not None:
        rate = context.rate if rate is None else rate
        freq = context.freq if freq is None else freq
        hw = context.hw if hw is None else hw
    self.rate = rate
    self._rate_from_meta = False  # `rate` came from an RxMeta, so it is this recording's alone
    self._opened = False
    self.hw = hw
    self.captures = [(0, freq)]   # (first sample, frequency) (SigMF)
    self.annotations = []
    self._datetime = None
    self._last_index = None       # the stream index after the last RxMeta written
    self._rate_warned = False
    self.f = None
    if open:
        self.open()
freq property
freq

The frequency of the samples being written now (SigMF: the last capture's)

open
open()

Open the file for writing (truncating it unless append=True)

Source code in src/pysdrlib/file/sink.py
def open(self):
    """Open the file for writing (truncating it unless `append=True`)"""
    self.log.trace("open()")
    if self.f is not None:
        self.log.warning("File is already open!")
    else:
        self.f = open(self.path, "ab" if self.append else "wb")
        if self._opened and not self.append:
            self._start_over()
        self._opened = True
        if self.sigmf:
            self._datetime = _sigmf.now()
            self._write_meta()
close
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
def close(self):
    """Close the file (writing the SigMF metadata), logging a warning if `clip=True` saturated any samples"""
    self.log.trace("close()")
    if self.f is None:
        self.log.warning("File is already closed!")
    else:
        self.f.close()
        self.f = None
        if self.sigmf:
            self._write_meta()
        if self.clipped:
            self.log.warning("%d samples clipped writing %s", self.clipped, self.path)
retune
retune(freq)

The samples written from now on are at freq (a new SigMF capture)

Source code in src/pysdrlib/file/sink.py
def retune(self, freq):
    """The samples written from now on are at `freq` (a new SigMF capture)"""
    self._capture(self.count, freq)
write
write(samples, meta=None)

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.

Source code in src/pysdrlib/file/sink.py
def write(self, samples, meta=None):
    """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`.
    """
    if self.f is None:
        raise pysdr_err.NotOpen("Cannot call `write` when file isn't open")
    arr = np.asarray(samples)
    if arr.ndim != 1:
        raise ValueError(f"write() takes 1-D samples, got shape {arr.shape}; flatten or write per channel")
    if self.scale:
        arr = self.fmt.unscale(arr)
    nclipped = 0
    if self.clip:
        arr, nclipped = self._clip(arr)
    try:
        self.fmt.write(self.f, arr)
    except RangeError as e:
        raise RangeError(f"{e} (FileSink(clip=True) saturates instead)") from e
    # only after the write succeeded, so a failed write leaves the counters alone
    if meta is not None:
        self._note(meta)
        self._events(meta, self.count)
    self.count += len(arr)
    self.clipped += nclipped
flush
flush()

Write buffered samples to disk (and the SigMF metadata so far)

Source code in src/pysdrlib/file/sink.py
def flush(self):
    """Write buffered samples to disk (and the SigMF metadata so far)"""
    if self.f is not None:
        self.f.flush()
        if self.sigmf:
            self._write_meta()