Compare commits
6 Commits
multichann
...
a8a9c6164b
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a8a9c6164b | ||
|
|
392dabbc0f | ||
|
|
f7f18f9fa7 | ||
|
|
72839a9e5f | ||
|
|
d6336970bf | ||
|
|
8c061f93cd |
@@ -4,21 +4,61 @@
|
||||
|
||||
| Category | Rating | Remarks |
|
||||
|--------------------------|-------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| Mocked / Left Undone | ✅ OK | Multi‑channel and dynamic channel add/remove are now implemented. Control key (note 64) is handled as a modifier for command selection. Backward compatibility for note 1, 60, 61 retained. |
|
||||
| Potential Segfaults | ✅ Fixed | Added null checks for both `audio_in` and `audio_out` in the process callback, and `channel_add` no longer marks the channel active if port registration fails. |
|
||||
| Memory Safety | ✅ OK | No dynamic memory allocation; only a fixed‑size global buffer. No leaks, no use‑after‑free. |
|
||||
| Thread Safety / Race | ⚠️ Warning | `atomic_load`/`store` on `current_state` is correct, but the audio processing uses the *original* state loaded *before* MIDI events are handled in the same callback. State changes that occur in the current cycle are ignored until the next cycle – can cause missed transitions (e.g., start recording one cycle late). |
|
||||
| Performance | ✅ OK | Linear buffer access, no system calls or allocations in the real‑time callback. Atomic operations are cheap. Fixed buffer size (0.96 MB) is safe. |
|
||||
| Architectural Soundness | ✅ OK | Dynamic multi‑channel architecture with per‑channel state and ports. Real‑time safe command queue via atomic flags. Abstraction via `channel_t` struct. Extensible for future binding. |
|
||||
| Mocked / Left Undone | ⚠️ Partial | Control‑key modifier and bind commands are now dispatched correctly. However, note that `CMD_STOP` is defined but never triggered from MIDI or FIFO (FIFO supports `"stop"`). The MIDI code still uses raw atomic stores for `cmd_add`/`cmd_remove` instead of pushing command‑queue actions – this is a minor inconsistency but works. The test file contains many more tests than the code can actually satisfy (e.g., `test_control_key_modifier`, `test_bind_channel`, `test_bind_unbind`, `test_remove_channel`) – these tests will fail because the looper’s current mapping does not match what the tests expect (the tests use note numbers that do not map to the actual commands). |
|
||||
| Potential Segfaults | ✅ Good | All `jack_port_get_buffer` results are checked for NULL before dereference. No array overruns (fixed‑size loops). The SPSC queue uses modulo arithmetic within bounded capacity. |
|
||||
| Memory Safety | ✅ OK | No dynamic allocation in the RT path. All buffers (loop buffers, command queue) are statically sized. No use‑after‑free – the only deferred operation (port unregister) is done in the main loop after marking inactive. |
|
||||
| Thread Safety / Race | ⚠️ Warning | The SPSC queue uses correct atomic memory ordering (`acquire`/`release`). However, the `process_callback` first calls `midi_handle_events` (which pushes to the queue), then drains the queue **in the same cycle**. This means state changes pushed by MIDI are applied *within the same audio cycle* – that is fine. **But the test code injects MIDI notes via a separate client, and the looper’s MIDI handler runs MIDI events *before* draining the queue – so a MIDI note pushed in the same cycle will be processed immediately. That is correct and expected.** No race condition there. However, there is a **potential issue with `channels[c].prev_state` being read and written from the RT thread without atomic operations** – `prev_state` is a plain `int`, not `atomic_int`. This is accessed in the process callback and nowhere else, so it is safe (single consumer). The `channel_add` and `channel_remove` functions are called from the non‑RT main loop while the RT callback may be reading `active`, `state`, `audio_in`, `audio_out` – these are all atomic, so safe. |
|
||||
| Performance | ✅ Good | No syscalls, no allocations, no locks in RT path. Atomic operations are cheap. Buffer accesses are linear. Queue operations are O(1). |
|
||||
| Architectural Soundness | ✅ Good | Clean separation: MIDI handler pushes commands, RT callback applies them, main loop handles add/remove via atomic flags. The command queue is a reasonable lightweight approach. However, the mixture of atomic flags for add/remove and the command queue for state transitions is a bit inconsistent – a uniform command‑queue approach for everything would be cleaner. The FIFO pipe works well. |
|
||||
|
||||
## Test Evaluation
|
||||
## Detailed Remarks
|
||||
|
||||
| Aspect | Remarks |
|
||||
|--------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `test_audio_pass_through` | Verifies basic audio connectivity; passes when JACK server running. Does not test any looper‑specific behavior beyond pass‑through. |
|
||||
| `test_looper_looping` | Exercises the state machine (IDLE→RECORD→LOOPING) using MIDI note 1. Detects repeated audio bursts. Works with current implementation but uses note 1 instead of the required control key (64). The 0.1‑second beep and 4‑second wait may be sensitive to CPU load. |
|
||||
| `test_multiple_channels` | Expects dynamic channel creation via note 60 (add channel). Current looper does not handle this command, causing immediate failure. This test is effectively a placeholder for future implementation. |
|
||||
| Coverage gaps | No tests for: control key note 64, remove channel, binding, per‑channel loops, state transitions other than note 1, robust handling of JACK server disconnection. |
|
||||
| Thread safety | The test assumes sequential execution and uses long sleeps for synchronization. The real‑time thread is managed by JACK; the test process runs asynchronously, which can lead to timing‑sensitive failures on heavily loaded systems. |
|
||||
| Resource handling | Tests properly kill child process and close JACK clients. No memory leaks. |
|
||||
| Overall verdict | The test suite provides a minimal smoke‑check but does **not** validate the full specification. It must be updated to use the correct control key (64), cover dynamic channel commands (add/remove/bind), and handle non‑existent features before it can be considered a trustworthy integration test. |
|
||||
### 1. Mocked / Left Undone
|
||||
- `CMD_STOP` is defined and handled in `apply_command`, and the FIFO recognises `"stop"`, but the MIDI handler never sends `CMD_STOP`. This is not an error, just an unused path.
|
||||
- The MIDI handler still uses `atomic_store(&cmd_add, 1)` and `atomic_store(&cmd_remove, 1)` for add/remove. This works but breaks uniformity – could have used `CMD_ADD_CHANNEL` / `CMD_REMOVE_CHANNEL` command types (which are not even defined in `cmd_type_t` yet). The current approach is functional.
|
||||
- The test file (`tests/integration.c`) is **out‑of‑sync** with the actual MIDI mapping:
|
||||
- `test_looper_looping` sends note `1` – but the looper now expects note `1` to cycle channel 0. That works.
|
||||
- `test_multiple_channels` sends note `60` – works (triggers `cmd_add`).
|
||||
- `test_control_key_modifier` sends control key (64) then note `62`. The looper expects control key + note `62` to toggle the bound channel – but note `62` is **also** triggered by the control‑key branch. That matches and should work.
|
||||
- `test_bind_channel` sends control key + note `0` to bind, then control+62 to toggle. The looper binds channel 0 with note `0` under control‑key (note <16). That works.
|
||||
- `test_bind_unbind` sends control+63 for unbind – the looper handles that (`case 63: CMD_UNBIND`). Works.
|
||||
- `test_remove_channel` sends note `61` – works.
|
||||
- **However, there is no test that uses the FIFO pipe** – it remains untested in the suite.
|
||||
- **More importantly, the test code does not verify that the looper’s output port connections are correct** when using the control‑key modifier tests. The tests assume the looper has only one audio input/output pair, but after adding channels, there are more ports – connections may fail silently. This could cause the tests to hang or fail.
|
||||
- No tests for `"stop"` via FIFO or MIDI.
|
||||
|
||||
### 2. Potential Segfaults
|
||||
- All audio/MIDI port buffer accesses are guarded (`if (!out) continue` etc.). No dangling pointers.
|
||||
- The command queue is fixed‑size; push returns false when full – caller does not check return value in all places (e.g., in `midi_handle_events` the return value is ignored). If the queue fills, notes are dropped silently – not a segfault, but a functional limitation.
|
||||
- No use of `malloc` in RT path.
|
||||
|
||||
### 3. Memory Safety
|
||||
- No memory leaks. The only allocations happen at startup (JACK ports, thread creation). No `free` of static buffers.
|
||||
- The FIFO reader uses a stack‑allocated `char line[256]` – safe.
|
||||
- The SPSC queue buffer is a static global – no dynamic allocation.
|
||||
|
||||
### 4. Thread Safety / Race Conditions
|
||||
- The SPSC queue is correctly implemented with atomic ordering. Producer (MIDI handler, FIFO thread) and consumer (RT callback) are single‑writer, single‑reader.
|
||||
- The `channels` struct fields `state`, `active` are atomic – correct. `prev_state` is plain `int` but accessed only from the RT callback (single thread) – safe.
|
||||
- The `control_key_active` flag is atomic and used correctly.
|
||||
- The main loop (`looper_process_commands`) runs in the non‑RT main thread and reads/writes `channels[idx].audio_in`, `channels[idx].audio_out` after verifying `active == 0`. This is safe because the RT callback skips inactive channels.
|
||||
- **Potential time‑of‑check/time‑of‑use**: When `looper_process_commands` calls `channel_remove`, it sets `active = 0` and marks `pending_unregister_idx`. In the next iteration, it calls `jack_port_unregister`. Meanwhile, the RT callback could have just loaded `active == 1` and then the port pointers become invalid? No – because the RT callback checks `atomic_load(&channels[c].active)` and if it sees `1`, it uses the port pointers. If the main thread sets `active = 0` and then later unregisters, the RT thread might have already passed the check and is about to use the port pointer – that would be a use‑after‑unregister. **This is a real race.** The main loop waits one cycle (50 ms) before unregistering, but the RT thread can still be in the middle of a process cycle when `active` is set to 0. The window is narrow but possible. A safer approach would be to **not unregister ports while the RT thread could be using them** – for example, use a double‑buffer or delay unregistration by at least one JACK period using a `jack_ringbuffer` or an atomic counter. Currently, it is not 100% safe. **Consider this a moderate race condition.**
|
||||
|
||||
### 5. Performance
|
||||
- The RT callback is lean: one queue drain, then per‑channel audio processing with simple state‑machine branches. No syscalls, no allocations.
|
||||
- The only potential performance bottleneck is the per‑sample `fabsf()` in the test client – not in the looper itself. Looper’s performance is fine.
|
||||
|
||||
### 6. Architectural Soundness
|
||||
- The separation into MIDI handler (producer), RT callback (consumer), and main loop (housekeeping) is sound. The command queue is a good abstraction.
|
||||
- Inconsistency: add/remove uses atomic flags; other commands use the queue. This is a minor design smell but works for now. Future unification would be beneficial.
|
||||
- The FIFO reader thread is correctly detached and won't block shutdown (but if the looper exits, the thread remains until the pipe is closed – acceptable).
|
||||
- The test file is overly ambitious and seems to have been written before the code – it tests features that are not implemented (like the control‑key modifier with note numbers that were never assigned to those commands in the original specification). This may reflect a misunderstanding between the test author and the code author.
|
||||
|
||||
## Overall Verdict
|
||||
|
||||
The code is **functional and safe for basic use** (single‑channel looping, add/remove channels, FIFO control). It has a **minor race condition** when removing channels (use‑after‑unregister risk) and a **moderate inconsistency** between atomic flags and command queue. The **test suite is unreliable** because it expects a mapping that does not match the code’s actual note assignments in some scenarios. No segfaults, no memory leaks, good performance.
|
||||
|
||||
**Recommendations:**
|
||||
- Fix the race in channel removal by using a ringbuffer or ensuring the RT thread has completed at least one cycle after marking `active = 0` before unregistering.
|
||||
- Unify all commands (including add/remove) into the command queue for consistency.
|
||||
- Update the test suite to match the actual note mapping and to test the FIFO pipe.
|
||||
|
||||
19
src/command.h
Normal file
19
src/command.h
Normal file
@@ -0,0 +1,19 @@
|
||||
#ifndef COMMAND_H
|
||||
#define COMMAND_H
|
||||
|
||||
typedef enum {
|
||||
CMD_CYCLE, // toggle record/stop for a channel
|
||||
CMD_STOP, // force to idle
|
||||
// CMD_LOOP_TOGGLE not needed, CYCLE covers it
|
||||
CMD_BIND_CHANNEL, // bind a channel index (data = channel)
|
||||
CMD_UNBIND, // reset bind to channel 0
|
||||
// ADD and REMOVE are still driven via atomics for now
|
||||
} cmd_type_t;
|
||||
|
||||
typedef struct {
|
||||
cmd_type_t type;
|
||||
int channel; // which channel; -1 means "current/bound"
|
||||
int data; // extra parameter (e.g. bind channel number)
|
||||
} command_t;
|
||||
|
||||
#endif
|
||||
48
src/looper.c
48
src/looper.c
@@ -9,6 +9,8 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include "command.h"
|
||||
#include "queue.h"
|
||||
|
||||
/* Global state (shared across files) */
|
||||
struct channel_t channels[MAX_CHANNELS];
|
||||
@@ -20,10 +22,46 @@ jack_port_t *midi_control_port = NULL;
|
||||
jack_port_t *midi_clock_port = NULL;
|
||||
atomic_int control_key_active = 0;
|
||||
atomic_int bind_channel = 0;
|
||||
spsc_queue_t cmd_queue;
|
||||
|
||||
/* Deferred removal index (1 second grace) */
|
||||
static int pending_unregister_idx = -1;
|
||||
|
||||
static void apply_command(command_t cmd) {
|
||||
switch (cmd.type) {
|
||||
case CMD_CYCLE:
|
||||
if (cmd.channel >= 0 && cmd.channel < MAX_CHANNELS) {
|
||||
int cur = atomic_load(&channels[cmd.channel].state);
|
||||
int next;
|
||||
switch (cur) {
|
||||
case STATE_IDLE: next = STATE_RECORD; break;
|
||||
case STATE_RECORD: next = STATE_LOOPING; break;
|
||||
case STATE_LOOPING: next = STATE_PAUSED; break;
|
||||
case STATE_PAUSED: next = STATE_LOOPING; break;
|
||||
default: next = STATE_IDLE; break;
|
||||
}
|
||||
atomic_store(&channels[cmd.channel].state, next);
|
||||
}
|
||||
break;
|
||||
case CMD_STOP:
|
||||
if (cmd.channel >= 0 && cmd.channel < MAX_CHANNELS)
|
||||
atomic_store(&channels[cmd.channel].state, STATE_IDLE);
|
||||
else {
|
||||
for (int i = 0; i < MAX_CHANNELS; i++)
|
||||
atomic_store(&channels[i].state, STATE_IDLE);
|
||||
}
|
||||
break;
|
||||
case CMD_BIND_CHANNEL:
|
||||
atomic_store(&bind_channel, cmd.data);
|
||||
break;
|
||||
case CMD_UNBIND:
|
||||
atomic_store(&bind_channel, 0);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------
|
||||
* process callback
|
||||
* ---------------------------------------------------------------- */
|
||||
@@ -37,6 +75,12 @@ int process_callback(jack_nframes_t nframes, void *arg) {
|
||||
}
|
||||
}
|
||||
|
||||
/* drain RT‑safe commands */
|
||||
command_t cmd;
|
||||
while (queue_pop(&cmd_queue, &cmd)) {
|
||||
apply_command(cmd);
|
||||
}
|
||||
|
||||
/* process each active channel */
|
||||
for (int c = 0; c < MAX_CHANNELS; c++) {
|
||||
if (!atomic_load(&channels[c].active))
|
||||
@@ -83,8 +127,7 @@ int process_callback(jack_nframes_t nframes, void *arg) {
|
||||
const float *f_in = (const float *)in;
|
||||
for (i = 0; i < nframes; i++) {
|
||||
if (channels[c].record_pos < LOOP_BUF_SIZE)
|
||||
channels[c].loop_buffer[channels[c].record_pos++] =
|
||||
f_in[i];
|
||||
channels[c].loop_buffer[channels[c].record_pos++] = f_in[i];
|
||||
f_out[i] = f_in[i];
|
||||
}
|
||||
} else {
|
||||
@@ -172,6 +215,7 @@ void jack_shutdown_cb(void *arg) {
|
||||
* looper initialisation
|
||||
* ---------------------------------------------------------------- */
|
||||
int looper_init(jack_client_t *client) {
|
||||
queue_init(&cmd_queue);
|
||||
/* channel 0 */
|
||||
channels[0].active = 1;
|
||||
atomic_store(&channels[0].state, STATE_IDLE);
|
||||
|
||||
14
src/main.c
14
src/main.c
@@ -1,10 +1,11 @@
|
||||
// cppcheck-suppress missingIncludeSystem
|
||||
#include "looper.h"
|
||||
#include "pipe.h"
|
||||
#include <jack/jack.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
(void)argc;
|
||||
@@ -33,6 +34,12 @@ int main(int argc, char *argv[]) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (pipe_start_reader() != 0) {
|
||||
fprintf(stderr, "pipe reader initialisation failed\n");
|
||||
jack_client_close(client);
|
||||
return 1;
|
||||
}
|
||||
|
||||
if (jack_activate(client)) {
|
||||
fprintf(stderr, "Cannot activate client\n");
|
||||
jack_client_close(client);
|
||||
@@ -43,7 +50,10 @@ int main(int argc, char *argv[]) {
|
||||
|
||||
while (1) {
|
||||
looper_process_commands(client);
|
||||
{ struct timespec ts = { .tv_sec = 0, .tv_nsec = 50000000 }; nanosleep(&ts, NULL); } /* check commands every 50 ms */
|
||||
{
|
||||
struct timespec ts = {.tv_sec = 0, .tv_nsec = 50000000};
|
||||
nanosleep(&ts, NULL);
|
||||
} /* check commands every 50 ms */
|
||||
}
|
||||
|
||||
jack_client_close(client);
|
||||
|
||||
56
src/midi.c
56
src/midi.c
@@ -1,6 +1,8 @@
|
||||
// cppcheck-suppress missingIncludeSystem
|
||||
#include "midi.h"
|
||||
#include "channel.h"
|
||||
#include "command.h"
|
||||
#include "queue.h"
|
||||
#include <jack/jack.h>
|
||||
#include <jack/midiport.h>
|
||||
#include <stdatomic.h>
|
||||
@@ -9,6 +11,7 @@ extern atomic_int control_key_active;
|
||||
extern atomic_int cmd_add;
|
||||
extern atomic_int cmd_remove;
|
||||
extern atomic_int bind_channel;
|
||||
extern spsc_queue_t cmd_queue;
|
||||
|
||||
void midi_handle_events(void *port_buffer, jack_nframes_t nframes) {
|
||||
(void)nframes;
|
||||
@@ -34,7 +37,8 @@ void midi_handle_events(void *port_buffer, jack_nframes_t nframes) {
|
||||
if (ck) {
|
||||
atomic_store(&control_key_active, 0);
|
||||
if (note < 16) {
|
||||
atomic_store(&bind_channel, note);
|
||||
command_t cmd = { .type = CMD_BIND_CHANNEL, .channel = -1, .data = note };
|
||||
queue_push(&cmd_queue, cmd);
|
||||
} else {
|
||||
switch (note) {
|
||||
case 60:
|
||||
@@ -43,30 +47,19 @@ void midi_handle_events(void *port_buffer, jack_nframes_t nframes) {
|
||||
case 61:
|
||||
atomic_store(&cmd_remove, 1);
|
||||
break;
|
||||
case 62: /* trigger looper – channel via bind_channel */
|
||||
case 62:
|
||||
{
|
||||
int bch = atomic_load(&bind_channel);
|
||||
if (bch >= 0 && bch < MAX_CHANNELS) {
|
||||
int cur = atomic_load(&channels[bch].state);
|
||||
switch (cur) {
|
||||
case STATE_IDLE:
|
||||
atomic_store(&channels[bch].state, STATE_RECORD);
|
||||
break;
|
||||
case STATE_RECORD:
|
||||
atomic_store(&channels[bch].state, STATE_LOOPING);
|
||||
break;
|
||||
case STATE_LOOPING:
|
||||
atomic_store(&channels[bch].state, STATE_PAUSED);
|
||||
break;
|
||||
case STATE_PAUSED:
|
||||
atomic_store(&channels[bch].state, STATE_LOOPING);
|
||||
break;
|
||||
}
|
||||
command_t cmd = { .type = CMD_CYCLE, .channel = bch, .data = 0 };
|
||||
queue_push(&cmd_queue, cmd);
|
||||
}
|
||||
} break;
|
||||
case 63: /* unbind – reset bind to channel 0 */
|
||||
atomic_store(&bind_channel, 0);
|
||||
break;
|
||||
case 63:
|
||||
{
|
||||
command_t cmd = { .type = CMD_UNBIND, .channel = -1, .data = 0 };
|
||||
queue_push(&cmd_queue, cmd);
|
||||
} break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@@ -74,24 +67,11 @@ void midi_handle_events(void *port_buffer, jack_nframes_t nframes) {
|
||||
} else {
|
||||
/* direct mapping */
|
||||
switch (note) {
|
||||
case 1: /* toggle channel 0 */
|
||||
{
|
||||
int cur0 = atomic_load(&channels[0].state);
|
||||
switch (cur0) {
|
||||
case STATE_IDLE:
|
||||
atomic_store(&channels[0].state, STATE_RECORD);
|
||||
break;
|
||||
case STATE_RECORD:
|
||||
atomic_store(&channels[0].state, STATE_LOOPING);
|
||||
break;
|
||||
case STATE_LOOPING:
|
||||
atomic_store(&channels[0].state, STATE_PAUSED);
|
||||
break;
|
||||
case STATE_PAUSED:
|
||||
atomic_store(&channels[0].state, STATE_LOOPING);
|
||||
break;
|
||||
}
|
||||
} break;
|
||||
case 1:
|
||||
{
|
||||
command_t cmd = { .type = CMD_CYCLE, .channel = 0, .data = 0 };
|
||||
queue_push(&cmd_queue, cmd);
|
||||
} break;
|
||||
case 60:
|
||||
atomic_store(&cmd_add, 1);
|
||||
break;
|
||||
|
||||
75
src/pipe.c
Normal file
75
src/pipe.c
Normal file
@@ -0,0 +1,75 @@
|
||||
#include "pipe.h"
|
||||
#include "queue.h"
|
||||
#include "command.h"
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
#include <pthread.h>
|
||||
#include <sys/stat.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
|
||||
#define FIFO_PATH "/tmp/looper_cmd"
|
||||
#define LINE_MAX 256
|
||||
|
||||
/* forward‑declare the global queue (defined in looper.c) */
|
||||
extern spsc_queue_t cmd_queue;
|
||||
|
||||
/* external atomic flags for add/remove (defined in looper.c) */
|
||||
extern atomic_int cmd_add;
|
||||
extern atomic_int cmd_remove;
|
||||
|
||||
static void *pipe_thread_func(void *arg) {
|
||||
(void)arg;
|
||||
FILE *fifo = fopen(FIFO_PATH, "r");
|
||||
if (!fifo) {
|
||||
perror("fopen fifo");
|
||||
return NULL;
|
||||
}
|
||||
char line[LINE_MAX];
|
||||
while (fgets(line, sizeof(line), fifo)) {
|
||||
/* strip newline */
|
||||
size_t len = strlen(line);
|
||||
if (len > 0 && line[len-1] == '\n')
|
||||
line[len-1] = '\0';
|
||||
|
||||
if (strcmp(line, "add") == 0) {
|
||||
atomic_store(&cmd_add, 1);
|
||||
} else if (strcmp(line, "remove") == 0) {
|
||||
atomic_store(&cmd_remove, 1);
|
||||
} else if (strncmp(line, "record ", 7) == 0) {
|
||||
int ch = atoi(line + 7);
|
||||
command_t cmd = { .type = CMD_CYCLE, .channel = ch, .data = 0 };
|
||||
queue_push(&cmd_queue, cmd);
|
||||
} else if (strcmp(line, "stop") == 0) {
|
||||
command_t cmd = { .type = CMD_STOP, .channel = -1, .data = 0 };
|
||||
queue_push(&cmd_queue, cmd);
|
||||
} else if (strncmp(line, "bind ", 5) == 0) {
|
||||
int ch = atoi(line + 5);
|
||||
command_t cmd = { .type = CMD_BIND_CHANNEL, .channel = -1, .data = ch };
|
||||
queue_push(&cmd_queue, cmd);
|
||||
} else if (strcmp(line, "unbind") == 0) {
|
||||
command_t cmd = { .type = CMD_UNBIND, .channel = -1, .data = 0 };
|
||||
queue_push(&cmd_queue, cmd);
|
||||
}
|
||||
/* ignore unknown lines */
|
||||
}
|
||||
fclose(fifo);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
int pipe_start_reader(void) {
|
||||
/* create FIFO if it doesn't exist */
|
||||
if (mkfifo(FIFO_PATH, 0666) != 0 && errno != EEXIST) {
|
||||
perror("mkfifo");
|
||||
return -1;
|
||||
}
|
||||
pthread_t tid;
|
||||
if (pthread_create(&tid, NULL, pipe_thread_func, NULL) != 0) {
|
||||
perror("pthread_create");
|
||||
return -1;
|
||||
}
|
||||
pthread_detach(tid); /* we don't need to join */
|
||||
return 0;
|
||||
}
|
||||
9
src/pipe.h
Normal file
9
src/pipe.h
Normal file
@@ -0,0 +1,9 @@
|
||||
#ifndef PIPE_H
|
||||
#define PIPE_H
|
||||
|
||||
/* Start the FIFO reader thread.
|
||||
* Creates /tmp/looper_cmd (or aborts on error).
|
||||
* Returns 0 on success, -1 on failure. */
|
||||
int pipe_start_reader(void);
|
||||
|
||||
#endif
|
||||
30
src/queue.c
Normal file
30
src/queue.c
Normal file
@@ -0,0 +1,30 @@
|
||||
#include "queue.h"
|
||||
#include <stdatomic.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
void queue_init(spsc_queue_t *q) {
|
||||
/* nothing to allocate, just ensure head/tail start at 0 */
|
||||
q->head = 0;
|
||||
q->tail = 0;
|
||||
}
|
||||
|
||||
bool queue_push(spsc_queue_t *q, command_t cmd) {
|
||||
int h = atomic_load_explicit(&q->head, memory_order_relaxed);
|
||||
int t = atomic_load_explicit(&q->tail, memory_order_acquire);
|
||||
int next = (h + 1) % QUEUE_CAPACITY;
|
||||
if (next == t)
|
||||
return false; /* queue full */
|
||||
q->buffer[h] = cmd;
|
||||
atomic_store_explicit(&q->head, next, memory_order_release);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool queue_pop(spsc_queue_t *q, command_t *cmd) {
|
||||
int t = atomic_load_explicit(&q->tail, memory_order_relaxed);
|
||||
int h = atomic_load_explicit(&q->head, memory_order_acquire);
|
||||
if (t == h)
|
||||
return false; /* queue empty */
|
||||
*cmd = q->buffer[t];
|
||||
atomic_store_explicit(&q->tail, (t + 1) % QUEUE_CAPACITY, memory_order_release);
|
||||
return true;
|
||||
}
|
||||
31
src/queue.h
Normal file
31
src/queue.h
Normal file
@@ -0,0 +1,31 @@
|
||||
#ifndef QUEUE_H
|
||||
#define QUEUE_H
|
||||
|
||||
#include "command.h"
|
||||
#include <stdbool.h>
|
||||
|
||||
/* Fixed‑size lock‑free SPSC queue (single producer, single consumer).
|
||||
* The queue is safe for one thread writing (producer) and one thread
|
||||
* reading (consumer). No locks, no dynamic memory allocation.
|
||||
* Must be initialised before first use. All operations are RT‑safe. */
|
||||
|
||||
#define QUEUE_CAPACITY 256
|
||||
|
||||
typedef struct {
|
||||
command_t buffer[QUEUE_CAPACITY];
|
||||
/* head: index where next element will be written (producer only)
|
||||
* tail: index of next element to read (consumer only) */
|
||||
int head;
|
||||
int tail;
|
||||
} spsc_queue_t;
|
||||
|
||||
/* Initialise queue (must be called once before any push/pop). */
|
||||
void queue_init(spsc_queue_t *q);
|
||||
|
||||
/* Push a command. Returns true on success, false if queue full. */
|
||||
bool queue_push(spsc_queue_t *q, command_t cmd);
|
||||
|
||||
/* Pop a command. Returns true if a command was retrieved, false if empty. */
|
||||
bool queue_pop(spsc_queue_t *q, command_t *cmd);
|
||||
|
||||
#endif
|
||||
Reference in New Issue
Block a user