summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAndre Bezerra <amelco.herman@gmail.com>2026-11-10 12:52:41 -0300
committerAndre Bezerra <amelco.herman@gmail.com>2026-11-17 11:59:21 -0300
commit4a9b361b62a90b4f9cd2f7fb64471c5e3d3c8c4f (patch)
treebec936e6e40b1b5bc5df6130f145ca9de81f44c7
parentd995bad0ea725d779710cac221bf9558a1ab57b3 (diff)
add metronome
-rw-r--r--README.md37
-rwxr-xr-xbuild.sh2
-rw-r--r--main.c40
-rw-r--r--metronome.c347
-rw-r--r--metronome.h17
5 files changed, 435 insertions, 8 deletions
diff --git a/README.md b/README.md
index b92f421..9558cd2 100644
--- a/README.md
+++ b/README.md
@@ -11,8 +11,9 @@ into six stereo WAV stems using the HTDemucs six-source ONNX model:
- `<music_identifier>_piano.wav`
Separation is implemented in `main.c`; stem playback is implemented in
-`playback.c` and `playback.h`. The bundled ONNX Runtime 1.21 binary is the
-official Linux x86-64 CPU release.
+`playback.c` and `playback.h`, and the metronome in `metronome.c` and
+`metronome.h`. The bundled ONNX Runtime 1.21 binary is the official Linux
+x86-64 CPU release.
## Model setup
@@ -39,10 +40,12 @@ input/output contract.
./stemsep -i /path/to/song.wav -m song
./stemsep -i /path/to/song.mp3 -m song
./stemsep -m song -p bdv
+./stemsep --bpm 120 -t 4
```
-`-m` is required for both separation and playback. Options may be passed in
-either order. A music identifier may contain letters, digits, `_`, and `-`.
+`-m` is required for both separation and playback, and is not used by the
+metronome. Options may be passed in either order. A music identifier may contain
+letters, digits, `_`, and `-`.
`-i` accepts either format; the file type is detected from its contents, not
its name. `-wav <file>` is still accepted as a deprecated alias for `-i`.
@@ -81,6 +84,29 @@ to the playback position line (`00:01:23 / 00:04:46 (29%)`). mpv errors are
still shown, and `PIPEWIRE_DEBUG=0` is set for mpv unless it is already set, so
libpipewire's probing messages do not appear.
+## Metronome
+
+`--bpm <tempo>` runs `stemsep` as a standalone metronome instead of a separator
+or player. It cannot be combined with `-i`, `-m`, or `-p`:
+
+```sh
+./stemsep --bpm 120 # 120 BPM, 4 beats per bar
+./stemsep --bpm 96 -t 3 # 96 BPM, 3 beats per bar
+./stemsep --bpm 140 -t 2 # 140 BPM, 2 beats per bar
+```
+
+`-t` (or `--time-signature`) sets how many beats each bar contains; the default
+is `4`. Common values are `2` (binary), `3` (ternary), and `4` (quaternary),
+and any value from 2 to 16 is accepted. The strong beat of every bar is played
+one octave above the weak beats, at a slightly higher level, so the downbeat is
+audible at a glance. Tempo accepts a decimal number between 1 and 1000 beats per
+minute.
+
+One bar is synthesized at startup as a mono 44.1-kHz float32 WAV file in
+`$XDG_RUNTIME_DIR/stemsep-metronome.wav` (`/tmp` when that variable is unset)
+and handed to `mpv` with `--loop-file=inf`, so the bar repeats until you press
+`q`. Like `-p`, this mode requires `mpv` in `PATH`.
+
With missing parameters, a wrong flag, or incompatible modes, the program
prints an error followed by:
@@ -88,6 +114,7 @@ prints an error followed by:
Usage:
./stemsep -i <audio_file> -m <music_identifier>
./stemsep -m <music_identifier> -p <stem_letters>
+ ./stemsep --bpm <tempo> [-t <beats_per_bar>]
```
For identifier `song`, output is written to `./song_stems/` in the current
@@ -104,7 +131,7 @@ can leave an incomplete directory that must be removed manually.
containing `stemsep`, the ONNX Runtime shared library, the 258 MB model, and
the license notices. The payload is a zstd-compressed archive appended to a
small statically linked launcher. `mpv` is not part of the bundle: playback
-(`-p`) still requires `mpv` in `PATH`.
+(`-p`) and the metronome (`--bpm`) still require `mpv` in `PATH`.
```sh
./package.sh --portable
diff --git a/build.sh b/build.sh
index 5d65898..f98cb19 100755
--- a/build.sh
+++ b/build.sh
@@ -3,6 +3,6 @@ set -eu
cd -- "$(dirname -- "$0")"
gcc -std=c11 -O3 -DNDEBUG -Wall -Wextra -Wpedantic \
-Ithird_party/onnxruntime/include -Ithird_party/dr_mp3 \
- main.c audio.c audio_wav.c audio_mp3.c playback.c \
+ main.c audio.c audio_wav.c audio_mp3.c playback.c metronome.c \
-Lthird_party/onnxruntime/lib -Wl,-rpath,\$ORIGIN/third_party/onnxruntime/lib \
-Wl,--no-as-needed -lonnxruntime -lm -ldl -pthread -o stemsep
diff --git a/main.c b/main.c
index eacf9df..1591461 100644
--- a/main.c
+++ b/main.c
@@ -22,6 +22,7 @@
#include "audio.h"
#include "bytes.h"
+#include "metronome.h"
#include "playback.h"
#ifndef STEMSEP_TEST_FAKE_MODEL
@@ -1492,14 +1493,17 @@ static void print_usage(const char *program)
fprintf(stderr,
"Usage:\n"
" %s -i <audio_file> -m <music_identifier>\n"
- " %s -m <music_identifier> -p <stem_letters>\n",
- program, program);
+ " %s -m <music_identifier> -p <stem_letters>\n"
+ " %s --bpm <tempo> [-t <beats_per_bar>]\n",
+ program, program, program);
}
typedef struct {
const char *input_path;
const char *identifier;
const char *play_selection;
+ const char *bpm;
+ const char *time_signature;
} CommandLine;
static bool parse_command_line(int argc, char **argv, CommandLine *command,
@@ -1519,6 +1523,11 @@ static bool parse_command_line(int argc, char **argv, CommandLine *command,
destination = &command->identifier;
} else if (strcmp(flag, "-p") == 0) {
destination = &command->play_selection;
+ } else if (strcmp(flag, "--bpm") == 0) {
+ destination = &command->bpm;
+ } else if (strcmp(flag, "-t") == 0 ||
+ strcmp(flag, "--time-signature") == 0) {
+ destination = &command->time_signature;
} else {
return set_error(error, "unknown option '%s'", flag);
}
@@ -1530,6 +1539,17 @@ static bool parse_command_line(int argc, char **argv, CommandLine *command,
}
*destination = argv[++index];
}
+ if (command->bpm != NULL) {
+ if (command->input_path != NULL || command->identifier != NULL ||
+ command->play_selection != NULL) {
+ return set_error(error,
+ "option '--bpm' cannot be combined with '-i', '-m' or '-p'");
+ }
+ return true;
+ }
+ if (command->time_signature != NULL) {
+ return set_error(error, "option '-t' requires '--bpm'");
+ }
if (command->identifier == NULL) {
return set_error(error, "option '-m' is required");
}
@@ -1569,6 +1589,22 @@ int main(int argc, char **argv)
print_usage(argv[0]);
return EXIT_USAGE;
}
+ if (command.bpm != NULL) {
+ double bpm = 0.0;
+ unsigned beats = METRONOME_DEFAULT_BEATS;
+
+ if (!metronome_bpm_validate(command.bpm, &bpm, error.message,
+ sizeof(error.message)) ||
+ (command.time_signature != NULL &&
+ !metronome_beats_validate(command.time_signature, &beats,
+ error.message,
+ sizeof(error.message)))) {
+ fprintf(stderr, "error: %s\n", error.message);
+ print_usage(argv[0]);
+ return EXIT_USAGE;
+ }
+ return metronome_run(bpm, beats);
+ }
if (command.play_selection != NULL) {
return playback_run(command.identifier, command.play_selection);
}
diff --git a/metronome.c b/metronome.c
new file mode 100644
index 0000000..3982462
--- /dev/null
+++ b/metronome.c
@@ -0,0 +1,347 @@
+#define _POSIX_C_SOURCE 200809L
+
+#include "metronome.h"
+
+#include <errno.h>
+#include <fcntl.h>
+#include <math.h>
+#include <stdarg.h>
+#include <stdbool.h>
+#include <stddef.h>
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <unistd.h>
+
+#include "bytes.h"
+
+#define METRONOME_MIN_BPM 1.0
+#define METRONOME_MAX_BPM 1000.0
+#define METRONOME_MIN_BEATS 2U
+#define METRONOME_MAX_BEATS 16U
+
+#define METRONOME_SAMPLE_RATE 44100U
+#define METRONOME_HEADER_BYTES 56U
+#define METRONOME_WRITE_BLOCK_FRAMES 4096U
+
+#define METRONOME_ACCENT_HZ 1760.0
+#define METRONOME_BEAT_HZ 880.0
+#define METRONOME_ACCENT_AMPLITUDE 0.85
+#define METRONOME_BEAT_AMPLITUDE 0.55
+#define METRONOME_CLICK_SECONDS 0.05
+#define METRONOME_ATTACK_SECONDS 0.002
+#define METRONOME_DECAY 100.0
+
+#ifndef M_PI
+#define M_PI 3.14159265358979323846264338327950288
+#endif
+
+enum {
+ METRONOME_EXEC_FAILURE = 127
+};
+
+static bool write_message(char *message, size_t message_size,
+ const char *format, ...)
+{
+ va_list arguments;
+
+ if (message != NULL && message_size > 0U) {
+ va_start(arguments, format);
+ (void)vsnprintf(message, message_size, format, arguments);
+ va_end(arguments);
+ }
+ return false;
+}
+
+bool metronome_bpm_validate(const char *text, double *bpm, char *message,
+ size_t message_size)
+{
+ char *end = NULL;
+ double value;
+
+ if (text == NULL || text[0] == '\0') {
+ return write_message(message, message_size,
+ "option '--bpm' requires a tempo");
+ }
+ errno = 0;
+ value = strtod(text, &end);
+ if (end == text || *end != '\0' || errno == ERANGE || !isfinite(value)) {
+ return write_message(message, message_size,
+ "invalid tempo '%s': expected a number of beats per minute",
+ text);
+ }
+ if (value < METRONOME_MIN_BPM || value > METRONOME_MAX_BPM) {
+ return write_message(message, message_size,
+ "invalid tempo '%s': use a value between %g and %g",
+ text, METRONOME_MIN_BPM, METRONOME_MAX_BPM);
+ }
+ *bpm = value;
+ return true;
+}
+
+bool metronome_beats_validate(const char *text, unsigned *beats, char *message,
+ size_t message_size)
+{
+ char *end = NULL;
+ long value;
+
+ if (text == NULL || text[0] == '\0') {
+ return write_message(message, message_size,
+ "option '-t' requires a time signature");
+ }
+ errno = 0;
+ value = strtol(text, &end, 10);
+ if (end == text || *end != '\0' || errno == ERANGE) {
+ return write_message(message, message_size,
+ "invalid time signature '%s': expected a number of beats",
+ text);
+ }
+ if (value < (long)METRONOME_MIN_BEATS || value > (long)METRONOME_MAX_BEATS) {
+ return write_message(message, message_size,
+ "invalid time signature '%s': use between %u and %u beats per bar",
+ text, METRONOME_MIN_BEATS, METRONOME_MAX_BEATS);
+ }
+ *beats = (unsigned)value;
+ return true;
+}
+
+static char *metronome_file_path(void)
+{
+ static const char file_name[] = "stemsep-metronome.wav";
+ static const char fallback_directory[] = "/tmp";
+ const char *directory = getenv("XDG_RUNTIME_DIR");
+ size_t directory_length;
+ size_t path_length;
+ char *path;
+
+ if (directory == NULL || directory[0] == '\0') {
+ directory = fallback_directory;
+ }
+ directory_length = strlen(directory);
+ while (directory_length > 0U && directory[directory_length - 1U] == '/') {
+ --directory_length;
+ }
+ if (directory_length == 0U ||
+ directory_length > SIZE_MAX - sizeof(file_name) - 1U) {
+ errno = ENAMETOOLONG;
+ return NULL;
+ }
+ path_length = directory_length + sizeof(file_name) + 1U;
+ path = malloc(path_length);
+ if (path == NULL) {
+ return NULL;
+ }
+ memcpy(path, directory, directory_length);
+ path[directory_length] = '/';
+ memcpy(path + directory_length + 1U, file_name, sizeof(file_name));
+ return path;
+}
+
+static bool write_bytes(FILE *file, const void *data, size_t size)
+{
+ return fwrite(data, 1U, size, file) == size;
+}
+
+static bool write_header(FILE *file, uint32_t frames)
+{
+ uint8_t header[METRONOME_HEADER_BYTES];
+ uint32_t data_bytes = frames * (uint32_t)sizeof(float);
+
+ memset(header, 0, sizeof(header));
+ memcpy(header, "RIFF", 4U);
+ store_u32_le(header + 4U, data_bytes + METRONOME_HEADER_BYTES - 8U);
+ memcpy(header + 8U, "WAVE", 4U);
+ memcpy(header + 12U, "fmt ", 4U);
+ store_u32_le(header + 16U, 16U);
+ store_u16_le(header + 20U, 3U);
+ store_u16_le(header + 22U, 1U);
+ store_u32_le(header + 24U, METRONOME_SAMPLE_RATE);
+ store_u32_le(header + 28U, METRONOME_SAMPLE_RATE * (uint32_t)sizeof(float));
+ store_u16_le(header + 32U, (uint16_t)sizeof(float));
+ store_u16_le(header + 34U, 32U);
+ memcpy(header + 36U, "fact", 4U);
+ store_u32_le(header + 40U, 4U);
+ store_u32_le(header + 44U, frames);
+ memcpy(header + 48U, "data", 4U);
+ store_u32_le(header + 52U, data_bytes);
+ return write_bytes(file, header, sizeof(header));
+}
+
+static double click_sample(size_t index, double frequency, double amplitude)
+{
+ double seconds = (double)index / (double)METRONOME_SAMPLE_RATE;
+ double attack_frames = METRONOME_ATTACK_SECONDS * (double)METRONOME_SAMPLE_RATE;
+ double envelope = exp(-seconds * METRONOME_DECAY);
+ double value;
+
+ if ((double)index < attack_frames) {
+ envelope *= (double)index / attack_frames;
+ }
+ value = amplitude * envelope *
+ sin(2.0 * M_PI * frequency * seconds);
+ return value;
+}
+
+static bool write_click(FILE *file, uint64_t frames, double frequency,
+ double amplitude)
+{
+ uint8_t block[METRONOME_WRITE_BLOCK_FRAMES * sizeof(float)];
+ uint64_t offset = 0U;
+
+ while (offset < frames) {
+ uint64_t remaining = frames - offset;
+ size_t count = remaining > METRONOME_WRITE_BLOCK_FRAMES
+ ? METRONOME_WRITE_BLOCK_FRAMES
+ : (size_t)remaining;
+ size_t index;
+
+ for (index = 0U; index < count; ++index) {
+ float value = (float)click_sample((size_t)offset + index, frequency,
+ amplitude);
+ uint32_t encoded;
+
+ memcpy(&encoded, &value, sizeof(encoded));
+ store_u32_le(block + index * sizeof(float), encoded);
+ }
+ if (!write_bytes(file, block, count * sizeof(float))) {
+ return false;
+ }
+ offset += count;
+ }
+ return true;
+}
+
+static bool write_silence(FILE *file, uint64_t frames)
+{
+ static const uint8_t zeros[METRONOME_WRITE_BLOCK_FRAMES * sizeof(float)];
+
+ while (frames > 0U) {
+ size_t count = frames > METRONOME_WRITE_BLOCK_FRAMES
+ ? METRONOME_WRITE_BLOCK_FRAMES
+ : (size_t)frames;
+
+ if (!write_bytes(file, zeros, count * sizeof(float))) {
+ return false;
+ }
+ frames -= count;
+ }
+ return true;
+}
+
+static bool write_bar(FILE *file, uint64_t frames_per_beat, unsigned beats)
+{
+ uint64_t click_frames =
+ (uint64_t)llround(METRONOME_CLICK_SECONDS * (double)METRONOME_SAMPLE_RATE);
+ unsigned beat;
+
+ if (click_frames > frames_per_beat) {
+ click_frames = frames_per_beat;
+ }
+ for (beat = 0U; beat < beats; ++beat) {
+ bool accent = beat == 0U;
+
+ if (!write_click(file, click_frames,
+ accent ? METRONOME_ACCENT_HZ : METRONOME_BEAT_HZ,
+ accent ? METRONOME_ACCENT_AMPLITUDE
+ : METRONOME_BEAT_AMPLITUDE)) {
+ return false;
+ }
+ if (!write_silence(file, frames_per_beat - click_frames)) {
+ return false;
+ }
+ }
+ return true;
+}
+
+int metronome_run(double bpm, unsigned beats_per_bar)
+{
+ char *path;
+ char *arguments[6];
+ FILE *file;
+ int descriptor;
+ int flags = O_WRONLY | O_CREAT | O_TRUNC;
+ uint64_t frames_per_beat;
+ uint64_t bar_frames;
+ int saved_errno;
+
+ frames_per_beat = (uint64_t)llround(60.0 * (double)METRONOME_SAMPLE_RATE / bpm);
+ if (frames_per_beat == 0U) {
+ frames_per_beat = 1U;
+ }
+ if (frames_per_beat > UINT64_MAX / beats_per_bar) {
+ fprintf(stderr, "error: tempo %g is too slow for a single metronome bar\n",
+ bpm);
+ return 1;
+ }
+ bar_frames = frames_per_beat * beats_per_bar;
+ if (bar_frames > UINT32_MAX / sizeof(float)) {
+ fprintf(stderr, "error: tempo %g is too slow for a single metronome bar\n",
+ bpm);
+ return 1;
+ }
+
+ path = metronome_file_path();
+ if (path == NULL) {
+ fprintf(stderr, "error: cannot build the metronome file path: %s\n",
+ strerror(errno));
+ return 1;
+ }
+
+#ifdef O_CLOEXEC
+ flags |= O_CLOEXEC;
+#endif
+#ifdef O_NOFOLLOW
+ flags |= O_NOFOLLOW;
+#endif
+ descriptor = open(path, flags, 0600);
+ if (descriptor < 0) {
+ fprintf(stderr, "error: cannot create '%s': %s\n", path, strerror(errno));
+ free(path);
+ return 1;
+ }
+ file = fdopen(descriptor, "wb");
+ if (file == NULL) {
+ saved_errno = errno;
+ (void)close(descriptor);
+ fprintf(stderr, "error: cannot open '%s' for writing: %s\n", path,
+ strerror(saved_errno));
+ free(path);
+ return 1;
+ }
+
+ if (!write_header(file, (uint32_t)bar_frames) ||
+ !write_bar(file, frames_per_beat, beats_per_bar) ||
+ fflush(file) != 0) {
+ saved_errno = errno;
+ (void)fclose(file);
+ fprintf(stderr, "error: cannot write '%s': %s\n", path,
+ saved_errno != 0 ? strerror(saved_errno) : "I/O error");
+ free(path);
+ return 1;
+ }
+ if (fclose(file) != 0) {
+ saved_errno = errno;
+ fprintf(stderr, "error: cannot close '%s': %s\n", path,
+ strerror(saved_errno));
+ free(path);
+ return 1;
+ }
+
+ fprintf(stderr, "Metronome: %g BPM, %u beat%s per bar\n", bpm, beats_per_bar,
+ beats_per_bar == 1U ? "" : "s");
+
+ arguments[0] = (char *)"mpv";
+ arguments[1] = (char *)"--no-video";
+ arguments[2] = (char *)"--loop-file=inf";
+ arguments[3] = (char *)"--msg-level=cplayer=warn,ao=warn";
+ arguments[4] = path;
+ arguments[5] = NULL;
+
+ (void)setenv("PIPEWIRE_DEBUG", "0", 0);
+ execvp("mpv", arguments);
+ saved_errno = errno;
+ fprintf(stderr, "error: cannot execute mpv: %s\n", strerror(saved_errno));
+ free(path);
+ return METRONOME_EXEC_FAILURE;
+}
diff --git a/metronome.h b/metronome.h
new file mode 100644
index 0000000..1a81778
--- /dev/null
+++ b/metronome.h
@@ -0,0 +1,17 @@
+#ifndef STEMSEP_METRONOME_H
+#define STEMSEP_METRONOME_H
+
+#include <stdbool.h>
+#include <stddef.h>
+
+#define METRONOME_DEFAULT_BEATS 4U
+
+bool metronome_bpm_validate(const char *text, double *bpm, char *message,
+ size_t message_size);
+
+bool metronome_beats_validate(const char *text, unsigned *beats, char *message,
+ size_t message_size);
+
+int metronome_run(double bpm, unsigned beats_per_bar);
+
+#endif