Ver código fonte

Add Linux port of the radio front panel

Replace the LPC1114 with software on the Linux board, driving the S1D13700
LCD and the keys through TCA9539 I2C expanders:

- panel core shared by all frontends: init, pixel conversion, write
  planner and the TCA9539 byte stream
- simulator of the expander and controller, with panel core tests
- UI and MPD client, with GTK (simulated panel), i2c-dev and DRM
  frontends
- DRM kernel driver and a device tree overlay

The review recommendations are applied to the core and the driver,
including retry of failed updates, enable-before-plane ordering and
recovery of the control line state after a lost message. The control
lines are mapped to the actual board, and the geometry and gray test
patterns were confirmed on the real panel.
k4be 2 semanas atrás
commit
d0931c2515
15 arquivos alterados com 2309 adições e 0 exclusões
  1. 7 0
      .gitignore
  2. 80 0
      Makefile
  3. 78 0
      README.md
  4. 94 0
      app/app.h
  5. 241 0
      app/app_core.c
  6. 74 0
      app/log_kmsg.c
  7. 160 0
      app/main_drm.c
  8. 329 0
      app/main_gtk.c
  9. 286 0
      app/main_i2c.c
  10. 269 0
      app/mpd_client.c
  11. 96 0
      app/platform_linux.c
  12. 25 0
      app/platform_linux.h
  13. 204 0
      app/ui_render.c
  14. 270 0
      docs/REPORT.md
  15. 96 0
      tests/fake_mpd.py

+ 7 - 0
.gitignore

@@ -0,0 +1,7 @@
+build/
+driver/*.mod
+driver/*.mod.c
+driver/.*.cmd
+driver/Module.symvers
+driver/modules.order
+driver/.tmp_versions/

+ 80 - 0
Makefile

@@ -0,0 +1,80 @@
+# Linux port: run from this directory.
+#   make test        panel core tests (no hardware, no libraries)
+#   make gtk         window with simulated panel and on-screen keys
+#   make target      i2c-dev and DRM frontends for the real panel
+#   make dtbo        device tree overlay
+#   make module      DRM driver, against KDIR (default: running kernel source)
+
+BUILD   := build
+CC      ?= gcc
+CFLAGS  ?= -O2 -g
+CFLAGS  += -std=gnu11 -Wall -Wextra -MMD -MP
+CFLAGS  += -Idriver -Isim -Iapp
+KDIR    ?= /usr/src/linux
+
+CORE     := driver/s1d13700_core.c
+SIM      := sim/s1d13700_sim.c
+APP      := app/app_core.c app/ui_render.c app/mpd_client.c app/log_kmsg.c
+PLATFORM := app/platform_linux.c
+
+APP_PKGS := glib-2.0 cairo pangocairo libmpdclient
+GTK_PKGS := gtk+-3.0 $(APP_PKGS)
+
+objs = $(addprefix $(BUILD)/,$(1:.c=.o))
+
+.PHONY: all test asan gtk target dtbo module clean
+all: test gtk
+
+# ---- tests -----------------------------------------------------------------
+$(BUILD)/test_panel: tests/test_panel.c $(CORE) $(SIM)
+	@mkdir -p $(dir $@)
+	$(CC) $(CFLAGS) -o $@ $^
+
+$(BUILD)/test_panel_asan: tests/test_panel.c $(CORE) $(SIM)
+	@mkdir -p $(dir $@)
+	$(CC) $(CFLAGS) -fsanitize=address,undefined -fno-sanitize-recover=all -o $@ $^
+
+test: $(BUILD)/test_panel
+	$<
+
+asan: $(BUILD)/test_panel_asan
+	$<
+
+# ---- applications ----------------------------------------------------------
+gtk: $(BUILD)/radio-gtk
+target: $(BUILD)/radio-i2c $(BUILD)/radio-drm
+
+$(BUILD)/radio-gtk: CFLAGS += $(shell pkg-config --cflags $(GTK_PKGS))
+$(BUILD)/radio-gtk: LDLIBS += $(shell pkg-config --libs $(GTK_PKGS))
+$(BUILD)/radio-gtk: $(call objs,app/main_gtk.c $(APP) $(CORE) $(SIM))
+	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
+
+$(BUILD)/radio-i2c: CFLAGS += $(shell pkg-config --cflags $(APP_PKGS))
+$(BUILD)/radio-i2c: LDLIBS += $(shell pkg-config --libs $(APP_PKGS))
+$(BUILD)/radio-i2c: $(call objs,app/main_i2c.c $(PLATFORM) $(APP) $(CORE))
+	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
+
+$(BUILD)/radio-drm: CFLAGS += $(shell pkg-config --cflags $(APP_PKGS) libdrm)
+$(BUILD)/radio-drm: LDLIBS += $(shell pkg-config --libs $(APP_PKGS) libdrm)
+$(BUILD)/radio-drm: $(call objs,app/main_drm.c $(PLATFORM) $(APP))
+	$(CC) $(CFLAGS) -o $@ $^ $(LDLIBS)
+
+$(BUILD)/%.o: %.c
+	@mkdir -p $(dir $@)
+	$(CC) $(CFLAGS) -c -o $@ $<
+
+# ---- device tree and kernel module -----------------------------------------
+dtbo: $(BUILD)/radio-panel.dtbo
+
+$(BUILD)/radio-panel.dtbo: dts/radio-panel.dts
+	@mkdir -p $(dir $@)
+	dtc -@ -I dts -O dtb -o $@ $<
+
+module:
+	$(MAKE) -C $(KDIR) M=$(CURDIR)/driver modules
+
+clean:
+	rm -rf $(BUILD)
+	-$(MAKE) -C $(KDIR) M=$(CURDIR)/driver clean
+
+-include $(shell find $(BUILD) -name '*.d' 2>/dev/null)

+ 78 - 0
README.md

@@ -0,0 +1,78 @@
+# Linux port
+
+Replaces the LPC1114 firmware: the panel and keys hang off I²C expanders on the
+Linux board. Nothing here has run on real hardware yet.
+
+| Path | What |
+|---|---|
+| `driver/s1d13700_core.*` | Panel core, used by everything: init, 2 bpp conversion, write planner, TCA9539 stream |
+| `driver/s1d13700_drm.c` | DRM driver (6.x kernels) |
+| `sim/` | Model of the TCA9539 and S1D13700: decodes the I²C bytes and flags bus faults |
+| `app/` | UI and MPD client, plus the frontends: `main_gtk.c`, `main_i2c.c`, `main_drm.c` |
+| `dts/radio-panel.dts` | Overlay for the keys, backlight and panel |
+| `tests/` | Panel core tests and a fake MPD server |
+
+## Building
+
+    make test          # panel core tests, no hardware or libraries
+    make gtk           # needs gtk+-3.0, cairo, pangocairo, libmpdclient
+    make target        # i2c-dev and DRM frontends; DRM also needs libdrm
+    make dtbo
+    make module KDIR=/path/to/kernel
+
+## Running
+
+Window with the simulated panel, using a real MPD:
+
+    build/radio-gtk --host radio.lo
+
+The window shows the simulator's display memory, and the traffic each update
+costs. Keys: `Z X C V B` for prev/play/pause/stop/next, arrows, `Enter`, `Esc`,
+`M`, `L`, `Space` for pause.
+
+Real panel through i2c-dev, for bring-up or on a kernel too old for the driver:
+
+    build/radio-i2c --bus N --pattern geometry
+    build/radio-i2c --bus N --pattern gray
+    build/radio-i2c --bus N --host radio.lo
+
+`--bus` must name a known adapter; motherboard and display buses are always
+refused. Only use the bus number of the adapter the panel is wired to.
+
+## Wiring
+
+**U1, TCA9539 at 0x74** (A1=L, A0=L), raw I²C client of the panel code
+
+| Pin | Signal | Module pin |
+|---|---|---|
+| P0.0-7 | D0-D7 | D0-D7 |
+| P1.0 | Backlight enable (active high, assumed) | |
+| P1.1 | RES# | RST |
+| P1.2 | A0 | A15 |
+| P1.3 | WR# | WE |
+| P1.4 | RD# | RE |
+| P1.5 | CS# (held low after reset; was hardwired low on the old board) | CS0 |
+| P1.6-7 | spare | |
+
+**U2, TCA9539 at 0x75** (A1=L, A0=H), stock `gpio-pca953x`
+
+Each key has its own pin to ground and a 10k pull-up (the TCA9539 has no
+internal ones). `INT` goes to a host GPIO with a pull-up.
+
+| Pin | Key | Pin | Key |
+|---|---|---|---|
+| P0.0 | Esc | P1.0 | Down |
+| P0.1 | Next | P1.1 | Pause |
+| P0.2 | Stop | P1.2 | OK |
+| P0.3 | Menu | P1.3 | Left |
+| P0.4 | List | P1.4 | Play |
+| P0.5 | Up | P1.5 | Backlight enable (active high, pull-down) |
+| P0.6 | Prev | P1.6-7 | spare |
+| P0.7 | Right | | |
+
+## To confirm on hardware
+
+- The TCA9539 stays in the register pair across a long write (the whole stream depends on it)
+- Panel size: 240×160 is assumed; `--pattern geometry` shows the real one
+- TC/R (`--tcr`) for frame rate; 162 comes from the AVR project's 2 bpp setup
+- Pixel polarity (white = level 0 here)

+ 94 - 0
app/app.h

@@ -0,0 +1,94 @@
+/*
+ * Radio UI: everything that is the same in the window and on the real panel.
+ * The frontends supply a way to show pixels and feed in key presses.
+ */
+#ifndef RADIO_APP_H
+#define RADIO_APP_H
+
+#include <cairo.h>
+#include <glib.h>
+#include <stdbool.h>
+#include <stdint.h>
+
+enum radio_key {
+	RK_ESC, RK_NEXT, RK_STOP, RK_MENU, RK_LIST, RK_UP, RK_PREV,
+	RK_RIGHT, RK_DOWN, RK_PAUSE, RK_OK, RK_LEFT, RK_PLAY,
+	RK_COUNT
+};
+
+enum play_state { PLAY_UNKNOWN, PLAY_PLAYING, PLAY_PAUSED, PLAY_STOPPED };
+
+#define LOG_ROWS	8
+#define LOG_COLS	44
+#define TITLE_MAX	512
+
+struct radio_state {
+	bool connected;
+	char server[128];
+
+	enum play_state state;
+	char title[TITLE_MAX];
+	int song_pos;		/* -1: none */
+	unsigned int queue_len;
+	unsigned int elapsed_ms;
+	gint64 elapsed_stamp_us;	/* monotonic time elapsed_ms was read */
+	unsigned int total_ms;	/* 0: unknown, e.g. a stream */
+	int volume;		/* -1: unknown */
+	bool repeat, random;
+
+	char log[LOG_ROWS][LOG_COLS * 4 + 1];	/* UTF-8, wrapped */
+};
+
+/* Current position, advanced locally between MPD updates while playing */
+unsigned int radio_state_elapsed_ms(const struct radio_state *s);
+
+/* ---- rendering ---------------------------------------------------------- */
+void ui_render(cairo_t *cr, const struct radio_state *s, int width, int height);
+
+/* ---- app ---------------------------------------------------------------- */
+struct app_frontend {
+	void *ctx;
+	/* pixels is the whole frame; (x, y, w, h) bounds what changed */
+	void (*present)(void *ctx, const uint32_t *pixels, int stride,
+			int x, int y, int w, int h);
+	void (*backlight)(void *ctx, bool on);
+};
+
+struct app_options {
+	const char *host;
+	unsigned int port;
+	int width, height;
+	bool kmsg;		/* show this machine's kernel log */
+};
+
+struct app;
+
+struct app *app_new(const struct app_options *opt, const struct app_frontend *fe);
+void app_free(struct app *app);
+void app_key(struct app *app, enum radio_key key);
+void app_log(struct app *app, const char *text);
+
+/* ---- MPD client --------------------------------------------------------- */
+struct mpdc;
+
+enum mpdc_command {
+	MPDC_PLAY, MPDC_TOGGLE, MPDC_STOP, MPDC_NEXT, MPDC_PREV,
+	MPDC_VOLUME_UP, MPDC_VOLUME_DOWN, MPDC_REFRESH,
+};
+
+/* Called on the GLib main loop whenever *state may have changed */
+typedef void (*mpdc_changed_fn)(void *user);
+typedef void (*mpdc_log_fn)(void *user, const char *text);
+
+struct mpdc *mpdc_new(const char *host, unsigned int port, struct radio_state *state,
+		      mpdc_changed_fn changed, mpdc_log_fn log, void *user);
+void mpdc_free(struct mpdc *m);
+void mpdc_command(struct mpdc *m, enum mpdc_command cmd);
+
+/* ---- kernel log --------------------------------------------------------- */
+struct log_kmsg;
+
+struct log_kmsg *log_kmsg_new(mpdc_log_fn log, void *user);
+void log_kmsg_free(struct log_kmsg *k);
+
+#endif /* RADIO_APP_H */

+ 241 - 0
app/app_core.c

@@ -0,0 +1,241 @@
+#include <stdlib.h>
+#include <string.h>
+
+#include "app.h"
+
+#define BACKLIGHT_TIMEOUT_S	30
+#define KEY_LOCKOUT_US		300000	/* as the firmware: 300 ms after a press */
+#define LOG_REDRAW_MS		1000	/* scrolling is the costliest redraw */
+
+struct app {
+	struct app_options opt;
+	struct app_frontend fe;
+	struct radio_state state;
+	struct mpdc *mpd;
+	struct log_kmsg *kmsg;
+
+	cairo_surface_t *surface;
+	uint32_t *prev;
+	bool prev_valid;
+
+	guint render_id;
+	guint log_timer_id;
+	guint tick_id;
+	guint backlight_id;
+	gint64 key_time_us[RK_COUNT];
+};
+
+unsigned int radio_state_elapsed_ms(const struct radio_state *s)
+{
+	gint64 extra;
+	unsigned int ms = s->elapsed_ms;
+
+	/* with the link down the player's position is unknown, so hold it */
+	if (!s->connected || s->state != PLAY_PLAYING || !s->elapsed_stamp_us)
+		return ms;
+	extra = (g_get_monotonic_time() - s->elapsed_stamp_us) / 1000;
+	ms += (unsigned int)extra;
+	return (s->total_ms && ms > s->total_ms) ? s->total_ms : ms;
+}
+
+/* Render, and hand the frontend the bounding box of what actually changed */
+static gboolean render_now(gpointer data)
+{
+	struct app *app = data;
+	int w = app->opt.width, h = app->opt.height;
+	int stride, x, y, x0 = w, y0 = h, x1 = 0, y1 = 0;
+	const uint32_t *pixels;
+	cairo_t *cr;
+
+	app->render_id = 0;
+
+	cr = cairo_create(app->surface);
+	ui_render(cr, &app->state, w, h);
+	cairo_destroy(cr);
+	cairo_surface_flush(app->surface);
+
+	pixels = (const uint32_t *)cairo_image_surface_get_data(app->surface);
+	stride = cairo_image_surface_get_stride(app->surface);
+
+	for (y = 0; y < h; y++) {
+		const uint32_t *a = (const uint32_t *)((const char *)pixels + y * stride);
+		const uint32_t *b = app->prev + y * w;
+
+		if (app->prev_valid && !memcmp(a, b, (size_t)w * 4))
+			continue;
+		for (x = 0; x < w; x++) {
+			if (app->prev_valid && a[x] == b[x])
+				continue;
+			if (x < x0)
+				x0 = x;
+			if (x >= x1)
+				x1 = x + 1;
+		}
+		if (y < y0)
+			y0 = y;
+		y1 = y + 1;
+		memcpy(app->prev + y * w, a, (size_t)w * 4);
+	}
+	app->prev_valid = true;
+
+	if (x1 > x0)
+		app->fe.present(app->fe.ctx, pixels, stride, x0, y0, x1 - x0, y1 - y0);
+	return G_SOURCE_REMOVE;
+}
+
+static void schedule_render(struct app *app)
+{
+	if (!app->render_id)
+		app->render_id = g_idle_add(render_now, app);
+}
+
+static void on_mpd_changed(void *user)
+{
+	schedule_render(user);
+}
+
+static gboolean log_timer(gpointer data)
+{
+	struct app *app = data;
+
+	app->log_timer_id = 0;
+	schedule_render(app);
+	return G_SOURCE_REMOVE;
+}
+
+/* Append one wrapped row, scrolling the pane; batched into one redraw */
+static void log_push_row(struct app *app, const char *start, const char *end)
+{
+	struct radio_state *s = &app->state;
+	size_t len = (size_t)(end - start);
+
+	memmove(s->log[0], s->log[1], sizeof(s->log[0]) * (LOG_ROWS - 1));
+	if (len > sizeof(s->log[0]) - 1)
+		len = sizeof(s->log[0]) - 1;
+	memcpy(s->log[LOG_ROWS - 1], start, len);
+	s->log[LOG_ROWS - 1][len] = '\0';
+}
+
+void app_log(struct app *app, const char *text)
+{
+	char *clean = g_utf8_make_valid(text, -1);
+	const char *p = clean;
+
+	do {
+		const char *q = p;
+		int n = 0;
+
+		while (*q && n < LOG_COLS) {
+			q = g_utf8_next_char(q);
+			n++;
+		}
+		log_push_row(app, p, q);
+		p = q;
+	} while (*p);
+
+	g_free(clean);
+
+	if (!app->log_timer_id)
+		app->log_timer_id = g_timeout_add(LOG_REDRAW_MS, log_timer, app);
+}
+
+static void on_log(void *user, const char *text)
+{
+	app_log(user, text);
+}
+
+static gboolean tick(gpointer data)
+{
+	struct app *app = data;
+
+	if (app->state.state == PLAY_PLAYING)
+		schedule_render(app);
+	return G_SOURCE_CONTINUE;
+}
+
+static gboolean backlight_expired(gpointer data)
+{
+	struct app *app = data;
+
+	app->backlight_id = 0;
+	if (app->fe.backlight)
+		app->fe.backlight(app->fe.ctx, false);
+	return G_SOURCE_REMOVE;
+}
+
+static void backlight_wake(struct app *app)
+{
+	if (app->fe.backlight)
+		app->fe.backlight(app->fe.ctx, true);
+	if (app->backlight_id)
+		g_source_remove(app->backlight_id);
+	app->backlight_id = g_timeout_add_seconds(BACKLIGHT_TIMEOUT_S,
+						  backlight_expired, app);
+}
+
+void app_key(struct app *app, enum radio_key key)
+{
+	gint64 now = g_get_monotonic_time();
+
+	if ((unsigned int)key >= RK_COUNT)
+		return;
+	if (now - app->key_time_us[key] < KEY_LOCKOUT_US)
+		return;
+	app->key_time_us[key] = now;
+
+	backlight_wake(app);
+
+	switch (key) {
+	case RK_PREV:	mpdc_command(app->mpd, MPDC_PREV); break;
+	case RK_PLAY:	mpdc_command(app->mpd, MPDC_PLAY); break;
+	case RK_PAUSE:	mpdc_command(app->mpd, MPDC_TOGGLE); break;
+	case RK_STOP:	mpdc_command(app->mpd, MPDC_STOP); break;
+	case RK_NEXT:	mpdc_command(app->mpd, MPDC_NEXT); break;
+	case RK_ESC:	mpdc_command(app->mpd, MPDC_REFRESH); break;
+	case RK_UP:	mpdc_command(app->mpd, MPDC_VOLUME_UP); break;
+	case RK_DOWN:	mpdc_command(app->mpd, MPDC_VOLUME_DOWN); break;
+	default:	break;	/* MENU, LIST, OK, LEFT, RIGHT: not assigned yet */
+	}
+}
+
+struct app *app_new(const struct app_options *opt, const struct app_frontend *fe)
+{
+	struct app *app = g_new0(struct app, 1);
+
+	app->opt = *opt;
+	app->fe = *fe;
+	app->state.song_pos = -1;
+	app->state.volume = -1;
+	g_strlcpy(app->state.server, opt->host, sizeof(app->state.server));
+
+	app->surface = cairo_image_surface_create(CAIRO_FORMAT_RGB24,
+						  opt->width, opt->height);
+	app->prev = g_new0(uint32_t, (gsize)opt->width * opt->height);
+
+	app->mpd = mpdc_new(opt->host, opt->port, &app->state,
+			    on_mpd_changed, on_log, app);
+	if (opt->kmsg)
+		app->kmsg = log_kmsg_new(on_log, app);
+
+	app->tick_id = g_timeout_add_seconds(1, tick, app);
+	backlight_wake(app);
+	schedule_render(app);
+	return app;
+}
+
+void app_free(struct app *app)
+{
+	if (app->render_id)
+		g_source_remove(app->render_id);
+	if (app->log_timer_id)
+		g_source_remove(app->log_timer_id);
+	if (app->backlight_id)
+		g_source_remove(app->backlight_id);
+	g_source_remove(app->tick_id);
+	if (app->kmsg)
+		log_kmsg_free(app->kmsg);
+	mpdc_free(app->mpd);
+	cairo_surface_destroy(app->surface);
+	g_free(app->prev);
+	g_free(app);
+}

+ 74 - 0
app/log_kmsg.c

@@ -0,0 +1,74 @@
+/* Kernel log pane source: follows /dev/kmsg from the moment it is opened. */
+#include <errno.h>
+#include <fcntl.h>
+#include <glib-unix.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "app.h"
+
+struct log_kmsg {
+	int fd;
+	guint watch_id;
+	mpdc_log_fn log;
+	void *user;
+};
+
+static gboolean on_kmsg(gint fd, GIOCondition cond, gpointer data)
+{
+	struct log_kmsg *k = data;
+	char buf[4096];
+	ssize_t n;
+
+	(void)cond;
+	for (;;) {
+		char *text, *end;
+
+		n = read(fd, buf, sizeof(buf) - 1);
+		if (n < 0 && errno == EPIPE)
+			continue;	/* records were overwritten; carry on */
+		if (n <= 0)
+			break;
+		buf[n] = '\0';
+
+		/* "prio,seq,usec,flags;message\n" then optional " KEY=value" lines */
+		text = strchr(buf, ';');
+		if (!text)
+			continue;
+		text++;
+		end = strchr(text, '\n');
+		if (end)
+			*end = '\0';
+		k->log(k->user, text);
+	}
+	if (n == 0 || (n < 0 && errno != EAGAIN)) {
+		k->watch_id = 0;
+		return G_SOURCE_REMOVE;
+	}
+	return G_SOURCE_CONTINUE;
+}
+
+struct log_kmsg *log_kmsg_new(mpdc_log_fn log, void *user)
+{
+	struct log_kmsg *k = g_new0(struct log_kmsg, 1);
+
+	k->log = log;
+	k->user = user;
+	k->fd = open("/dev/kmsg", O_RDONLY | O_NONBLOCK | O_CLOEXEC);
+	if (k->fd < 0) {
+		log(user, "Nie można otworzyć /dev/kmsg");
+		return k;
+	}
+	lseek(k->fd, 0, SEEK_END);
+	k->watch_id = g_unix_fd_add(k->fd, G_IO_IN, on_kmsg, k);
+	return k;
+}
+
+void log_kmsg_free(struct log_kmsg *k)
+{
+	if (k->watch_id)
+		g_source_remove(k->watch_id);
+	if (k->fd >= 0)
+		close(k->fd);
+	g_free(k);
+}

+ 160 - 0
app/main_drm.c

@@ -0,0 +1,160 @@
+/*
+ * UI on the panel through the s1d13700-tca DRM driver: one dumb buffer, with
+ * each change reported as a dirty rectangle.
+ */
+#include <errno.h>
+#include <fcntl.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/mman.h>
+#include <unistd.h>
+#include <xf86drm.h>
+#include <xf86drmMode.h>
+
+#include "platform_linux.h"
+
+#define DRIVER_NAME	"s1d13700-tca"
+
+struct drm_dev {
+	int fd;
+	uint32_t fb_id, pitch;
+	uint8_t *map;
+	const char *backlight;
+};
+
+/* Only ever our own device: never take over the machine's real display */
+static int open_panel(void)
+{
+	char path[32];
+	int i, fd;
+
+	for (i = 0; i < 16; i++) {
+		drmVersionPtr v;
+		bool match;
+
+		snprintf(path, sizeof(path), "/dev/dri/card%d", i);
+		fd = open(path, O_RDWR | O_CLOEXEC);
+		if (fd < 0)
+			continue;
+		v = drmGetVersion(fd);
+		match = v && !strcmp(v->name, DRIVER_NAME);
+		drmFreeVersion(v);
+		if (match)
+			return fd;
+		close(fd);
+	}
+	return -1;
+}
+
+static int setup_output(struct drm_dev *d, drmModeModeInfo *mode)
+{
+	drmModeRes *res = drmModeGetResources(d->fd);
+	drmModeConnector *conn;
+	uint32_t handles[4] = { 0 }, pitches[4] = { 0 }, offsets[4] = { 0 };
+	uint32_t handle, pitch, crtc;
+	uint64_t size, offset;
+	int ret = -1;
+
+	if (!res || res->count_connectors < 1 || res->count_crtcs < 1)
+		goto out_res;
+	conn = drmModeGetConnector(d->fd, res->connectors[0]);
+	if (!conn || conn->count_modes < 1)
+		goto out_conn;
+
+	*mode = conn->modes[0];
+	crtc = res->crtcs[0];
+
+	if (drmModeCreateDumbBuffer(d->fd, mode->hdisplay, mode->vdisplay, 32, 0,
+				    &handle, &pitch, &size))
+		goto out_conn;
+	handles[0] = handle;
+	pitches[0] = pitch;
+	if (drmModeAddFB2(d->fd, mode->hdisplay, mode->vdisplay,
+			  0x34325258 /* XR24 */, handles, pitches, offsets, &d->fb_id, 0))
+		goto out_conn;
+	if (drmModeMapDumbBuffer(d->fd, handle, &offset))
+		goto out_conn;
+	d->map = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, d->fd, (off_t)offset);
+	if (d->map == MAP_FAILED)
+		goto out_conn;
+	memset(d->map, 0xff, size);
+	d->pitch = pitch;
+
+	if (drmModeSetCrtc(d->fd, crtc, d->fb_id, 0, 0, &conn->connector_id, 1, mode))
+		goto out_conn;
+	ret = 0;
+out_conn:
+	drmModeFreeConnector(conn);
+out_res:
+	drmModeFreeResources(res);
+	return ret;
+}
+
+static void present(void *ctx, const uint32_t *pixels, int stride, int x, int y, int w, int h)
+{
+	struct drm_dev *d = ctx;
+	drmModeClip clip = { (uint16_t)x, (uint16_t)y, (uint16_t)(x + w), (uint16_t)(y + h) };
+	int row;
+
+	for (row = y; row < y + h; row++)
+		memcpy(d->map + (size_t)row * d->pitch + (size_t)x * 4,
+		       (const char *)pixels + row * stride + x * 4, (size_t)w * 4);
+	if (drmModeDirtyFB(d->fd, d->fb_id, &clip, 1))
+		g_printerr("DIRTYFB failed: %s\n", strerror(errno));
+}
+
+static void backlight(void *ctx, bool on)
+{
+	platform_backlight_set(((struct drm_dev *)ctx)->backlight, on);
+}
+
+int main(int argc, char **argv)
+{
+	static struct drm_dev d;
+	static int port = 6600;
+	static char *host, *input, *blpath;
+	static gboolean kmsg;
+	static GOptionEntry entries[] = {
+		{ "host", 0, 0, G_OPTION_ARG_STRING, &host, "MPD host (localhost)", "NAME" },
+		{ "port", 0, 0, G_OPTION_ARG_INT, &port, "MPD port (6600)", "N" },
+		{ "input", 0, 0, G_OPTION_ARG_FILENAME, &input, "Key input device (auto: " DEFAULT_KEYS_NAME ")", "PATH" },
+		{ "backlight", 0, 0, G_OPTION_ARG_FILENAME, &blpath, "Backlight sysfs brightness file", "PATH" },
+		{ "kmsg", 0, 0, G_OPTION_ARG_NONE, &kmsg, "Show the kernel log", NULL },
+		{ NULL, 0, 0, 0, NULL, NULL, NULL },
+	};
+	GOptionContext *ctx = g_option_context_new("- radio panel over DRM");
+	struct app_frontend fe = { &d, present, backlight };
+	struct app_options opt;
+	drmModeModeInfo mode;
+	GError *err = NULL;
+	struct app *app;
+
+	g_option_context_add_main_entries(ctx, entries, NULL);
+	if (!g_option_context_parse(ctx, &argc, &argv, &err)) {
+		g_printerr("%s\n", err->message);
+		return 1;
+	}
+	d.backlight = blpath ? blpath : DEFAULT_BACKLIGHT;
+
+	d.fd = open_panel();
+	if (d.fd < 0) {
+		g_printerr("no %s DRM device found\n", DRIVER_NAME);
+		return 1;
+	}
+	if (setup_output(&d, &mode)) {
+		g_printerr("cannot set up the display: %s\n", strerror(errno));
+		return 1;
+	}
+
+	opt = (struct app_options){ host ? host : "localhost", port,
+				    mode.hdisplay, mode.vdisplay, kmsg };
+	app = app_new(&opt, &fe);
+	if (!platform_keys_start(app, input))
+		g_printerr("no key input device, running display-only\n");
+
+	platform_run();
+
+	app_free(app);
+	return 0;
+}

+ 329 - 0
app/main_gtk.c

@@ -0,0 +1,329 @@
+/*
+ * Development window. Frames take the real path: conversion, planner, TCA9539
+ * byte stream, then the simulated expander and controller. The window shows
+ * the simulator's display memory, so it is what the panel would receive.
+ */
+#include <gdk/gdkkeysyms.h>
+#include <gtk/gtk.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "app.h"
+#include "s1d13700_core.h"
+#include "s1d13700_sim.h"
+
+#define SCL_HZ		400000
+#define TX_CAP		1025	/* the driver's message limit */
+
+struct gui {
+	struct app *app;
+	struct s1d_config cfg;
+	struct s1d_panel panel;
+	struct s1d_sim sim;
+	uint8_t shadow[S1D_VRAM_SIZE];
+	uint8_t next[S1D_VRAM_SIZE];
+	uint8_t tx[TX_CAP];
+	uint8_t *levels;
+
+	cairo_surface_t *image;
+	GtkWidget *window, *lcd, *stats;
+	GtkWidget *buttons[RK_COUNT];
+	bool backlight;
+	unsigned long total_bytes;
+	guint frames;
+	int scale;
+
+	gchar **press;
+	int press_next;
+	const char *snapshot;
+};
+
+static const struct key_def {
+	enum radio_key key;
+	const char *label;
+	guint keyval, keyval2;
+	int col, row;		/* button grid */
+} key_defs[] = {
+	{ RK_PREV,  "⏮ Prev (Z)",   GDK_KEY_z, GDK_KEY_Z, 0, 0 },
+	{ RK_PLAY,  "▶ Play (X)",   GDK_KEY_x, GDK_KEY_X, 1, 0 },
+	{ RK_PAUSE, "⏯ Pause (C)",  GDK_KEY_c, GDK_KEY_space, 2, 0 },
+	{ RK_STOP,  "⏹ Stop (V)",   GDK_KEY_v, GDK_KEY_V, 3, 0 },
+	{ RK_NEXT,  "⏭ Next (B)",   GDK_KEY_b, GDK_KEY_B, 4, 0 },
+	{ RK_ESC,   "Esc",          GDK_KEY_Escape, 0, 0, 1 },
+	{ RK_UP,    "▲ Vol+ (↑)",   GDK_KEY_Up, 0, 2, 1 },
+	{ RK_MENU,  "Menu (M)",     GDK_KEY_m, GDK_KEY_M, 4, 1 },
+	{ RK_LEFT,  "◀ (←)",        GDK_KEY_Left, 0, 1, 2 },
+	{ RK_OK,    "OK (Enter)",   GDK_KEY_Return, GDK_KEY_KP_Enter, 2, 2 },
+	{ RK_RIGHT, "▶ (→)",        GDK_KEY_Right, 0, 3, 2 },
+	{ RK_DOWN,  "▼ Vol− (↓)",   GDK_KEY_Down, 0, 2, 3 },
+	{ RK_LIST,  "List (L)",     GDK_KEY_l, GDK_KEY_L, 4, 3 },
+};
+
+static int sim_xfer(void *ctx, const uint8_t *buf, size_t len)
+{
+	s1d_sim_i2c_write(ctx, buf, len);
+	return 0;
+}
+
+static void sim_delay(void *ctx, unsigned int ms)
+{
+	(void)ctx;
+	(void)ms;
+}
+
+static const struct s1d_ops sim_ops = { sim_xfer, sim_delay };
+
+static void update_image(struct gui *g)
+{
+	unsigned int w = g->cfg.width, h = g->cfg.height, x, y;
+	/* LCD look, from background to darkest level */
+	static const uint32_t lit[] = { 0xc4d890, 0x8ca060, 0x506438, 0x142010 };
+	static const uint32_t dark[] = { 0x4a5238, 0x363e2a, 0x242a1e, 0x101410 };
+	const uint32_t *pal = g->backlight ? lit : dark;
+	uint8_t *data;
+	int stride;
+	bool shown;
+
+	shown = s1d_sim_render(&g->sim, w, h, g->levels);
+	cairo_surface_flush(g->image);
+	data = cairo_image_surface_get_data(g->image);
+	stride = cairo_image_surface_get_stride(g->image);
+
+	for (y = 0; y < h; y++) {
+		uint32_t *row = (uint32_t *)(data + y * stride);
+
+		for (x = 0; x < w; x++)
+			row[x] = shown ? pal[g->levels[y * w + x] & 3] : pal[0];
+	}
+	cairo_surface_mark_dirty(g->image);
+	gtk_widget_queue_draw(g->lcd);
+}
+
+static void present(void *ctx, const uint32_t *pixels, int stride, int x, int y, int w, int h)
+{
+	struct gui *g = ctx;
+	char text[256];
+	int err, faults;
+
+	s1d_convert_xrgb8888(&g->cfg, pixels, stride, g->next, x, y, x + w, y + h);
+
+	memset(&g->panel.stats, 0, sizeof(g->panel.stats));
+	err = s1d_panel_update(&g->panel, g->next, y, y + h);
+	g->total_bytes += g->panel.stats.i2c_bytes;
+	g->frames++;
+	faults = s1d_sim_fault_count(&g->sim);
+
+	snprintf(text, sizeof(text),
+		 "last update: %lu LCD writes, %lu seeks, %lu I²C bytes, %.1f ms at 400 kHz  |  "
+		 "total %lu bytes in %u updates%s",
+		 g->panel.stats.writes, g->panel.stats.seeks, g->panel.stats.i2c_bytes,
+		 s1d_stats_bus_us(&g->panel.stats, SCL_HZ) / 1000.0,
+		 g->total_bytes, g->frames,
+		 err || faults ? "  |  BUS FAULTS, see stderr" : "");
+	gtk_label_set_text(GTK_LABEL(g->stats), text);
+	if (faults)
+		g_printerr("simulator faults: %d\n", faults);
+
+	update_image(g);
+}
+
+static void backlight(void *ctx, bool on)
+{
+	struct gui *g = ctx;
+
+	g->backlight = on;
+	update_image(g);
+}
+
+static gboolean lcd_draw(GtkWidget *w, cairo_t *cr, gpointer data)
+{
+	struct gui *g = data;
+
+	(void)w;
+	cairo_scale(cr, g->scale, g->scale);
+	cairo_set_source_surface(cr, g->image, 0, 0);
+	cairo_pattern_set_filter(cairo_get_source(cr), CAIRO_FILTER_NEAREST);
+	cairo_paint(cr);
+	return TRUE;
+}
+
+static void key_clicked(GtkButton *b, gpointer data)
+{
+	struct gui *g = data;
+
+	app_key(g->app, GPOINTER_TO_INT(g_object_get_data(G_OBJECT(b), "key")));
+}
+
+static gboolean key_press(GtkWidget *w, GdkEventKey *ev, gpointer data)
+{
+	struct gui *g = data;
+	unsigned int i;
+
+	(void)w;
+	for (i = 0; i < G_N_ELEMENTS(key_defs); i++) {
+		if (ev->keyval == key_defs[i].keyval ||
+		    (key_defs[i].keyval2 && ev->keyval == key_defs[i].keyval2)) {
+			app_key(g->app, key_defs[i].key);
+			return TRUE;
+		}
+	}
+	return FALSE;
+}
+
+static void build_window(struct gui *g)
+{
+	GtkWidget *box, *grid;
+	unsigned int i;
+
+	g->window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
+	gtk_window_set_title(GTK_WINDOW(g->window), "Radio panel simulator");
+	gtk_window_set_resizable(GTK_WINDOW(g->window), FALSE);
+	g_signal_connect(g->window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
+	g_signal_connect(g->window, "key-press-event", G_CALLBACK(key_press), g);
+
+	box = gtk_box_new(GTK_ORIENTATION_VERTICAL, 6);
+	gtk_container_set_border_width(GTK_CONTAINER(box), 8);
+	gtk_container_add(GTK_CONTAINER(g->window), box);
+
+	g->lcd = gtk_drawing_area_new();
+	gtk_widget_set_size_request(g->lcd, (int)g->cfg.width * g->scale,
+				    (int)g->cfg.height * g->scale);
+	g_signal_connect(g->lcd, "draw", G_CALLBACK(lcd_draw), g);
+	gtk_box_pack_start(GTK_BOX(box), g->lcd, FALSE, FALSE, 0);
+
+	g->stats = gtk_label_new("");
+	gtk_label_set_xalign(GTK_LABEL(g->stats), 0);
+	gtk_label_set_line_wrap(GTK_LABEL(g->stats), TRUE);
+	gtk_label_set_max_width_chars(GTK_LABEL(g->stats), 60);
+	gtk_box_pack_start(GTK_BOX(box), g->stats, FALSE, FALSE, 0);
+
+	grid = gtk_grid_new();
+	gtk_grid_set_row_spacing(GTK_GRID(grid), 4);
+	gtk_grid_set_column_spacing(GTK_GRID(grid), 4);
+	gtk_grid_set_column_homogeneous(GTK_GRID(grid), TRUE);
+	gtk_box_pack_start(GTK_BOX(box), grid, FALSE, FALSE, 0);
+
+	for (i = 0; i < G_N_ELEMENTS(key_defs); i++) {
+		const struct key_def *d = &key_defs[i];
+		GtkWidget *b = gtk_button_new_with_label(d->label);
+
+		/* a focused button would take Space and Enter from the shortcuts */
+		gtk_widget_set_can_focus(b, FALSE);
+		g_object_set_data(G_OBJECT(b), "key", GINT_TO_POINTER(d->key));
+		g_signal_connect(b, "clicked", G_CALLBACK(key_clicked), g);
+		gtk_grid_attach(GTK_GRID(grid), b, d->col, d->row, 1, 1);
+		g->buttons[d->key] = b;
+	}
+}
+
+/* ---- scripted runs, for automated checks -------------------------------- */
+
+static const char *const key_names[RK_COUNT] = {
+	[RK_ESC] = "esc", [RK_NEXT] = "next", [RK_STOP] = "stop",
+	[RK_MENU] = "menu", [RK_LIST] = "list", [RK_UP] = "up",
+	[RK_PREV] = "prev", [RK_RIGHT] = "right", [RK_DOWN] = "down",
+	[RK_PAUSE] = "pause", [RK_OK] = "ok", [RK_LEFT] = "left",
+	[RK_PLAY] = "play",
+};
+
+static gboolean press_next(gpointer data)
+{
+	struct gui *g = data;
+	const char *name = g->press[g->press_next];
+	int i;
+
+	if (!name)
+		return G_SOURCE_REMOVE;
+	g->press_next++;
+	for (i = 0; i < RK_COUNT; i++)
+		if (!strcmp(name, key_names[i]))
+			gtk_button_clicked(GTK_BUTTON(g->buttons[i]));
+	return G_SOURCE_CONTINUE;
+}
+
+static gboolean finish(gpointer data)
+{
+	struct gui *g = data;
+
+	if (g->snapshot) {
+		GtkAllocation a;
+		cairo_surface_t *s;
+		cairo_t *cr;
+
+		gtk_widget_get_allocation(g->window, &a);
+		s = cairo_image_surface_create(CAIRO_FORMAT_RGB24, a.width, a.height);
+		cr = cairo_create(s);
+		gtk_widget_draw(g->window, cr);
+		cairo_destroy(cr);
+		cairo_surface_write_to_png(s, g->snapshot);
+		cairo_surface_destroy(s);
+	}
+	gtk_main_quit();
+	return G_SOURCE_REMOVE;
+}
+
+int main(int argc, char **argv)
+{
+	static struct gui g;
+	static char *host, *press, *snapshot;
+	static int port = 6600, width = 240, height = 160, bpp = 2, tcr = 162;
+	static int scale = 3, exit_after;
+	static gboolean kmsg;
+	static GOptionEntry entries[] = {
+		{ "host", 0, 0, G_OPTION_ARG_STRING, &host, "MPD host (radio.lo)", "NAME" },
+		{ "port", 0, 0, G_OPTION_ARG_INT, &port, "MPD port (6600)", "N" },
+		{ "width", 0, 0, G_OPTION_ARG_INT, &width, "Panel width (240)", "PX" },
+		{ "height", 0, 0, G_OPTION_ARG_INT, &height, "Panel height (160)", "PX" },
+		{ "bpp", 0, 0, G_OPTION_ARG_INT, &bpp, "Bits per pixel: 1, 2, 4 (2)", "N" },
+		{ "scale", 0, 0, G_OPTION_ARG_INT, &scale, "Window zoom (3)", "N" },
+		{ "kmsg", 0, 0, G_OPTION_ARG_NONE, &kmsg, "Show this machine's kernel log", NULL },
+		{ "press", 0, 0, G_OPTION_ARG_STRING, &press, "Click these keys, comma separated", "LIST" },
+		{ "snapshot", 0, 0, G_OPTION_ARG_FILENAME, &snapshot, "Write the window to a PNG before exiting", "FILE" },
+		{ "exit-after", 0, 0, G_OPTION_ARG_INT, &exit_after, "Quit after this many ms", "MS" },
+		{ NULL, 0, 0, 0, NULL, NULL, NULL },
+	};
+	struct app_frontend fe = { &g, present, backlight };
+	struct app_options opt;
+	GError *err = NULL;
+	guint64 size;
+
+	if (!gtk_init_with_args(&argc, &argv, NULL, entries, NULL, &err)) {
+		g_printerr("%s\n", err ? err->message : "cannot open display");
+		return 1;
+	}
+
+	g.cfg = (struct s1d_config){ width, height, bpp, tcr };
+	g.scale = scale;
+	g.backlight = true;
+	g.snapshot = snapshot;
+
+	s1d_sim_init(&g.sim);
+	if (s1d_panel_setup(&g.panel, &g.cfg, &sim_ops, &g.sim, g.shadow, g.tx, sizeof(g.tx)) ||
+	    s1d_panel_init(&g.panel)) {
+		g_printerr("invalid panel configuration\n");
+		return 1;
+	}
+
+	size = (guint64)width * height;
+	g.levels = g_malloc(size);
+	g.image = cairo_image_surface_create(CAIRO_FORMAT_RGB24, width, height);
+
+	build_window(&g);
+	update_image(&g);
+	gtk_widget_show_all(g.window);
+
+	opt = (struct app_options){ host ? host : "radio.lo", port, width, height, kmsg };
+	g.app = app_new(&opt, &fe);
+
+	if (press) {
+		g.press = g_strsplit(press, ",", -1);
+		g_timeout_add(400, press_next, &g);
+	}
+	if (exit_after)
+		g_timeout_add(exit_after, finish, &g);
+
+	gtk_main();
+
+	app_free(g.app);
+	return s1d_sim_fault_count(&g.sim) ? 2 : 0;
+}

+ 286 - 0
app/main_i2c.c

@@ -0,0 +1,286 @@
+/*
+ * Drives the real panel directly through /dev/i2c-N, with no kernel driver.
+ * This is the bring-up tool (--pattern), and the way to run on a kernel too
+ * old for the DRM driver.
+ *
+ * Writing a raw byte stream to the wrong bus can reach anything attached to
+ * it, so the adapter is checked by name before the first transfer.
+ */
+#include <errno.h>
+#include <fcntl.h>
+#include <linux/i2c-dev.h>
+#include <linux/i2c.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#include "platform_linux.h"
+#include "s1d13700_core.h"
+
+#define TX_CAP		1025
+
+/* Never, whatever the options: motherboard and display buses */
+static const char *const denied_adapters[] = { "PIIX4", "AMDGPU", "DPMST", "i801", "SMBus" };
+/* Known to be a dedicated bus for this panel */
+static const char *const known_adapters[] = { "MCP2221", "FT260", "i2c-tiny-usb", "mv64xxx" };
+
+struct panel_dev {
+	int fd;
+	unsigned int addr;
+	struct s1d_config cfg;
+	struct s1d_panel panel;
+	uint8_t shadow[S1D_VRAM_SIZE];
+	uint8_t next[S1D_VRAM_SIZE];
+	uint8_t tx[TX_CAP];
+	const char *backlight;
+};
+
+static int dev_xfer(void *ctx, const uint8_t *buf, size_t len)
+{
+	struct panel_dev *d = ctx;
+	struct i2c_msg msg = { d->addr, 0, (uint16_t)len, (uint8_t *)buf };
+	struct i2c_rdwr_ioctl_data data = { &msg, 1 };
+
+	return ioctl(d->fd, I2C_RDWR, &data) < 0 ? -errno : 0;
+}
+
+static void dev_delay(void *ctx, unsigned int ms)
+{
+	(void)ctx;
+	usleep(ms * 1000);
+}
+
+static const struct s1d_ops dev_ops = { dev_xfer, dev_delay };
+
+static void present(void *ctx, const uint32_t *pixels, int stride, int x, int y, int w, int h)
+{
+	struct panel_dev *d = ctx;
+	int err;
+
+	s1d_convert_xrgb8888(&d->cfg, pixels, stride, d->next, x, y, x + w, y + h);
+	err = s1d_panel_update(&d->panel, d->next, y, y + h);
+	if (err)
+		g_printerr("panel update failed: %s\n", strerror(-err));
+}
+
+/* sysfs if a path was given, otherwise the pin on the panel's own expander */
+static void backlight(void *ctx, bool on)
+{
+	struct panel_dev *d = ctx;
+	int err;
+
+	if (d->backlight) {
+		platform_backlight_set(d->backlight, on);
+		return;
+	}
+	err = s1d_panel_backlight(&d->panel, on);
+	if (err)
+		g_printerr("backlight: %s\n", strerror(-err));
+}
+
+static int open_bus(int bus, const char *allow)
+{
+	char path[64], name[128] = "";
+	unsigned long funcs = 0;
+	unsigned int i;
+	bool ok = false;
+	FILE *f;
+	int fd;
+
+	snprintf(path, sizeof(path), "/sys/class/i2c-dev/i2c-%d/name", bus);
+	f = fopen(path, "r");
+	if (!f || !fgets(name, sizeof(name), f)) {
+		g_printerr("i2c-%d: cannot read the adapter name\n", bus);
+		if (f)
+			fclose(f);
+		return -1;
+	}
+	fclose(f);
+	name[strcspn(name, "\n")] = '\0';
+
+	for (i = 0; i < G_N_ELEMENTS(denied_adapters); i++) {
+		if (strstr(name, denied_adapters[i])) {
+			g_printerr("i2c-%d (%s): refusing, this is not a panel bus\n", bus, name);
+			return -1;
+		}
+	}
+	for (i = 0; i < G_N_ELEMENTS(known_adapters); i++)
+		if (strstr(name, known_adapters[i]))
+			ok = true;
+	if (allow && !strcmp(allow, name))
+		ok = true;
+	if (!ok) {
+		g_printerr("i2c-%d (%s): unknown adapter; if it really is the panel's bus,\n"
+			   "pass --allow-adapter=\"%s\"\n", bus, name, name);
+		return -1;
+	}
+
+	snprintf(path, sizeof(path), "/dev/i2c-%d", bus);
+	fd = open(path, O_RDWR | O_CLOEXEC);
+	if (fd < 0) {
+		g_printerr("%s: %s\n", path, strerror(errno));
+		return -1;
+	}
+	if (ioctl(fd, I2C_FUNCS, &funcs) < 0 || !(funcs & I2C_FUNC_I2C)) {
+		g_printerr("i2c-%d (%s): no raw I2C support\n", bus, name);
+		close(fd);
+		return -1;
+	}
+	printf("using i2c-%d (%s)\n", bus, name);
+	return fd;
+}
+
+/* ---- bring-up patterns -------------------------------------------------- */
+
+static void put(uint32_t *fb, unsigned int w, unsigned int x, unsigned int y, uint32_t c)
+{
+	fb[y * w + x] = c;
+}
+
+/* Border, plus ticks every 10 px and long ticks every 50: shows the real size */
+static void pattern_geometry(uint32_t *fb, unsigned int w, unsigned int h)
+{
+	unsigned int x, y, i;
+
+	for (x = 0; x < w; x++) {
+		put(fb, w, x, 0, 0);
+		put(fb, w, x, h - 1, 0);
+		if (!(x % 10))
+			for (i = 0; i < (x % 50 ? 4u : 10u); i++)
+				put(fb, w, x, 1 + i, 0);
+	}
+	for (y = 0; y < h; y++) {
+		put(fb, w, 0, y, 0);
+		put(fb, w, w - 1, y, 0);
+		if (!(y % 10))
+			for (i = 0; i < (y % 50 ? 4u : 10u); i++)
+				put(fb, w, 1 + i, y, 0);
+	}
+	/* a diagonal shows skew from a wrong line length */
+	for (i = 0; i < h && i < w; i++)
+		put(fb, w, i, i, 0);
+}
+
+static void pattern_gray(uint32_t *fb, unsigned int w, unsigned int h)
+{
+	static const uint32_t levels[] = { 0xffffff, 0xaaaaaa, 0x555555, 0x000000 };
+	unsigned int x, y;
+
+	for (y = 0; y < h; y++)
+		for (x = 0; x < w; x++)
+			put(fb, w, x, y, levels[x * 4 / w]);
+}
+
+static int show_pattern(struct panel_dev *d, const char *name)
+{
+	unsigned int w = d->cfg.width, h = d->cfg.height;
+	uint32_t *fb = g_malloc((gsize)w * h * 4);
+	int err;
+
+	memset(fb, 0xff, (gsize)w * h * 4);
+	if (!strcmp(name, "geometry")) {
+		pattern_geometry(fb, w, h);
+	} else if (!strcmp(name, "gray")) {
+		pattern_gray(fb, w, h);
+	} else {
+		g_printerr("unknown pattern '%s' (geometry, gray)\n", name);
+		g_free(fb);
+		return 1;
+	}
+
+	s1d_convert_xrgb8888(&d->cfg, fb, w * 4, d->next, 0, 0, w, h);
+	err = s1d_panel_update(&d->panel, d->next, 0, h);
+	g_free(fb);
+	if (err) {
+		g_printerr("pattern failed: %s\n", strerror(-err));
+		return 1;
+	}
+	printf("pattern sent: %lu I2C bytes in %lu messages\n",
+	       d->panel.stats.i2c_bytes, d->panel.stats.i2c_msgs);
+	return 0;
+}
+
+int main(int argc, char **argv)
+{
+	static struct panel_dev d;
+	static int bus = -1, addr = 0x74, port = 6600;
+	static int width = 240, height = 160, bpp = 2, tcr = 162, tx_cap = TX_CAP;
+	static gboolean no_backlight;
+	static char *host, *pattern, *allow, *input, *blpath;
+	static gboolean kmsg;
+	static GOptionEntry entries[] = {
+		{ "bus", 0, 0, G_OPTION_ARG_INT, &bus, "I2C bus number (required)", "N" },
+		{ "addr", 0, 0, G_OPTION_ARG_INT, &addr, "Expander address (0x74 = 116)", "N" },
+		{ "allow-adapter", 0, 0, G_OPTION_ARG_STRING, &allow, "Accept the adapter with this exact name", "NAME" },
+		{ "width", 0, 0, G_OPTION_ARG_INT, &width, "Panel width (240)", "PX" },
+		{ "height", 0, 0, G_OPTION_ARG_INT, &height, "Panel height (160)", "PX" },
+		{ "bpp", 0, 0, G_OPTION_ARG_INT, &bpp, "Bits per pixel: 1, 2, 4 (2)", "N" },
+		{ "tcr", 0, 0, G_OPTION_ARG_INT, &tcr, "TC/R, sets the frame rate (162)", "N" },
+		{ "tx-cap", 0, 0, G_OPTION_ARG_INT, &tx_cap, "Largest I2C message, 7.." G_STRINGIFY(TX_CAP) " (" G_STRINGIFY(TX_CAP) ")", "BYTES" },
+		{ "no-backlight", 0, 0, G_OPTION_ARG_NONE, &no_backlight, "Leave the expander's backlight pin off", NULL },
+		{ "pattern", 0, 0, G_OPTION_ARG_STRING, &pattern, "Show a test pattern and exit: geometry, gray", "NAME" },
+		{ "host", 0, 0, G_OPTION_ARG_STRING, &host, "MPD host (localhost)", "NAME" },
+		{ "port", 0, 0, G_OPTION_ARG_INT, &port, "MPD port (6600)", "N" },
+		{ "input", 0, 0, G_OPTION_ARG_FILENAME, &input, "Key input device (auto: " DEFAULT_KEYS_NAME ")", "PATH" },
+		{ "backlight", 0, 0, G_OPTION_ARG_FILENAME, &blpath, "Backlight sysfs brightness file (default: expander pin P1.0)", "PATH" },
+		{ "kmsg", 0, 0, G_OPTION_ARG_NONE, &kmsg, "Show the kernel log", NULL },
+		{ NULL, 0, 0, 0, NULL, NULL, NULL },
+	};
+	GOptionContext *ctx = g_option_context_new("- radio panel over i2c-dev");
+	struct app_frontend fe = { &d, present, backlight };
+	struct app_options opt;
+	GError *err = NULL;
+	struct app *app;
+	int ret;
+
+	g_option_context_add_main_entries(ctx, entries, NULL);
+	if (!g_option_context_parse(ctx, &argc, &argv, &err)) {
+		g_printerr("%s\n", err->message);
+		return 1;
+	}
+	if (bus < 0) {
+		g_printerr("--bus is required\n");
+		return 1;
+	}
+
+	d.fd = open_bus(bus, allow);
+	if (d.fd < 0)
+		return 1;
+
+	d.addr = addr;
+	d.cfg = (struct s1d_config){ width, height, bpp, tcr };
+	d.backlight = blpath;
+	if (tx_cap < 0 || tx_cap > TX_CAP) {
+		g_printerr("--tx-cap: at most %d\n", TX_CAP);
+		return 1;
+	}
+
+	ret = s1d_panel_setup(&d.panel, &d.cfg, &dev_ops, &d, d.shadow, d.tx, tx_cap);
+	if (ret) {
+		g_printerr("invalid panel configuration\n");
+		return 1;
+	}
+	if (!blpath && !no_backlight)
+		s1d_panel_backlight(&d.panel, true);
+	ret = s1d_panel_init(&d.panel);
+	if (ret) {
+		g_printerr("panel init failed: %s\n", strerror(-ret));
+		return 1;
+	}
+
+	if (pattern)
+		return show_pattern(&d, pattern);
+
+	opt = (struct app_options){ host ? host : "localhost", port, width, height, kmsg };
+	app = app_new(&opt, &fe);
+	if (!platform_keys_start(app, input))
+		g_printerr("no key input device, running display-only\n");
+
+	platform_run();
+
+	app_free(app);
+	s1d_panel_display(&d.panel, false);
+	return 0;
+}

+ 269 - 0
app/mpd_client.c

@@ -0,0 +1,269 @@
+/*
+ * MPD connection on the GLib main loop. The connection sits in "idle" so
+ * changes arrive as events instead of being polled; anything else first leaves
+ * idle, does its work and goes back.
+ */
+#include <glib-unix.h>
+#include <mpd/client.h>
+#include <stdio.h>
+#include <string.h>
+
+#include "app.h"
+
+#define CONNECT_TIMEOUT_MS	2000
+#define RECONNECT_S		3
+
+struct mpdc {
+	char *host;
+	unsigned int port;
+	struct radio_state *state;
+	mpdc_changed_fn changed;
+	mpdc_log_fn log;
+	void *user;
+
+	struct mpd_connection *conn;
+	guint watch_id;
+	guint retry_id;
+	bool was_connected;
+};
+
+static gboolean on_readable(gint fd, GIOCondition cond, gpointer data);
+static gboolean try_connect(gpointer data);
+
+static void note(struct mpdc *m, const char *text)
+{
+	m->log(m->user, text);
+}
+
+static void drop_connection(struct mpdc *m, const char *why)
+{
+	char buf[200];
+
+	if (m->watch_id) {
+		g_source_remove(m->watch_id);
+		m->watch_id = 0;
+	}
+	if (m->conn) {
+		mpd_connection_free(m->conn);
+		m->conn = NULL;
+	}
+	m->state->connected = false;
+	if (m->was_connected && why) {
+		snprintf(buf, sizeof(buf), "MPD: %s", why);
+		note(m, buf);
+	}
+	m->was_connected = false;
+	if (!m->retry_id)
+		m->retry_id = g_timeout_add_seconds(RECONNECT_S, try_connect, m);
+	m->changed(m->user);
+}
+
+/*
+ * Returns false if the connection was lost. A command MPD merely refused,
+ * such as changing the volume with no mixer, does not end the session.
+ */
+static bool check_connection(struct mpdc *m)
+{
+	char buf[256];
+
+	switch (mpd_connection_get_error(m->conn)) {
+	case MPD_ERROR_SUCCESS:
+		return true;
+	case MPD_ERROR_SERVER:
+		snprintf(buf, sizeof(buf), "MPD: %s",
+			 mpd_connection_get_error_message(m->conn));
+		note(m, buf);
+		if (mpd_connection_clear_error(m->conn))
+			return true;
+		break;
+	default:
+		break;
+	}
+	g_strlcpy(buf, mpd_connection_get_error_message(m->conn), sizeof(buf));
+	drop_connection(m, buf);
+	return false;
+}
+
+static void format_title(char *out, size_t size, const struct mpd_song *song)
+{
+	const char *artist = mpd_song_get_tag(song, MPD_TAG_ARTIST, 0);
+	const char *title = mpd_song_get_tag(song, MPD_TAG_TITLE, 0);
+	const char *name = mpd_song_get_tag(song, MPD_TAG_NAME, 0);
+	const char *uri = mpd_song_get_uri(song);
+	const char *slash;
+
+	if (artist && title) {
+		snprintf(out, size, "%s - %s", artist, title);
+	} else if (title && name) {	/* a stream announcing what it plays */
+		snprintf(out, size, "%s: %s", name, title);
+	} else if (title || name) {
+		g_strlcpy(out, title ? title : name, size);
+	} else {
+		slash = strrchr(uri, '/');
+		g_strlcpy(out, (slash && slash[1] && !strstr(uri, "://")) ? slash + 1 : uri, size);
+	}
+}
+
+static void refresh(struct mpdc *m)
+{
+	struct radio_state *s = m->state;
+	struct mpd_status *status;
+	struct mpd_song *song;
+
+	status = mpd_run_status(m->conn);
+	if (!status) {
+		check_connection(m);
+		return;
+	}
+
+	switch (mpd_status_get_state(status)) {
+	case MPD_STATE_PLAY:	s->state = PLAY_PLAYING; break;
+	case MPD_STATE_PAUSE:	s->state = PLAY_PAUSED; break;
+	case MPD_STATE_STOP:	s->state = PLAY_STOPPED; break;
+	default:		s->state = PLAY_UNKNOWN; break;
+	}
+	s->song_pos = mpd_status_get_song_pos(status);
+	s->queue_len = mpd_status_get_queue_length(status);
+	s->elapsed_ms = mpd_status_get_elapsed_ms(status);
+	s->elapsed_stamp_us = g_get_monotonic_time();
+	s->total_ms = mpd_status_get_total_time(status) * 1000;
+	s->volume = mpd_status_get_volume(status);
+	s->repeat = mpd_status_get_repeat(status);
+	s->random = mpd_status_get_random(status);
+	mpd_status_free(status);
+
+	s->title[0] = '\0';
+	/* as the firmware: a stopped player shows no title */
+	if (s->state != PLAY_STOPPED) {
+		song = mpd_run_current_song(m->conn);
+		if (song) {
+			format_title(s->title, sizeof(s->title), song);
+			mpd_song_free(song);
+		} else if (!check_connection(m)) {
+			return;
+		}
+	}
+	m->changed(m->user);
+}
+
+static void enter_idle(struct mpdc *m)
+{
+	if (!m->conn)
+		return;
+	if (!mpd_send_idle_mask(m->conn, MPD_IDLE_QUEUE | MPD_IDLE_PLAYER |
+				MPD_IDLE_MIXER | MPD_IDLE_OPTIONS))
+		check_connection(m);
+}
+
+static gboolean on_readable(gint fd, GIOCondition cond, gpointer data)
+{
+	struct mpdc *m = data;
+
+	(void)fd;
+	if (cond & (G_IO_HUP | G_IO_ERR)) {
+		m->watch_id = 0;
+		drop_connection(m, "connection closed");
+		return G_SOURCE_REMOVE;
+	}
+
+	mpd_recv_idle(m->conn, false);
+	if (!check_connection(m))
+		return G_SOURCE_REMOVE;	/* drop_connection removed this source */
+
+	refresh(m);
+	if (m->conn)
+		enter_idle(m);
+	return m->conn ? G_SOURCE_CONTINUE : G_SOURCE_REMOVE;
+}
+
+static gboolean try_connect(gpointer data)
+{
+	struct mpdc *m = data;
+	struct mpd_connection *c;
+	char buf[200];
+
+	m->retry_id = 0;
+
+	c = mpd_connection_new(m->host, m->port, CONNECT_TIMEOUT_MS);
+	if (!c || mpd_connection_get_error(c) != MPD_ERROR_SUCCESS) {
+		if (c)
+			mpd_connection_free(c);
+		m->retry_id = g_timeout_add_seconds(RECONNECT_S, try_connect, m);
+		return G_SOURCE_REMOVE;
+	}
+
+	m->conn = c;
+	m->state->connected = true;
+	m->was_connected = true;
+	snprintf(buf, sizeof(buf), "Połączono z MPD: %s", m->host);
+	note(m, buf);
+
+	refresh(m);
+	if (m->conn) {
+		m->watch_id = g_unix_fd_add(mpd_connection_get_fd(m->conn),
+					    G_IO_IN | G_IO_HUP | G_IO_ERR,
+					    on_readable, m);
+		enter_idle(m);
+	}
+	return G_SOURCE_REMOVE;
+}
+
+void mpdc_command(struct mpdc *m, enum mpdc_command cmd)
+{
+	bool ok = true;
+
+	if (!m->conn) {
+		note(m, "Brak połączenia z MPD");
+		return;
+	}
+
+	/* leave idle; any event it reports is covered by the refresh below */
+	mpd_run_noidle(m->conn);
+	if (!check_connection(m))
+		return;
+
+	switch (cmd) {
+	case MPDC_PLAY:		ok = mpd_run_play(m->conn); break;
+	case MPDC_TOGGLE:	ok = mpd_run_toggle_pause(m->conn); break;
+	case MPDC_STOP:		ok = mpd_run_stop(m->conn); break;
+	case MPDC_NEXT:		ok = mpd_run_next(m->conn); break;
+	case MPDC_PREV:		ok = mpd_run_previous(m->conn); break;
+	case MPDC_VOLUME_UP:	ok = mpd_run_change_volume(m->conn, 1); break;
+	case MPDC_VOLUME_DOWN:	ok = mpd_run_change_volume(m->conn, -1); break;
+	case MPDC_REFRESH:	break;
+	}
+	if (!ok && !check_connection(m))
+		return;
+
+	refresh(m);
+	if (m->conn)
+		enter_idle(m);
+}
+
+struct mpdc *mpdc_new(const char *host, unsigned int port, struct radio_state *state,
+		      mpdc_changed_fn changed, mpdc_log_fn log, void *user)
+{
+	struct mpdc *m = g_new0(struct mpdc, 1);
+
+	m->host = g_strdup(host);
+	m->port = port;
+	m->state = state;
+	m->changed = changed;
+	m->log = log;
+	m->user = user;
+	/* not directly: the owner must finish construction first */
+	m->retry_id = g_idle_add(try_connect, m);
+	return m;
+}
+
+void mpdc_free(struct mpdc *m)
+{
+	if (m->watch_id)
+		g_source_remove(m->watch_id);
+	if (m->retry_id)
+		g_source_remove(m->retry_id);
+	if (m->conn)
+		mpd_connection_free(m->conn);
+	g_free(m->host);
+	g_free(m);
+}

+ 96 - 0
app/platform_linux.c

@@ -0,0 +1,96 @@
+#include <errno.h>
+#include <fcntl.h>
+#include <glib-unix.h>
+#include <linux/input.h>
+#include <stdio.h>
+#include <string.h>
+#include <sys/ioctl.h>
+#include <unistd.h>
+
+#include "platform_linux.h"
+
+static const struct {
+	unsigned short code;
+	enum radio_key key;
+} keymap[] = {
+	{ KEY_ESC, RK_ESC }, { KEY_NEXTSONG, RK_NEXT }, { KEY_STOPCD, RK_STOP },
+	{ KEY_MENU, RK_MENU }, { KEY_LIST, RK_LIST }, { KEY_UP, RK_UP },
+	{ KEY_PREVIOUSSONG, RK_PREV }, { KEY_RIGHT, RK_RIGHT },
+	{ KEY_DOWN, RK_DOWN }, { KEY_PAUSECD, RK_PAUSE }, { KEY_OK, RK_OK },
+	{ KEY_LEFT, RK_LEFT }, { KEY_PLAYCD, RK_PLAY },
+};
+
+static gboolean on_input(gint fd, GIOCondition cond, gpointer data)
+{
+	struct app *app = data;
+	struct input_event ev;
+	unsigned int i;
+
+	(void)cond;
+	while (read(fd, &ev, sizeof(ev)) == (ssize_t)sizeof(ev)) {
+		/* 1 press, 2 autorepeat: app_key() applies the lockout */
+		if (ev.type != EV_KEY || ev.value == 0)
+			continue;
+		for (i = 0; i < G_N_ELEMENTS(keymap); i++)
+			if (keymap[i].code == ev.code)
+				app_key(app, keymap[i].key);
+	}
+	return G_SOURCE_CONTINUE;
+}
+
+static int find_keys_device(void)
+{
+	char path[32], name[64];
+	int i, fd;
+
+	for (i = 0; i < 32; i++) {
+		snprintf(path, sizeof(path), "/dev/input/event%d", i);
+		fd = open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC);
+		if (fd < 0)
+			continue;
+		if (ioctl(fd, EVIOCGNAME(sizeof(name)), name) > 0 &&
+		    !strcmp(name, DEFAULT_KEYS_NAME))
+			return fd;
+		close(fd);
+	}
+	return -1;
+}
+
+bool platform_keys_start(struct app *app, const char *path)
+{
+	int fd = path ? open(path, O_RDONLY | O_NONBLOCK | O_CLOEXEC) : find_keys_device();
+
+	if (fd < 0)
+		return false;
+	g_unix_fd_add(fd, G_IO_IN, on_input, app);
+	return true;
+}
+
+void platform_backlight_set(const char *path, bool on)
+{
+	FILE *f;
+
+	if (!path)
+		return;
+	f = fopen(path, "w");
+	if (!f)
+		return;
+	fputs(on ? "1\n" : "0\n", f);
+	fclose(f);
+}
+
+static gboolean on_signal(gpointer data)
+{
+	g_main_loop_quit(data);
+	return G_SOURCE_REMOVE;
+}
+
+void platform_run(void)
+{
+	GMainLoop *loop = g_main_loop_new(NULL, FALSE);
+
+	g_unix_signal_add(SIGINT, on_signal, loop);
+	g_unix_signal_add(SIGTERM, on_signal, loop);
+	g_main_loop_run(loop);
+	g_main_loop_unref(loop);
+}

+ 25 - 0
app/platform_linux.h

@@ -0,0 +1,25 @@
+/* What the real-hardware frontends share: key events and the backlight. */
+#ifndef RADIO_PLATFORM_LINUX_H
+#define RADIO_PLATFORM_LINUX_H
+
+#include <stdbool.h>
+
+#include "app.h"
+
+#define DEFAULT_KEYS_NAME	"radio-keys"
+#define DEFAULT_BACKLIGHT	"/sys/class/backlight/radio-backlight/brightness"
+
+/*
+ * Feed key presses from an evdev device into the app. path may be NULL to
+ * look for the input device named DEFAULT_KEYS_NAME. Returns false, leaving
+ * the UI display-only, if there is none.
+ */
+bool platform_keys_start(struct app *app, const char *path);
+
+/* Write to a sysfs brightness file; a NULL path does nothing. */
+void platform_backlight_set(const char *path, bool on);
+
+/* Run the GLib main loop until SIGINT or SIGTERM. */
+void platform_run(void);
+
+#endif /* RADIO_PLATFORM_LINUX_H */

+ 204 - 0
app/ui_render.c

@@ -0,0 +1,204 @@
+#include <math.h>
+#include <pango/pangocairo.h>
+#include <stdio.h>
+
+#include "app.h"
+
+/* Absolute sizes: these are panel pixels, not points */
+#define FONT_TITLE	"DejaVu Sans 11px"
+#define FONT_STATUS	"DejaVu Sans Mono 10px"
+#define FONT_SMALL	"DejaVu Sans 9px"
+#define FONT_LOG	"DejaVu Sans Mono 9px"
+
+#define TITLE_Y		0
+#define TITLE_LINES	3
+#define STATUS_Y	40
+#define ICON_SIZE	12
+#define BAR_Y		54
+#define OPTIONS_Y	60
+#define LINK_Y		71
+#define LOG_Y		85
+#define LOG_LINE_H	9
+
+static PangoLayout *new_layout(cairo_t *cr, const char *font)
+{
+	PangoLayout *l = pango_cairo_create_layout(cr);
+	PangoFontDescription *d = pango_font_description_from_string(font);
+	cairo_font_options_t *fo = cairo_font_options_create();
+
+	/* crisp glyphs that survive reduction to four gray levels */
+	cairo_font_options_set_antialias(fo, CAIRO_ANTIALIAS_GRAY);
+	cairo_font_options_set_hint_style(fo, CAIRO_HINT_STYLE_FULL);
+	cairo_font_options_set_hint_metrics(fo, CAIRO_HINT_METRICS_ON);
+	pango_cairo_context_set_font_options(pango_layout_get_context(l), fo);
+	cairo_font_options_destroy(fo);
+
+	pango_layout_set_font_description(l, d);
+	pango_font_description_free(d);
+	return l;
+}
+
+static void draw_text(cairo_t *cr, const char *font, int x, int y, int w,
+		      PangoAlignment align, const char *text)
+{
+	PangoLayout *l = new_layout(cr, font);
+
+	pango_layout_set_width(l, w * PANGO_SCALE);
+	pango_layout_set_alignment(l, align);
+	pango_layout_set_ellipsize(l, PANGO_ELLIPSIZE_END);
+	pango_layout_set_text(l, text, -1);
+	cairo_move_to(cr, x, y);
+	pango_cairo_show_layout(cr, l);
+	g_object_unref(l);
+}
+
+static void draw_title(cairo_t *cr, int w, const char *text)
+{
+	PangoLayout *l = new_layout(cr, FONT_TITLE);
+
+	pango_layout_set_width(l, w * PANGO_SCALE);
+	pango_layout_set_wrap(l, PANGO_WRAP_WORD_CHAR);
+	pango_layout_set_ellipsize(l, PANGO_ELLIPSIZE_END);
+	pango_layout_set_height(l, -TITLE_LINES);
+	pango_layout_set_text(l, text, -1);
+	cairo_move_to(cr, 1, TITLE_Y);
+	pango_cairo_show_layout(cr, l);
+	g_object_unref(l);
+}
+
+static void draw_icon(cairo_t *cr, enum play_state state, int x, int y)
+{
+	int s = ICON_SIZE;
+
+	switch (state) {
+	case PLAY_PLAYING:
+		cairo_move_to(cr, x + 2, y);
+		cairo_line_to(cr, x + s, y + s / 2.0);
+		cairo_line_to(cr, x + 2, y + s);
+		cairo_close_path(cr);
+		cairo_fill(cr);
+		break;
+	case PLAY_PAUSED:
+		cairo_rectangle(cr, x + 2, y, 3, s);
+		cairo_rectangle(cr, x + 7, y, 3, s);
+		cairo_fill(cr);
+		break;
+	case PLAY_STOPPED:
+		cairo_rectangle(cr, x + 1, y + 1, s - 2, s - 2);
+		cairo_fill(cr);
+		break;
+	default:
+		break;
+	}
+}
+
+static void format_time(char *buf, size_t size, unsigned int ms)
+{
+	unsigned int t = ms / 1000;
+
+	if (t >= 3600)
+		snprintf(buf, size, "%u:%02u:%02u", t / 3600, t / 60 % 60, t % 60);
+	else
+		snprintf(buf, size, "%u:%02u", t / 60, t % 60);
+}
+
+static void draw_status(cairo_t *cr, const struct radio_state *s, int w)
+{
+	char buf[64], a[16], b[16];
+	unsigned int elapsed;
+
+	draw_icon(cr, s->state, 2, STATUS_Y);
+	if (s->state == PLAY_STOPPED || s->song_pos < 0)
+		return;
+
+	snprintf(buf, sizeof(buf), "#%d/%u", s->song_pos + 1, s->queue_len);
+	draw_text(cr, FONT_STATUS, 20, STATUS_Y, 90, PANGO_ALIGN_LEFT, buf);
+
+	elapsed = radio_state_elapsed_ms(s);
+	format_time(a, sizeof(a), elapsed);
+	if (s->total_ms) {
+		format_time(b, sizeof(b), s->total_ms);
+		snprintf(buf, sizeof(buf), "%s/%s", a, b);
+	} else {
+		g_strlcpy(buf, a, sizeof(buf));
+	}
+	draw_text(cr, FONT_STATUS, 110, STATUS_Y, w - 112, PANGO_ALIGN_RIGHT, buf);
+
+	if (s->total_ms) {
+		int bar_w = w - 22;
+		int fill = (int)((guint64)elapsed * bar_w / s->total_ms);
+
+		cairo_set_line_width(cr, 1);
+		cairo_rectangle(cr, 20.5, BAR_Y + 0.5, bar_w - 1, 3);
+		cairo_stroke(cr);
+		cairo_rectangle(cr, 20, BAR_Y, fill, 4);
+		cairo_fill(cr);
+	}
+}
+
+static void draw_options(cairo_t *cr, const struct radio_state *s, int w)
+{
+	char buf[64];
+
+	if (!s->connected)
+		return;
+
+	snprintf(buf, sizeof(buf), "Włączone:%s%s",
+		 s->repeat ? " repeat" : "", s->random ? " random" : "");
+	draw_text(cr, FONT_SMALL, 1, OPTIONS_Y, 170, PANGO_ALIGN_LEFT, buf);
+
+	if (s->volume >= 0)
+		snprintf(buf, sizeof(buf), "Głośność %d%%", s->volume);
+	else
+		g_strlcpy(buf, "Głośność –", sizeof(buf));
+	draw_text(cr, FONT_SMALL, 150, OPTIONS_Y, w - 151, PANGO_ALIGN_RIGHT, buf);
+}
+
+static void draw_link(cairo_t *cr, const struct radio_state *s, int w)
+{
+	char buf[192];
+
+	if (s->connected)
+		return;
+
+	cairo_rectangle(cr, 0, LINK_Y, w, 12);
+	cairo_fill(cr);
+	cairo_set_source_rgb(cr, 1, 1, 1);
+	snprintf(buf, sizeof(buf), "Brak połączenia z %s", s->server);
+	draw_text(cr, FONT_SMALL, 2, LINK_Y, w - 4, PANGO_ALIGN_LEFT, buf);
+	cairo_set_source_rgb(cr, 0, 0, 0);
+}
+
+static void draw_log(cairo_t *cr, const struct radio_state *s, int w, int h)
+{
+	int i;
+
+	cairo_set_line_width(cr, 1);
+	cairo_move_to(cr, 0, LOG_Y - 1.5);
+	cairo_line_to(cr, w, LOG_Y - 1.5);
+	cairo_stroke(cr);
+
+	for (i = 0; i < LOG_ROWS; i++) {
+		int y = LOG_Y + i * LOG_LINE_H;
+
+		if (y + LOG_LINE_H > h)
+			break;
+		if (s->log[i][0])
+			draw_text(cr, FONT_LOG, 1, y - 1, w - 1, PANGO_ALIGN_LEFT, s->log[i]);
+	}
+}
+
+void ui_render(cairo_t *cr, const struct radio_state *s, int width, int height)
+{
+	cairo_set_antialias(cr, CAIRO_ANTIALIAS_NONE);
+	cairo_set_source_rgb(cr, 1, 1, 1);
+	cairo_paint(cr);
+	cairo_set_source_rgb(cr, 0, 0, 0);
+
+	if (s->title[0])
+		draw_title(cr, width - 2, s->title);
+	draw_status(cr, s, width);
+	draw_options(cr, s, width);
+	draw_link(cr, s, width);
+	draw_log(cr, s, width, height);
+}

+ 270 - 0
docs/REPORT.md

@@ -0,0 +1,270 @@
+# Radio front panel: Linux port report
+
+Status as of 2026-11-09. All code is in `linux/`. The LPC1114 firmware in the
+repository root is unchanged.
+
+**Update 2026-11-10:** the panel now runs on real hardware through i2c-dev
+(`radio-i2c --pattern geometry|gray` over a USB I²C bridge at 400 kHz): 240×160,
+2 bpp and pixel polarity confirmed. The control lines were remapped to the
+actual board (see `linux/README.md`), and the review in
+`linux/s1d13700-recommendations.md` was applied to the core and the DRM
+driver. The DRM driver, keys and device tree overlay are still untested on
+hardware.
+
+## 1. Summary
+
+The LPC1114 is replaced by software on the Linux board, with the S1D13700 LCD
+and the keys attached through two TCA9539 I²C expanders.
+
+**Works today, without hardware:** the full UI runs in a desktop window against
+the real MPD on `radio.lo`, with on-screen buttons and keyboard shortcuts. Every
+frame takes the real path down to individual TCA9539 bytes, and a simulator of
+the expander and LCD controller decodes those bytes to produce the picture.
+
+**Written and compiled, but never run:** the DRM kernel driver, the DRM frontend,
+the i2c-dev frontend against a real bus, and the device tree overlay. No part of
+this has touched real hardware, so everything about the hardware itself is still
+unconfirmed (section 7).
+
+## 2. Decisions and how they changed
+
+| Topic | Original plan | Now | Reason |
+|---|---|---|---|
+| Keys | 4×4 matrix, `gpio-matrix-keypad` | 13 keys sensed directly, `gpio-keys` | 13 keys + backlight = 14 of U2's 16 pins; no scanning |
+| UI toolkit | LVGL | Cairo + Pango on GLib | LVGL was not installed; Pango handles Polish text directly |
+| Development | USB adapter first | Window + simulator first | Most of the logic needs no hardware |
+| MPD | Local | Host is an option; default `radio.lo` in the window, `localhost` on the panel frontends | Remote development |
+| Kernel | DRM driver only | DRM driver **and** an i2c-dev frontend | The i2c-dev path needs no kernel changes, so it works on 4.19 |
+
+**The stock `gpio-pca953x` driver is used for U2 only.** U1 needs one continuous
+I²C write alternating both ports, which the GPIO API cannot express; going
+through `gpiod` would cost roughly 2.5-3× more bus time per LCD byte. An I²C
+address binds to one driver, which is another reason for a separate expander.
+
+## 3. Architecture
+
+    MPD (libmpdclient, idle events) ─┐
+    /dev/kmsg (optional) ────────────┤
+    keys (evdev or window buttons) ──┤
+                                     ▼
+                       app_core.c  +  ui_render.c (Cairo/Pango)
+                                     │  XRGB8888 frame + changed rectangle
+             ┌───────────────────────┼─────────────────────────┐
+             ▼                       ▼                         ▼
+        main_gtk.c              main_i2c.c                main_drm.c
+             │                       │                  dumb buffer + DIRTYFB
+             │                       │                         ▼
+             │                       │                  s1d13700_drm.c
+             ▼                       ▼                         ▼
+       ┌───────────────── s1d13700_core.c ──────────────────────┐
+       │ XRGB→2 bpp · byte diff against shadow · write planner  │
+       │ · TCA9539 stream encoder                               │
+       └────────────────────────────────────────────────────────┘
+             │                       │                         │
+       s1d13700_sim.c          /dev/i2c-N (I2C_RDWR)    i2c_master_send()
+
+The core has no OS dependency, so the code tested on the desktop is the code
+that drives the panel.
+
+## 4. Components
+
+### Panel core (`linux/driver/s1d13700_core.*`)
+
+- **Stream encoder.** One write message starts with command byte `0x02`, then
+  alternates P0 (data) and P1 (control). Each LCD cycle is
+  `data, WR=0, data, WR=1`. A0 changes get their own P0/P1 pair with WR# high,
+  because A0 needs setup time before the WR# edge and shares a port with it. A
+  cycle is never split across messages, so WR# is not left low when the bus is
+  released.
+- **Init.** Programs expander outputs before directions, holds reset 20 ms, then
+  configures the controller. Based on the AVR project's sequence, with changes
+  from the datasheet: `FX=7` and `HDOT=0` (required above 1 bpp), `CM=1` (required
+  in graphics mode; the AVR code had 0), grayscale value 1 (the LPC's 3 is
+  reserved). VRAM is cleared before the display is turned on.
+- **Planner.** Compares each frame with a shadow of VRAM at byte level, so even a
+  client that redraws everything costs only what changed. Rows with changes form
+  bands, and each band is written horizontally or vertically (`CSRDIR` down),
+  whichever is cheaper. Unchanged gaps up to 6 bytes (the cost of a seek) are
+  rewritten rather than skipped.
+- **Error handling.** A transport error makes the next update rewrite the frame.
+
+### Simulator (`linux/sim/`)
+
+Models the TCA9539 register pairs and the S1D13700 indirect interface, seeing only
+the I²C bytes. It counts faults: A0 changing with a WR# edge, parameters with no
+command or too many of them, unknown commands, bad registers, messages ending
+between P0 and P1, inconsistent SYSTEM SET, and writes during reset. The window
+frontend exits with an error code if any occurred.
+
+### Application (`linux/app/`)
+
+| File | Role |
+|---|---|
+| `app_core.c` | Render scheduling, changed-area detection, keys, backlight timeout, log batching |
+| `ui_render.c` | Screen layout: title, state icon, track, time, progress, options, volume, link warning, log |
+| `mpd_client.c` | Event-driven MPD connection; reconnects every 3 s |
+| `log_kmsg.c` | Follows the kernel log |
+| `main_gtk.c` | Window with simulated panel, buttons, shortcuts and a live traffic readout |
+| `main_i2c.c` | Real panel through i2c-dev, plus `--pattern geometry` / `gray` for bring-up |
+| `main_drm.c` | Real panel through the DRM driver |
+| `platform_linux.c` | evdev keys, sysfs backlight, signal handling |
+
+Behaviour kept from the firmware: 300 ms key lockout, 30 s backlight, the same
+command for each key, no title while stopped. New: event-driven updates instead
+of 2 s polling, proper Polish characters, a progress bar, volume display. Log
+redraws are batched to at most one per second.
+
+Key mapping in the window: `Z X C V B` prev/play/pause/stop/next, arrows
+(Up/Down = volume), `Enter` OK, `Esc` refresh, `M` menu, `L` list, `Space` pause.
+OK, Menu, List, Left and Right wake the backlight only, as in the firmware.
+
+### DRM driver (`linux/driver/s1d13700_drm.c`)
+
+Atomic KMS driver modelled on the in-tree `st7571-i2c`, built against 6.18. Plane
+updates convert damage into a pending frame; a worker sends it, merging anything
+that arrives meanwhile. Messages are capped at 1025 bytes (about 23 ms) so other
+devices on the bus get a turn, and the adapter's `max_write_len` is honoured.
+Offers XRGB8888 and fbdev emulation, with counters in debugfs. Size, depth and
+TC/R are module parameters.
+
+### Device tree (`linux/dts/radio-panel.dts`)
+
+Binds U1 to the driver, U2 to `gpio-pca953x`, and defines `radio-keys` and
+`radio-backlight`. Numeric constants are used so it works with
+`armbian-add-overlay`. Wiring tables are in `linux/README.md`.
+
+## 5. Bus cost
+
+| Update (240×160, 2 bpp, 400 kHz) | I²C bytes | Bus time | Source |
+|---|---|---|---|
+| One 8×13 digit | 157 | 3.6 ms | test suite |
+| Full frame | 38 462 (38 messages) | 866 ms | test suite |
+| Stopped screen from blank | 2 779 | 63 ms | window, real MPD |
+| Typical small update | 113-177 | 2.6-4.0 ms | window, fake MPD |
+
+These are calculated from the bytes sent, assuming an ideal 400 kHz bus. Real
+timing will be slower.
+
+## 6. Verification performed
+
+| Check | Result |
+|---|---|
+| Panel tests: init values, invalid configs, no-change = no traffic, direction choice, gap merging, 2000 random update rounds at 1/2/4 bpp and message sizes 7/61/1025, error recovery, pixel conversion | Pass, also under ASan and UBSan |
+| The simulator's fault detector fires on bad streams | Pass |
+| All frontends, the overlay and the module compile; module with `W=1` | No warnings shown |
+| Window buttons against a fake MPD: Next, Up, Down, Pause, Prev, Stop, Play, Esc, Menu | The seven MPD commands sent correctly; Menu sends none |
+| Real MPD on `radio.lo` (0.21.4), read-only | Connects and displays correctly; player state not changed |
+| MPD pushing a change | Triggers a refresh (fake server) |
+| Server lost, then back | Warning shown, reconnects automatically (fake server) |
+| `radio-i2c` on PIIX4, AMDGPU I²C and AUX buses | All refused, no traffic |
+
+The kernel module was built but **never loaded**. The window's keyboard shortcuts
+were not exercised automatically (no input injection tool here), and neither was
+real MPD with key presses, to avoid changing playback.
+
+## 7. Not verified
+
+These can only be settled with hardware.
+
+- **TCA9539 write behaviour.** The whole stream relies on writes toggling within
+  the register pair. The datasheet text I confirmed describes this for reads.
+  Everything else depends on it, so test it first.
+- **Panel geometry.** 240×160 is an assumption. The sources disagree: the LPC UI
+  assumes 240×168 but sets 160 lines, and the AVR's C/R=79 implies 320 px.
+- **TC/R and frame rate.** 162 is taken from the AVR's working 2 bpp setup.
+- **Pixel polarity and how the gray levels look.**
+- **Flicker.** The datasheet recommends display memory access during blanking,
+  which can't be synchronised over I²C. The existing firmware doesn't either.
+- **A0 timing margin.** The conservative extra cycle may be removable, saving
+  about a third of the seek cost.
+- **`radio-keys` device name.** Assumed from the node name; `--input` overrides it.
+- **DRM driver and frontend behaviour at runtime.** Also `/dev/kmsg` on the target.
+
+## 8. Kernel: 4.19.62-sunxi or upgrade
+
+| | Stay on 4.19 | Upgrade to current |
+|---|---|---|
+| Panel | `radio-i2c` | `radio-drm` + driver, or `radio-i2c` |
+| Kernel changes | Overlay only | Overlay + module |
+| Standard graphics tools | No | Yes (DRM, fbdev emulation) |
+
+The driver cannot build on 4.19: it depends on damage tracking, shmem and client
+helpers from much later kernels. There is no 4.19 tree here to measure the gap.
+
+**Recommendation:** bring up on 4.19 with `radio-i2c`, which gets a working panel
+with no kernel risk. Upgrade only if standard graphics tools turn out to be
+wanted, since the application does not need DRM.
+
+**Allwinner I²C:** the `i2c-mv64xxx` driver has no FIFO handling, so it takes
+about one interrupt per byte, up to 44 000 per second during a long update. Short
+updates make this brief, but a full frame lasts most of a second. Measure the CPU
+cost on the board.
+
+## 9. Remaining work
+
+**Phase 0: bring-up (needs an adapter or the SoC)**
+- [ ] Wire U1 and the LCD, confirm 3.3 V logic
+- [ ] Capture one write on a logic analyzer: pair toggling, WR#/A0 order
+- [ ] `--pattern geometry`: find the real size, fix defaults and the UI layout
+- [ ] `--pattern gray`: confirm polarity and levels; tune `--tcr`
+- [ ] Decide whether the A0 extra cycle can go
+
+**Phase 1: keys and backlight**
+- [ ] Rewire the keypad for direct sensing, 13 pull-ups (see section 11)
+- [ ] Set the real root `compatible`, I²C bus and INT pin in the overlay
+- [ ] Check with `evtest`: all 13 keys, no bus traffic while idle
+- [ ] Check the backlight through sysfs
+
+**Phase 2: application on the board**
+- [ ] Build on the SoC or cross-compile; install fonts (DejaVu)
+- [ ] Add a systemd unit with restart and `WatchdogSec` (the firmware had a watchdog; the app has no `sd_notify` yet)
+- [ ] Measure CPU load and real update times
+- [ ] Decide on volume control (section 11)
+- [ ] Tune font sizes and layout on the real panel
+
+**Phase 3: DRM (only if upgrading)**
+- [ ] Upgrade the kernel; build the module for the target
+- [ ] Test with `modetest` and `radio-drm`
+- [ ] Add R1/R2 formats and a blank/power-save path if useful
+- [ ] Keep fbcon off this panel: a blinking cursor means constant I²C traffic
+
+**Phase 4: cutover**
+- [ ] Remove the firmware, serial autologin and `utils/`
+- [ ] Update the top-level README
+
+**Possible later improvements**
+- Hardware log scrolling via the controller's split screen (about 10× less traffic per scroll; needs a private interface in the driver)
+- Optional XOR pulse circuit for WR#, doubling throughput
+- Features for the unassigned keys
+- Connect to MPD without blocking the UI: a dead host currently stalls it for up to 2 s per attempt
+
+## 10. Known limitations
+
+- MPD connection and DNS lookup block the main loop (up to 2 s per retry).
+- Only XRGB8888 is exposed by the driver; gray conversion is a plain threshold with no dithering.
+- The layout assumes 240×160; other sizes need its constants changed.
+- `SLEEP` power save is not used; blanking is display-off only.
+- The window's log pane shows only application messages unless `--kmsg` is given, and then shows the desktop's log rather than the radio's.
+
+## 11. Open questions
+
+1. **Is the keypad a physical matrix?** The firmware scans it as one. If the traces are wired that way, direct sensing needs rework; otherwise `gpio-matrix-keypad` remains an option with no code changes to the app.
+2. **Volume.** `radio.lo` reports `volume: n/a`, and the old scripts used `amixer set DAC` directly. If MPD has no working mixer, the Up/Down keys will only log an error. The fix is either an MPD mixer configuration or an ALSA path on the board.
+3. **Which SoC exactly?** The overlay's `compatible`, bus and INT pin are placeholders.
+4. **Are other devices on the chosen I²C bus?** A dedicated bus is preferable.
+
+## 12. Safety note for the development machine
+
+The development PC is an AMD BC-250. Its `I2C_HEADER1` and possibly its PIIX4
+SMBus ports reach the voltage regulators (ISL69247, ISL95712). Do not attach the
+expanders there, and do not run `i2cdetect` scans on buses 6-10.
+`radio-i2c` refuses those buses by name. Use a dedicated USB adapter such as an
+MCP2221A; this needs `CONFIG_HID_MCP2221` and `CONFIG_GPIOLIB` enabled.
+
+## 13. References
+
+- [S1D13700F01 hardware specification, Rev. 4.07](https://global-origin.epson.com/products_and_drivers/semicon/pdf/id003161.pdf)
+- [TCA9539 datasheet (SCPS202C)](https://www.ti.com/lit/ds/symlink/tca9539.pdf)
+- [BC-250 pinouts](https://elektricm.github.io/amd-bc250-docs/hardware/pinouts)
+- In-tree template: `drivers/gpu/drm/sitronix/st7571-i2c.c`
+- AVR graphics driver: `~/avr-svn/zdalny_termometr_odb/common/`

+ 96 - 0
tests/fake_mpd.py

@@ -0,0 +1,96 @@
+#!/usr/bin/env python3
+"""Minimal MPD server for exercising the UI's commands without touching a real
+player. Records every command received to the file given as the second
+argument. Usage: fake_mpd.py PORT LOGFILE [IDLE_EVENT_SECONDS]
+"""
+import socketserver
+import sys
+import threading
+
+log_path = sys.argv[2]
+idle_event_s = float(sys.argv[3]) if len(sys.argv) > 3 else None
+
+
+class Player:
+    state = "play"
+    volume = 50
+    song = 2
+
+
+player = Player()
+
+
+def record(line):
+    with open(log_path, "a") as f:
+        f.write(line + "\n")
+
+
+class Handler(socketserver.StreamRequestHandler):
+    def send(self, text):
+        self.wfile.write(text.encode())
+        self.wfile.flush()
+
+    def handle(self):
+        self.send("OK MPD 0.21.4\n")
+        announced = False
+        for raw in self.rfile:
+            line = raw.decode("utf8").strip()
+            cmd = line.split(" ")[0]
+            if cmd != "idle":
+                record(line)
+            if cmd == "idle":
+                # normally answered by the following noidle; optionally
+                # announce a change once per connection, as a real server would
+                if idle_event_s is not None and not announced:
+                    announced = True
+                    threading.Timer(
+                        idle_event_s, self.send, ["changed: player\nOK\n"]
+                    ).start()
+                continue
+            if cmd == "status":
+                self.send(
+                    f"volume: {player.volume}\nrepeat: 1\nrandom: 1\nsingle: 0\n"
+                    f"consume: 0\nplaylist: 7\nplaylistlength: 10\n"
+                    f"state: {player.state}\nsong: {player.song}\nsongid: 3\n"
+                    "time: 83:296\nelapsed: 83.100\nbitrate: 320\nduration: 296.000\n"
+                    "OK\n"
+                )
+            elif cmd == "currentsong":
+                self.send(
+                    "file: muzyka/test.flac\nArtist: Zażółć Gęślą\n"
+                    "Title: Jaźń – bardzo długi tytuł utworu, który na pewno "
+                    "nie zmieści się w jednej linii wyświetlacza\n"
+                    f"Pos: {player.song}\nId: 3\nOK\n"
+                )
+            elif cmd == "noidle":
+                self.send("OK\n")
+            elif cmd == "volume":
+                player.volume += int(line.split(" ")[1].strip('"'))
+                self.send("OK\n")
+            elif cmd == "stop":
+                player.state = "stop"
+                self.send("OK\n")
+            elif cmd == "play":
+                player.state = "play"
+                self.send("OK\n")
+            elif cmd == "pause":
+                player.state = "pause" if player.state == "play" else "play"
+                self.send("OK\n")
+            elif cmd == "next":
+                player.song += 1
+                self.send("OK\n")
+            elif cmd == "previous":
+                player.song -= 1
+                self.send("OK\n")
+            elif cmd == "close":
+                return
+            else:
+                self.send(f"ACK [5@0] {{{cmd}}} unknown command\n")
+
+
+class Server(socketserver.ThreadingTCPServer):
+    allow_reuse_address = True
+    daemon_threads = True
+
+
+Server(("127.0.0.1", int(sys.argv[1])), Handler).serve_forever()