Episode 3: Sending UDP Streams

Send a pipeline’s output as UDP packets with a UDPSender, and read them with a plain socket.

UDP is the simplest way to put numbers on the network: no stream to find, no handshake, just packets sent to an address. This episode streams the recorder’s output over UDP and reads it in a program that knows nothing about g.Pype.

The pipeline

The same Generator, Keyboard and Router as the two episodes before, and again no window.

12    p = gp.Pipeline()
13
14    source = gp.Generator(sampling_rate=250, channel_count=8,
15                          signal_frequency=10, signal_amplitude=10,
16                          noise_amplitude=10)
17    keyboard = gp.Keyboard()
18    router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
Send it

A UDPSender sends to 127.0.0.1, port 56000, unless you pass ip= and port=. It sends one packet per frame; frame_size_out= gathers samples into larger packets first.

20    # One packet per frame, to 127.0.0.1 port 56000 unless you pass ip
21    # and port; frame_size_out would gather samples into larger packets
22    sender = gp.UDPSender()
23
24    p.connect(source, router["in1"])
25    p.connect(keyboard, router["in2"])
26    p.connect(router, sender)
27
28    p.start()
29    input("Streaming. Press Enter to stop.")
30    p.stop()
31    p.close()
A packet is only numbers

Each packet holds one frame: the samples in order, each sample all its channels, as 64-bit floats, and nothing else. A source built without a frame_size takes one from its rate, 4 samples at 250 Hz, so the nine channels here make a packet of:

4 samples x 9 channels x 8 bytes = 288 bytes, 62.5 packets a second

The arrival-stamp channel every live source adds is stripped before the sender, so the packet holds only the channels you see.

The other end

The receiver has to know the layout in advance. A packet carries no header, no channel count, no rate and no names, so the second file fixes the port and the channel count in constants, and the number format where it decodes, and they must match the sender: nine channels for the eight signals plus the key codes.

15UDP_IP = "127.0.0.1"
16UDP_PORT = 56000
17CHANNEL_COUNT = 9  # eight signals and the key codes
18SAMPLING_RATE = 250
19TIME_WINDOW = 10  # seconds shown
20AMPLITUDE_LIMIT = 50  # one lane spans twice this
21MAX_POINTS = TIME_WINDOW * SAMPLING_RATE

It works out the samples per packet from the packet’s size, so a different frame size still reads correctly. Get the channel count wrong, and the reshape either fails or, worse, puts the numbers in the wrong columns without a word.

60        try:
61            while True:
62                packet, _ = self.sock.recvfrom(65536)
63                # One frame of 64-bit floats, sample by sample; how many
64                # samples follows from the packet's size
65                frame = np.frombuffer(packet, dtype=np.float64)
66                frame = frame.reshape((-1, CHANNEL_COUNT))
67                rows = (self.index + np.arange(len(frame))) % MAX_POINTS
68                self.buffer[rows, :] = frame
69                self.index += len(frame)
70        except BlockingIOError:
71            pass  # nothing more to read
UDP never waits and never complains

Sending to a port nobody listens on raises no error, and a packet lost on the way is simply gone: the sender does not know and does not resend. That is the trade. Nothing is ever delayed by the network, and nothing guarantees it arrives. When the other end needs names, a rate and a stream it can find, use LSL instead.

Result

Start the receiver first, then the sender. The receiver’s window shows nine lanes, the eight signals and the key codes as spikes on the last, and goes quiet the moment the sender stops.

Summary

In this episode, you learned how to:

  • send a pipeline’s output as UDP packets with a UDPSender

  • read the packets with a plain socket that knows the layout

  • weigh UDP’s trade: never delayed, never guaranteed

Proceed to Episode 4, where the direction turns around and a pipeline receives trigger codes over UDP.

Nodes in this episode: Generator, Keyboard, Router, UDPSender

File s4e3_sending_udp.py – View file on GitHub

 1"""Season 4, Episode 3: signal and key presses sent as UDP packets.
 2
 3Headless on purpose: the pipeline streams until you press Enter. Read
 4it with s4e3_foreign_receiver.py. UDP drops a packet rather than delay
 5it, which is the trade this episode makes.
 6"""
 7
 8import gpype as gp
 9
10if __name__ == "__main__":
11
12    p = gp.Pipeline()
13
14    source = gp.Generator(sampling_rate=250, channel_count=8,
15                          signal_frequency=10, signal_amplitude=10,
16                          noise_amplitude=10)
17    keyboard = gp.Keyboard()
18    router = gp.Router(input_channels=[gp.Router.ALL, gp.Router.ALL])
19
20    # One packet per frame, to 127.0.0.1 port 56000 unless you pass ip
21    # and port; frame_size_out would gather samples into larger packets
22    sender = gp.UDPSender()
23
24    p.connect(source, router["in1"])
25    p.connect(keyboard, router["in2"])
26    p.connect(router, sender)
27
28    p.start()
29    input("Streaming. Press Enter to stop.")
30    p.stop()
31    p.close()

File s4e3_foreign_receiver.py – View file on GitHub

 1"""Season 4, Episode 3: a receiver that is not g.Pype reads the packets.
 2
 3Nothing here imports gpype: a socket and a plot. A packet carries no
 4header, so the port, the channel count and the number format below
 5have to match the sending pipeline. Requires pyqtgraph and PySide6.
 6"""
 7
 8import socket
 9import sys
10
11import numpy as np
12import pyqtgraph as pg
13from pyqtgraph.Qt import QtCore, QtWidgets
14
15UDP_IP = "127.0.0.1"
16UDP_PORT = 56000
17CHANNEL_COUNT = 9  # eight signals and the key codes
18SAMPLING_RATE = 250
19TIME_WINDOW = 10  # seconds shown
20AMPLITUDE_LIMIT = 50  # one lane spans twice this
21MAX_POINTS = TIME_WINDOW * SAMPLING_RATE
22
23
24class UdpScope(QtWidgets.QMainWindow):
25    """A time-series plot fed by a UDP socket."""
26
27    def __init__(self):
28        super().__init__()
29        self.setWindowTitle("UDP receiver")
30
31        plot = pg.PlotWidget()
32        self.setCentralWidget(plot)
33        self.item = plot.getPlotItem()
34        self.item.showGrid(x=True, y=True, alpha=0.3)
35        self.item.getViewBox().setMouseEnabled(x=False, y=False)
36        self.item.setLabels(left="Channels", bottom="Time (s)")
37        self.item.setYRange(0, CHANNEL_COUNT)
38        self.item.setXRange(0, TIME_WINDOW)
39        self.item.getAxis("left").setTicks([[
40            (CHANNEL_COUNT - i - 0.5, f"CH{i + 1}")
41            for i in range(CHANNEL_COUNT)]])
42        self.curves = [self.item.plot(pen=pg.mkPen(width=1))
43                       for _ in range(CHANNEL_COUNT)]
44
45        # A ring buffer the size of the window
46        self.times = np.arange(MAX_POINTS) / SAMPLING_RATE
47        self.buffer = np.zeros((MAX_POINTS, CHANNEL_COUNT))
48        self.index = 0
49
50        # A non-blocking socket, drained on a timer
51        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
52        self.sock.bind((UDP_IP, UDP_PORT))
53        self.sock.setblocking(False)
54        self.timer = QtCore.QTimer()
55        self.timer.timeout.connect(self.update_plot)
56        self.timer.start(40)
57
58    def update_plot(self):
59        """Drain the socket into the ring buffer and redraw."""
60        try:
61            while True:
62                packet, _ = self.sock.recvfrom(65536)
63                # One frame of 64-bit floats, sample by sample; how many
64                # samples follows from the packet's size
65                frame = np.frombuffer(packet, dtype=np.float64)
66                frame = frame.reshape((-1, CHANNEL_COUNT))
67                rows = (self.index + np.arange(len(frame))) % MAX_POINTS
68                self.buffer[rows, :] = frame
69                self.index += len(frame)
70        except BlockingIOError:
71            pass  # nothing more to read
72        step = max(1, MAX_POINTS // max(1, self.width()))
73        for i, curve in enumerate(self.curves):
74            lane = CHANNEL_COUNT - i - 0.5
75            curve.setData(self.times[::step],
76                          self.buffer[::step, i] / AMPLITUDE_LIMIT / 2 + lane)
77
78
79if __name__ == "__main__":
80    app = QtWidgets.QApplication(sys.argv)
81    window = UdpScope()
82    window.resize(1000, 500)
83    window.show()
84    sys.exit(app.exec())