1
0
Fork 0
forked from hanez/xtc

Phase 7: Add MIDI clips, instrument and piano roll

This commit is contained in:
Johannes Findeisen 2026-10-27 00:53:41 +01:00
commit cacc086805
38 changed files with 1373 additions and 74 deletions

View file

@ -5,15 +5,18 @@
#ifdef XTC_HAVE_JACK
#include <jack/jack.h>
#include <jack/midiport.h>
#include <errno.h>
struct xtc_backend {
jack_client_t *client;
jack_port_t *input, *output;
jack_port_t *input, *output, *midi_input;
xtc_realtime *engine;
xtc_audio_plan *audio;
xtc_midi_plan *midi;
unsigned int panic_requested, panic_seen, midi_dropped;
xtc_recorder *recorder; /* Borrowed, installed while callbacks quiescent. */
float *timeline;
float *timeline, *instrument;
size_t max_frames;
uint64_t sample_position;
unsigned int expected_rate;
@ -22,12 +25,46 @@ struct xtc_backend {
int ready, running; /* Control thread only. */
};
static xtc_result render_midi(xtc_backend *backend, uint64_t position, jack_nframes_t frames)
{
xtc_midi_event events[XTC_MIDI_MAX_EVENTS];
size_t count = 0;
uint32_t i, total;
unsigned int requested = __atomic_load_n(&backend->panic_requested, __ATOMIC_ACQUIRE);
void *buffer;
if (!backend->midi) return XTC_OK;
if (requested != backend->panic_seen) {
xtc_midi_plan_panic(backend->midi, position); backend->panic_seen = requested;
}
buffer = jack_port_get_buffer(backend->midi_input, frames);
total = buffer ? jack_midi_get_event_count(buffer) : 0;
if (!buffer || total > XTC_MIDI_MAX_EVENTS) {
(void)__atomic_fetch_add(&backend->midi_dropped, total ? total : 1U, __ATOMIC_RELAXED);
xtc_midi_plan_panic(backend->midi, position);
} else for (i = 0; i < total; ++i) {
jack_midi_event_t raw;
xtc_result result;
if (jack_midi_event_get(&raw, buffer, i) != 0 || raw.time >= frames) {
(void)__atomic_fetch_add(&backend->midi_dropped, 1U, __ATOMIC_RELAXED);
xtc_midi_plan_panic(backend->midi, position); count = 0; break;
}
result = xtc_midi_decode(raw.buffer, raw.size, (unsigned int)raw.time, events + count);
if (result == XTC_ERR_UNSUPPORTED) continue;
if (result != XTC_OK || (count && events[count].offset < events[count - 1].offset)) {
(void)__atomic_fetch_add(&backend->midi_dropped, 1U, __ATOMIC_RELAXED);
xtc_midi_plan_panic(backend->midi, position); count = 0; break;
}
++count;
}
return xtc_midi_plan_render(backend->midi, position, events, count, backend->instrument, (size_t)frames);
}
static int process(jack_nframes_t frames, void *context)
{
xtc_backend *backend = context;
float *output = jack_port_get_buffer(backend->output, frames);
xtc_result result = XTC_OK;
if (output == NULL) {
(void)__atomic_fetch_add(&backend->panic_requested, 1U, __ATOMIC_RELEASE);
if (backend->recorder) xtc_recorder_push(backend->recorder, NULL, 1U);
__atomic_store_n(&backend->process_result, (unsigned int)XTC_ERR_IO, __ATOMIC_RELAXED);
return 0;
@ -43,9 +80,11 @@ static int process(jack_nframes_t frames, void *context)
if (backend->recorder) xtc_recorder_push(backend->recorder, input, (size_t)frames);
if (backend->audio)
result = xtc_audio_plan_render(backend->audio, position, backend->timeline, (size_t)frames);
if (result == XTC_OK) result = render_midi(backend, position, frames);
if (result == XTC_OK)
result = xtc_realtime_process_audio(backend->engine, input,
backend->audio ? backend->timeline : NULL, output, (size_t)frames);
result = xtc_realtime_process_sources(backend->engine, input,
backend->audio ? backend->timeline : NULL,
backend->midi ? backend->instrument : NULL, output, (size_t)frames);
}
if (result == XTC_OK) {
uint64_t position = __atomic_load_n(&backend->sample_position, __ATOMIC_RELAXED);
@ -53,6 +92,7 @@ static int process(jack_nframes_t frames, void *context)
else __atomic_store_n(&backend->sample_position, position + frames, __ATOMIC_RELAXED);
}
if (result != XTC_OK) {
(void)__atomic_fetch_add(&backend->panic_requested, 1U, __ATOMIC_RELEASE);
if (backend->recorder) xtc_recorder_push(backend->recorder, NULL, 1U);
memset(output, 0, (size_t)frames * sizeof(*output));
}
@ -64,6 +104,13 @@ static void shutdown_callback(void *context)
xtc_backend *backend = context;
__atomic_store_n(&backend->lost, 1U, __ATOMIC_RELEASE);
}
static void port_connection(jack_port_id_t source, jack_port_id_t destination, int connected, void *context)
{
xtc_backend *backend = context;
if (!connected && (jack_port_by_id(backend->client, source) == backend->midi_input ||
jack_port_by_id(backend->client, destination) == backend->midi_input))
(void)__atomic_fetch_add(&backend->panic_requested, 1U, __ATOMIC_RELEASE);
}
static int rate_callback(jack_nframes_t rate, void *context)
{
xtc_backend *backend = context;
@ -82,6 +129,7 @@ static int xrun_callback(void *context)
{
xtc_backend *backend = context;
(void)__atomic_fetch_add(&backend->xruns, 1U, __ATOMIC_RELAXED);
(void)__atomic_fetch_add(&backend->panic_requested, 1U, __ATOMIC_RELEASE);
return 0;
}
@ -101,10 +149,13 @@ xtc_result xtc_backend_open(const xtc_backend_config *config, xtc_backend **out_
backend = calloc(1U, sizeof(*backend));
if (backend == NULL) return XTC_ERR_OUT_OF_MEMORY;
backend->timeline = calloc(config->max_frames, sizeof(float));
if (!backend->timeline) { free(backend); return XTC_ERR_OUT_OF_MEMORY; }
backend->instrument = calloc(config->max_frames, sizeof(float));
if (!backend->timeline || !backend->instrument) {
free(backend->timeline); free(backend->instrument); free(backend); return XTC_ERR_OUT_OF_MEMORY;
}
backend->max_frames = config->max_frames;
backend->client = jack_client_open(config->client_name, JackNoStartServer, &status);
if (backend->client == NULL) { free(backend->timeline); free(backend); return XTC_ERR_IO; }
if (backend->client == NULL) { free(backend->instrument); free(backend->timeline); free(backend); return XTC_ERR_IO; }
backend->expected_rate = (unsigned int)jack_get_sample_rate(backend->client);
backend->rate = backend->expected_rate;
backend->frames = (unsigned int)jack_get_buffer_size(backend->client);
@ -113,8 +164,10 @@ xtc_result xtc_backend_open(const xtc_backend_config *config, xtc_backend **out_
if (result != XTC_OK) goto fail;
backend->input = jack_port_register(backend->client, "input", JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0U);
backend->output = jack_port_register(backend->client, "output", JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0U);
if (backend->input == NULL || backend->output == NULL) { result = XTC_ERR_IO; goto fail; }
if (jack_set_process_callback(backend->client, process, backend) != 0 ||
backend->midi_input = jack_port_register(backend->client, "midi_in", JACK_DEFAULT_MIDI_TYPE, JackPortIsInput, 0U);
if (backend->input == NULL || backend->output == NULL || backend->midi_input == NULL) { result = XTC_ERR_IO; goto fail; }
if (jack_set_port_connect_callback(backend->client, port_connection, backend) != 0 ||
jack_set_process_callback(backend->client, process, backend) != 0 ||
jack_set_sample_rate_callback(backend->client, rate_callback, backend) != 0 ||
jack_set_buffer_size_callback(backend->client, buffer_callback, backend) != 0 ||
jack_set_xrun_callback(backend->client, xrun_callback, backend) != 0) {
@ -134,6 +187,8 @@ fail:
}
xtc_realtime_destroy(backend->engine);
xtc_audio_plan_destroy(backend->audio);
xtc_midi_plan_destroy(backend->midi);
free(backend->instrument);
free(backend->timeline);
free(backend);
return result;
@ -146,6 +201,8 @@ xtc_result xtc_backend_close(xtc_backend *backend)
if (jack_client_close(backend->client) != 0) return XTC_ERR_IO;
xtc_realtime_destroy(backend->engine);
xtc_audio_plan_destroy(backend->audio);
xtc_midi_plan_destroy(backend->midi);
free(backend->instrument);
free(backend->timeline);
free(backend);
return XTC_OK;
@ -157,6 +214,8 @@ xtc_result xtc_backend_start(xtc_backend *backend)
if (__atomic_load_n(&backend->lost, __ATOMIC_ACQUIRE) ||
__atomic_load_n(&backend->rate_changed, __ATOMIC_ACQUIRE)) return XTC_ERR_INVALID_STATE;
if (backend->running) return XTC_ERR_INVALID_STATE;
xtc_midi_plan_reset(backend->midi);
backend->panic_seen = __atomic_load_n(&backend->panic_requested, __ATOMIC_ACQUIRE);
if (jack_activate(backend->client) != 0) return XTC_ERR_IO;
backend->running = 1;
return XTC_OK;
@ -165,9 +224,10 @@ xtc_result xtc_backend_stop(xtc_backend *backend)
{
if (backend == NULL) return XTC_ERR_INVALID_ARGUMENT;
if (!backend->ready) return XTC_ERR_INVALID_STATE;
if (!backend->running) return XTC_OK;
if (!backend->running) { xtc_midi_plan_reset(backend->midi); return XTC_OK; }
if (jack_deactivate(backend->client) != 0) return XTC_ERR_IO;
backend->running = 0;
xtc_midi_plan_reset(backend->midi);
xtc_realtime_collect(backend->engine);
return XTC_OK;
}
@ -177,6 +237,7 @@ xtc_result xtc_backend_seek(xtc_backend *backend, uint64_t sample)
if (!backend->ready || backend->running ||
__atomic_load_n(&backend->lost, __ATOMIC_ACQUIRE) ||
__atomic_load_n(&backend->rate_changed, __ATOMIC_ACQUIRE)) return XTC_ERR_INVALID_STATE;
xtc_midi_plan_reset(backend->midi);
__atomic_store_n(&backend->sample_position, sample, __ATOMIC_RELAXED);
return XTC_OK;
}
@ -204,13 +265,16 @@ xtc_result xtc_backend_submit(xtc_backend *backend, const xtc_graph *graph)
xtc_result xtc_backend_prepare_project(xtc_backend *backend, const xtc_project *project)
{
xtc_audio_plan *candidate = NULL;
xtc_midi_plan *midi = NULL;
xtc_result result;
if (!backend || !project) return XTC_ERR_INVALID_ARGUMENT;
if (!backend->ready || backend->running) return XTC_ERR_INVALID_STATE;
result = xtc_audio_plan_create(project, backend->expected_rate, &candidate);
if (result == XTC_OK) result = xtc_midi_plan_create(project, backend->expected_rate, &midi);
if (result == XTC_OK) result = xtc_backend_submit(backend, xtc_project_graph(project));
if (result != XTC_OK) { xtc_audio_plan_destroy(candidate); return result; }
if (result != XTC_OK) { xtc_audio_plan_destroy(candidate); xtc_midi_plan_destroy(midi); return result; }
xtc_audio_plan_destroy(backend->audio); backend->audio = candidate;
xtc_midi_plan_destroy(backend->midi); backend->midi = midi;
return XTC_OK;
}
const char *xtc_backend_asset_issue(const xtc_backend *backend)
@ -228,6 +292,20 @@ xtc_result xtc_backend_set_recorder(xtc_backend *backend, xtc_recorder *recorder
backend->recorder = recorder;
return XTC_OK;
}
xtc_result xtc_backend_panic(xtc_backend *backend)
{
if (!backend) return XTC_ERR_INVALID_ARGUMENT;
if (!backend->ready) return XTC_ERR_INVALID_STATE;
(void)__atomic_fetch_add(&backend->panic_requested, 1U, __ATOMIC_RELEASE);
if (!backend->running) xtc_midi_plan_reset(backend->midi);
return XTC_OK;
}
xtc_result xtc_backend_midi_port_name(const xtc_backend *backend, const char **out)
{
if (!backend || !out) return XTC_ERR_INVALID_ARGUMENT;
if (!backend->ready) return XTC_ERR_INVALID_STATE;
*out = jack_port_name(backend->midi_input); return XTC_OK;
}
void xtc_backend_collect(xtc_backend *backend)
{ if (backend != NULL) xtc_realtime_collect(backend->engine); }
xtc_result xtc_backend_get_status(const xtc_backend *backend, xtc_backend_status *out_status)
@ -236,6 +314,7 @@ xtc_result xtc_backend_get_status(const xtc_backend *backend, xtc_backend_status
if (backend == NULL || out_status == NULL) return XTC_ERR_INVALID_ARGUMENT;
if (!backend->ready) return XTC_ERR_INVALID_STATE;
(void)xtc_realtime_get_status(backend->engine, &engine_status);
out_status->midi_dropped = __atomic_load_n(&backend->midi_dropped, __ATOMIC_RELAXED);
out_status->asset_issues = (unsigned int)xtc_audio_plan_issues(backend->audio, NULL);
out_status->sample_rate = __atomic_load_n(&backend->rate, __ATOMIC_RELAXED);
out_status->buffer_frames = __atomic_load_n(&backend->frames, __ATOMIC_RELAXED);
@ -297,6 +376,10 @@ xtc_result xtc_backend_disconnect(xtc_backend *backend, xtc_port_direction direc
{ return route(backend, direction, remote, 1); }
#else
xtc_result xtc_backend_panic(xtc_backend *backend)
{ (void)backend; return XTC_ERR_UNSUPPORTED; }
xtc_result xtc_backend_midi_port_name(const xtc_backend *backend, const char **out)
{ (void)backend; (void)out; return XTC_ERR_UNSUPPORTED; }
xtc_result xtc_backend_prepare_project(xtc_backend *backend, const xtc_project *project)
{ (void)backend; (void)project; return XTC_ERR_UNSUPPORTED; }
const char *xtc_backend_asset_issue(const xtc_backend *backend)

View file

@ -109,7 +109,7 @@ xtc_result xtc_plan_meter_peak(const xtc_plan *plan, size_t node_id, float *out_
return XTC_OK;
}
xtc_result xtc_plan_process_audio(xtc_plan *plan, const float *input, const float *timeline, float *output,
xtc_result xtc_plan_process_sources(xtc_plan *plan, const float *input, const float *timeline, const float *instrument, float *output,
size_t frame_count)
{
size_t index, frame, edge;
@ -126,7 +126,9 @@ xtc_result xtc_plan_process_audio(xtc_plan *plan, const float *input, const floa
double phase = plan->phases[node];
for (frame = 0U; frame < frame_count; ++frame) {
float sample = 0.0f;
if (spec.type == XTC_NODE_AUDIO) {
if (spec.type == XTC_NODE_INSTRUMENT) {
sample = instrument ? instrument[frame] : 0.0f;
} else if (spec.type == XTC_NODE_AUDIO) {
sample = timeline ? timeline[frame] : 0.0f;
} else if (spec.type == XTC_NODE_OSCILLATOR) {
sample = (float)sin(XTC_TAU * phase);
@ -172,3 +174,6 @@ xtc_result xtc_graph_process_offline(xtc_graph *graph, const float *input,
xtc_result xtc_plan_process(xtc_plan *plan, const float *input, float *output, size_t frames)
{ return xtc_plan_process_audio(plan, input, NULL, output, frames); }
xtc_result xtc_plan_process_audio(xtc_plan *plan, const float *input, const float *timeline, float *output, size_t frames)
{ return xtc_plan_process_sources(plan, input, timeline, NULL, output, frames); }

View file

@ -80,7 +80,7 @@ xtc_result xtc_realtime_get_status(const xtc_realtime *engine,
return XTC_OK;
}
xtc_result xtc_realtime_process_audio(xtc_realtime *engine, const float *input, const float *timeline,
xtc_result xtc_realtime_process_sources(xtc_realtime *engine, const float *input, const float *timeline, const float *instrument,
float *output, size_t frame_count)
{
xtc_result result = XTC_OK;
@ -107,7 +107,7 @@ xtc_result xtc_realtime_process_audio(xtc_realtime *engine, const float *input,
}
}
if (engine->active != NULL)
result = xtc_plan_process_audio(engine->active, input, timeline, output, frame_count);
result = xtc_plan_process_sources(engine->active, input, timeline, instrument, output, frame_count);
else
memset(output, 0, frame_count * sizeof(*output));
}
@ -120,3 +120,6 @@ xtc_result xtc_realtime_process_audio(xtc_realtime *engine, const float *input,
xtc_result xtc_realtime_process(xtc_realtime *engine, const float *input, float *output, size_t frames)
{ return xtc_realtime_process_audio(engine, input, NULL, output, frames); }
xtc_result xtc_realtime_process_audio(xtc_realtime *engine, const float *input, const float *timeline, float *output, size_t frames)
{ return xtc_realtime_process_sources(engine, input, timeline, NULL, output, frames); }

View file

@ -59,6 +59,8 @@ xtc_result xtc_graph_add_oscillator(xtc_graph *graph, float frequency, size_t *o
}
xtc_result xtc_graph_add_meter(xtc_graph *graph, size_t *out_node_id)
{ return add_node(graph, XTC_NODE_METER, 0.0f, out_node_id); }
xtc_result xtc_graph_add_instrument(xtc_graph *graph, size_t *out_node_id)
{ return add_node(graph, XTC_NODE_INSTRUMENT, 0.0f, out_node_id); }
xtc_result xtc_graph_add_audio(xtc_graph *graph, size_t *out_node_id)
{ return add_node(graph, XTC_NODE_AUDIO, 0.0f, out_node_id); }
xtc_result xtc_graph_add_output(xtc_graph *graph, size_t *out_node_id)
@ -72,7 +74,7 @@ xtc_result xtc_graph_get_port(const xtc_graph *graph, size_t node_id,
node_id = node_index(graph, node_id);
if (node_id == SIZE_MAX) return XTC_ERR_NOT_FOUND;
type = graph->nodes[node_id].type;
if (port_id > 1U || (port_id == 0U && (type == XTC_NODE_OSCILLATOR || type == XTC_NODE_AUDIO)) ||
if (port_id > 1U || (port_id == 0U && (type == XTC_NODE_OSCILLATOR || type == XTC_NODE_AUDIO || type == XTC_NODE_INSTRUMENT)) ||
(port_id == 1U && type == XTC_NODE_OUTPUT)) return XTC_ERR_NOT_FOUND;
out_port->direction = port_id == 0U ? XTC_PORT_INPUT : XTC_PORT_OUTPUT;
out_port->signal_type = XTC_SIGNAL_AUDIO;
@ -228,6 +230,7 @@ xtc_result xtc_graph_apply_edit(const xtc_graph *source, const xtc_graph_edit *e
case XTC_NODE_GAIN: result = xtc_graph_add_gain(graph, edit->data.add.value, &added_id); break;
case XTC_NODE_OSCILLATOR: result = xtc_graph_add_oscillator(graph, edit->data.add.value, &added_id); break;
case XTC_NODE_METER: result = xtc_graph_add_meter(graph, &added_id); break;
case XTC_NODE_INSTRUMENT: result = xtc_graph_add_instrument(graph, &added_id); break;
case XTC_NODE_AUDIO: result = xtc_graph_add_audio(graph, &added_id); break;
case XTC_NODE_OUTPUT: result = xtc_graph_add_output(graph, &added_id); break;
default: result = XTC_ERR_INVALID_ARGUMENT; break;

View file

@ -14,6 +14,7 @@ const char *node_name(xtc_node_type type)
case XTC_NODE_OSCILLATOR: return "Oscillator";
case XTC_NODE_GAIN: return "Gain";
case XTC_NODE_METER: return "Meter";
case XTC_NODE_INSTRUMENT: return "Instrument";
case XTC_NODE_AUDIO: return "Audio clips";
case XTC_NODE_OUTPUT: return "Output";
}
@ -187,7 +188,7 @@ void GraphWidget::draw()
fl_font(FL_HELVETICA, 12);
if (node.type == XTC_NODE_OSCILLATOR) std::snprintf(text, sizeof(text), "%.0f Hz", static_cast<double>(node.value));
else if (node.type == XTC_NODE_GAIN) std::snprintf(text, sizeof(text), "x %.2f", static_cast<double>(node.value));
else std::snprintf(text, sizeof(text), "%s", node.type == XTC_NODE_METER ? "Peak pass-through" : node.type == XTC_NODE_AUDIO ? "Timeline mix source" : "Mono audio output");
else std::snprintf(text, sizeof(text), "%s", node.type == XTC_NODE_METER ? "Peak pass-through" : node.type == XTC_NODE_INSTRUMENT ? "MIDI sine source" : node.type == XTC_NODE_AUDIO ? "Timeline mix source" : "Mono audio output");
fl_draw(text, left + 10, top + 37);
for (size_t port = 0U; port < 2U; ++port) {
int px, py;

View file

@ -1,6 +1,7 @@
#include "main_window.hpp"
#include "graph_widget.hpp"
#include "sequencer_widget.hpp"
#include "piano_roll.hpp"
#include <FL/Fl_Native_File_Chooser.H>
#include "xtc/xtc_version.h"
@ -40,6 +41,8 @@ MainWindow::MainWindow(bool prompt_unsaved)
menu->add("File/Save As", FL_CTRL + FL_SHIFT + 's', file_callback, this);
menu->add("File/Import WAV", FL_CTRL + 'i', audio_file_callback, this);
menu->add("File/Relink selected audio", 0, audio_file_callback, this);
menu->add("Audio/Panic", FL_F + 9, panic_callback, this);
menu->add("View/Piano roll", FL_CTRL + '4', piano_callback, this);
menu->add("Audio/Record WAV", FL_SHIFT + FL_F + 5, audio_file_callback, this);
menu->add("File/Quit", FL_CTRL + 'q', close_callback, this);
menu->add("Audio/Start engine", FL_F + 5, play_callback, this);
@ -58,7 +61,10 @@ MainWindow::MainWindow(bool prompt_unsaved)
record_ = new Fl_Button(306, 40, 90, 30, "Record");
record_->callback(audio_file_callback, this);
record_->tooltip("Record JACK input to WAV; choose path, then Stop to finalize and add the take.");
indicator_ = new Fl_Box(404, 40, 584, 30, "Audio: disconnected");
auto *panic = new Fl_Button(404, 40, 70, 30, "Panic");
panic->callback(panic_callback, this);
panic->tooltip("Silence held instrument notes (F9).");
indicator_ = new Fl_Box(482, 40, 506, 30, "Audio: disconnected");
indicator_->align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE);
indicator_->labelfont(FL_BOLD);
auto *hint = new Fl_Box(12, 78, 976, 24,
@ -75,6 +81,9 @@ MainWindow::MainWindow(bool prompt_unsaved)
auto *delete_region = new Fl_Button(246, 150, 130, 26, "Delete region/track");
auto *zoom_in = new Fl_Button(384, 150, 80, 26, "Zoom +");
auto *zoom_out = new Fl_Button(472, 150, 80, 26, "Zoom -");
auto *add_midi = new Fl_Button(560, 150, 110, 26, "Add MIDI clip");
auto *piano = new Fl_Button(678, 150, 100, 26, "Piano roll");
piano->callback(piano_callback, this);
auto *timeline_hint = new Fl_Box(20, 548, 956, 28,
"Import WAV (Ctrl+I) or Record. Drag body to move, edges to trim; ruler seeks while stopped.");
timeline_hint->align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE); timeline_hint->labelsize(12);
@ -84,6 +93,7 @@ MainWindow::MainWindow(bool prompt_unsaved)
sequencer_->before_edit = before_arrangement_edit;
sequencer_->callback([](Fl_Widget *, void *c) { static_cast<MainWindow *>(c)->mark_dirty(); }, this);
add_track->callback([](Fl_Widget *, void *c) { static_cast<SequencerWidget *>(c)->add_track(); }, sequencer_);
add_midi->callback([](Fl_Widget *, void *c) { static_cast<SequencerWidget *>(c)->add_midi_clip(); }, sequencer_);
add_region->callback([](Fl_Widget *, void *c) { static_cast<SequencerWidget *>(c)->add_region(); }, sequencer_);
delete_region->callback([](Fl_Widget *, void *c) { static_cast<SequencerWidget *>(c)->delete_selection(); }, sequencer_);
zoom_in->callback([](Fl_Widget *, void *c) { static_cast<SequencerWidget *>(c)->zoom(1); }, sequencer_);
@ -126,6 +136,8 @@ MainWindow::MainWindow(bool prompt_unsaved)
audio->callback([](Fl_Widget *, void *context) {
(void)static_cast<GraphWidget *>(context)->add_node(XTC_NODE_AUDIO);
}, graph_widget_);
auto *instrument = new Fl_Button(788, 150, 130, 26, "Add instrument");
instrument->callback([](Fl_Widget *, void *c) { (void)static_cast<GraphWidget *>(c)->add_node(XTC_NODE_INSTRUMENT); }, graph_widget_);
auto *remove = new Fl_Button(512, 150, 130, 26, "Delete selection");
remove->callback([](Fl_Widget *, void *context) {
(void)static_cast<GraphWidget *>(context)->delete_selected();
@ -299,9 +311,9 @@ void MainWindow::refresh_status()
indicator_->labelcolor(fault ? fl_rgb_color(255, 155, 120) :
running_ ? fl_rgb_color(125, 225, 160) : fl_rgb_color(215, 215, 215));
char text[256];
std::snprintf(text, sizeof(text), "JACK | %u Hz | %u frames | mono | %u blocks | %u xruns | %s | %u asset issues",
std::snprintf(text, sizeof(text), "JACK | %u Hz | %u frames | mono | %u blocks | %u xruns | %s | %u asset issues | %u MIDI drops",
status.sample_rate, status.buffer_frames, status.processed_blocks, status.xruns,
xtc_result_string(status.process_result), status.asset_issues);
xtc_result_string(status.process_result), status.asset_issues, status.midi_dropped);
set_label(status_, text);
if (fault) set_label(graph_state_, "Graph: engine unavailable — Reconnect required");
else if (status.submitted_revision != status.active_revision)
@ -330,6 +342,7 @@ bool MainWindow::close_window()
running_ = false;
closing_ = true;
Fl::remove_timeout(timer_callback, this);
if (piano_window_) piano_window_->hide();
hide();
return true;
}
@ -359,7 +372,7 @@ void MainWindow::view_callback(Fl_Widget *widget, void *view)
}
void MainWindow::about_callback(Fl_Widget *, void *)
{
fl_message("%s %s\nModular audio workstation\nPhase 6: WAV import, graph clip playback and bounded recording; MIDI follows.",
fl_message("%s %s\nModular audio workstation\nPhase 7: MIDI input, sine instrument, persisted notes and piano roll.",
XTC_PROJECT_NAME, XTC_VERSION_STRING);
}
void MainWindow::timer_callback(void *context)
@ -378,7 +391,11 @@ void MainWindow::timer_callback(void *context)
void MainWindow::mark_dirty()
{ dirty_ = true; copy_label("xtc * — unsaved changes"); }
{
graph_widget_->set_graph(xtc_project_graph(project_.get()));
if (piano_) piano_->set_project(project_.get(), piano_->clip());
dirty_ = true; copy_label("xtc * — unsaved changes");
}
bool MainWindow::discard_changes()
{
return !dirty_ || !prompt_unsaved_ ||
@ -414,13 +431,18 @@ xtc_result MainWindow::install_project(xtc_project *candidate)
}
xtc_audio_plan *offline = nullptr;
if (r == XTC_OK && !ready_) r = xtc_audio_plan_create(candidate, 48000, &offline);
if (r != XTC_OK) return r;
xtc_midi_plan *offline_midi = nullptr;
if (r == XTC_OK && !ready_) r = xtc_midi_plan_create(candidate, 48000, &offline_midi);
xtc_midi_plan_destroy(offline_midi);
if (r != XTC_OK) { xtc_audio_plan_destroy(offline); return r; }
std::string issue = ready_ ? xtc_backend_asset_issue(backend_) : "";
if (offline) {
const char *path = "";
xtc_audio_plan_issues(offline, &path); issue = path;
xtc_audio_plan_destroy(offline);
}
if (piano_window_) piano_window_->hide();
if (piano_) piano_->set_project(candidate, UINT64_MAX);
project_.reset(candidate);
graph_widget_->reset_layout();
graph_widget_->set_graph(xtc_project_graph(candidate));
@ -577,3 +599,38 @@ void MainWindow::audio_file_callback(Fl_Widget *widget, void *context)
} else if (r == XTC_OK) r = recording ? window->record_audio(chooser.filename()) : window->import_audio(chooser.filename());
if (r != XTC_OK) window->report_error("Project audio operation failed", r);
}
xtc_result MainWindow::open_piano_roll()
{
xtc_clip_info clip{};
if (xtc_project_find_clip(project_.get(), sequencer_->selected_clip(), &clip) != XTC_OK || !clip.midi)
return XTC_ERR_INVALID_STATE;
if (!piano_window_) {
piano_window_ = std::make_unique<Fl_Double_Window>(900, 620, "xtc — Piano roll");
piano_window_->begin();
auto *hint = new Fl_Box(12, 8, 876, 32,
"Source ticks: click draws; drag body moves/pitches, right edge resizes; right-click/Delete removes. Snap 1/16.");
hint->align(FL_ALIGN_LEFT | FL_ALIGN_INSIDE); hint->labelsize(12);
auto *scroll = new Fl_Scroll(12, 48, 876, 560);
piano_ = new PianoRollWidget(12, 48, project_.get(), clip.id, before_arrangement_edit, this);
piano_->callback([](Fl_Widget *, void *c) { static_cast<MainWindow *>(c)->mark_dirty(); }, this);
scroll->end(); piano_window_->end(); piano_window_->resizable(scroll);
scroll->scroll_to(0, 60 * 16);
} else piano_->set_project(project_.get(), clip.id);
piano_window_->show(); return XTC_OK;
}
void MainWindow::piano_callback(Fl_Widget *, void *context)
{
auto *window = static_cast<MainWindow *>(context);
if (window->recorder_) { window->report_error("Stop recording before editing MIDI", XTC_ERR_INVALID_STATE); return; }
xtc_result r = window->open_piano_roll();
if (r != XTC_OK) set_label(window->error_, "Select a MIDI clip, then open Piano roll.");
}
void MainWindow::panic_callback(Fl_Widget *, void *context)
{
auto *window = static_cast<MainWindow *>(context);
if (!window->ready_) return;
xtc_result r = xtc_backend_panic(window->backend_);
if (r != XTC_OK) window->report_error("Panic failed", r);
}

View file

@ -8,6 +8,7 @@
#include "xtc/xtc_backend.h"
class GraphWidget;
class PianoRollWidget;
class SequencerWidget;
class Fl_Box;
class Fl_Button;
@ -22,12 +23,18 @@ public:
using Fl_Double_Window::show;
int handle(int event) override;
xtc_result open_piano_roll();
PianoRollWidget *piano_roll() const { return piano_; }
xtc_result import_audio(const char *path);
xtc_result record_audio(const char *path);
xtc_result save_project(const char *path);
xtc_result open_project(const char *path);
private:
std::unique_ptr<xtc_project, decltype(&xtc_project_destroy)> project_{nullptr, xtc_project_destroy};
std::unique_ptr<Fl_Double_Window> piano_window_;
PianoRollWidget *piano_ = nullptr;
static void piano_callback(Fl_Widget *, void *context);
static void panic_callback(Fl_Widget *, void *context);
SequencerWidget *sequencer_ = nullptr;
xtc_recorder *recorder_ = nullptr;
std::string recording_path_;

138
src/gui/piano_roll.cpp Normal file
View file

@ -0,0 +1,138 @@
#include "piano_roll.hpp"
#include <FL/Fl.H>
#include <FL/fl_draw.H>
#include <FL/fl_ask.H>
#include <algorithm>
#include <cstdio>
namespace { constexpr int key_width = 64, row_height = 16, scale = 96, header = 28; }
PianoRollWidget::PianoRollWidget(int left, int top, xtc_project *project, uint64_t clip, BeforeEdit before, void *context)
: Fl_Widget(left, top, 900, header + 128 * row_height), project_(project), clip_(clip), before_(before), context_(context)
{ set_project(project, clip); }
void PianoRollWidget::set_project(xtc_project *project, uint64_t clip)
{
if (project != project_ || clip != clip_) mode_ = 0;
project_ = project; clip_ = clip;
xtc_clip_info c{};
int width = xtc_project_find_clip(project_, clip_, &c) == XTC_OK ?
static_cast<int>(c.source_length_tick * scale / 960) + key_width + 20 : 900;
size(std::max(900, width), header + 128 * row_height);
redraw();
}
uint64_t PianoRollWidget::tick(int px) const
{ return static_cast<uint64_t>(std::max(0, px - x() - key_width)) * 960U / scale / 240U * 240U; }
xtc_result PianoRollWidget::change(xtc_result result)
{
if (result == XTC_OK) { do_callback(); redraw(); }
else fl_alert("Note unchanged: %s", xtc_result_string(result));
return result;
}
xtc_result PianoRollWidget::add_note(uint64_t start, uint64_t length, unsigned int pitch,
unsigned int velocity, unsigned int channel)
{
xtc_result r = before_ ? before_(context_) : XTC_OK;
uint64_t id;
if (r == XTC_OK) r = xtc_project_add_note(project_, clip_, start, length, pitch, velocity, channel, &id);
if (r == XTC_OK) selected_ = id;
return change(r);
}
xtc_result PianoRollWidget::delete_selected()
{
xtc_result r = before_ ? before_(context_) : XTC_OK;
if (r == XTC_OK) r = xtc_project_remove_note(project_, selected_);
if (r == XTC_OK) selected_ = UINT64_MAX;
return change(r);
}
void PianoRollWidget::draw()
{
fl_push_clip(x(), y(), w(), h());
fl_color(fl_rgb_color(30, 33, 38)); fl_rectf(x(), y(), w(), h());
xtc_clip_info clip{};
if (xtc_project_find_clip(project_, clip_, &clip) != XTC_OK || !clip.midi) { fl_pop_clip(); return; }
int cx, cy, cw, ch; fl_clip_box(x(), y(), w(), h(), cx, cy, cw, ch);
fl_font(FL_HELVETICA, 11);
for (int pitch = 0; pitch < 128; ++pitch) {
int py = y() + header + (127 - pitch) * row_height;
if (py + row_height < cy || py > cy + ch) continue;
int pc = pitch % 12;
bool black = pc == 1 || pc == 3 || pc == 6 || pc == 8 || pc == 10;
fl_color(black ? fl_rgb_color(29, 31, 35) : fl_rgb_color(43, 46, 52));
fl_rectf(cx, py, cw, row_height - 1);
fl_color(black ? fl_rgb_color(60, 63, 70) : fl_rgb_color(130, 135, 140));
fl_rectf(x(), py, key_width - 2, row_height - 1);
if (!pc) {
char text[20]; std::snprintf(text, sizeof(text), "C%d", pitch / 12 - 1);
fl_color(FL_WHITE); fl_draw(text, x() + 6, py + 12);
}
}
int first = std::max(0, (cx - x() - key_width) / (scale / 4));
int last = (cx + cw - x() - key_width) / (scale / 4) + 1;
for (int step = first; step <= last; ++step) {
int px = x() + key_width + step * (scale / 4);
fl_color(step % 16 == 0 ? fl_rgb_color(95, 98, 105) : fl_rgb_color(52, 55, 62));
fl_line(px, cy, px, cy + ch);
}
size_t count = 0; xtc_project_note_count(project_, &count);
for (size_t i = 0; i < count; ++i) {
xtc_note_info n{}; xtc_project_get_note(project_, i, &n);
if (n.clip_id != clip_) continue;
int left = x() + key_width + static_cast<int>(n.start_tick * scale / 960);
int right = left + std::max(3, static_cast<int>(n.length_tick * scale / 960));
int py = y() + header + (127 - static_cast<int>(n.pitch)) * row_height;
int a = std::max(cx, left), b = std::min(cx + cw, right);
if (a >= b || py + row_height < cy || py > cy + ch) continue;
fl_color(n.id == selected_ ? fl_rgb_color(230, 190, 80) : fl_rgb_color(90, 175, 130));
fl_rectf(a, py + 1, b - a, row_height - 3);
}
fl_pop_clip();
}
int PianoRollWidget::handle(int event)
{
if (event == FL_PUSH) {
take_focus(); mode_ = 0;
size_t count = 0; xtc_project_note_count(project_, &count);
selected_ = UINT64_MAX;
for (size_t i = count; i > 0; --i) {
xtc_note_info n{}; xtc_project_get_note(project_, i - 1, &n);
int left = x() + key_width + static_cast<int>(n.start_tick * scale / 960);
int right = left + std::max(3, static_cast<int>(n.length_tick * scale / 960));
int top = y() + header + (127 - static_cast<int>(n.pitch)) * row_height;
if (n.clip_id == clip_ && Fl::event_x() >= left && Fl::event_x() < right &&
Fl::event_y() >= top && Fl::event_y() < top + row_height) {
selected_ = n.id; original_ = n; drag_x_ = Fl::event_x(); drag_y_ = Fl::event_y();
mode_ = right - Fl::event_x() <= 6 ? 2 : 1; break;
}
}
if (selected_ != UINT64_MAX && Fl::event_button() == FL_RIGHT_MOUSE) { delete_selected(); mode_ = 0; }
else if (Fl::event_button() == FL_LEFT_MOUSE && selected_ == UINT64_MAX &&
Fl::event_x() >= x() + key_width && Fl::event_y() >= y() + header) {
int pitch = 127 - (Fl::event_y() - y() - header) / row_height;
xtc_clip_info c{}; uint64_t start = tick(Fl::event_x());
if (pitch >= 0 && pitch <= 127 && xtc_project_find_clip(project_, clip_, &c) == XTC_OK && start < c.source_length_tick)
add_note(start, std::min<uint64_t>(960, c.source_length_tick - start), static_cast<unsigned int>(pitch));
}
redraw(); return 1;
}
if (event == FL_DRAG) return mode_ != 0;
if (event == FL_RELEASE && mode_) {
int mode = mode_; mode_ = 0;
int64_t delta = static_cast<int64_t>(Fl::event_x() - drag_x_) * 960 / scale / 240 * 240;
xtc_clip_info c{}; if (xtc_project_find_clip(project_, clip_, &c) != XTC_OK) return 1;
int64_t start = static_cast<int64_t>(original_.start_tick), length = static_cast<int64_t>(original_.length_tick);
unsigned int pitch = original_.pitch;
if (mode == 1) {
start = std::clamp<int64_t>(start + delta, 0, static_cast<int64_t>(c.source_length_tick) - length);
pitch = static_cast<unsigned int>(std::clamp(static_cast<int>(pitch) - (Fl::event_y() - drag_y_) / row_height, 0, 127));
} else {
int64_t maximum = static_cast<int64_t>(c.source_length_tick) - start;
length = std::clamp<int64_t>(length + delta, std::min<int64_t>(240, maximum), maximum);
}
xtc_result r = before_ ? before_(context_) : XTC_OK;
if (r == XTC_OK) r = xtc_project_edit_note(project_, selected_, static_cast<uint64_t>(start),
static_cast<uint64_t>(length), pitch, original_.velocity, original_.channel);
change(r); return 1;
}
if (event == FL_KEYDOWN && Fl::event_key() == FL_Delete) { delete_selected(); return 1; }
if (event == FL_KEYDOWN && Fl::event_key() == FL_Escape) { mode_ = 0; return 1; }
if (event == FL_FOCUS || event == FL_UNFOCUS) return 1;
return Fl_Widget::handle(event);
}

27
src/gui/piano_roll.hpp Normal file
View file

@ -0,0 +1,27 @@
#ifndef XTC_PIANO_ROLL_HPP
#define XTC_PIANO_ROLL_HPP
#include <FL/Fl_Widget.H>
#include "xtc/xtc_midi.h"
class PianoRollWidget : public Fl_Widget {
public:
using BeforeEdit = xtc_result (*)(void *);
PianoRollWidget(int x, int y, xtc_project *project, uint64_t clip, BeforeEdit before, void *context);
void set_project(xtc_project *project, uint64_t clip);
uint64_t clip() const { return clip_; }
xtc_result add_note(uint64_t start, uint64_t length, unsigned int pitch,
unsigned int velocity = 100, unsigned int channel = 0);
xtc_result delete_selected();
int handle(int event) override;
protected:
void draw() override;
private:
xtc_project *project_;
uint64_t clip_, selected_ = UINT64_MAX;
BeforeEdit before_;
void *context_;
xtc_note_info original_{};
int mode_ = 0, drag_x_ = 0, drag_y_ = 0;
xtc_result change(xtc_result result);
uint64_t tick(int px) const;
};
#endif

View file

@ -1,4 +1,5 @@
#include "sequencer_widget.hpp"
#include "xtc/xtc_midi.h"
#include <FL/Fl.H>
#include <FL/Fl_Scroll.H>
#include <FL/fl_draw.H>
@ -55,6 +56,20 @@ xtc_result SequencerWidget::add_region()
if (r == XTC_OK) clip_ = id;
changed(r); return r;
}
xtc_result SequencerWidget::add_midi_clip()
{
xtc_result r = before_edit ? before_edit(context_) : XTC_OK;
uint64_t id;
if (r == XTC_OK) {
if (track_ == UINT64_MAX) {
xtc_track_info t{};
r = xtc_project_get_track(project_, 0, &t); track_ = r == XTC_OK ? t.id : UINT64_MAX;
}
if (r == XTC_OK) r = xtc_project_add_midi_clip(project_, track_, cursor_, 3840, &id);
if (r == XTC_OK) clip_ = id;
}
changed(r); return r;
}
xtc_result SequencerWidget::delete_selection()
{
if (before_edit) { xtc_result r = before_edit(context_); if (r != XTC_OK) { changed(r); return r; } }
@ -99,7 +114,7 @@ void SequencerWidget::draw()
fl_color(c.id == clip_ ? fl_rgb_color(100, 170, 205) : fl_rgb_color(65, 120, 150));
fl_rectf(a, py + 5, b - a, 44);
fl_push_clip(a, py + 5, b - a, 44); fl_color(FL_WHITE);
fl_draw(c.asset_path[0] ? "Audio" : c.name, std::max(a, left + 6), py + 31); fl_pop_clip();
fl_draw(c.midi ? "MIDI" : c.asset_path[0] ? "Audio" : c.name, std::max(a, left + 6), py + 31); fl_pop_clip();
}
}
int playhead = x() + 120 + static_cast<int>(cursor_ * static_cast<unsigned int>(scale_) / 960U);

View file

@ -15,6 +15,7 @@ public:
void position(uint64_t tick) { cursor_ = tick; redraw(); }
xtc_result add_track();
xtc_result add_region();
xtc_result add_midi_clip();
xtc_result delete_selection();
void zoom(int direction);
xtc_project *project() const { return project_; }

View file

@ -1,5 +1,7 @@
# MIDI and events
MIDI input, MIDI clips, event scheduling, panic behavior, and device handling
are not implemented yet. Define a bounded event representation and explicit
sample-offset semantics before adding real-time event delivery.
`model.c` implements bounded MIDI clips and stable source-relative notes through
`xtc_midi.h`. `instrument.c` prepares timeline spans and renders the sine
instrument with sample-offset live events, note-off and panic handling.
Preparation/destruction are control-thread operations; render/runtime state has
one audio owner. See [MIDI workflow, ownership and limits](../../docs/MIDI.md).

173
src/midi/instrument.c Normal file
View file

@ -0,0 +1,173 @@
#include "xtc/xtc_midi.h"
#include "../project/project_internal.h"
#include <math.h>
#include <stdlib.h>
#include <string.h>
#define TAU 6.28318530717958647692
typedef struct { uint64_t start, end, age; unsigned int pitch, velocity, channel; } span;
typedef struct { uint64_t time; int change; } endpoint;
typedef struct { unsigned int active, channel, pitch, velocity; uint64_t age; double phase; } voice;
struct xtc_midi_plan {
span notes[XTC_PROJECT_MAX_NOTES];
size_t count;
voice voices[XTC_MIDI_VOICES];
double step[128];
uint64_t cutoff[16], next_position, age;
};
xtc_result xtc_midi_decode(const unsigned char *bytes, size_t size, unsigned int offset, xtc_midi_event *out)
{
xtc_midi_event e;
unsigned int command;
if (!bytes || !size || !out) return XTC_ERR_INVALID_ARGUMENT;
command = bytes[0] & 240U;
if (command != 128 && command != 144 && command != 176) return XTC_ERR_UNSUPPORTED;
if (size != 3 || bytes[1] > 127 || bytes[2] > 127) return XTC_ERR_INVALID_ARGUMENT;
if (command == 176 && bytes[1] != 120 && bytes[1] != 123) return XTC_ERR_UNSUPPORTED;
e.offset = offset; e.channel = bytes[0] & 15U; e.pitch = bytes[1]; e.velocity = bytes[2];
e.type = command == 176 ? XTC_MIDI_ALL_OFF :
command == 128 || !e.velocity ? XTC_MIDI_NOTE_OFF : XTC_MIDI_NOTE_ON;
*out = e; return XTC_OK;
}
static int compare_endpoint(const void *left, const void *right)
{
const endpoint *a = left, *b = right;
if (a->time != b->time) return a->time < b->time ? -1 : 1;
return a->change - b->change; /* End before start at the same sample. */
}
void xtc_midi_plan_reset(xtc_midi_plan *p)
{
if (!p) return;
memset(p->voices, 0, sizeof(p->voices)); memset(p->cutoff, 0, sizeof(p->cutoff));
p->next_position = UINT64_MAX; p->age = 0;
}
xtc_result xtc_midi_plan_create(const xtc_project *project, unsigned int rate, xtc_midi_plan **out)
{
xtc_midi_plan *p;
endpoint *points;
size_t i;
int active = 0;
if (!out) return XTC_ERR_INVALID_ARGUMENT;
*out = NULL;
if (!project || !rate || rate > 768000) return XTC_ERR_INVALID_ARGUMENT;
p = calloc(1, sizeof(*p)); points = calloc(XTC_PROJECT_MAX_NOTES * 2U, sizeof(*points));
if (!p || !points) { free(p); free(points); return XTC_ERR_OUT_OF_MEMORY; }
for (i = 0; i < 128; ++i) {
double frequency = 440.0 * pow(2.0, ((double)i - 69.0) / 12.0);
p->step[i] = frequency < rate * 0.5 ? frequency / rate : 0;
}
for (i = 0; i < project->note_count; ++i) {
const xtc_note_info *n = project->notes + i;
xtc_clip_info c;
uint64_t begin, end;
span *s = p->notes + p->count;
xtc_result r = xtc_project_find_clip(project, n->clip_id, &c);
if (r != XTC_OK) { free(points); free(p); return XTC_ERR_INVALID_STATE; }
begin = n->start_tick > c.offset_tick ? n->start_tick : c.offset_tick;
end = n->start_tick + n->length_tick < c.offset_tick + c.length_tick ?
n->start_tick + n->length_tick : c.offset_tick + c.length_tick;
if (end <= begin) continue;
r = xtc_project_tick_to_sample(project, c.start_tick + begin - c.offset_tick, rate, &s->start);
if (r == XTC_OK) r = xtc_project_tick_to_sample(project, c.start_tick + end - c.offset_tick, rate, &s->end);
if (r == XTC_OK) r = xtc_project_tick_to_sample(project, begin - n->start_tick, rate, &s->age);
if (r != XTC_OK) { free(points); free(p); return r; }
if (s->end <= s->start) continue;
s->pitch = n->pitch; s->velocity = n->velocity; s->channel = n->channel;
points[p->count * 2].time = s->start; points[p->count * 2].change = 1;
points[p->count * 2 + 1].time = s->end; points[p->count * 2 + 1].change = -1;
++p->count;
}
qsort(points, p->count * 2, sizeof(*points), compare_endpoint);
for (i = 0; i < p->count * 2; ++i) {
active += points[i].change;
if (active > (int)XTC_MIDI_VOICES) { free(points); free(p); return XTC_ERR_CAPACITY; }
}
free(points); xtc_midi_plan_reset(p); *out = p; return XTC_OK;
}
void xtc_midi_plan_destroy(xtc_midi_plan *p) { free(p); }
static void channel_off(xtc_midi_plan *p, unsigned int channel, uint64_t position)
{
size_t i;
for (i = 0; i < XTC_MIDI_VOICES; ++i)
if (p->voices[i].channel == channel) p->voices[i].active = 0;
p->cutoff[channel] = position == UINT64_MAX ? position : position + 1;
}
void xtc_midi_plan_panic(xtc_midi_plan *p, uint64_t position)
{
unsigned int c;
if (!p) return;
for (c = 0; c < 16; ++c) channel_off(p, c, position);
p->next_position = position;
}
static void event(xtc_midi_plan *p, const xtc_midi_event *e, uint64_t position)
{
size_t i, slot = SIZE_MAX;
if (e->type == XTC_MIDI_ALL_OFF) { channel_off(p, e->channel, position); return; }
for (i = 0; i < XTC_MIDI_VOICES; ++i) {
if (p->voices[i].active && p->voices[i].channel == e->channel && p->voices[i].pitch == e->pitch) {
slot = i; break;
}
}
if (e->type == XTC_MIDI_NOTE_OFF) {
if (slot != SIZE_MAX) p->voices[slot].active = 0;
return;
}
if (slot == SIZE_MAX) {
for (i = 0; i < XTC_MIDI_VOICES; ++i) if (!p->voices[i].active) { slot = i; break; }
}
if (slot == SIZE_MAX) {
slot = 0;
for (i = 1; i < XTC_MIDI_VOICES; ++i) if (p->voices[i].age < p->voices[slot].age) slot = i;
}
p->voices[slot].active = 1; p->voices[slot].channel = e->channel;
p->voices[slot].pitch = e->pitch; p->voices[slot].velocity = e->velocity;
p->voices[slot].phase = 0; p->voices[slot].age = p->age++;
}
static void segment(xtc_midi_plan *p, uint64_t position, float *out, size_t frames)
{
size_t i, j;
for (i = 0; i < p->count; ++i) {
const span *s = p->notes + i;
uint64_t begin = position > s->start ? position : s->start;
uint64_t end = position + frames < s->end ? position + frames : s->end;
double step = p->step[s->pitch];
if (!step || s->start < p->cutoff[s->channel] || end <= begin) continue;
for (j = (size_t)(begin - position); j < (size_t)(end - position); ++j) {
double phase = fmod((double)(position + j - s->start + s->age) * step, 1.0);
out[j] += (float)(sin(TAU * phase) * 0.1 * s->velocity / 127.0);
}
}
for (i = 0; i < XTC_MIDI_VOICES; ++i) {
voice *v = p->voices + i;
double step = p->step[v->pitch];
if (!v->active || !step) continue;
for (j = 0; j < frames; ++j) {
out[j] += (float)(sin(TAU * v->phase) * 0.1 * v->velocity / 127.0);
v->phase += step; if (v->phase >= 1) v->phase -= 1;
}
}
}
xtc_result xtc_midi_plan_render(xtc_midi_plan *p, uint64_t position,
const xtc_midi_event *events, size_t count, float *out, size_t frames)
{
size_t i, cursor = 0;
if (!p || !out || count > XTC_MIDI_MAX_EVENTS || (count && !events) ||
frames > 65536U || position > UINT64_MAX - frames) return XTC_ERR_INVALID_ARGUMENT;
for (i = 0; i < count; ++i) {
const xtc_midi_event *e = events + i;
if (e->offset >= frames || (i && e->offset < events[i - 1].offset) ||
e->type < XTC_MIDI_NOTE_ON || e->type > XTC_MIDI_ALL_OFF ||
e->pitch > 127 || e->velocity > 127 || e->channel > 15 ||
(e->type == XTC_MIDI_NOTE_ON && !e->velocity)) return XTC_ERR_INVALID_ARGUMENT;
}
if (!frames) return XTC_OK;
if (p->next_position != position) xtc_midi_plan_reset(p);
memset(out, 0, frames * sizeof(*out));
for (i = 0; i < count; ++i) {
size_t next = events[i].offset;
segment(p, position + cursor, out + cursor, next - cursor);
event(p, events + i, position + next); cursor = next;
}
segment(p, position + cursor, out + cursor, frames - cursor);
p->next_position = position + frames;
return XTC_OK;
}

88
src/midi/model.c Normal file
View file

@ -0,0 +1,88 @@
#include "../project/project_internal.h"
#include "../graph/graph_internal.h"
#include <string.h>
xtc_result xtc_project_add_midi_clip(xtc_project *p, uint64_t track, uint64_t start, uint64_t length, uint64_t *out)
{
xtc_project *c = NULL;
xtc_result r;
size_t i, source = SIZE_MAX, output = SIZE_MAX;
uint64_t id;
if (!p || !out) return XTC_ERR_INVALID_ARGUMENT;
r = xtc_project_clone(p, &c);
if (r == XTC_OK) r = xtc_project_add_clip(c, track, "MIDI", start, length, &id);
if (r == XTC_OK) {
c->clips[c->clip_count - 1].midi = 1;
for (i = 0; i < c->graph->node_count; ++i) {
xtc_node *n = c->graph->nodes + i;
if (n->type == XTC_NODE_INSTRUMENT) source = n->id;
if (n->type == XTC_NODE_OUTPUT) output = n->id;
}
if (source == SIZE_MAX) {
r = xtc_graph_add_instrument(c->graph, &source);
if (r == XTC_OK && output == SIZE_MAX) r = xtc_graph_add_output(c->graph, &output);
if (r == XTC_OK) r = xtc_graph_connect(c->graph, source, output);
}
}
if (r == XTC_OK) {
xtc_graph *old = p->graph; *p = *c; c->graph = old; *out = id;
}
xtc_project_destroy(c); return r;
}
xtc_result xtc_project_note_count(const xtc_project *p, size_t *out)
{
if (!p || !out) return XTC_ERR_INVALID_ARGUMENT;
*out = p->note_count; return XTC_OK;
}
xtc_result xtc_project_get_note(const xtc_project *p, size_t i, xtc_note_info *out)
{
if (!p || !out) return XTC_ERR_INVALID_ARGUMENT;
if (i >= p->note_count) return XTC_ERR_NOT_FOUND;
*out = p->notes[i]; return XTC_OK;
}
static xtc_result valid_note(const xtc_project *p, uint64_t clip, uint64_t start, uint64_t length,
unsigned int pitch, unsigned int velocity, unsigned int channel)
{
xtc_clip_info c;
if (pitch > 127 || !velocity || velocity > 127 || channel > 15 || !length) return XTC_ERR_INVALID_ARGUMENT;
if (xtc_project_find_clip(p, clip, &c) != XTC_OK) return XTC_ERR_NOT_FOUND;
if (!c.midi) return XTC_ERR_INVALID_STATE;
if (start >= c.source_length_tick || length > c.source_length_tick - start) return XTC_ERR_INVALID_ARGUMENT;
return XTC_OK;
}
xtc_result xtc_project_add_note(xtc_project *p, uint64_t clip, uint64_t start, uint64_t length,
unsigned int pitch, unsigned int velocity, unsigned int channel, uint64_t *out)
{
xtc_result r;
xtc_note_info n;
if (!p || !out) return XTC_ERR_INVALID_ARGUMENT;
r = valid_note(p, clip, start, length, pitch, velocity, channel);
if (r != XTC_OK) return r;
if (p->note_count == XTC_PROJECT_MAX_NOTES || p->next_note_id == UINT64_MAX) return XTC_ERR_CAPACITY;
memset(&n, 0, sizeof(n));
n.id = p->next_note_id++; n.clip_id = clip; n.start_tick = start; n.length_tick = length;
n.pitch = pitch; n.velocity = velocity; n.channel = channel;
p->notes[p->note_count++] = n; *out = n.id; return XTC_OK;
}
xtc_result xtc_project_edit_note(xtc_project *p, uint64_t id, uint64_t start, uint64_t length,
unsigned int pitch, unsigned int velocity, unsigned int channel)
{
size_t i;
xtc_result r;
if (!p) return XTC_ERR_INVALID_ARGUMENT;
for (i = 0; i < p->note_count; ++i) if (p->notes[i].id == id) break;
if (i == p->note_count) return XTC_ERR_NOT_FOUND;
r = valid_note(p, p->notes[i].clip_id, start, length, pitch, velocity, channel);
if (r != XTC_OK) return r;
p->notes[i].start_tick = start; p->notes[i].length_tick = length;
p->notes[i].pitch = pitch; p->notes[i].velocity = velocity; p->notes[i].channel = channel;
return XTC_OK;
}
xtc_result xtc_project_remove_note(xtc_project *p, uint64_t id)
{
size_t i;
if (!p) return XTC_ERR_INVALID_ARGUMENT;
for (i = 0; i < p->note_count; ++i) if (p->notes[i].id == id) break;
if (i == p->note_count) return XTC_ERR_NOT_FOUND;
memmove(p->notes + i, p->notes + i + 1, (p->note_count - i - 1) * sizeof(*p->notes));
--p->note_count; return XTC_OK;
}

View file

@ -19,7 +19,7 @@ static xtc_result line(reader *input)
char *cursor;
input->count = 0U;
while ((byte = fgetc(input->file)) != EOF) {
if (++input->bytes > 2097152U) return XTC_ERR_FORMAT;
if (++input->bytes > 4194304U) return XTC_ERR_FORMAT;
if (byte == '\n') break;
if (byte < 32 || byte > 126 || used == sizeof(input->line) - 1U) return XTC_ERR_FORMAT;
input->line[used++] = (char)byte;
@ -89,7 +89,7 @@ static xtc_result read_project(reader *input, xtc_project *project)
size_t i, j;
xtc_graph *graph = project->graph;
READ("XTC_PROJECT", 2U); NUM(1U, version);
if (version != 1U && version != 2U) return XTC_ERR_UNSUPPORTED;
if (version < 1U || version > 3U) return XTC_ERR_UNSUPPORTED;
format_version = version;
READ("APP", 4U);
for (i = 1U; i < 4U; ++i) { NUM(i, value); if (value > UINT_MAX) return XTC_ERR_FORMAT; }
@ -104,11 +104,11 @@ static xtc_result read_project(reader *input, xtc_project *project)
for (i = 0U; i < (size_t)node_count; ++i) {
xtc_node node;
READ("NODE", 4U); NUM(1U, value); NUM(2U, version);
if (value >= next_id || value >= SIZE_MAX || version < XTC_NODE_GAIN || version > (format_version == 1U ? XTC_NODE_OUTPUT : XTC_NODE_AUDIO) ||
if (value >= next_id || value >= SIZE_MAX || version < XTC_NODE_GAIN || version > (format_version == 1U ? XTC_NODE_OUTPUT : format_version == 2U ? XTC_NODE_AUDIO : XTC_NODE_INSTRUMENT) ||
!decode_float(input->tokens[3], &node.value)) return XTC_ERR_FORMAT;
node.id = (size_t)value; node.type = (xtc_node_type)version;
if (node.type == XTC_NODE_OSCILLATOR && node.value < 0.0f) return XTC_ERR_FORMAT;
if ((node.type == XTC_NODE_METER || node.type == XTC_NODE_OUTPUT || node.type == XTC_NODE_AUDIO) && node.value != 0.0f) return XTC_ERR_FORMAT;
if ((node.type == XTC_NODE_METER || node.type == XTC_NODE_OUTPUT || node.type == XTC_NODE_AUDIO || node.type == XTC_NODE_INSTRUMENT) && node.value != 0.0f) return XTC_ERR_FORMAT;
for (j = 0U; j < i; ++j) if (graph->nodes[j].id == node.id) return XTC_ERR_FORMAT;
graph->nodes[graph->node_count++] = node;
}
@ -134,18 +134,37 @@ static xtc_result read_project(reader *input, xtc_project *project)
NUM(1U, clip->id); NUM(2U, clip->track_id); NUM(3U, clip->start_tick);
NUM(4U, clip->length_tick); NUM(5U, clip->offset_tick); NUM(6U, clip->source_length_tick);
if (!decode_name(input->tokens[7], clip->name)) return XTC_ERR_FORMAT;
if (format_version == 2U) {
if (format_version >= 2U) {
size_t k, length;
READ("ASSET", 2U);
if (!strcmp(input->tokens[1], "-")) continue;
length = strlen(input->tokens[1]);
if (!length || length % 2 || length >= XTC_ASSET_PATH_BYTES * 2U) return XTC_ERR_FORMAT;
for (k = 0; k < length / 2; ++k) {
int high = hex_digit(input->tokens[1][k * 2]), low = hex_digit(input->tokens[1][k * 2 + 1]);
if (high < 0 || low < 0 || (high == 0 && low == 0)) return XTC_ERR_FORMAT;
clip->asset_path[k] = (char)(high * 16 + low);
if (strcmp(input->tokens[1], "-")) {
length = strlen(input->tokens[1]);
if (!length || length % 2 || length >= XTC_ASSET_PATH_BYTES * 2U) return XTC_ERR_FORMAT;
for (k = 0; k < length / 2; ++k) {
int high = hex_digit(input->tokens[1][k * 2]), low = hex_digit(input->tokens[1][k * 2 + 1]);
if (high < 0 || low < 0 || (high == 0 && low == 0)) return XTC_ERR_FORMAT;
clip->asset_path[k] = (char)(high * 16 + low);
}
clip->asset_path[length / 2] = 0;
}
clip->asset_path[length / 2] = 0;
}
if (format_version >= 3U) {
READ("MIDI", 2U); NUM(1U, value);
if (value > 1) return XTC_ERR_FORMAT;
clip->midi = (int)value;
}
}
if (format_version >= 3U) {
READ("NOTES", 3U); NUM(1U, project->next_note_id); NUM(2U, value);
if (value > XTC_PROJECT_MAX_NOTES) return XTC_ERR_FORMAT;
project->note_count = (size_t)value;
for (i = 0; i < project->note_count; ++i) {
xtc_note_info *n = project->notes + i;
READ("NOTE", 8U);
NUM(1U, n->id); NUM(2U, n->clip_id); NUM(3U, n->start_tick); NUM(4U, n->length_tick);
NUM(5U, value); if (value > 127) return XTC_ERR_FORMAT; n->pitch = (unsigned int)value;
NUM(6U, value); if (!value || value > 127) return XTC_ERR_FORMAT; n->velocity = (unsigned int)value;
NUM(7U, value); if (value > 15) return XTC_ERR_FORMAT; n->channel = (unsigned int)value;
}
}
READ("END", 1U);
@ -164,7 +183,7 @@ static xtc_result write_project(FILE *file, const xtc_project *project)
const xtc_graph *graph = project->graph;
size_t i;
if (sizeof(float) != sizeof(uint32_t) || FLT_RADIX != 2 || FLT_MANT_DIG != 24 || FLT_MAX_EXP != 128) return XTC_ERR_UNSUPPORTED;
if (fprintf(file, "XTC_PROJECT 2\nAPP %d %d %d\nTEMPO %u\nIDS %" PRIu64 " %" PRIu64 "\nGRAPH %d %zu %zu %zu\n",
if (fprintf(file, "XTC_PROJECT 3\nAPP %d %d %d\nTEMPO %u\nIDS %" PRIu64 " %" PRIu64 "\nGRAPH %d %zu %zu %zu\n",
XTC_VERSION_MAJOR, XTC_VERSION_MINOR, XTC_VERSION_PATCH, project->tempo,
project->next_track_id, project->next_clip_id, graph->require_output_nodes,
graph->next_id, graph->node_count, graph->edge_count) < 0) return XTC_ERR_IO;
@ -190,6 +209,13 @@ static xtc_result write_project(FILE *file, const xtc_project *project)
if (clip->asset_path[0]) {
if (!write_name(file, clip->asset_path)) return XTC_ERR_IO;
} else if (fputs("-\n", file) == EOF) return XTC_ERR_IO;
if (fprintf(file, "MIDI %d\n", clip->midi) < 0) return XTC_ERR_IO;
}
if (fprintf(file, "NOTES %" PRIu64 " %zu\n", project->next_note_id, project->note_count) < 0) return XTC_ERR_IO;
for (i = 0; i < project->note_count; ++i) {
const xtc_note_info *n = project->notes + i;
if (fprintf(file, "NOTE %" PRIu64 " %" PRIu64 " %" PRIu64 " %" PRIu64 " %u %u %u\n",
n->id, n->clip_id, n->start_tick, n->length_tick, n->pitch, n->velocity, n->channel) < 0) return XTC_ERR_IO;
}
return fputs("END\n", file) == EOF ? XTC_ERR_IO : XTC_OK;
}

View file

@ -142,7 +142,11 @@ xtc_result xtc_project_remove_track(xtc_project *project, uint64_t id)
project->clip_count = count;
memmove(project->tracks + index, project->tracks + index + 1U,
(project->track_count - index - 1U) * sizeof(*project->tracks));
--project->track_count; return XTC_OK;
--project->track_count;
count = 0;
for (i = 0; i < project->note_count; ++i)
if (clip_index(project, project->notes[i].clip_id) != SIZE_MAX) project->notes[count++] = project->notes[i];
project->note_count = count; return XTC_OK;
}
xtc_result xtc_project_add_clip(xtc_project *project, uint64_t track, const char *name,
uint64_t start, uint64_t length, uint64_t *id)
@ -165,7 +169,14 @@ xtc_result xtc_project_remove_clip(xtc_project *project, uint64_t id)
if (index == SIZE_MAX) return XTC_ERR_NOT_FOUND;
memmove(project->clips + index, project->clips + index + 1U,
(project->clip_count - index - 1U) * sizeof(*project->clips));
--project->clip_count; return XTC_OK;
--project->clip_count;
{
size_t i, count = 0;
for (i = 0; i < project->note_count; ++i)
if (project->notes[i].clip_id != id) project->notes[count++] = project->notes[i];
project->note_count = count;
}
return XTC_OK;
}
xtc_result xtc_project_edit_clip(xtc_project *project, uint64_t id, uint64_t track,
uint64_t start, uint64_t length, uint64_t offset)
@ -208,7 +219,7 @@ xtc_result xtc_project_validate(const xtc_project *project)
{
size_t i, j;
if (project->tempo < 20000U || project->tempo > 300000U ||
project->track_count > XTC_PROJECT_MAX_TRACKS || project->clip_count > XTC_PROJECT_MAX_CLIPS) return XTC_ERR_FORMAT;
project->track_count > XTC_PROJECT_MAX_TRACKS || project->clip_count > XTC_PROJECT_MAX_CLIPS || project->note_count > XTC_PROJECT_MAX_NOTES) return XTC_ERR_FORMAT;
for (i = 0U; i < project->track_count; ++i) {
if (project->tracks[i].id >= project->next_track_id || !xtc_project_valid_name(project->tracks[i].name)) return XTC_ERR_FORMAT;
for (j = 0U; j < i; ++j) if (project->tracks[j].id == project->tracks[i].id) return XTC_ERR_FORMAT;
@ -221,10 +232,20 @@ xtc_result xtc_project_validate(const xtc_project *project)
if (byte < 32U || byte == 127U) return XTC_ERR_FORMAT;
}
if (path_length == XTC_ASSET_PATH_BYTES || (path_length && clip->asset_path[0] != '/')) return XTC_ERR_FORMAT;
if ((clip->midi != 0 && clip->midi != 1) || (clip->midi && path_length)) return XTC_ERR_FORMAT;
if (clip->id >= project->next_clip_id || track_index(project, clip->track_id) == SIZE_MAX ||
!xtc_project_valid_name(clip->name) || !valid_range(clip->start_tick, clip->length_tick, clip->offset_tick, clip->source_length_tick)) return XTC_ERR_FORMAT;
for (j = 0U; j < i; ++j) if (project->clips[j].id == clip->id) return XTC_ERR_FORMAT;
}
for (i = 0; i < project->note_count; ++i) {
const xtc_note_info *n = project->notes + i;
size_t c = clip_index(project, n->clip_id);
if (c == SIZE_MAX || !project->clips[c].midi || n->id >= project->next_note_id ||
n->pitch > 127 || !n->velocity || n->velocity > 127 || n->channel > 15 ||
!n->length_tick || n->start_tick >= project->clips[c].source_length_tick ||
n->length_tick > project->clips[c].source_length_tick - n->start_tick) return XTC_ERR_FORMAT;
for (j = 0; j < i; ++j) if (project->notes[j].id == n->id) return XTC_ERR_FORMAT;
}
return XTC_OK;
}
@ -238,6 +259,7 @@ xtc_result xtc_project_set_clip_asset(xtc_project *project, uint64_t id, const c
if ((unsigned char)path[i] < 32U || path[i] == 127) return XTC_ERR_INVALID_ARGUMENT;
index = clip_index(project, id);
if (index == SIZE_MAX) return XTC_ERR_NOT_FOUND;
if (project->clips[index].midi) return XTC_ERR_INVALID_STATE;
memmove(project->clips[index].asset_path, path, length + 1U);
return XTC_OK;
}

View file

@ -1,11 +1,15 @@
#ifndef XTC_PROJECT_INTERNAL_H
#define XTC_PROJECT_INTERNAL_H
#include "xtc/xtc_project.h"
#include "xtc/xtc_midi.h"
struct xtc_project {
xtc_graph *graph;
uint64_t next_track_id, next_clip_id;
unsigned int tempo;
size_t track_count, clip_count;
uint64_t next_note_id;
size_t note_count;
xtc_note_info notes[XTC_PROJECT_MAX_NOTES];
xtc_track_info tracks[XTC_PROJECT_MAX_TRACKS];
xtc_clip_info clips[XTC_PROJECT_MAX_CLIPS];
};