diff options
| author | Andre Bezerra <amelco.herman@gmail.com> | 2026-08-19 09:17:21 -0300 |
|---|---|---|
| committer | Andre Bezerra <amelco.herman@gmail.com> | 2026-08-19 09:17:21 -0300 |
| commit | 5f69ee978ed63fc8fc6e5cb48e2c7b0a71a865bd (patch) | |
| tree | abb7ae2aee54c594da15878c6c0b092c18c85935 | |
| parent | 6888ed0381c78cfeba0b2d6b471226bc47a2b3b1 (diff) | |
add playback feature
| -rw-r--r-- | .gitignore | 3 | ||||
| -rw-r--r-- | README.md | 57 | ||||
| -rwxr-xr-x | build.sh | 2 | ||||
| -rw-r--r-- | main.c | 136 | ||||
| -rw-r--r-- | playback.c | 226 | ||||
| -rw-r--r-- | playback.h | 12 |
6 files changed, 379 insertions, 57 deletions
@@ -1,4 +1,5 @@ /stemsep /models/*.onnx /*_stems/ -tmp/
\ No newline at end of file +tmp/ +/**/*.wav @@ -3,15 +3,16 @@ `stemsep` is a Linux command-line program that separates an uncompressed WAV file into six stereo WAV stems using the HTDemucs six-source ONNX model: -- `drums.wav` -- `bass.wav` -- `other.wav` -- `vocals.wav` -- `guitar.wav` -- `piano.wav` +- `<music_identifier>_drums.wav` +- `<music_identifier>_bass.wav` +- `<music_identifier>_other.wav` +- `<music_identifier>_vocals.wav` +- `<music_identifier>_guitar.wav` +- `<music_identifier>_piano.wav` -All application code is in `main.c`. The bundled ONNX Runtime 1.21 binary is -the official Linux x86-64 CPU release. +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. ## Model setup @@ -35,20 +36,44 @@ input/output contract. ```sh ./build.sh -./stemsep -wav /path/to/song.wav +./stemsep -wav /path/to/song.wav -m song +./stemsep -m song -p bdv ``` -With no parameters, a wrong flag, or extra parameters, the program prints: +`-m` is required for both separation and playback. Options may be passed in +either order. A music identifier may contain letters, digits, `_`, and `-`. + +The `-p` value selects any combination of stems using lowercase letters: + +- `g`: guitar +- `b`: bass +- `d`: drums +- `p`: piano +- `v`: vocals +- `o`: other + +Letter order does not matter, and repeated letters are treated as one. For +example, `bdbd` and `db` both play bass and drums. `mpv` runs in the foreground +and remains attached to the terminal so its normal playback controls work. +`stemsep` assumes `mpv` is installed and available in `PATH`; requested files +are passed directly to mpv, which reports any missing-file errors. + +With missing parameters, a wrong flag, or incompatible modes, the program +prints an error followed by: ```text -Usage: ./stemsep -wav <wav_file> +Usage: + ./stemsep -wav <wav_file> -m <music_identifier> + ./stemsep -m <music_identifier> -p <stem_letters> ``` -For `song.wav`, output is written to `song_stems/` beside the input file. Each -stem is first written as a `.part` file and is published only after all six -files finish successfully; normal errors and interruptions remove incomplete -files. An existing output directory is never overwritten. A process crash or -power loss can leave an incomplete directory that must be removed manually. +For identifier `song`, output is written to `./song_stems/` in the current +directory, regardless of the input WAV's location. Each output filename is +prefixed with the identifier, such as `song_drums.wav`. Each stem is first +written as a `.part` file and is published only after all six files finish +successfully; normal errors and interruptions remove incomplete files. An +existing output directory is never overwritten. A process crash or power loss +can leave an incomplete directory that must be removed manually. ## WAV support @@ -1,4 +1,4 @@ #!/bin/sh set -eu cd -- "$(dirname -- "$0")" -gcc -std=c11 -O3 -DNDEBUG -Wall -Wextra -Wpedantic -Ithird_party/onnxruntime/include main.c -Lthird_party/onnxruntime/lib -Wl,-rpath,\$ORIGIN/third_party/onnxruntime/lib -Wl,--no-as-needed -lonnxruntime -lm -ldl -pthread -o stemsep +gcc -std=c11 -O3 -DNDEBUG -Wall -Wextra -Wpedantic -Ithird_party/onnxruntime/include main.c playback.c -Lthird_party/onnxruntime/lib -Wl,-rpath,\$ORIGIN/third_party/onnxruntime/lib -Wl,--no-as-needed -lonnxruntime -lm -ldl -pthread -o stemsep @@ -20,6 +20,8 @@ #include <sys/types.h> #include <unistd.h> +#include "playback.h" + #ifndef STEMSEP_TEST_FAKE_MODEL #include "onnxruntime_c_api.h" #endif @@ -196,7 +198,7 @@ static char *path_directory(const char *path, Error *error) length = (size_t)(slash - path); directory = malloc(length + 1U); if (directory == NULL) { - (void)set_error(error, "cannot allocate an output path: %s", strerror(errno)); + (void)set_error(error, "cannot allocate a directory path: %s", strerror(errno)); return NULL; } memcpy(directory, path, length); @@ -204,32 +206,27 @@ static char *path_directory(const char *path, Error *error) return directory; } -static char *input_stem_name(const char *path, Error *error) +static char *output_directory_name(const char *identifier, Error *error) { - const char *slash = strrchr(path, '/'); - const char *base = slash == NULL ? path : slash + 1; - size_t length = strlen(base); - char *stem; + static const char prefix[] = "./"; + static const char suffix[] = "_stems"; + size_t length = strlen(identifier); + size_t total; + char *directory; - if (length == 0U) { - (void)set_error(error, "input path does not name a file"); - return NULL; - } - if (length > 4U && strcasecmp(base + length - 4U, ".wav") == 0) { - length -= 4U; - } - if (length > SIZE_MAX - 7U) { - (void)set_error(error, "input filename is too long"); + if (length > SIZE_MAX - (sizeof(prefix) - 1U) - sizeof(suffix)) { + (void)set_error(error, "music identifier is too long"); return NULL; } - stem = malloc(length + sizeof("_stems")); - if (stem == NULL) { - (void)set_error(error, "cannot allocate an output name: %s", strerror(errno)); + total = sizeof(prefix) - 1U + length + sizeof(suffix); + directory = malloc(total); + if (directory == NULL) { + (void)set_error(error, "cannot allocate an output directory name: %s", + strerror(errno)); return NULL; } - memcpy(stem, base, length); - memcpy(stem + length, "_stems", sizeof("_stems")); - return stem; + (void)snprintf(directory, total, "./%s_stems", identifier); + return directory; } static char *read_executable_path(Error *error) @@ -1234,7 +1231,7 @@ static void wav_writer_cleanup(WavWriter *writer, bool remove_files) } static bool output_set_create(OutputSet *outputs, const char *directory, - Error *error) + const char *identifier, Error *error) { unsigned stem; @@ -1252,9 +1249,26 @@ static bool output_set_create(OutputSet *outputs, const char *directory, } outputs->directory_created = true; for (stem = 0U; stem < MODEL_STEMS; ++stem) { - if (!wav_writer_open(&outputs->writers[stem], directory, STEM_NAMES[stem], error)) { + size_t identifier_length = strlen(identifier); + size_t stem_length = strlen(STEM_NAMES[stem]); + char *prefixed_name; + + if (identifier_length > SIZE_MAX - stem_length - 2U) { + return set_error(error, "output filename is too long"); + } + prefixed_name = malloc(identifier_length + stem_length + 2U); + if (prefixed_name == NULL) { + return set_error(error, "cannot allocate an output filename: %s", + strerror(errno)); + } + (void)snprintf(prefixed_name, identifier_length + stem_length + 2U, + "%s_%s", identifier, STEM_NAMES[stem]); + if (!wav_writer_open(&outputs->writers[stem], directory, prefixed_name, + error)) { + free(prefixed_name); return false; } + free(prefixed_name); } return true; } @@ -1850,7 +1864,54 @@ static bool install_signal_handlers(Error *error) static void print_usage(const char *program) { - fprintf(stderr, "Usage: %s -wav <wav_file>\n", program); + fprintf(stderr, + "Usage:\n" + " %s -wav <wav_file> -m <music_identifier>\n" + " %s -m <music_identifier> -p <stem_letters>\n", + program, program); +} + +typedef struct { + const char *wav_path; + const char *identifier; + const char *play_selection; +} CommandLine; + +static bool parse_command_line(int argc, char **argv, CommandLine *command, + Error *error) +{ + int index; + + memset(command, 0, sizeof(*command)); + for (index = 1; index < argc; ++index) { + const char *flag = argv[index]; + const char **destination; + + if (strcmp(flag, "-wav") == 0) { + destination = &command->wav_path; + } else if (strcmp(flag, "-m") == 0) { + destination = &command->identifier; + } else if (strcmp(flag, "-p") == 0) { + destination = &command->play_selection; + } else { + return set_error(error, "unknown option '%s'", flag); + } + if (*destination != NULL) { + return set_error(error, "option '%s' was provided more than once", flag); + } + if (index + 1 >= argc || argv[index + 1][0] == '\0') { + return set_error(error, "option '%s' requires a value", flag); + } + *destination = argv[++index]; + } + if (command->identifier == NULL) { + return set_error(error, "option '-m' is required"); + } + if ((command->wav_path == NULL) == (command->play_selection == NULL)) { + return set_error(error, "provide exactly one of '-wav' or '-p'"); + } + return stem_identifier_validate(command->identifier, error->message, + sizeof(error->message)); } int main(int argc, char **argv) @@ -1860,9 +1921,8 @@ int main(int argc, char **argv) Resampler resampler; Model model; OutputSet outputs; + CommandLine command; char *model_path = NULL; - char *input_directory = NULL; - char *output_name = NULL; char *output_directory = NULL; float *input = NULL; float *accumulator = NULL; @@ -1876,16 +1936,22 @@ int main(int argc, char **argv) memset(&model, 0, sizeof(model)); memset(&outputs, 0, sizeof(outputs)); - if (argc != 3 || strcmp(argv[1], "-wav") != 0 || argv[2][0] == '\0') { + if (!parse_command_line(argc, argv, &command, &error)) { + if (error.message[0] != '\0') { + fprintf(stderr, "error: %s\n", error.message); + } print_usage(argv[0]); return EXIT_USAGE; } + if (command.play_selection != NULL) { + return playback_run(command.identifier, command.play_selection); + } if (!install_signal_handlers(&error)) { exit_code = EXIT_INTERNAL; goto cleanup; } - if (!regular_readable_file(argv[2], &error, "input WAV") || - !wav_reader_open(&reader, argv[2], &error)) { + if (!regular_readable_file(command.wav_path, &error, "input WAV") || + !wav_reader_open(&reader, command.wav_path, &error)) { exit_code = EXIT_INPUT; goto cleanup; } @@ -1914,13 +1980,7 @@ int main(int argc, char **argv) } #endif - input_directory = path_directory(argv[2], &error); - output_name = input_stem_name(argv[2], &error); - if (input_directory == NULL || output_name == NULL) { - exit_code = EXIT_INTERNAL; - goto cleanup; - } - output_directory = join_path(input_directory, output_name, &error); + output_directory = output_directory_name(command.identifier, &error); if (output_directory == NULL) { exit_code = EXIT_INTERNAL; goto cleanup; @@ -1953,7 +2013,7 @@ int main(int argc, char **argv) exit_code = EXIT_MODEL; goto cleanup; } - if (!output_set_create(&outputs, output_directory, &error)) { + if (!output_set_create(&outputs, output_directory, command.identifier, &error)) { exit_code = EXIT_OUTPUT; goto cleanup; } @@ -1979,8 +2039,6 @@ cleanup: free(accumulator); free(input); free(output_directory); - free(output_name); - free(input_directory); free(model_path); resampler_destroy(&resampler); wav_reader_close(&reader); diff --git a/playback.c b/playback.c new file mode 100644 index 0000000..39d6e49 --- /dev/null +++ b/playback.c @@ -0,0 +1,226 @@ +#define _POSIX_C_SOURCE 200809L + +#include "playback.h" + +#include <errno.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> + +enum { + PLAYBACK_STEM_COUNT = 6, + PLAYBACK_EXEC_FAILURE = 127 +}; + +typedef struct { + char letter; + const char *name; +} PlaybackStem; + +static const PlaybackStem PLAYBACK_STEMS[PLAYBACK_STEM_COUNT] = { + {'g', "guitar"}, + {'b', "bass"}, + {'d', "drums"}, + {'p', "piano"}, + {'v', "vocals"}, + {'o', "other"} +}; + +static void write_message(char *message, size_t message_size, + const char *format, ...) +{ + va_list arguments; + + if (message == NULL || message_size == 0U) { + return; + } + va_start(arguments, format); + (void)vsnprintf(message, message_size, format, arguments); + va_end(arguments); +} + +bool stem_identifier_validate(const char *identifier, char *message, + size_t message_size) +{ + const unsigned char *character; + + if (identifier == NULL || identifier[0] == '\0') { + write_message(message, message_size, "music identifier cannot be empty"); + return false; + } + for (character = (const unsigned char *)identifier; + *character != '\0'; ++character) { + bool valid = (*character >= (unsigned char)'a' && + *character <= (unsigned char)'z') || + (*character >= (unsigned char)'A' && + *character <= (unsigned char)'Z') || + (*character >= (unsigned char)'0' && + *character <= (unsigned char)'9') || + *character == (unsigned char)'_' || + *character == (unsigned char)'-'; + if (!valid) { + write_message(message, message_size, + "invalid music identifier '%s': use only letters, digits, '_' and '-'", + identifier); + return false; + } + } + return true; +} + +static int stem_index(char letter) +{ + int index; + + for (index = 0; index < PLAYBACK_STEM_COUNT; ++index) { + if (PLAYBACK_STEMS[index].letter == letter) { + return index; + } + } + return -1; +} + +static char *stem_path(const char *identifier, const char *stem_name) +{ + static const char path_prefix[] = "./"; + static const char directory_suffix[] = "_stems/"; + static const char extension[] = ".wav"; + size_t identifier_length = strlen(identifier); + size_t stem_length = strlen(stem_name); + size_t total; + char *path; + + if (identifier_length > SIZE_MAX - identifier_length || + identifier_length * 2U > SIZE_MAX - sizeof(directory_suffix) - + stem_length - sizeof(extension) - + sizeof(path_prefix)) { + errno = ENAMETOOLONG; + return NULL; + } + total = sizeof(path_prefix) - 1U + identifier_length * 2U + + sizeof(directory_suffix) - 1U + stem_length + + sizeof(extension) + 1U; + path = malloc(total); + if (path == NULL) { + return NULL; + } + (void)snprintf(path, total, "./%s_stems/%s_%s.wav", identifier, + identifier, stem_name); + return path; +} + +static char *external_file_argument(const char *path) +{ + static const char prefix[] = "--external-file="; + size_t path_length = strlen(path); + char *argument; + + if (path_length > SIZE_MAX - sizeof(prefix)) { + errno = ENAMETOOLONG; + return NULL; + } + argument = malloc(sizeof(prefix) + path_length); + if (argument == NULL) { + return NULL; + } + memcpy(argument, prefix, sizeof(prefix) - 1U); + memcpy(argument + sizeof(prefix) - 1U, path, path_length + 1U); + return argument; +} + +int playback_run(const char *identifier, const char *selection) +{ + bool selected[PLAYBACK_STEM_COUNT] = {false}; + char *paths[PLAYBACK_STEM_COUNT] = {NULL}; + char *external_arguments[PLAYBACK_STEM_COUNT - 1] = {NULL}; + char filter[128]; + char filter_argument[sizeof(filter) + sizeof("--lavfi-complex=")]; + char *arguments[4 + PLAYBACK_STEM_COUNT] = {NULL}; + size_t selected_count = 0U; + size_t argument_count = 0U; + size_t index; + int saved_errno; + + if (selection == NULL || selection[0] == '\0') { + fprintf(stderr, "error: -p requires at least one lowercase stem letter\n"); + return 2; + } + for (index = 0U; selection[index] != '\0'; ++index) { + int mapped_index = stem_index(selection[index]); + if (mapped_index < 0) { + fprintf(stderr, + "error: invalid -p selection '%s': use only lowercase letters g, b, d, p, v and o\n", + selection); + return 2; + } + selected[mapped_index] = true; + } + + for (index = 0U; index < PLAYBACK_STEM_COUNT; ++index) { + if (selected[index]) { + paths[selected_count] = stem_path(identifier, PLAYBACK_STEMS[index].name); + if (paths[selected_count] == NULL) { + fprintf(stderr, "error: cannot allocate playback path: %s\n", + strerror(errno)); + goto allocation_failure; + } + ++selected_count; + } + } + + arguments[argument_count++] = (char *)"mpv"; + arguments[argument_count++] = (char *)"--no-video"; + if (selected_count > 1U) { + size_t offset = 0U; + for (index = 0U; index < selected_count; ++index) { + int written = snprintf(filter + offset, sizeof(filter) - offset, + "[aid%zu]", index + 1U); + if (written < 0 || (size_t)written >= sizeof(filter) - offset) { + fprintf(stderr, "error: cannot construct mpv audio filter\n"); + goto allocation_failure; + } + offset += (size_t)written; + } + (void)snprintf(filter + offset, sizeof(filter) - offset, + "amix=inputs=%zu[ao]", selected_count); + (void)snprintf(filter_argument, sizeof(filter_argument), + "--lavfi-complex=%s", filter); + arguments[argument_count++] = filter_argument; + } + arguments[argument_count++] = paths[0]; + for (index = 1U; index < selected_count; ++index) { + external_arguments[index - 1U] = external_file_argument(paths[index]); + if (external_arguments[index - 1U] == NULL) { + fprintf(stderr, "error: cannot allocate mpv argument: %s\n", + strerror(errno)); + goto allocation_failure; + } + arguments[argument_count++] = external_arguments[index - 1U]; + } + arguments[argument_count] = NULL; + + execvp("mpv", arguments); + saved_errno = errno; + fprintf(stderr, "error: cannot execute mpv: %s\n", strerror(saved_errno)); + for (index = 0U; index < PLAYBACK_STEM_COUNT - 1U; ++index) { + free(external_arguments[index]); + } + for (index = 0U; index < PLAYBACK_STEM_COUNT; ++index) { + free(paths[index]); + } + return PLAYBACK_EXEC_FAILURE; + +allocation_failure: + for (index = 0U; index < PLAYBACK_STEM_COUNT - 1U; ++index) { + free(external_arguments[index]); + } + for (index = 0U; index < PLAYBACK_STEM_COUNT; ++index) { + free(paths[index]); + } + return 1; +} diff --git a/playback.h b/playback.h new file mode 100644 index 0000000..58a2017 --- /dev/null +++ b/playback.h @@ -0,0 +1,12 @@ +#ifndef STEMSEP_PLAYBACK_H +#define STEMSEP_PLAYBACK_H + +#include <stdbool.h> +#include <stddef.h> + +bool stem_identifier_validate(const char *identifier, char *message, + size_t message_size); + +int playback_run(const char *identifier, const char *selection); + +#endif |
