This is the security camera I built on a Raspberry Pi 5 with two camera modules: a wide-angle NoIR camera and a High Quality camera with a telephoto lens. A Python program owns the cameras, watches for motion and records clips. A small Go program streams live video to any number of browsers. nginx sits in front with TLS and a password. At the end you will have the same system running, and you will know what every piece does, including a line-by-line walkthrough of the Go server.

It is written for someone with a new Pi 5, one or two camera modules, and no prior experience with any of this. If you only have one camera, there is a one-camera version of the Python file and I point out where it differs.

Last verified: December 2026. Versions used: Raspberry Pi OS Lite (64-bit) based on Debian 13 “trixie” (image dated 30 Nov 2026), Picamera2 0.3.37 manual, Go 1.27.4 for the Pi (the Go code was compiled and tested here with Go 1.24.7), nginx 1.26.3 as packaged in Debian 13, OpenCV 4.10.

What you are building

Architecture: browser to nginx, nginx to Go for streams and Flask for the page, Python owns both cameras and feeds Go over Unix sockets Two processes on one Pi. Python owns the cameras; Go only moves JPEGs to viewers.

There are four moving parts.

The Python process (picam.py, run by picam.service). It opens both cameras with Picamera2, the official Python library for Raspberry Pi cameras. Each camera produces two streams at once: a large main stream and a smaller lores (low resolution) stream of 1280×720. The lores stream is compressed to JPEG frames by Picamera2’s MJPEG encoder. MJPEG (Motion JPEG) is just a sequence of independent JPEG images, which is why a browser can show it in a plain <img> tag. The same JPEGs go to three places: a Unix socket for the Go server, an ffmpeg process when a recording is running, and an FPS counter. Separately, a motion loop grabs raw lores frames and compares them with OpenCV. Python also serves the web page and a /status JSON endpoint with Flask on 127.0.0.1:8080.

The Go process (picam-stream, run by picam-stream.service). It connects to one Unix socket per camera, reads frames, and sends each frame to every connected browser on /stream/0 and /stream/1. A Unix socket is a file-system path that two processes on the same machine use like a network connection, without touching the network.

nginx. A reverse proxy: it accepts HTTPS from browsers, checks a password, sends /stream/... to Go and everything else to Flask.

ffmpeg. Started by Python for each clip. It reads JPEGs on standard input and writes H.264 video into an .mp4 file in ~/recordings.

Why two languages? One Python process doing everything stopped keeping up once two cameras were streaming. Python threads share one Global Interpreter Lock (the GIL), so only one thread runs Python code at a time however many cores the Pi has, and pushing every frame to every browser piles up behind that lock. Go has no such lock, its goroutines (lightweight threads managed by the Go runtime) use all cores, and the streaming server is about 190 lines of standard library code. Python keeps what it is good at here: Picamera2 and OpenCV.

How it got to this shape

Four stages from one Python process on a Pi Zero 2 W to Python plus Go on a Pi 5 Each stage was a response to something that broke or got slow.

It started on a Pi Zero 2 W with one Camera Module 3 Wide NoIR and a single Python/Flask process serving MJPEG on port 8080. I moved to a Pi 5 because I wanted the best performance I could get, and OpenCV motion detection needed more than the Zero had to give. Then I put nginx and Let’s Encrypt in front, added the HQ camera, and kept everything in one Python process. With both cameras streaming in the browser, the video got choppy.

The first fix stayed in Python: stream the 1280×720 lores frames instead of full resolution, stop polling for frames in a sleep loop, and run motion detection on raw lores frames instead of decoding JPEGs. Both cameras then logged a steady 30 fps on Python’s own counter, but htop showed the single Python process using most of one core. I read that as the GIL ceiling, and it is why streaming moved to Go. The rest of this article describes that final version.

Parts

Part What I used Notes
Computer Raspberry Pi 5, 4GB Sold in 1GB to 16GB versions. 4GB was enough for this.
Camera 0 Raspberry Pi Camera Module 3 NoIR Wide Sony IMX708, 4608×2592, 120° diagonal field of view, autofocus, no IR filter
Camera 1 (optional) Raspberry Pi High Quality Camera, C/CS mount Sony IMX477, 12.3 MP, 4056×3040, integrated IR cut filter, no lens included
Lens for camera 1 A 16 mm telephoto lens Any C or CS lens works. Pick the focal length for your view.
Camera cables Raspberry Pi Camera Cable, “Standard to Mini” variant, one per camera The cables in the camera boxes do not fit a Pi 5 (see Step 2). Comes in 200, 300 and 500 mm.
Power Raspberry Pi 27W USB-C Power Supply 5.1 V, 5 A. The official supply for a Pi 5; my notes do not record which supply I used.
Case and cooling Raspberry Pi Case for Raspberry Pi 5 Built-in fan plus a small heatsink. I still needed an extra fan (see field notes).
Storage A large microSD card to start Move recordings to an SSD later (see Storage)

I left prices out. Check the Raspberry Pi product pages for current prices and resellers.

Step 1: Install Raspberry Pi OS

Use Raspberry Pi OS Lite (64-bit). Lite has no desktop, which leaves more memory and CPU for the cameras, and it already includes rpicam-apps-lite, the command-line camera tools. Picamera2 you install in Step 3.

  1. Install Raspberry Pi Imager on your laptop from the Raspberry Pi website and insert the microSD card.
  2. In Imager, choose Raspberry Pi 5 as the device, Raspberry Pi OS Lite (64-bit) as the OS, and your card as storage.
  3. On the Customisation tab, set a hostname (I use picam in this article), a username and password, your Wi-Fi details, and under Remote access turn on Enable SSH with Use public key authentication. Paste your laptop’s SSH public key there. If you do not have one, run ssh-keygen -t ed25519 on your laptop first and paste the contents of ~/.ssh/id_ed25519.pub.
  4. Write the card, put it in the Pi, and power it on.

My examples use the username pi. If you chose another username, substitute it wherever you see pi or /home/pi.

From your laptop:

ssh pi@picam.local

On the Pi, confirm you are on the 64-bit OS and bring it up to date:

dpkg --print-architecture
sudo apt update && sudo apt full-upgrade -y
sudo reboot

dpkg --print-architecture must print arm64. If it prints armhf you flashed the 32-bit image; flash the 64-bit one, because the packages and the Go download in Step 3 assume it. (Do not use uname -m for this check: a Pi 5 always runs a 64-bit kernel, so it prints aarch64 even on the 32-bit image.)

Step 2: Connect and check the cameras

The Pi 5 has two 4-lane MIPI connectors that take either a camera or a display, so it can run two cameras directly. They are the smaller 22-way connector also used on the Pi Zero. Camera Module 3 and the HQ Camera have the older, wider 15-way connector and ship with a cable for it. That is why you need the Raspberry Pi Camera Cable in its “Standard to Mini” variant: the mini end goes into the Pi 5, the standard end into the camera.

With the Pi powered off and unplugged:

  1. On the Pi 5, gently lift the plastic latch on a camera connector. It is fragile.
  2. Slide in the mini end of the cable with the metal contacts facing the Ethernet port, push it in fully, and press the latch down.
  3. Open the latch on the camera board, insert the standard end, and close it.
  4. Repeat for the second camera on the other connector.

Power on and list the cameras:

rpicam-hello --list-cameras

You should see one entry per camera, numbered from 0. Abridged, mine looked like this:

Available cameras
-----------------
0 : imx708_wide_noir [4608x2592 10-bit] ...
    Modes: ... 1536x864 ... 2304x1296 ... 4608x2592 ...
1 : imx477 [4056x3040 12-bit RGGB] ...
    Modes: ... 1332x990 ... 2028x1080 ... 2028x1520 ... 4056x2160 ... 4056x3040 ...

These indexes are what Picamera2(0) and Picamera2(1) open. My code assumes 0 is the Wide and 1 is the HQ; if yours are the other way round, swap the cables. The main sizes in the code (2304×1296 and 2028×1520) are taken from these native sensor modes.

If you get command not found for libcamera-hello while following an older guide, that is expected: since Bookworm the tools are named rpicam-*.

For a quick picture without a screen, save one still from each camera and copy it to your laptop:

rpicam-still -n --camera 0 -o cam0.jpg
rpicam-still -n --camera 1 -o cam1.jpg

-n skips the preview window, which a Pi without a screen does not need. On your laptop, scp pi@picam.local:cam*.jpg . fetches both.

Step 3: Install the software

Install the Python libraries, ffmpeg, nginx and the tools for certificates and passwords. The Picamera2 documentation says it is preinstalled on the desktop images but not on Lite, so the first line installs it without the desktop packages, as its README recommends for Lite. If it is already there, the line changes nothing.

sudo apt install -y --no-install-recommends python3-picamera2
sudo apt install -y python3-opencv python3-flask ffmpeg nginx certbot apache2-utils wget

Check the user can reach the cameras. The user Imager creates is normally in the video group:

groups

Now Go. Debian’s golang-go package lags behind, so install the official release. As of December 2026 that is Go 1.27.4; check go.dev/dl for a newer one and change the version in these commands if there is.

cd ~
wget https://go.dev/dl/go1.27.4.linux-arm64.tar.gz
sha256sum go1.27.4.linux-arm64.tar.gz

Compare the hash with the one listed for go1.27.4.linux-arm64.tar.gz on go.dev/dl. For 1.27.4 it is 3392582988a273a87ab5043ee1b2c9c17a2c3c00580bf9326c47a2e0aaaeac92. Then install it the way the Go documentation says, removing any old tree first:

sudo rm -rf /usr/local/go && sudo tar -C /usr/local -xzf go1.27.4.linux-arm64.tar.gz
echo 'export PATH=$PATH:/usr/local/go/bin' >> ~/.profile
source ~/.profile
go version

Expected output:

go version go1.27.4 linux/arm64

You can also skip Go on the Pi entirely: build on your laptop with GOOS=linux GOARCH=arm64 go build and copy the binary over with scp. The program uses only the standard library, so cross-compiling needs nothing else.

Step 4: The Python camera process

The full file is picam.py (about 600 lines including the HTML page). For one camera, use picam_one_camera.py instead: it drops camera 1, its recorder and its threads, and changes the recording logic to need only one recorder. Every changed line is marked ONE CAMERA; lines that only served camera 1 are simply deleted. The page will show an empty second panel and the Go server will log that it is waiting for /tmp/picam1.sock; both are harmless.

Copy the file to the Pi as /home/pi/picam.py (for example scp picam.py pi@picam.local:). Below are the parts that matter, in the order the program runs them.

Camera configuration: main and lores

def init_camera(index, main_size, transform=None):
    cam = Picamera2(index)
    kwargs = dict(
        main     = {"size": main_size,   "format": "YUV420"},
        lores    = {"size": STREAM_SIZE, "format": "YUV420"},
        encode   = "lores",
        controls = {"FrameRate": CAM_FPS},
    )
    if transform:
        kwargs["transform"] = transform
    cam.configure(cam.create_video_configuration(**kwargs))
    return cam

create_video_configuration asks for two output streams from the camera’s image signal processor (ISP): main at a native sensor mode and lores at STREAM_SIZE = (1280, 720). Both use YUV420, a format that stores brightness (Y) at full resolution and colour (U and V) at quarter resolution. encode="lores" tells Picamera2 that the encoder attached later reads the lores stream. FrameRate fixes both cameras at 30 fps.

The HQ camera is mounted upside down in my build, so camera 1 gets a transform:

cam1 = init_camera(1, CAM1_MAIN, transform=Transform(hflip=1, vflip=1))
cam1.start_recording(MJPEGEncoder(), FileOutput(output1))

Transform comes from libcamera, not from picamera2 (from libcamera import Transform). Horizontal plus vertical flip is a 180° rotation, and it is one of only four transforms Picamera2 supports.

start_recording(MJPEGEncoder(), FileOutput(output1)) starts the encoder on the lores stream and sends every JPEG it produces to output1. On the Pi 5, MJPEG encoding is done in software with the FFmpeg libraries, since there is no hardware encoder on this model. That CPU cost is one reason the browser stream is 1280×720 and not full resolution.

The comment above CAM0_MAIN says the main stream is full resolution and for recording only. The code disagrees: nothing reads main, and recordings are made from the same lores JPEGs the browser sees, so clips are 1280×720. More under “What I would change”.

Getting frames out: StreamOutput

FileOutput accepts any file-like object, including a socket, so the program hands it this class:

class StreamOutput(io.BufferedIOBase):
    def __init__(self, name, sock_path):
        self.name       = name
        self.sock_path  = sock_path
        self.frame      = None
        self.count      = 0
        self.lock       = threading.Condition()
        self._sock      = None
        self._sock_lock = threading.Lock()
        threading.Thread(target=self._serve_socket, daemon=True).start()

Picamera2 calls write(buf) once per encoded JPEG:

    def write(self, buf):
        # Notify any local Flask stream clients (fallback)
        with self.lock:
            self.frame = buf
            self.count += 1
            self.lock.notify_all()

        # Send to Go with 4-byte big-endian length prefix
        with self._sock_lock:
            if self._sock:
                try:
                    self._sock.sendall(struct.pack('>I', len(buf)) + buf)
                except (BrokenPipeError, OSError):
                    log.warning(f"[{self.name}] Go socket disconnected")
                    self._sock = None

        return len(buf)

Two things happen. First, it stores the frame and wakes anything waiting on the threading.Condition. The comment mentions Flask stream clients, but those routes were removed when streaming moved to Go. The only waiter left is distributor_loop, which counts FPS and feeds the recorder. Second, if Go is connected, it sends the frame prefixed with its length as a 4-byte big-endian unsigned integer (struct.pack('>I', ...)). If the send fails, it forgets the connection and keeps going. The camera never waits for Go.

Python is the side that listens:

    def _serve_socket(self):
        try:
            os.remove(self.sock_path)
        except FileNotFoundError:
            pass
        srv = _socket.socket(_socket.AF_UNIX, _socket.SOCK_STREAM)
        srv.bind(self.sock_path)
        srv.listen(1)
        log.info(f"[{self.name}] Socket listening on {self.sock_path}")
        while True:
            conn, _ = srv.accept()
            log.info(f"[{self.name}] Go server connected on {self.sock_path}")
            with self._sock_lock:
                self._sock = conn

It deletes a stale socket file left by a previous run, binds /tmp/picam0.sock (or picam1), and accepts connections forever. Each new connection replaces the previous one. Only one consumer gets frames at a time, which matters in the field notes when two Go servers ran at once.

Motion detection on the Y plane

Each camera has its own motion_loop thread:

            frame  = cam.capture_array("lores")
            skip_n += 1
            if skip_n % MOTION_DETECT_SKIP != 0:
                continue

            # YUV420 lores: Y plane is the first HEIGHT rows, already grayscale
            y_plane = frame[:STREAM_SIZE[1], :STREAM_SIZE[0]]
            gray = cv2.resize(y_plane, MOTION_SIZE, interpolation=cv2.INTER_NEAREST)
            gray = cv2.GaussianBlur(gray, (5, 5), 0)

capture_array("lores") returns the next raw lores frame as a NumPy array. A YUV420 frame is stored as a full plane of Y values followed by quarter planes of U and V, so the array has 1.5 times as many rows as the image is tall, all one byte wide. The first 720 rows are the Y plane, which is already a grayscale image. Slicing [:720, :1280] takes exactly that and also drops any row padding Picamera2 leaves on the right. The frame is then halved to 640×360 and blurred slightly so sensor noise does not look like movement.

Only every fifth frame is checked (MOTION_DETECT_SKIP = 5), so at 30 fps each camera does at most six checks a second. The comparison:

            delta    = cv2.absdiff(prev, gray)
            thresh   = cv2.threshold(delta, MOTION_THRESHOLD, 255, cv2.THRESH_BINARY)[1]
            thresh   = cv2.dilate(thresh, None, iterations=MOTION_DILATE_ITERS)
            contours, _ = cv2.findContours(
                thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
            )
            motion = any(cv2.contourArea(c) > MOTION_MIN_AREA for c in contours)

This is frame differencing. It subtracts the previous checked frame from this one, marks every pixel whose brightness changed by more than 25 (MOTION_THRESHOLD), grows those marks so nearby pixels join into blobs (dilate), outlines the blobs, and calls it motion if any blob covers more than 5000 pixels (MOTION_MIN_AREA). In a 640×360 image that is about 2% of the frame. It compares against the previous check, about a sixth of a second ago, not against a learned background. Fast lighting changes trigger it, and something moving very slowly may not.

When motion is seen, the loop records the time in state["last_motion_t"] and, if nothing is recording, starts a recording.

The recording state machine

States: idle, recording for 30 seconds, stopping, then a chain check that either records again or returns to idle A motion event on either camera records both cameras. Clips chain while motion continues.

start_recording makes a timestamped pair of file names and starts one ffmpeg per camera:

            cmd = [
                'ffmpeg', '-y',
                '-f', 'mjpeg', '-framerate', str(fps), '-i', 'pipe:0',
                '-c:v', 'libx264', '-preset', 'ultrafast', '-crf', '23',
                filename
            ]

ffmpeg reads a stream of JPEGs on standard input (-f mjpeg -i pipe:0), assumes 30 of them per second, and encodes H.264 with libx264. -preset ultrafast spends the least CPU per frame at the cost of larger files. -crf 23 is libx264’s default constant-quality setting: the bitrate rises and falls with how busy the picture is. Frames reach ffmpeg through a 180-frame queue (six seconds) and a writer thread, so an ffmpeg that falls behind loses the oldest queued frames instead of holding up the frame distributor.

After RECORD_SECONDS = 30, a timer thread stops both recorders by closing ffmpeg’s input, which makes ffmpeg finish the file. Then it checks whether motion is still going on:

            with state_lock:
                state["recording"] = False
                age = time.time() - state["last_motion_t"]
                still = age < MOTION_GRACE_PERIOD
                log.info(f"Chain check: last_motion_age={age:.1f}s grace={MOTION_GRACE_PERIOD}s still={still}")

If the last motion was less than 5 seconds ago (MOTION_GRACE_PERIOD), it starts a new pair of clips with the trigger continuation. The Chain check line is a debugging aid from the field notes below and can stay or go.

COOLDOWN_SECONDS = 3 is measured from when the previous recording started, so after a 30-second clip it never blocks anything. What it does do is stop the Wide and Tele motion threads from both launching a recording in the instant before the first one has set its recording flag.

One instance only, and the watchdog

At the very top, before touching any camera, the script takes a lock:

def acquire_pid_lock():
    if os.path.exists(PID_FILE):
        try:
            with open(PID_FILE) as f:
                old_pid = int(f.read().strip())
            os.kill(old_pid, 0)
            print(f"Another instance already running (PID {old_pid}). Exiting.")
            sys.exit(1)
        except (ProcessLookupError, ValueError):
            pass
    with open(PID_FILE, 'w') as f:
        f.write(str(os.getpid()))

os.kill(pid, 0) sends no signal; it only checks that the process exists. If it does, the second copy exits. A stale file is overwritten. A sturdier lock is in “What I would change”.

A watchdog thread checks every 5 seconds that each camera delivered a frame in the last 10 seconds, and after three bad checks in a row it calls sys.exit(1) so systemd will restart the service. As written, that does not work: sys.exit in a thread other than the main thread only ends that thread. The fix is in “What I would change”.

Life of one frame

Sequence: sensor, encoder, StreamOutput, distributor, Go socket reader, Publish, per-viewer handler, nginx, browser One 1280×720 frame from sensor to screen. The camera never waits for a viewer.

Run it by hand once

Before involving systemd, run it in the foreground and watch the log:

python3 ~/picam.py

You should see both sockets listening, both cameras initialised, Motion baseline set for each camera, and every 10 seconds a line like [Wide] 30.0 fps. Wave at a camera and you should get Motion area=... — recording and a pair of files in ~/recordings. Leave it running and open a second SSH session for the next step.

Step 5: The Go stream server

This is the whole program, exactly as I built and ran it. It is also at main.go.

package main

import (
    "bytes"
    "encoding/binary"
    "io"
    "log"
    "net"
    "net/http"
    "sync"
    "time"
)

// ---------------------------------------------------------------------------
// Broadcaster — holds the latest frame and fans it out to all HTTP clients
// ---------------------------------------------------------------------------
type Broadcaster struct {
    mu       sync.RWMutex
    frame    []byte
    clients  map[chan []byte]struct{}
    clientMu sync.Mutex
}

func NewBroadcaster() *Broadcaster {
    return &Broadcaster{
        clients: make(map[chan []byte]struct{}),
    }
}

func (b *Broadcaster) Publish(frame []byte) {
    // Store latest frame for new clients joining mid-stream
    b.mu.Lock()
    b.frame = frame
    b.mu.Unlock()

    // Fan out to all connected clients
    b.clientMu.Lock()
    defer b.clientMu.Unlock()
    for ch := range b.clients {
        select {
        case ch <- frame:
        default:
            // Client is too slow — drop this frame rather than blocking
        }
    }
}

func (b *Broadcaster) Subscribe() (chan []byte, []byte) {
    ch := make(chan []byte, 4) // small buffer so slow clients drop frames, not block
    b.clientMu.Lock()
    b.clients[ch] = struct{}{}
    b.clientMu.Unlock()

    // Send the latest frame immediately so the client doesn't wait
    b.mu.RLock()
    latest := b.frame
    b.mu.RUnlock()

    return ch, latest
}

func (b *Broadcaster) Unsubscribe(ch chan []byte) {
    b.clientMu.Lock()
    delete(b.clients, ch)
    b.clientMu.Unlock()
}

// ---------------------------------------------------------------------------
// Socket reader — reads length-prefixed MJPEG frames from a Unix socket
// Python writes: [4-byte big-endian length][JPEG bytes]
// ---------------------------------------------------------------------------
func socketReader(sockPath string, b *Broadcaster) {
    for {
        conn, err := net.Dial("unix", sockPath)
        if err != nil {
            log.Printf("[socket] waiting for %s: %v", sockPath, err)
            time.Sleep(2 * time.Second)
            continue
        }
        log.Printf("[socket] connected to %s", sockPath)

        for {
            // Read 4-byte length prefix
            var length uint32
            if err := binary.Read(conn, binary.BigEndian, &length); err != nil {
                log.Printf("[socket] read length error: %v", err)
                break
            }

            if length == 0 || length > 10*1024*1024 {
                log.Printf("[socket] invalid frame length %d, reconnecting", length)
                break
            }

            // Read exactly `length` bytes
            buf := make([]byte, length)
            if _, err := io.ReadFull(conn, buf); err != nil {
                log.Printf("[socket] read frame error: %v", err)
                break
            }

            b.Publish(buf)
        }

        conn.Close()
        log.Printf("[socket] disconnected from %s, reconnecting...", sockPath)
        time.Sleep(1 * time.Second)
    }
}

// ---------------------------------------------------------------------------
// HTTP handler — streams MJPEG to browser
// ---------------------------------------------------------------------------
func mjpegHandler(b *Broadcaster) http.HandlerFunc {
    boundary := "frame"
    return func(w http.ResponseWriter, r *http.Request) {
        log.Printf("[http] client connected: %s", r.RemoteAddr)

        w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary="+boundary)
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
        w.Header().Set("Connection", "keep-alive")

        ch, latest := b.Subscribe()
        defer b.Unsubscribe(ch)

        // Write latest frame immediately so browser doesn't show blank
        if latest != nil {
            writeFrame(w, latest, boundary)
        }

        for {
            select {
            case frame, ok := <-ch:
                if !ok {
                    return
                }
                if err := writeFrame(w, frame, boundary); err != nil {
                    log.Printf("[http] client disconnected: %s", r.RemoteAddr)
                    return
                }
            case <-r.Context().Done():
                log.Printf("[http] client context done: %s", r.RemoteAddr)
                return
            }
        }
    }
}

func writeFrame(w http.ResponseWriter, frame []byte, boundary string) error {
    var buf bytes.Buffer
    buf.WriteString("--" + boundary + "\r\n")
    buf.WriteString("Content-Type: image/jpeg\r\n\r\n")
    buf.Write(frame)
    buf.WriteString("\r\n")

    _, err := w.Write(buf.Bytes())
    if err != nil {
        return err
    }

    if f, ok := w.(http.Flusher); ok {
        f.Flush()
    }
    return nil
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
func main() {
    bc0 := NewBroadcaster()
    bc1 := NewBroadcaster()

    // Start socket readers for both cameras
    go socketReader("/tmp/picam0.sock", bc0)
    go socketReader("/tmp/picam1.sock", bc1)

    mux := http.NewServeMux()
    mux.HandleFunc("/stream/0", mjpegHandler(bc0))
    mux.HandleFunc("/stream/1", mjpegHandler(bc1))
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("ok"))
    })

    log.Println("Go MJPEG server listening on :8081")
    if err := http.ListenAndServe(":8081", mux); err != nil {
        log.Fatalf("server error: %v", err)
    }
}

Build it

The original go.mod was never saved, so create the module fresh. go mod init writes a short go.mod with the module name and a go version line.

mkdir -p ~/picam-go && cd ~/picam-go
vim main.go

In vim, press i to insert, paste the listing, then Esc and :wq to save and quit. Then:

go mod init picam
gofmt -l .
go vet ./...
go build -o picam-stream .

go mod init prints go: creating new go.mod: module picam, then suggests running go mod tidy; the program uses only the standard library, so you can skip that. Since Go 1.26 the new go.mod names the previous minor release (Go 1.27.4 writes go 1.26.0), which is fine. gofmt -l and go vet print nothing when the file is clean. I compiled this listing with Go 1.24.7, ran gofmt -l, go vet and a race-detector build (go build -race) with no findings, and cross-compiled it for linux/arm64. On the Pi I first built it with Go 1.22.2.

With picam.py still running in the other session:

./picam-stream

Expected log (each line also starts with a timestamp):

Go MJPEG server listening on :8081
[socket] connected to /tmp/picam0.sock
[socket] connected to /tmp/picam1.sock

From a third session, count the frames that arrive in five seconds:

curl -s --max-time 5 http://127.0.0.1:8081/stream/0 | grep -a -c -- '--frame'

At 30 fps you should get a number near 150. Stop both programs with Ctrl+C before Step 6. This listing listens on every network interface; Step 7 changes that to loopback only, and you can make that one-line change now if anyone you do not trust shares your network. Now the walkthrough.

Startup and constants

main builds one Broadcaster per camera, starts one socketReader goroutine per camera, registers three routes on a ServeMux (Go’s built-in request router), and blocks in http.ListenAndServe forever. The pattern "/stream/0" has no trailing slash, so it matches that exact path only. /health returns ok for monitoring.

The values sit inline rather than in named constants:

Value Where Meaning
"/tmp/picam0.sock", "/tmp/picam1.sock" main Must match SOCK_CAM0 and SOCK_CAM1 in picam.py
":8081" main Listen address. Empty host means every interface (see Step 7)
4 Subscribe Frames buffered per viewer before frames start being dropped
10*1024*1024 socketReader Largest frame accepted, 10 MiB
2 * time.Second socketReader Retry delay when Python is not listening
1 * time.Second socketReader Pause after a connection drops
"frame" mjpegHandler Multipart boundary string

The wire format

Byte layout: 4-byte big-endian length, then that many JPEG bytes, repeated The whole protocol between Python and Go. Nothing else crosses the socket.

A stream socket delivers bytes, not messages: one read might return half a JPEG or one and a half. The length prefix tells the reader where each frame ends. Python writes struct.pack('>I', len(buf)) + buf: > means big-endian (most significant byte first, the usual network byte order), I means 4-byte unsigned integer. A frame of 48,213 bytes (hex BC55) goes out as 00 00 BC 55 followed by the JPEG, which always starts with FF D8. There is no version byte, camera ID, timestamp or checksum. The socket path says which camera it is, and the kernel guarantees a local stream socket delivers bytes in order without corruption, so a checksum would protect against nothing.

socketReader: dial, read, reconnect

socketReader is two nested loops. The outer loop gets a connection; the inner loop reads frames from it.

The outer loop calls net.Dial("unix", sockPath). If Python is not running yet, the socket file does not exist or nobody is listening, the dial fails, and it logs waiting for ... and tries again in 2 seconds. This is what makes start order irrelevant: Go can start before Python, and it reconnects on its own when Python restarts.

The inner loop reads one frame per pass:

  1. binary.Read(conn, binary.BigEndian, &length) reads exactly 4 bytes into a uint32, decoding them most significant byte first. It returns io.EOF only if the connection ended cleanly between frames, and io.ErrUnexpectedEOF if it ended partway through the 4 bytes.
  2. A length of zero or over 10 MiB means the stream is out of step (or Python sent garbage). There is no way to find the next frame boundary in a raw byte stream, so the only safe recovery is to drop the connection and start fresh.
  3. buf := make([]byte, length) allocates a new slice for every frame. That is deliberate: the slice is handed to every viewer, and a new slice per frame means no viewer can ever see a buffer being overwritten.
  4. io.ReadFull(conn, buf) keeps reading until it has exactly length bytes or an error. A plain conn.Read could return fewer.
  5. b.Publish(buf) hands the frame to the hub.

Any error breaks out to conn.Close(), a log line, a one-second pause, and a new dial.

Broadcaster: the hub

Broadcaster holds two things, each with its own lock:

  • frame, the most recent JPEG, guarded by mu (a sync.RWMutex, which allows many readers or one writer).
  • clients, a set of per-viewer channels, guarded by clientMu (a plain sync.Mutex). Go has no set type, so it is a map[chan []byte]struct{}; the empty struct takes no memory.

Publish first replaces frame under mu, then walks every client channel under clientMu and offers it the frame. Subscribe creates a channel, adds it to the set, and returns the channel plus the latest frame so a new viewer sees a picture immediately instead of waiting for the next one. Unsubscribe removes the channel from the set.

Per-client channels and the slow-client policy

Publish sends to clients A and B; client C’s channel is full, so its frame is dropped while A and B are unaffected One slow viewer loses frames. Nobody else notices.

This is the key design decision in the file:

        select {
        case ch <- frame:
        default:
            // Client is too slow — drop this frame rather than blocking
        }

A select with a default case never blocks. If the viewer’s channel has room (up to 4 frames), the frame goes in; if it is full, the frame is skipped for that viewer only. A plain ch <- frame would make Publish wait for the slowest viewer, so socketReader would stop reading, the socket buffer would fill, and Python’s sendall would block inside the camera’s output callback. One phone on bad Wi-Fi would freeze the camera for everyone. With the drop policy, a slow viewer just sees fewer frames.

Four is small on purpose: a big buffer would let a slow viewer fall seconds behind live. And with MJPEG, dropping frames costs nothing, because every frame is a complete image.

This was tested on an x86-64 Linux machine, not on the Pi, with a script that imitates picam.py by sending 1280×720 test JPEGs at 30 fps into both sockets. Over the same 4 seconds, a normal curl received 111 frames while a curl --limit-rate 50k on the other stream received 19, and a client that connected and never read anything did not change the normal client’s 111. The race detector reported nothing.

The HTTP handler and multipart MJPEG

mjpegHandler returns a closure (a function that captures variables from where it was created), so each route gets a handler bound to its own Broadcaster.

It sets three headers. Content-Type: multipart/x-mixed-replace; boundary=frame is what makes this work: it tells the browser the response is a series of parts, each replacing the one before. Browsers support it in <img> tags. Cache-Control: no-cache, no-store, must-revalidate keeps proxies and the browser from storing it. Connection: keep-alive is redundant for HTTP/1.1 and harmless.

Then it subscribes, writes the latest frame if there is one, and loops on a select over two things: a frame arriving on its channel, or r.Context().Done(). The request context is cancelled when the client’s connection closes, so a viewer closing the tab ends the loop even if no frames are flowing.

Each part on the wire looks like this (the test above captured exactly these bytes):

--frame\r\n
Content-Type: image/jpeg\r\n
\r\n
<JPEG bytes: FF D8 ... FF D9>\r\n

writeFrame builds the part in a bytes.Buffer so it goes out in one Write, then calls Flush, because Go’s HTTP server buffers response bytes and a frame could otherwise sit there. With no Content-Length, Go sends the response with HTTP/1.1 chunked transfer encoding. Parts have no Content-Length either; browsers find the end of each JPEG from the next boundary.

The if !ok { return } branch handles a closed channel, but Unsubscribe never closes channels, so it never runs. That is harmless.

Concurrency and locking

Here are the goroutines that matter for one camera with two viewers: one socketReader, one handler goroutine per viewer (net/http starts one per connection), and the server’s own accept loop. Shared state and what protects it:

  • Broadcaster.frame: written by Publish, read by Subscribe. Protected by mu.
  • Broadcaster.clients: modified by Subscribe and Unsubscribe from handler goroutines, iterated by Publish. Protected by clientMu. Publish holds it while sending, which is safe only because every send is non-blocking. If those sends could block, a viewer’s Unsubscribe would wait behind Publish forever.
  • The frame bytes themselves: shared by every viewer without a lock. That is safe because nothing writes to a slice after socketReader fills it.

The two locks are never held at the same time, so they cannot deadlock. A new viewer can occasionally get the same frame twice (as latest and from the channel) because Subscribe registers before reading latest. Nobody can see that.

Shutdown

There is no shutdown code. When systemd stops the service it sends SIGTERM, Go’s default action is to exit, and the kernel closes every socket. Browsers see the stream end. Python’s next sendall fails with BrokenPipeError, so it logs Go socket disconnected and carries on without a consumer. When Go starts again, it dials, Python accepts, and frames flow. For this program that is fine. “What I would change” shows a graceful version anyway, because the trick it needs is worth knowing.

Step 6: Run both with systemd

systemd starts both programs at boot and restarts them if they die. Create the Python unit:

sudo vim /etc/systemd/system/picam.service
[Unit]
Description=PiCam cameras, motion detection, recording and web UI (Python)
After=network.target

[Service]
Type=simple
User=pi
ExecStart=/usr/bin/python3 /home/pi/picam.py
Restart=always
RestartSec=15
TimeoutStopSec=20
UMask=0077

[Install]
WantedBy=multi-user.target

And the Go unit:

sudo vim /etc/systemd/system/picam-stream.service
[Unit]
Description=PiCam MJPEG stream server (Go)
After=picam.service
Requires=picam.service

[Service]
Type=simple
User=pi
ExecStart=/home/pi/picam-go/picam-stream
Restart=always
RestartSec=5
TimeoutStopSec=10

[Install]
WantedBy=multi-user.target

What each choice does:

  • User=pi: neither program needs root. systemd also sets $HOME for that user, which is how ~/recordings resolves.
  • Restart=always with RestartSec=15 for Python: if the process dies, wait 15 seconds, then start it again. I chose the long delay to give the cameras time to be released after a crash before a new process tries to open them. Go restarts after 5 seconds because it opens no hardware.
  • TimeoutStopSec=20: on stop, systemd sends SIGTERM and, if the process is still alive after 20 seconds, SIGKILL. The default is 90 seconds.
  • UMask=0077: every file Python creates (the Unix sockets, the PID file, the recordings) is readable only by the pi user. More on why in Step 7.
  • Requires= plus After= on the Go unit: starting the stream server also starts the camera service, and if you explicitly stop or restart picam.service, the stream server stops or restarts with it. When Python crashes and systemd restarts it, Go is either restarted along with it or keeps running and reconnects on its own; both work.
  • Do not add PrivateTmp=yes to either unit. It gives each service its own private /tmp, and the two processes would no longer see each other’s sockets.

My original unit file also had KillMode=control-group. That is the default (systemd kills every process in the service’s control group on stop), so I left it out.

Enable and start both, then check:

sudo systemctl daemon-reload
sudo systemctl enable --now picam.service picam-stream.service
systemctl status picam.service picam-stream.service --no-pager
journalctl -u picam.service -f

The status output lists every process in each service’s control group. For picam.service that is one python3 process, plus one or two ffmpeg children while a clip records. Press Ctrl+C to leave journalctl. Reboot once and confirm both come back on their own.

One rule: from now on, start and stop these programs only with systemctl. Running a second copy by hand is how I broke it (see field notes).

Step 7: nginx, TLS and a password

A camera feed with no login is a camera anyone can watch, so put access control in front of it before you expose anything. You have two reasonable designs.

Option A: public HTTPS with a password. Forward ports 80 and 443 on your router to the Pi, point a DNS name at your home IP, get a Let’s Encrypt certificate, and require a password in nginx. Use it if you want to open the feed from anywhere without extra software.

Option B: expose nothing, use a VPN. No port forwarding. You reach the Pi over WireGuard, an encrypted VPN, from your phone or laptop, so nobody on the internet can even attempt a login. This is the stronger option and the one I would choose today. The cost is setting up WireGuard on the Pi or your router and on each device; I cover WireGuard in WireGuard Tunnel: Connecting Your Home Network to AWS.

Both use the same nginx proxy and password. Only the certificate differs.

Create the password file

sudo htpasswd -c /etc/nginx/picam.htpasswd <USER>

It asks for a password twice. -c creates the file and overwrites an existing one, so leave it off when adding a second user. Use a long random password: Basic authentication sends it with every request, so it is only as safe as the TLS around it, and Option A exposes the login prompt to the whole internet. Then make the file readable by nginx and nobody else:

sudo chown root:www-data /etc/nginx/picam.htpasswd
sudo chmod 640 /etc/nginx/picam.htpasswd

Option A: Let’s Encrypt certificate

Create a DNS record for <YOUR_DOMAIN> pointing at your public IP, and forward TCP 80 and 443 from your router to the Pi. Let’s Encrypt’s HTTP-01 check connects to port 80 and fetches a file under /.well-known/acme-challenge/, so port 80 has to work before you can get a certificate.

Start with a port-80-only site:

sudo vim /etc/nginx/sites-available/picam
server {
    listen 80;
    server_name <YOUR_DOMAIN>;

    location /.well-known/acme-challenge/ {
        root /var/www/html;
    }

    location / {
        return 301 https://$host$request_uri;
    }
}

Enable it, disable the default site, and reload:

sudo ln -s /etc/nginx/sites-available/picam /etc/nginx/sites-enabled/picam
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx

nginx -t should end with test is successful. Now request the certificate. The webroot method writes the challenge file into /var/www/html, which the block above serves. The deploy hook reloads nginx after each renewal so it picks up the new certificate.

sudo certbot certonly --webroot -w /var/www/html -d <YOUR_DOMAIN> --deploy-hook "systemctl reload nginx"

Certificates land in /etc/letsencrypt/live/<YOUR_DOMAIN>/. Check renewal is scheduled and works:

systemctl list-timers | grep certbot
sudo certbot renew --dry-run

Now open the site file again and add the HTTPS server below the port-80 block:

server {
    listen 443 ssl;
    server_name <YOUR_DOMAIN>;

    ssl_certificate     /etc/letsencrypt/live/<YOUR_DOMAIN>/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/<YOUR_DOMAIN>/privkey.pem;
    ssl_protocols       TLSv1.2 TLSv1.3;

    auth_basic           "camera";
    auth_basic_user_file /etc/nginx/picam.htpasswd;

    location /stream/ {
        proxy_pass         http://127.0.0.1:8081;
        proxy_http_version 1.1;
        proxy_set_header   Connection "";
        proxy_set_header   Host $host;
        proxy_buffering    off;
    }

    location / {
        proxy_pass         http://127.0.0.1:8080;
        proxy_http_version 1.1;
        proxy_set_header   Connection "";
        proxy_set_header   Host $host;
    }
}
sudo nginx -t && sudo systemctl reload nginx

The complete file is nginx-picam.conf. Open https://<YOUR_DOMAIN>/ and you should get a login prompt, then both cameras. The <img> tags and the /status requests reuse the credentials you just typed because they are on the same site.

Why each streaming directive is there

  • proxy_buffering off on /stream/: by default nginx buffers responses from the backend. For a stream that never ends, buffering adds delay and memory for nothing. With it off, nginx passes each chunk to the browser as soon as it arrives.
  • proxy_http_version 1.1 and Connection "": nginx 1.26, the version in Debian 13, talks HTTP/1.0 to backends by default and sends Connection: close. HTTP/1.1 lets Go send its usual chunked response, and the empty Connection header stops nginx from asking the backend to close. This pair is the documented setup for keepalive connections to a backend. (nginx 1.29.7 and later default to 1.1.)
  • proxy_pass http://127.0.0.1:... instead of localhost: nginx resolves localhost to every address it has, including the IPv6 ::1, and uses them in turn. If a backend listens only on 127.0.0.1, the ::1 attempts fail and fill the error log.
  • Timeouts stay at their defaults. proxy_read_timeout (60 s) is the longest nginx waits between two reads from Go, not the length of the response, so with 30 frames a second it never fires. If Python stops producing frames, the stream closes after a minute, which is what you want. send_timeout (60 s) is the same for writes to the browser: a viewer whose network vanishes is cut off after a minute, and that closes nginx’s connection to Go, which ends that viewer’s goroutine.
  • The ACME challenge location is in the port-80 block, not the HTTPS one. My original config, which certbot’s nginx plugin managed, had it under 443. With the webroot method the challenge must be answered on port 80: Let’s Encrypt does follow a redirect to HTTPS, but with a password on the HTTPS server the redirected request would hit the login and fail.

I also dropped some lines from my original config: chunked_transfer_encoding off (a documented workaround for clients that cannot handle chunked encoding, which browsers can), proxy_cache off (the default), X-Real-IP and X-Forwarded-* (neither backend reads them), and the include lines for certbot’s nginx plugin files, which certonly --webroot does not create.

Option B: no port forwarding, self-signed certificate

Skip the router changes and the Let’s Encrypt section. Generate a certificate for the Pi’s local name instead:

sudo openssl req -x509 -newkey rsa:3072 -noenc -days 825 \
  -keyout /etc/nginx/picam-selfsigned.key -out /etc/nginx/picam-selfsigned.crt \
  -subj "/CN=picam.local" -addext "subjectAltName=DNS:picam.local"
sudo chmod 600 /etc/nginx/picam-selfsigned.key

Create /etc/nginx/sites-available/picam from nginx-picam.conf with three changes: server_name picam.local; in both blocks, the two ssl_certificate lines pointing at /etc/nginx/picam-selfsigned.crt and .key, and no ACME location (the port-80 block can be just the redirect). Enable it and remove the default site with the same ln -s, rm and nginx -t commands as in Option A. Your browser will warn about the certificate the first time; check the fingerprint against openssl x509 -in /etc/nginx/picam-selfsigned.crt -noout -fingerprint -sha256 and accept it. Then reach https://picam.local/ at home, or through your WireGuard tunnel from outside (by the Pi’s tunnel address if .local names do not resolve over the VPN).

Keep the internals internal

Flask already binds 127.0.0.1:8080. The Go listing binds :8081, which means every interface, so anyone on your home network could open http://picam.local:8081/stream/0 and skip nginx and its password. Fix that before you rely on the password. Either deploy the version in the next section, or change that one string and rebuild:

cd ~/picam-go
sed -i 's/":8081"/"127.0.0.1:8081"/' main.go
grep -n 8081 main.go
go build -o picam-stream . && sudo systemctl restart picam-stream.service

grep should show "127.0.0.1:8081" on the ListenAndServe line (the log message above it still says :8081). Confirm from the Pi that only loopback is listening:

ss -ltn | grep -E ':(8080|8081)'

Both lines must show 127.0.0.1:, not *: or 0.0.0.0:.

The Unix sockets are the other door. On Linux, connecting to a Unix stream socket requires write permission on the socket file, and a new socket file gets full permissions minus the process umask. systemd’s default umask for services is 0022, which already denies write to other users. UMask=0077 in picam.service goes further and makes the sockets, the PID file and every recording owner-only, so another account on the Pi can neither connect to the stream nor read the clips. Check after a restart:

ls -l /tmp/picam0.sock /tmp/picam1.sock

Expected permissions are srwx------ owned by pi. The umask only applies to new files, so if you ran picam.py by hand in Step 4, tighten the folder it created then:

chmod 700 ~/recordings

What I would change

These are changes I would make now, kept separate so the listings above stay what I actually ran.

In the Go server

The listing has no data races, and the drop-frames design is right. Four things are worth fixing:

  1. Listen on loopback only. Covered above.
  2. A write deadline per frame. w.Write can block. When a viewer stops reading without closing the connection (a phone that went to sleep on Wi-Fi), its handler goroutine sits in Write and never gets back to the select that watches r.Context(). Behind nginx, send_timeout eventually ends it. If Go is ever exposed directly, nothing does until TCP gives up, which on Linux takes many minutes. http.ResponseController (Go 1.20 and later) can set a deadline on each write.
  3. Check the first write. The error from writing the latest frame is ignored. The next write catches it, so this is tidiness.
  4. Graceful shutdown. http.Server.Shutdown waits for active connections to go idle, and a stream never goes idle, so calling it alone would just hang until its timeout. The fix is to derive every request context from one that is cancelled on SIGTERM, via BaseContext. The handlers already return when their context is done, so the streams end and Shutdown completes.

The Broadcaster and socketReader stay exactly the same. Here is everything from the HTTP handler down, with these changes. The complete file, with the extra imports (context, errors, os, os/signal, syscall), is hardened/main.go.

// ---------------------------------------------------------------------------
// HTTP handler — streams MJPEG to browser
// ---------------------------------------------------------------------------

// listenAddr keeps the stream server off the network. nginx on the same
// machine is the only thing that should ever connect to it.
const listenAddr = "127.0.0.1:8081"

// frameWriteTimeout bounds how long one frame may take to reach a client.
// A viewer that stops reading without closing its connection is dropped
// after this long instead of holding a goroutine for minutes.
const frameWriteTimeout = 5 * time.Second

func mjpegHandler(b *Broadcaster) http.HandlerFunc {
    boundary := "frame"
    return func(w http.ResponseWriter, r *http.Request) {
        log.Printf("[http] client connected: %s", r.RemoteAddr)

        w.Header().Set("Content-Type", "multipart/x-mixed-replace; boundary="+boundary)
        w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")

        rc := http.NewResponseController(w)
        ch, latest := b.Subscribe()
        defer b.Unsubscribe(ch)

        if latest != nil {
            if err := writeFrame(rc, w, latest, boundary); err != nil {
                log.Printf("[http] client disconnected: %s", r.RemoteAddr)
                return
            }
        }

        for {
            select {
            case frame := <-ch:
                if err := writeFrame(rc, w, frame, boundary); err != nil {
                    log.Printf("[http] client disconnected: %s", r.RemoteAddr)
                    return
                }
            case <-r.Context().Done():
                log.Printf("[http] client context done: %s", r.RemoteAddr)
                return
            }
        }
    }
}

func writeFrame(rc *http.ResponseController, w http.ResponseWriter, frame []byte, boundary string) error {
    var buf bytes.Buffer
    buf.WriteString("--" + boundary + "\r\n")
    buf.WriteString("Content-Type: image/jpeg\r\n\r\n")
    buf.Write(frame)
    buf.WriteString("\r\n")

    if err := rc.SetWriteDeadline(time.Now().Add(frameWriteTimeout)); err != nil {
        return err
    }
    if _, err := w.Write(buf.Bytes()); err != nil {
        return err
    }
    return rc.Flush()
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
func main() {
    bc0 := NewBroadcaster()
    bc1 := NewBroadcaster()

    go socketReader("/tmp/picam0.sock", bc0)
    go socketReader("/tmp/picam1.sock", bc1)

    mux := http.NewServeMux()
    mux.HandleFunc("/stream/0", mjpegHandler(bc0))
    mux.HandleFunc("/stream/1", mjpegHandler(bc1))
    mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
        w.WriteHeader(http.StatusOK)
        w.Write([]byte("ok"))
    })

    // ctx is cancelled on SIGTERM (systemctl stop) or SIGINT (Ctrl+C).
    ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
    defer stop()

    srv := &http.Server{
        Addr:              listenAddr,
        Handler:           mux,
        ReadHeaderTimeout: 10 * time.Second,
        // Every request context derives from ctx, so cancelling ctx ends
        // the streaming loops and lets Shutdown finish.
        BaseContext: func(net.Listener) context.Context { return ctx },
    }

    go func() {
        log.Printf("Go MJPEG server listening on %s", listenAddr)
        if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
            log.Fatalf("server error: %v", err)
        }
    }()

    <-ctx.Done()
    log.Println("shutting down")
    shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    if err := srv.Shutdown(shutdownCtx); err != nil {
        log.Printf("shutdown: %v", err)
    }
}

I built it with gofmt -l, go vet, a normal build and a race build, all clean, and ran the same fake-camera test. On that development machine, a client that connected and never read was dropped within about 10 seconds of connecting (the kernel’s socket buffers absorbed the first few seconds of frames, then the 5-second deadline expired), while the original kept it for as long as the client stayed connected. On SIGTERM the hardened version logged shutting down, ended the open streams, and exited cleanly.

In the Python process

Make the watchdog actually restart the process. Python’s threading documentation says a SystemExit raised in a thread is silently ignored, and a quick test confirms it: a thread that calls sys.exit(1) logs its message and ends, and the process keeps running. So when a camera stalls, the watchdog logs Persistent stall — exiting for systemd restart and then nothing happens. Replace the sys.exit(1) inside watchdog_loop with:

                    os._exit(1)

os._exit ends the whole process immediately, without running atexit handlers, so the PID file stays behind. The lock already treats a PID file whose process is gone as stale, and systemd’s Restart=always brings the service back.

Fix the disk cleanup before your card fills. cleanup_old_recordings runs at the start of each recording. When the disk is over 80% used or under 2 GB free, it deletes the oldest clips until both limits are met again. But inside the loop it updates only its free-space figure, never the percentage. On a large card the 80% limit trips first, the percentage never changes inside the loop, and it deletes every clip in the folder. A test with the function copied out of picam.py and a fake file system at 85% usage deleted all 10 test clips when one was enough. This is a reading of the code and a test, not something the notes show happening on the Pi. A version that measures the disk again after every deletion, and never deletes more than 20 files in one pass in case something other than recordings filled the disk:

def disk_ok():
    st = os.statvfs(RECORDINGS_DIR)
    free_gb  = st.f_bavail * st.f_frsize / 1024 ** 3
    used_pct = 100 * (1 - st.f_bavail / st.f_blocks) if st.f_blocks else 0
    return free_gb >= MIN_FREE_GB and used_pct <= MAX_DISK_USAGE_PCT

def cleanup_old_recordings(max_delete=20):
    try:
        if disk_ok():
            return
        paths = sorted(
            (os.path.join(RECORDINGS_DIR, f)
             for f in os.listdir(RECORDINGS_DIR) if f.endswith('.mp4')),
            key=os.path.getmtime,
        )
        for path in paths[:max_delete]:
            if disk_ok():
                break
            size_mb = os.path.getsize(path) / (1024 * 1024)
            os.remove(path)
            log.info(f"Cleaned up {os.path.basename(path)} ({size_mb:.1f} MB)")
    except Exception as e:
        log.error(f"Cleanup error: {e}")

With this version the same test kept 9 of 10 clips.

Use a kernel lock instead of a PID file. The PID-file check has a gap between “check” and “write”, and os.kill raises PermissionError (which is not caught) if the old PID now belongs to another user’s process. An exclusive flock is held by the kernel and released automatically when the process dies, however it dies:

import fcntl
LOCK_FILE = '/tmp/picam.lock'
_lock_fd = open(LOCK_FILE, 'w')
try:
    fcntl.flock(_lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
    print("Another instance already running. Exiting.")
    sys.exit(1)

This runs in the main thread at import time, so sys.exit works here. Keep _lock_fd open for the life of the process.

Decide what the main stream is for. Right now both cameras run a full-size main stream that nothing reads, and the recordings are 1280×720 MJPEG re-encoded to H.264. If you want full-resolution clips, encode main directly, at a real CPU cost on the Pi 5’s software encoders. If 720p clips are fine, shrink main to the lores size and save ISP bandwidth and memory. Either way, fix the comment.

Handle a half-started recording. start_recording only starts the stop timer if both ffmpeg processes started. If the first starts and the second fails, the first records forever and blocks every future recording. Stop whichever one did start when the other fails.

Tidying: Response and numpy are unused imports, MOTION_BLUR_SIZE is unused since the blur became (5, 5), the docstring mentions a /recordings route that does not exist, and chained clips have a short gap while one ffmpeg finishes and the next starts.

Field notes: what broke

About 20 copies of picam.py. The dual-camera stream was choppy, and ps showed about 20 separate instances of the camera program running at once. The explanation at the time was the restart policy: Restart=always with RestartSec=5 restarting the service before the old process died. I rebooted, lengthened RestartSec, and added the PID lock. The systemd documentation does not support that explanation. A restart is a stop followed by a start, systemd’s default KillMode=control-group kills every process in the service on stop, and one unit runs one main process. Since ps showed real processes and not just thread rows, the explanation that fits best is copies started outside systemd, which is exactly what happened with the Go server later. The PID lock makes that impossible either way. The lesson: count processes with pgrep -a -f picam.py and compare with systemctl status, which lists only the service’s control group, before you theorise. Anything in the first list and not the second was started by hand. (In htop, press H to hide thread rows, or one process can look like fifteen.)

Wasted work per frame. The single-process version MJPEG-encoded full-resolution frames (2304×1296 and 2028×1520) for every viewer, waited for new frames in a time.sleep(0.01) polling loop, and decoded full-size JPEGs for motion detection. The lores stream, a threading.Condition that wakes once per frame, and capture_array("lores") removed all three.

OpenCV error on YUV420. After that change, both cameras logged:

[ERROR] [Tele] Motion error: OpenCV(4.10.0) ... Invalid number of channels in input image: 'VScn::contains(scn)' where 'scn' is 1

The code still called cv2.cvtColor(small, cv2.COLOR_BGR2GRAY), which expects three colour channels. A YUV420 lores array is one channel of planar data. The Y plane is already grayscale, so the fix was to slice it and drop the conversion.

Removing the blur. I asked whether the GaussianBlur line was needed, was told no, and deleted it. Recording then started on noise: the first trigger logged Motion area=104. Putting a (5, 5) blur back was part of the fix for the next bug.

Clips that chained forever. Every clip ended with Motion continues — chaining recording, and 98 files (1.5 GB) piled up. My first theory was that the motion flags were not being cleared, so I raised the grace period from 2 to 5 seconds and made the chain check depend only on the timestamp. It still chained. The debug line Chain check: last_motion_age=0.1s grace=5s still=True showed that motion had been detected a tenth of a second earlier, every time: the detector was firing continuously on tiny changes. The real fix was sensitivity: MOTION_MIN_AREA from 100 to 5000, MOTION_THRESHOLD from 15 to 25, MOTION_DETECT_SKIP from 3 to 5, and the blur back. After that it behaved. If you see constant chaining, look at the logged areas before you touch the chaining logic.

Two Go servers fighting. The terminal filled with this, roughly every 5 seconds:

[socket] read length error: EOF
[socket] disconnected from /tmp/picam0.sock, reconnecting...
[socket] connected to /tmp/picam0.sock

I had started ~/picam-go/picam-stream & by hand and then enabled the systemd unit. Killing the manual copy (pkill -f picam-stream) and using only systemd fixed it. The mechanism can be reproduced on any Linux machine. The systemd copy starts and, usually before its bind fails (the two race), dials both sockets. Python’s accept loop replaces the manual copy’s connection with the new one, so the manual copy reads EOF. Then the systemd copy fails to bind port 8081 (address already in use), log.Fatalf exits, and the manual copy reconnects. systemd restarts the failed copy after RestartSec=5, which matches the 5-second rhythm.

The status bar that never updated (not browser caching). In the early single-camera version, the status line was stuck. The console said Uncaught TypeError: can't access property "addEventListener", img is null. The <script> was in <head> and ran before the <img> existed, so it threw before setInterval was ever called. I spent time on hard refreshes and private windows on the theory that the browser was caching an old page. A second problem hid the first: my edits had never reached the file on the Pi (grep DOMContentLoaded ~/picam.py returned nothing). The final page loads its script at the end of <body>, after the images. When a fix “does nothing”, check that the file you are running contains it.

The phone reloaded the stream every 3 seconds. The page treated the stream as dead if no img load event arrived for 5 seconds and reset img.src. Mobile browsers do not fire load for each MJPEG frame. The final page has no such health check.

Tools and APIs that moved. camera-streamer built from source failed on the Zero 2 W with Overwriting Request::controls() is not allowed and Can't queue buffer, so I switched to Picamera2. Recording through Picamera2’s FfmpegOutput while the MJPEG encoder was running would not stop cleanly, so ffmpeg became a subprocess fed with frames. Rotation went through NameError: name 'libcamera' is not defined, ImportError: cannot import name 'transforms' from 'picamera2' and RuntimeError: Transform has incorrect type (from passing a dict) before landing on from libcamera import Transform.

A lens that would not focus. The HQ camera with a 6 mm lens, pointed at a bright window, would not come into sharp focus. A 16 mm lens focused immediately. Point the camera at something with detail and even light while you focus, then aim it.

Feeds flashing black at 73 °C. With the official case and fan, the feeds started flashing black when the Pi reached 73 °C. vcgencmd get_throttled returned throttled=0x0, so the firmware had not throttled. An extra fan blowing on the case stopped it. I never found the exact cause. If you see it, measure the temperature first.

Measuring it yourself

I am not publishing CPU figures. The numbers I collected along the way disagree with each other depending on how they were read, and an honest before-and-after needs the same tool, the same view and the same viewers. Here is how to measure your own.

Frames produced, per camera, from Python’s own counter (every 10 seconds):

journalctl -u picam.service -f | grep fps

Frames delivered, measured at the Go server on the Pi (divide by 10):

curl -s --max-time 10 http://127.0.0.1:8081/stream/0 | grep -a -c -- '--frame'

Run the same through nginx from another machine with curl -u <USER> https://<YOUR_DOMAIN>/stream/0 ... to include TLS and your network. If the first number is 30 and the second is much lower, the bottleneck is delivery, not the camera.

CPU per process and per thread:

top -H -p "$(pgrep -d, -f 'picam.py|picam-stream')"

-H shows threads. In plain top, press 1 to see each core: one core near 100% while the others idle is the GIL signature. In htop, H toggles thread rows, which is the difference between “15 copies” and “one process with 15 threads”.

Temperature and throttling:

vcgencmd measure_temp
vcgencmd get_throttled

throttled=0x0 means nothing has happened since boot. Any other value is a bit field: bit 0 (0x1) is under-voltage now, bit 2 (0x4) is throttled now, and bits 16 to 19 mean the same events happened at some point since boot. Under-voltage usually means the power supply or its cable cannot keep up with the load.

Night vision

“NoIR” means the camera has no infrared cut filter. Normal cameras block infrared so daytime colours look right; without the filter, colours look off in daylight, but the sensor can see infrared light that people cannot. That only helps at night if something is producing infrared, which means an IR illuminator. My HQ camera has its IR filter, so at night only the NoIR camera benefits.

IR LEDs come in two common wavelengths. 850 nm LEDs give a faint red glow you can see in the dark, and camera sensors are noticeably more sensitive at 850 nm. 940 nm LEDs are close to invisible, but the sensor sees less of their light, so you need more of them for the same picture. Choose 850 nm for range, 940 nm if a glowing camera is a problem.

I designed an illuminator for the NoIR camera but have not built it yet, so treat this as a design method, not a tested circuit:

  • LEDs cannot run straight from a voltage source; each needs something to limit its current, usually a series resistor. Ohm’s law gives the value: R = (Vsupply − Vf) / I, where Vf is the LED’s forward voltage and I its rated current, both from the LED’s datasheet. Round up to the next standard value.
  • Check the resistor’s power: P = (Vsupply − Vf) × I. Use a resistor rated comfortably above that.
  • A GPIO pin cannot supply IR LED currents. Let the pin switch a logic-level N-channel MOSFET (one that turns fully on at 3.3 V on its gate) through a small gate resistor, with the LEDs and their resistors between the 5 V supply and the MOSFET’s drain, and the source to ground.
  • Add up the LED current. It comes out of the same supply as the Pi and both cameras.
  • Match the beam to the lens. Narrow LEDs (20° was my design) light a small spot in the middle of a 120° view. Angle some outward or use wide-angle LEDs.
  • Do not shine IR from behind the window the camera looks through; the reflection washes out the picture.

Storage

Clips are H.264 at CRF 23, so their size follows the scene, not a fixed bitrate. The best number I have is from my own folder: 98 clips of 30 seconds (both cameras) came to about 1.5 GB, roughly 15 MB per clip, or about 4 Mbit/s. As an estimate only, every hour of motion would then use about 3.7 GB for both cameras, and a busy street or noisy night footage can be much more. Measure yours:

du -sh ~/recordings
ffprobe -v error -show_entries format=duration,bit_rate -of default=nw=1 ~/recordings/<CLIP>.mp4

The cleanup (once fixed) deletes the oldest clips when the disk passes 80% used or drops under 2 GB free. That keeps the Pi from filling up, but it also means the oldest evidence goes first, and it only runs when a recording starts.

A microSD card has limited write endurance, and a security camera writes constantly. If you rely on this, move recordings off the card:

  • A USB 3 SSD or an NVMe drive on the Raspberry Pi M.2 HAT+. Mount it, then point RECORDINGS_DIR at it. If the drive is missing at boot, os.makedirs will happily create the folder on the SD card instead, so check it is mounted.
  • A network share on a NAS. This also keeps clips safe if someone takes the camera. Use a systemd mount with nofail, and expect clips to be lost if the share drops mid-recording.

Before you point it at anything

This is not legal advice. Recording laws vary by country, state and city. Audio is often regulated more strictly than video, and this build records no audio, so keep it that way unless you have checked. Do not aim cameras into neighbours’ windows, yards or other private spaces, and think about what a telephoto lens can see across the street. Check your local rules, and your lease or homeowners’ association if you have one, before you mount anything.

Sources and further reading