Skip to content

Shm

pysdrlib.shm

Streams in shared memory: one process publishes samples under a name, any other on the machine receives them like a radio

from pysdrlib.shm import ShmStream
with ShmStream("rpps.ch3", Fs=250e3, cf=433.92e6, bw=200e3) as out:    # the publisher
    out.publish(x, first)                                             # complex64, at stream index `first`

sdr = pysdrlib.open("shm@rpps.ch3")                                   # any other process
sdr.initialize(); x, m = sdr.read(65536, meta=True)

pysdrlib.find() lists the streams published (shm is a driver like any other, with nothing to build). A program that reads radios through pysdrlib reads these the same way: the publisher's rate and frequency, RxMeta.index and gaps across what the publisher lost, hw_time/wall_time from the publisher's clock, and a "freq" or "rate" Event when it retunes. A pysdrlib server shares a radio with its local clients over the same ring (ring), with the ZeroMQ socket in place of the manifest.

Publishing

ShmStream(...)
name Letters, digits, _, . and -; a . makes a namespace ("rpps.ch3"). Not / or @: the name is the @ part of a target string. Raises FileExistsError while a running process publishes it
Fs, cf Sample rate and centre frequency of what is published
capacity Samples the ring holds: default one second, at least 2^18, held to what /dev/shm has room for (OSError when not even that fits)
**info Anything else for readers, as JSON values (bw, label...): the manifest's "info", DeviceInfo.extra["info"], sdr.manifest["info"]
publish(x, first, wall_time=None) Append complex64 samples whose first has stream index first: at or after head, later leaves a gap. wall_time is time.time() of x[0], where the source knows it (RxMeta.wall_time); the first publish of a generation anchors readers' timestamps there (default: now)
retune(Fs=, cf=, capacity=, **info) A new generation on a new ring, its indices starting over. Readers finish the old one, then follow
close() Readers finish what is there, then their read raises err.Lost. Also on with exit, and when the object is collected

Receiving

  • pysdrlib.open("shm@NAME") (the end of a name will do, if only one stream has it), pysdrlib.open("shm", name=...), or pysdrlib.open("shm") when only one stream is published. directory= reads another directory.
  • The rate and frequency are the publisher's: setting them only clamps to them (raises with sdr.strict). There is no gain. sdr.manifest is the manifest of the generation being received.
  • Receiving starts with what is published next. A reader that falls a whole ring behind loses the oldest samples, a gap in RxMeta like a radio's overflow; the publisher never waits for a reader.
  • The stream ends (err.Lost after what is there is read) when the publisher closes it, or its process is gone.

The manifest

<directory>/<name>.json, replaced at once (never half written). The directory is $PYSDRLIB_SHM_DIR, else pysdrlib-shm in the temporary directory. stream.streams() lists the manifests of running publishers (prefix=: only names starting with it).

Field
format 1. A reader skips a manifest of a format it doesn't know
name, segment, gen, capacity The stream's name; the ring's shared-memory segment (a name, as SharedMemory(name=) takes); the generation (0, then one more for each retune, also the ring's stream_id); the ring's samples
Fs, cf Sample rate and centre frequency of the generation
pid The publisher's process: a manifest whose process is gone is left out
wall_time, wall_index time.time() of the ring sample wall_index (the generation's first published), or null before the first publish
anchors {segment: [wall_time, wall_index]} of the last 8 generations, for a reader still on one when the publisher retuned
info The publisher's own fields

A retune writes the new manifest, then closes the old ring and removes it; close closes the ring, removes the manifest, then the ring. A reader that sees its ring closed reads the manifest: a new segment is the next generation, none (or the same) is the end.

The ring's own rules (one writer, complex64, polling, gaps) are in ring. Tests are in tests/test_shm_stream.py (the ring alone: tests/test_shm.py).

Modules:

Name Description
device

ShmDevice: a stream another process publishes (ShmStream), received like a radio

ring

The ring: complex64 samples in a named shared-memory segment, one writer and any number of readers

stream

The writer's end of a named stream: a ring (ring.ShmWriter) and a manifest that says what is in it

device

ShmDevice: a stream another process publishes (ShmStream), received like a radio

Classes:

Name Description
ShmDevice

A stream published on this machine by ShmStream, received like a radio: the same read, stream, RxMeta

ShmDevice

ShmDevice()

Bases: NativeDevice

A stream published on this machine by ShmStream, received like a radio: the same read, stream, RxMeta and drop reporting.

sdr = pysdrlib.open("shm@rpps.ch3")              # or pysdrlib.open("shm", name="rpps.ch3")
sdr.initialize()                                  # the stream's rate and frequency
x, m = sdr.read(65536, meta=True)

The rate and frequency are the publisher's: setting them only clamps to them (raises with strict). When the publisher retunes, the stream follows, with a "freq" or "rate" Event in RxMeta. Receiving starts with what is published next, not what the ring still holds.

RxMeta.index counts the publisher's gaps, and a reader that fell a ring behind, as lost samples (gaps). hw_time is the wall-clock time of the first sample, from the time the publisher gave (or took) for the first sample of the generation, so RxMeta.wall_time is too.

When the publisher closes the stream (or its process ends), read raises err.Lost once what is there is read.

Methods:

Name Description
find

The streams published on this machine (a transmit channel in an air (pysdrlib.air) is virtual: listed by

Attributes:

Name Type Description
name str

The stream's name

Source code in src/pysdrlib/shm/device.py
def __init__(self):
    super().__init__()
    self.manifest: dict = None  # type: ignore   # the stream's manifest (its generation as received)
    self.directory = None
    self._ended = None          # why the stream ended (the publisher closed it, or is gone)
    self._thread = None
    self._stop = threading.Event()
    self._queue_size = 0        # samples the queue holds
    self._queue_lock = threading.RLock()   # the queue and its index base, between a read and the thread growing it
name property
name: str

The stream's name

find classmethod
find(directory=None)

The streams published on this machine (a transmit channel in an air (pysdrlib.air) is virtual: listed by find(virtual=True))

Source code in src/pysdrlib/shm/device.py
@classmethod
def find(cls, directory=None):
    """The streams published on this machine (a transmit channel in an air (`pysdrlib.air`) is virtual: listed by
    `find(virtual=True)`)"""
    from ..devices import DeviceInfo
    found = []
    for m in stream.streams(directory):
        info = m.get("info") or {}
        extra = {"info": info, "virtual": True} if info.get("air") else {"info": info}
        found.append(DeviceInfo("shm", f"{m['name']} ({m['Fs'] / 1e6:g} MS/s at {m['cf'] / 1e6:g} MHz)", m["name"],
                                open_args={"name": m["name"]}, extra=extra))
    return found

ring

The ring: complex64 samples in a named shared-memory segment, one writer and any number of readers

The ring itself is C++ (_native/include/hardware_shm.hpp, the ShmRing class in pysdrlib/base/lib/_samples), correct across processes; this maps the memory and cleans up. ShmStream (in stream) adds the manifest that names it; a pysdrlib server uses the ring alone, and tells its clients the segment's name (see pysdrlib.remote.protocol).

writer = ShmWriter(capacity=fit_capacity(1 << 20), stream_id=1)
writer.publish(samples, first_index)
reader = ShmReader(writer.name)                          # another process
n, first = reader.read(out, pos)                         # up to len(out) samples from stream index pos
  • One writer per ring, on one machine. Samples are complex64; out must be a C-contiguous complex64 array.
  • publish(samples, first): first at or after head (lower raises ValueError; higher records a gap). Only the 1024 most recent gaps are remembered.
  • The ring carries only samples, their indices and stream_id: the rate, frequency and time go beside it (ShmStream).
  • Size the ring with fit_capacity first: a segment is only filled as it is written, so one larger than /dev/shm has room for crashes the writer later, not now.
  • There is no blocking wait: poll head (a cheap atomic load) and sleep a few ms. Start a new reader at head (minus the backlog it wants), not at 0.
  • destroy removes the name; readers that have the ring mapped keep it until close, and see closed.
  • The writer is the process that made it: in a forked child, close_stream does nothing and destroy only unmaps.

Classes:

Name Description
ShmWriter

The server's end: creates the segment, and removes it with destroy

ShmReader

A client's end. Raises FileNotFoundError if there is no such segment here (the server is on another machine)

Functions:

Name Description
fit_capacity

wanted samples, held to what the machine can map: a segment is only filled as it is written, so one larger than

ShmWriter

ShmWriter(capacity: int, stream_id: int = 0)

The server's end: creates the segment, and removes it with destroy

Methods:

Name Description
publish

Append complex64 samples whose first has stream index first

close_stream

No more samples are coming (readers can still read what is there)

destroy

Remove the segment. Readers that have it mapped keep it until they let go

Source code in src/pysdrlib/shm/ring.py
def __init__(self, capacity: int, stream_id: int = 0):
    self.capacity = int(capacity)
    self.pid = os.getpid()   # the owner: a forked child inherits this object, not the ring's fate
    # short: macOS limits the name to 31 characters
    self.shm = shared_memory.SharedMemory(create=True, size=_samples.shm_segment_size(self.capacity),
                                          name=f"psdr-{secrets.token_hex(5)}-{stream_id}")
    self.ring = _samples.ShmRing(self.shm.buf, self.capacity, stream_id)
publish
publish(samples, first: int)

Append complex64 samples whose first has stream index first

Source code in src/pysdrlib/shm/ring.py
def publish(self, samples, first: int):
    """Append complex64 samples whose first has stream index `first`"""
    self.ring.publish(samples, first)
close_stream
close_stream()

No more samples are coming (readers can still read what is there)

Source code in src/pysdrlib/shm/ring.py
def close_stream(self):
    """No more samples are coming (readers can still read what is there)"""
    if self.shm is None or os.getpid() != self.pid:    # already destroyed (a new stream replaced this ring)
        return
    try:
        self.ring.close()
    except ValueError:      # destroyed on another thread between the check and here
        pass
destroy
destroy()

Remove the segment. Readers that have it mapped keep it until they let go

Source code in src/pysdrlib/shm/ring.py
def destroy(self):
    """Remove the segment. Readers that have it mapped keep it until they let go"""
    if self.shm is None:
        return
    shm, self.shm = self.shm, None
    owner = os.getpid() == self.pid
    if owner:
        self.ring.close()
    self.ring.release()
    shm.close()
    if not owner:
        return
    try:
        shm.unlink()
    except FileNotFoundError:
        pass

ShmReader

ShmReader(name: str)

A client's end. Raises FileNotFoundError if there is no such segment here (the server is on another machine)

Methods:

Name Description
read

Up to len(out) samples from stream index pos into out: (count, index of the first). The index is past pos

Attributes:

Name Type Description
head int

The stream index after the newest sample

Source code in src/pysdrlib/shm/ring.py
def __init__(self, name: str):
    self.shm = _attach(name)
    try:
        self.ring = _samples.ShmRing(self.shm.buf)
    except Exception:
        self.shm.close()
        raise
    self.name = name
head property
head: int

The stream index after the newest sample

read
read(out, pos: int)

Up to len(out) samples from stream index pos into out: (count, index of the first). The index is past pos when this reader was lapped or was inside a gap; with a count of 0 it is where to go on from

Source code in src/pysdrlib/shm/ring.py
def read(self, out, pos: int):
    """Up to len(out) samples from stream index `pos` into `out`: (count, index of the first). The index is past `pos`
    when this reader was lapped or was inside a gap; with a count of 0 it is where to go on from"""
    return self.ring.read(out, pos)

fit_capacity

fit_capacity(wanted: int, floor: int = MIN_CAPACITY) -> int

wanted samples, held to what the machine can map: a segment is only filled as it is written, so one larger than /dev/shm has room for would crash the writer when it runs out. Returns 0 if not even the smallest ring fits

Source code in src/pysdrlib/shm/ring.py
def fit_capacity(wanted: int, floor: int = MIN_CAPACITY) -> int:
    """`wanted` samples, held to what the machine can map: a segment is only filled as it is written, so one larger than
    /dev/shm has room for would crash the writer when it runs out. Returns 0 if not even the smallest ring fits"""
    wanted = min(MAX_CAPACITY, max(floor, int(wanted)))
    try:
        free = os.statvfs("/dev/shm").f_bavail * os.statvfs("/dev/shm").f_frsize
    except (OSError, AttributeError):   # no /dev/shm to ask (macOS, Windows): the system decides
        return wanted
    fits = int(free * 0.8 - _samples.shm_segment_size(0)) // 8
    return wanted if fits >= wanted else (fits if fits >= floor else 0)

stream

The writer's end of a named stream: a ring (ring.ShmWriter) and a manifest that says what is in it

with ShmStream("rpps.ch3", Fs=250e3, cf=433.92e6, bw=200e3) as out: # extras go to the manifest's "info" out.publish(x, first) # complex64; first is the stream index of x[0] (later than the last: a gap) out.retune(cf=434.1e6) # a new generation: readers follow it, with a freq / rate event

Classes:

Name Description
ShmStream

Publish a stream of samples under name, for any process on this machine to receive (pysdrlib.open("shm@NAME"))

Functions:

Name Description
stream_dir

Where the manifests are: directory, else $PYSDRLIB_SHM_DIR, else pysdrlib-shm in the temporary directory

read_manifest

The manifest at path, or None if there is none (a stream closed), it isn't one, or it's of a later format

streams

The manifests of the streams published here, by name. live: only those whose writer is still running. prefix:

ShmStream

ShmStream(name: str, Fs: float, cf: float, capacity: Optional[int] = None, directory=None, **info)

Publish a stream of samples under name, for any process on this machine to receive (pysdrlib.open("shm@NAME"))

name: letters, digits, _, . and - (a . makes a namespace: "rpps.ch3"). Fs, cf: the sample rate and centre frequency. capacity: samples the ring holds (default one second, at least ring.MIN_CAPACITY; held to what /dev/shm has room for). directory: where the manifest goes (see stream_dir). Every other keyword is written to the manifest's "info" (JSON values: a bandwidth, a label...) for readers to show.

Raises FileExistsError if name is published already (by a running process, or an open ShmStream of this one), OSError if /dev/shm has no room for a ring.

The stream is the process's that made it: a forked child's close (or exit) leaves it published, and the child can't retune it.

Methods:

Name Description
publish

Append complex64 samples whose first has stream index first (at or after head; later is a gap).

retune

The samples published from now on are at a new rate and/or frequency: a new generation, on a new ring. Readers

close

No more samples: readers drain what is there, then their stream ends (err.Lost)

Attributes:

Name Type Description
manifest dict

What readers find in the manifest

head int

The stream index after the newest sample published

Source code in src/pysdrlib/shm/stream.py
def __init__(self, name: str, Fs: float, cf: float, capacity: Optional[int] = None, directory=None, **info):
    if not isinstance(name, str) or not NAME.fullmatch(name):
        raise ValueError(f"{name!r}: a stream name is letters, digits, '_', '.' and '-'")
    self.name = name
    self.directory = stream_dir(directory)
    _secure(self.directory)
    self.path = manifest_path(name, self.directory)
    self.pid = os.getpid()
    self.writer = None
    with _open_lock:
        key = os.path.realpath(self.path)
        mine = _open_streams.get(key)
        if mine is not None and mine.writer is not None and mine.pid == self.pid:
            raise FileExistsError(f"the stream {name!r} is published already (by this process: close it first)")
        self._start(Fs, cf, capacity, info)
        _open_streams[key] = self
manifest property
manifest: dict

What readers find in the manifest

head property
head: int

The stream index after the newest sample published

publish
publish(samples, first: int, wall_time: Optional[float] = None)

Append complex64 samples whose first has stream index first (at or after head; later is a gap). wall_time: time.time() of samples[0], when the source knows it (RxMeta.wall_time); the first publish of a generation anchors the readers' timestamps there (default: now)

Source code in src/pysdrlib/shm/stream.py
def publish(self, samples, first: int, wall_time: Optional[float] = None):
    """Append complex64 `samples` whose first has stream index `first` (at or after `head`; later is a gap).
    wall_time: `time.time()` of samples[0], when the source knows it (`RxMeta.wall_time`); the first publish of a
    generation anchors the readers' timestamps there (default: now)"""
    if self.writer is None:
        raise ValueError(f"the stream {self.name!r} is closed")
    if self._anchor is None and len(samples):
        self._anchor = (float(wall_time) if wall_time is not None else time.time(), int(first))
        self._write_manifest()   # before the samples: a reader that has them finds the anchor
    self.writer.publish(samples, first)
retune
retune(Fs: Optional[float] = None, cf: Optional[float] = None, capacity: Optional[int] = None, **info)

The samples published from now on are at a new rate and/or frequency: a new generation, on a new ring. Readers drain the old one, then follow (a freq or rate event in their RxMeta). Stream indices start over with what is published next. info keywords update the manifest's "info" (None removes one)

Source code in src/pysdrlib/shm/stream.py
def retune(self, Fs: Optional[float] = None, cf: Optional[float] = None, capacity: Optional[int] = None, **info):
    """The samples published from now on are at a new rate and/or frequency: a new generation, on a new ring. Readers
    drain the old one, then follow (a freq or rate event in their RxMeta). Stream indices start over with what is
    published next. `info` keywords update the manifest's "info" (None removes one)"""
    if self.writer is None:
        raise ValueError(f"the stream {self.name!r} is closed")
    if os.getpid() != self.pid:
        raise ValueError(f"the stream {self.name!r} belongs to process {self.pid}: a forked child can't retune it")
    old = self.writer
    self.gen += 1
    self.Fs = float(Fs) if Fs is not None else self.Fs
    self.cf = float(cf) if cf is not None else self.cf
    self._capacity = capacity if capacity is not None else self._capacity
    for k, v in info.items():
        if v is None:
            self.info.pop(k, None)
        else:
            self.info[k] = v
    if self._anchor is not None:   # a reader that hasn't reached this generation's samples yet needs its anchor
        self._anchors[old.name] = list(self._anchor)
        while len(self._anchors) > ANCHORS:
            del self._anchors[next(iter(self._anchors))]
    self._anchor = None
    self.writer = self._new_ring()
    self._write_manifest()   # first: a reader that sees the old ring closed finds the new one
    old.close_stream()
    old.destroy()
close
close()

No more samples: readers drain what is there, then their stream ends (err.Lost)

Source code in src/pysdrlib/shm/stream.py
def close(self):
    """No more samples: readers drain what is there, then their stream ends (err.Lost)"""
    if self.writer is None:
        return
    writer, self.writer = self.writer, None
    if os.getpid() != self.pid:   # a forked child letting go of its parent's stream
        writer.destroy()
        return
    writer.close_stream()
    m = read_manifest(self.path)
    if m is not None and m.get("segment") == writer.name:   # (not one a later publisher of the name wrote)
        try:
            retry_busy(os.unlink, self.path)
        except FileNotFoundError:
            pass
    writer.destroy()

stream_dir

stream_dir(directory=None) -> str

Where the manifests are: directory, else $PYSDRLIB_SHM_DIR, else pysdrlib-shm in the temporary directory

Source code in src/pysdrlib/shm/stream.py
def stream_dir(directory=None) -> str:
    """Where the manifests are: `directory`, else $PYSDRLIB_SHM_DIR, else `pysdrlib-shm` in the temporary directory"""
    return str(directory or os.environ.get(DIR_ENV) or os.path.join(tempfile.gettempdir(), "pysdrlib-shm"))

read_manifest

read_manifest(path) -> Optional[dict]

The manifest at path, or None if there is none (a stream closed), it isn't one, or it's of a later format

Source code in src/pysdrlib/shm/stream.py
def read_manifest(path) -> Optional[dict]:
    """The manifest at `path`, or None if there is none (a stream closed), it isn't one, or it's of a later format"""
    try:
        with retry_busy(open, path, encoding="utf-8") as f:
            m = json.load(f)
    except (OSError, ValueError):
        return None
    if not isinstance(m, dict) or m.get("format") != FORMAT or not isinstance(m.get("segment"), str):
        return None
    return m

streams

streams(directory=None, live=True, prefix='') -> list

The manifests of the streams published here, by name. live: only those whose writer is still running. prefix: only the streams whose name starts with it (the others' manifests aren't read)

Source code in src/pysdrlib/shm/stream.py
def streams(directory=None, live=True, prefix="") -> list:
    """The manifests of the streams published here, by name. live: only those whose writer is still running. prefix:
    only the streams whose name starts with it (the others' manifests aren't read)"""
    d = stream_dir(directory)
    if not _trusted(d):
        return []
    try:
        files = sorted(f for f in os.listdir(d) if f.endswith(".json") and f.startswith(prefix))
    except OSError:
        return []
    found = []
    for f in files:
        m = read_manifest(os.path.join(d, f))
        if m is not None and (not live or _alive(m.get("pid"))):
            found.append(m)
    return found