feat: added MIDI CC recording and list event table operation support.
This commit is contained in:
@@ -6,6 +6,7 @@ import { KGProjectStorage } from './io/KGProjectStorage';
|
||||
import { KGConfigUpgrader } from './config-upgrader/KGConfigUpgrader';
|
||||
import { KGMidiRegion } from './region/KGMidiRegion';
|
||||
import { KGMidiNote } from './midi/KGMidiNote';
|
||||
import { KGMidiControllerEvent } from './midi/KGMidiControllerEvent';
|
||||
import { KGMidiPitchBend } from './midi/KGMidiPitchBend';
|
||||
import { KGRegion } from './region/KGRegion';
|
||||
import { generateUniqueId } from '../util/miscUtil';
|
||||
@@ -559,6 +560,15 @@ export class KGCore {
|
||||
pitchBend.getValue()
|
||||
));
|
||||
});
|
||||
region.getControllerEventsByType().forEach((events, controller) => {
|
||||
events.forEach(controllerEvent => {
|
||||
clonedRegion.addControllerEvent(controller, new KGMidiControllerEvent(
|
||||
generateUniqueId('KGMidiControllerEvent'),
|
||||
controllerEvent.getBeat(),
|
||||
controllerEvent.getValue()
|
||||
));
|
||||
});
|
||||
});
|
||||
|
||||
clonedItems.push(clonedRegion);
|
||||
break;
|
||||
|
||||
@@ -52,7 +52,7 @@ export class KGProject {
|
||||
@WithDefault(0)
|
||||
private projectStructureVersion: number = 0;
|
||||
|
||||
public static readonly CURRENT_PROJECT_STRUCTURE_VERSION: number = 8;
|
||||
public static readonly CURRENT_PROJECT_STRUCTURE_VERSION: number = 9;
|
||||
|
||||
@Expose()
|
||||
@Type(() => KGTrack, {
|
||||
|
||||
@@ -255,6 +255,16 @@ export class KGAudioBus {
|
||||
}
|
||||
}
|
||||
|
||||
public scheduleLiveMidiExpression(normalizedValue: number, time: number): void {
|
||||
this.liveExpressionNormalized = Math.max(0, Math.min(1, normalizedValue));
|
||||
|
||||
for (const activeSources of this.liveMidiSources.values()) {
|
||||
activeSources.forEach(({ gainNode }) => {
|
||||
this.setGainValue(gainNode, this.liveExpressionNormalized, time);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public setLiveMidiSustain(isDown: boolean, time?: number): void {
|
||||
this.sustainPedalDown = isDown;
|
||||
if (isDown) {
|
||||
|
||||
@@ -129,6 +129,8 @@ describe('KGAudioInterface preroll playback', () => {
|
||||
resetLiveMidiPitchBend: vi.fn(),
|
||||
setLiveMidiPitchBend: vi.fn(),
|
||||
scheduleLiveMidiPitchBend: vi.fn(),
|
||||
setLiveMidiExpression: vi.fn(),
|
||||
setLiveMidiSustain: vi.fn(),
|
||||
shouldPlayWithSolo: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
|
||||
@@ -154,6 +156,8 @@ describe('KGAudioInterface preroll playback', () => {
|
||||
resetLiveMidiPitchBend: vi.fn(),
|
||||
setLiveMidiPitchBend: vi.fn(),
|
||||
scheduleLiveMidiPitchBend: vi.fn(),
|
||||
setLiveMidiExpression: vi.fn(),
|
||||
setLiveMidiSustain: vi.fn(),
|
||||
shouldPlayWithSolo: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
|
||||
@@ -178,6 +182,8 @@ describe('KGAudioInterface preroll playback', () => {
|
||||
resetLiveMidiPitchBend: vi.fn(),
|
||||
setLiveMidiPitchBend: vi.fn(),
|
||||
scheduleLiveMidiPitchBend: vi.fn(),
|
||||
setLiveMidiExpression: vi.fn(),
|
||||
setLiveMidiSustain: vi.fn(),
|
||||
shouldPlayWithSolo: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
|
||||
@@ -204,6 +210,8 @@ describe('KGAudioInterface preroll playback', () => {
|
||||
resetLiveMidiPitchBend: vi.fn(),
|
||||
setLiveMidiPitchBend: vi.fn(),
|
||||
scheduleLiveMidiPitchBend: vi.fn(),
|
||||
setLiveMidiExpression: vi.fn(),
|
||||
setLiveMidiSustain: vi.fn(),
|
||||
shouldPlayWithSolo: vi.fn().mockReturnValue(true),
|
||||
};
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { KGMidiPitchBend } from '../midi/KGMidiPitchBend';
|
||||
import { TIME_CONSTANTS, AUDIO_INTERFACE_CONSTANTS } from '../../constants/coreConstants';
|
||||
import { FLUIDR3_INSTRUMENT_MAP } from '../../constants/generalMidiConstants';
|
||||
import {
|
||||
clampMidiControllerValue,
|
||||
MIDI_PITCH_BEND_CENTER,
|
||||
midiPitchBendToNormalized,
|
||||
pitchToNoteNameString,
|
||||
@@ -11,7 +12,9 @@ import {
|
||||
import {
|
||||
bakeMidiAutomationPointsInWindow,
|
||||
collectRegionMidiAutomationPoints,
|
||||
normalizeMidiAutomationPoints,
|
||||
resolveMidiAutomationValueAtBeat,
|
||||
resolveSustainExtendedEndBeat,
|
||||
} from '../../util/midiAutomationUtil';
|
||||
import * as Tone from 'tone';
|
||||
import { KGAudioBus } from './KGAudioBus';
|
||||
@@ -503,6 +506,26 @@ export class KGAudioInterface {
|
||||
};
|
||||
})
|
||||
);
|
||||
const trackControllerEvents = Array.from({ length: 128 }, (_, controller) => (
|
||||
collectRegionMidiAutomationPoints(
|
||||
track.getRegions()
|
||||
.filter(region => region.getCurrentType() === 'KGMidiRegion')
|
||||
.map(region => {
|
||||
const midiRegion = region as unknown as { getControllerEvents: (controller: number) => Array<{ getBeat: () => number; getValue: () => number }> };
|
||||
return {
|
||||
startBeat: region.getStartFromBeat(),
|
||||
points: midiRegion.getControllerEvents(controller).map(event => ({
|
||||
beat: event.getBeat(),
|
||||
value: event.getValue(),
|
||||
})),
|
||||
};
|
||||
})
|
||||
)
|
||||
));
|
||||
const expressionControllers = [1, 2, 7, 11];
|
||||
const mergedExpressionEvents = normalizeMidiAutomationPoints(
|
||||
expressionControllers.flatMap(controller => trackControllerEvents[controller])
|
||||
);
|
||||
|
||||
track.getRegions().forEach(region => {
|
||||
console.log(`Region ${region.getId().toString()}: type: ${region.getCurrentType()}`);
|
||||
@@ -517,9 +540,14 @@ export class KGAudioInterface {
|
||||
// Calculate absolute note timing in beats (note position + region start position)
|
||||
const noteStartBeat = note.getStartBeat() + regionStartBeat;
|
||||
const noteEndBeat = note.getEndBeat() + regionStartBeat;
|
||||
const sustainedEndBeat = resolveSustainExtendedEndBeat(
|
||||
trackControllerEvents[64],
|
||||
noteEndBeat,
|
||||
0
|
||||
);
|
||||
|
||||
// Skip notes outside loop range when looping
|
||||
if (noteStartBeat >= scheduleEndBeat || noteEndBeat <= scheduleStartBeat) {
|
||||
if (noteStartBeat >= scheduleEndBeat || sustainedEndBeat <= scheduleStartBeat) {
|
||||
return; // Skip notes outside the loop range
|
||||
}
|
||||
|
||||
@@ -530,7 +558,7 @@ export class KGAudioInterface {
|
||||
trackNotes.push({
|
||||
note,
|
||||
absoluteStartBeat: noteStartBeat,
|
||||
absoluteEndBeat: noteEndBeat,
|
||||
absoluteEndBeat: sustainedEndBeat,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -544,6 +572,20 @@ export class KGAudioInterface {
|
||||
MIDI_PITCH_BEND_CENTER
|
||||
);
|
||||
audioBus.setLiveMidiPitchBend(midiPitchBendToNormalized(initialPitchBendValue));
|
||||
const expressionInitialValue = resolveMidiAutomationValueAtBeat(
|
||||
mergedExpressionEvents,
|
||||
initialPitchBendBeat,
|
||||
127,
|
||||
'linear'
|
||||
);
|
||||
audioBus.setLiveMidiExpression(clampMidiControllerValue(expressionInitialValue) / 127);
|
||||
const sustainInitialValue = resolveMidiAutomationValueAtBeat(
|
||||
trackControllerEvents[64],
|
||||
initialPitchBendBeat,
|
||||
0,
|
||||
'step'
|
||||
);
|
||||
audioBus.setLiveMidiSustain(sustainInitialValue >= 64);
|
||||
|
||||
const pitchBendWindowStartBeat = isLooping ? scheduleStartBeat : Math.max(startPosition, 0);
|
||||
const bakedTrackPitchBends = bakeMidiAutomationPointsInWindow(
|
||||
@@ -572,6 +614,62 @@ export class KGAudioInterface {
|
||||
this.scheduledEvents.add(eventId);
|
||||
});
|
||||
|
||||
const bakedExpressionEvents = bakeMidiAutomationPointsInWindow(
|
||||
mergedExpressionEvents,
|
||||
pitchBendWindowStartBeat,
|
||||
scheduleEndBeat,
|
||||
{
|
||||
maxIntervalMs: interpolationIntervalMs,
|
||||
bpm: project.getBpm(),
|
||||
defaultValue: 127,
|
||||
interpolationMode: 'linear',
|
||||
quantizeValue: clampMidiControllerValue,
|
||||
}
|
||||
);
|
||||
|
||||
bakedExpressionEvents.forEach(({ beat, value }) => {
|
||||
if (!isLooping && beat <= pitchBendWindowStartBeat) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventId = Tone.Transport.schedule((time) => {
|
||||
const hasSoloedTracks = this.hasSoloedTracks();
|
||||
if (audioBus.shouldPlayWithSolo(hasSoloedTracks)) {
|
||||
audioBus.scheduleLiveMidiExpression(value / 127, time);
|
||||
}
|
||||
}, this.beatsToToneTime(beat));
|
||||
|
||||
this.scheduledEvents.add(eventId);
|
||||
});
|
||||
|
||||
const bakedSustainEvents = bakeMidiAutomationPointsInWindow(
|
||||
trackControllerEvents[64],
|
||||
pitchBendWindowStartBeat,
|
||||
scheduleEndBeat,
|
||||
{
|
||||
maxIntervalMs: interpolationIntervalMs,
|
||||
bpm: project.getBpm(),
|
||||
defaultValue: 0,
|
||||
interpolationMode: 'step',
|
||||
quantizeValue: clampMidiControllerValue,
|
||||
}
|
||||
);
|
||||
|
||||
bakedSustainEvents.forEach(({ beat, value }) => {
|
||||
if (!isLooping && beat <= pitchBendWindowStartBeat) {
|
||||
return;
|
||||
}
|
||||
|
||||
const eventId = Tone.Transport.schedule((time) => {
|
||||
const hasSoloedTracks = this.hasSoloedTracks();
|
||||
if (audioBus.shouldPlayWithSolo(hasSoloedTracks)) {
|
||||
audioBus.setLiveMidiSustain(value >= 64, time);
|
||||
}
|
||||
}, this.beatsToToneTime(beat));
|
||||
|
||||
this.scheduledEvents.add(eventId);
|
||||
});
|
||||
|
||||
trackNotes.forEach(({ note, absoluteStartBeat, absoluteEndBeat }) => {
|
||||
const noteDurationBeats = absoluteEndBeat - absoluteStartBeat;
|
||||
const noteStartTime = this.beatsToToneTime(absoluteStartBeat);
|
||||
@@ -929,6 +1027,21 @@ export class KGAudioInterface {
|
||||
}
|
||||
}
|
||||
|
||||
public scheduleLiveMidiExpression(trackId: string, normalizedValue: number, time: number): void {
|
||||
try {
|
||||
const audioBus = this.trackAudioBuses.get(trackId);
|
||||
if (!audioBus) {
|
||||
console.warn(`No audio bus found for track ${trackId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
audioBus.scheduleLiveMidiExpression(normalizedValue, time);
|
||||
console.log(`Scheduled live MIDI expression to ${normalizedValue} on track ${trackId}`);
|
||||
} catch (error) {
|
||||
console.error(`Error scheduling live MIDI expression for track ${trackId}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
public setLiveMidiSustain(trackId: string, isDown: boolean, time?: number): void {
|
||||
try {
|
||||
const audioBus = this.trackAudioBuses.get(trackId);
|
||||
|
||||
@@ -6,11 +6,13 @@ import type { KGAudioRegion } from '../region/KGAudioRegion';
|
||||
import type { InstrumentType } from '../track/KGMidiTrack';
|
||||
import { FLUIDR3_INSTRUMENT_MAP } from '../../constants/generalMidiConstants';
|
||||
import { AUDIO_INTERFACE_CONSTANTS } from '../../constants/coreConstants';
|
||||
import { MIDI_PITCH_BEND_CENTER, midiPitchBendToNormalized } from '../../util/midiUtil';
|
||||
import { clampMidiControllerValue, MIDI_PITCH_BEND_CENTER, midiPitchBendToNormalized } from '../../util/midiUtil';
|
||||
import {
|
||||
bakeMidiAutomationPointsInWindow,
|
||||
collectRegionMidiAutomationPoints,
|
||||
normalizeMidiAutomationPoints,
|
||||
resolveMidiAutomationValueAtBeat,
|
||||
resolveSustainExtendedEndBeat,
|
||||
type BakedMidiAutomationPoint,
|
||||
type MidiAutomationPoint,
|
||||
} from '../../util/midiAutomationUtil';
|
||||
@@ -124,6 +126,7 @@ export class KGOfflineRenderer {
|
||||
notes: Array<{ startBeat: number; endBeat: number; durationBeats: number; pitch: number; velocity: number }>;
|
||||
}>;
|
||||
pitchBends: MidiAutomationPoint[];
|
||||
controllerEventsByType: MidiAutomationPoint[][];
|
||||
}> = [];
|
||||
|
||||
const audioTrackData: Array<{
|
||||
@@ -187,8 +190,24 @@ export class KGOfflineRenderer {
|
||||
};
|
||||
})
|
||||
);
|
||||
const controllerEventsByType = Array.from({ length: 128 }, (_, controller) => (
|
||||
collectRegionMidiAutomationPoints(
|
||||
track.getRegions()
|
||||
.filter(region => region.getCurrentType() === 'KGMidiRegion')
|
||||
.map(region => {
|
||||
const midiRegion = region as unknown as { getControllerEvents: (controller: number) => Array<{ getBeat: () => number; getValue: () => number }> };
|
||||
return {
|
||||
startBeat: region.getStartFromBeat(),
|
||||
points: midiRegion.getControllerEvents(controller).map(event => ({
|
||||
beat: event.getBeat(),
|
||||
value: event.getValue(),
|
||||
})),
|
||||
};
|
||||
})
|
||||
)
|
||||
));
|
||||
|
||||
midiTrackData.push({ trackId, instrumentName, volume, muted, solo, regions, pitchBends });
|
||||
midiTrackData.push({ trackId, instrumentName, volume, muted, solo, regions, pitchBends, controllerEventsByType });
|
||||
} else if (track.getType() === 'Wave') {
|
||||
const volume = audioInterface.getTrackVolume(trackId);
|
||||
const muted = audioInterface.getTrackMuted(trackId);
|
||||
@@ -285,6 +304,9 @@ export class KGOfflineRenderer {
|
||||
// Track volumes are stored in dB across the app, with 0 meaning unity gain.
|
||||
sampler.volume.value = getOfflineTrackVolumeDb(trackInfo.volume, trackInfo.muted);
|
||||
sampler.connect(masterGain);
|
||||
const mergedExpressionEvents = normalizeMidiAutomationPoints(
|
||||
[1, 2, 7, 11].flatMap(controller => trackInfo.controllerEventsByType[controller])
|
||||
);
|
||||
const bakedTrackPitchBends = bakeMidiAutomationPointsInWindow(
|
||||
trackInfo.pitchBends,
|
||||
renderStartBeat,
|
||||
@@ -295,6 +317,18 @@ export class KGOfflineRenderer {
|
||||
defaultValue: MIDI_PITCH_BEND_CENTER,
|
||||
}
|
||||
);
|
||||
const bakedExpressionEvents = bakeMidiAutomationPointsInWindow(
|
||||
mergedExpressionEvents,
|
||||
renderStartBeat,
|
||||
renderEndBeat,
|
||||
{
|
||||
maxIntervalMs: interpolationIntervalMs,
|
||||
bpm: project.getBpm(),
|
||||
defaultValue: 127,
|
||||
interpolationMode: 'linear',
|
||||
quantizeValue: clampMidiControllerValue,
|
||||
}
|
||||
);
|
||||
|
||||
// Schedule all notes for this track
|
||||
for (const regionInfo of trackInfo.regions) {
|
||||
@@ -304,27 +338,42 @@ export class KGOfflineRenderer {
|
||||
|
||||
const offsetBeat = note.startBeat - renderStartBeat;
|
||||
const noteStartTime = offsetBeat * secondsPerBeat;
|
||||
const noteDuration = note.durationBeats * secondsPerBeat;
|
||||
const sustainedEndBeat = resolveSustainExtendedEndBeat(
|
||||
trackInfo.controllerEventsByType[64],
|
||||
note.endBeat,
|
||||
0
|
||||
);
|
||||
const noteDuration = Math.max(0, sustainedEndBeat - note.startBeat) * secondsPerBeat;
|
||||
const velocity = note.velocity / 127;
|
||||
const initialNormalizedPitchBend = midiPitchBendToNormalized(
|
||||
resolveMidiAutomationValueAtBeat(trackInfo.pitchBends, note.startBeat, MIDI_PITCH_BEND_CENTER)
|
||||
);
|
||||
const initialExpression = clampMidiControllerValue(
|
||||
resolveMidiAutomationValueAtBeat(mergedExpressionEvents, note.startBeat, 127, 'linear')
|
||||
) / 127;
|
||||
const offlineSource = createOfflinePitchBendAwareSource(
|
||||
sampler,
|
||||
audioBuffers,
|
||||
trackInfo.instrumentName,
|
||||
note.pitch,
|
||||
initialNormalizedPitchBend
|
||||
initialNormalizedPitchBend,
|
||||
initialExpression
|
||||
);
|
||||
if (!offlineSource) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const { source, basePlaybackRate } = offlineSource;
|
||||
const { source, basePlaybackRate, gainNode } = offlineSource;
|
||||
applyOfflinePitchBendAutomation(
|
||||
source,
|
||||
basePlaybackRate,
|
||||
bakedTrackPitchBends.filter(point => point.beat > note.startBeat && point.beat < note.endBeat),
|
||||
bakedTrackPitchBends.filter(point => point.beat > note.startBeat && point.beat < sustainedEndBeat),
|
||||
renderStartBeat,
|
||||
secondsPerBeat
|
||||
);
|
||||
applyOfflineExpressionAutomation(
|
||||
gainNode,
|
||||
bakedExpressionEvents.filter(point => point.beat > note.startBeat && point.beat < sustainedEndBeat),
|
||||
renderStartBeat,
|
||||
secondsPerBeat
|
||||
);
|
||||
@@ -494,13 +543,23 @@ function setOfflinePlaybackRate(
|
||||
playbackRate.value = value;
|
||||
}
|
||||
|
||||
function setOfflineGainValue(gainNode: Tone.Gain, value: number, time: number): void {
|
||||
if (typeof gainNode.gain.setValueAtTime === 'function') {
|
||||
gainNode.gain.setValueAtTime(value, time);
|
||||
return;
|
||||
}
|
||||
|
||||
gainNode.gain.value = value;
|
||||
}
|
||||
|
||||
function createOfflinePitchBendAwareSource(
|
||||
sampler: Tone.Sampler,
|
||||
audioBuffers: Tone.ToneAudioBuffers,
|
||||
instrumentName: InstrumentType,
|
||||
pitch: number,
|
||||
initialNormalizedPitchBend: number
|
||||
): { source: Tone.ToneBufferSource; basePlaybackRate: number } | null {
|
||||
initialNormalizedPitchBend: number,
|
||||
initialExpression: number
|
||||
): { source: Tone.ToneBufferSource; gainNode: Tone.Gain; basePlaybackRate: number } | null {
|
||||
const closestPitch = KGAudioBus.findClosestBufferedPitch(instrumentName, audioBuffers, pitch);
|
||||
if (closestPitch === null) {
|
||||
return null;
|
||||
@@ -513,20 +572,22 @@ function createOfflinePitchBendAwareSource(
|
||||
}
|
||||
|
||||
const basePlaybackRate = Math.pow(2, (pitch - closestPitch) / 12);
|
||||
const gainNode = new Tone.Gain(initialExpression).connect(sampler.output);
|
||||
const source = new Tone.ToneBufferSource({
|
||||
url: buffer,
|
||||
fadeIn: sampler.attack,
|
||||
fadeOut: sampler.release,
|
||||
curve: sampler.curve,
|
||||
playbackRate: KGAudioBus.applyNormalizedPitchBendToPlaybackRate(basePlaybackRate, initialNormalizedPitchBend),
|
||||
}).connect(sampler.output);
|
||||
}).connect(gainNode);
|
||||
setOfflinePlaybackRate(
|
||||
source,
|
||||
KGAudioBus.applyNormalizedPitchBendToPlaybackRate(basePlaybackRate, initialNormalizedPitchBend),
|
||||
0
|
||||
);
|
||||
setOfflineGainValue(gainNode, initialExpression, 0);
|
||||
|
||||
return { source, basePlaybackRate };
|
||||
return { source, gainNode, basePlaybackRate };
|
||||
}
|
||||
|
||||
export function applyOfflinePitchBendAutomation(
|
||||
@@ -546,6 +607,18 @@ export function applyOfflinePitchBendAutomation(
|
||||
});
|
||||
}
|
||||
|
||||
export function applyOfflineExpressionAutomation(
|
||||
gainNode: Tone.Gain,
|
||||
bakedExpressionEvents: BakedMidiAutomationPoint[],
|
||||
renderStartBeat: number,
|
||||
secondsPerBeat: number
|
||||
): void {
|
||||
bakedExpressionEvents.forEach(point => {
|
||||
const automationTime = (point.beat - renderStartBeat) * secondsPerBeat;
|
||||
setOfflineGainValue(gainNode, clampMidiControllerValue(point.value) / 127, automationTime);
|
||||
});
|
||||
}
|
||||
|
||||
export function getOfflineTrackVolumeDb(volumeDb: number, muted: boolean): number {
|
||||
const isSilent = muted || volumeDb <= AUDIO_INTERFACE_CONSTANTS.MIN_TRACK_VOLUME_DB;
|
||||
return isSilent ? -Infinity : volumeDb;
|
||||
|
||||
@@ -37,7 +37,13 @@ export { MoveNotesCommand } from './note/MoveNotesCommand';
|
||||
export { PasteNotesCommand } from './note/PasteNotesCommand';
|
||||
export { UpdateNotePropertiesCommand } from './note/UpdateNotePropertiesCommand';
|
||||
export { UpdatePitchBendPropertiesCommand } from './note/UpdatePitchBendPropertiesCommand';
|
||||
export { CreateMidiEventsCommand, type PitchBendCreationData, type NoteCreationData } from './note/CreateMidiEventsCommand';
|
||||
export { UpdateControllerEventPropertiesCommand } from './note/UpdateControllerEventPropertiesCommand';
|
||||
export {
|
||||
CreateMidiEventsCommand,
|
||||
type PitchBendCreationData,
|
||||
type NoteCreationData,
|
||||
type ControllerEventCreationData
|
||||
} from './note/CreateMidiEventsCommand';
|
||||
|
||||
// Project commands
|
||||
export { ChangeProjectPropertyCommand, type ProjectUpdateProperties } from './project/ChangeProjectPropertyCommand';
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { KGCommand } from '../KGCommand';
|
||||
import { KGCore } from '../../KGCore';
|
||||
import { KGMidiNote } from '../../midi/KGMidiNote';
|
||||
import { KGMidiControllerEvent } from '../../midi/KGMidiControllerEvent';
|
||||
import { KGMidiPitchBend } from '../../midi/KGMidiPitchBend';
|
||||
import { KGMidiRegion } from '../../region/KGMidiRegion';
|
||||
import { KGTrack } from '../../track/KGTrack';
|
||||
@@ -22,13 +23,27 @@ export interface PitchBendCreationData {
|
||||
pitchBendId?: string;
|
||||
}
|
||||
|
||||
export interface ControllerEventCreationData {
|
||||
regionId: string;
|
||||
controller: number;
|
||||
beat: number;
|
||||
value: number;
|
||||
controllerEventId?: string;
|
||||
}
|
||||
|
||||
export class CreateMidiEventsCommand extends KGCommand {
|
||||
private noteCreationData: NoteCreationData[];
|
||||
private pitchBendCreationData: PitchBendCreationData[];
|
||||
private controllerEventCreationData: ControllerEventCreationData[];
|
||||
private createdNotes: Array<{ note: KGMidiNote; regionId: string }> = [];
|
||||
private createdPitchBends: Array<{ pitchBend: KGMidiPitchBend; regionId: string }> = [];
|
||||
private createdControllerEvents: Array<{ controller: number; controllerEvent: KGMidiControllerEvent; regionId: string }> = [];
|
||||
|
||||
constructor(noteCreationData: NoteCreationData[], pitchBendCreationData: PitchBendCreationData[] = []) {
|
||||
constructor(
|
||||
noteCreationData: NoteCreationData[],
|
||||
pitchBendCreationData: PitchBendCreationData[] = [],
|
||||
controllerEventCreationData: ControllerEventCreationData[] = []
|
||||
) {
|
||||
super();
|
||||
this.noteCreationData = noteCreationData.map(data => ({
|
||||
...data,
|
||||
@@ -38,12 +53,17 @@ export class CreateMidiEventsCommand extends KGCommand {
|
||||
...data,
|
||||
pitchBendId: data.pitchBendId || generateUniqueId('KGMidiPitchBend'),
|
||||
}));
|
||||
this.controllerEventCreationData = controllerEventCreationData.map(data => ({
|
||||
...data,
|
||||
controllerEventId: data.controllerEventId || generateUniqueId('KGMidiControllerEvent'),
|
||||
}));
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
const tracks = KGCore.instance().getCurrentProject().getTracks();
|
||||
this.createdNotes = [];
|
||||
this.createdPitchBends = [];
|
||||
this.createdControllerEvents = [];
|
||||
|
||||
for (const noteData of this.noteCreationData) {
|
||||
const targetRegion = this.resolveRegion(tracks, noteData.regionId);
|
||||
@@ -68,6 +88,21 @@ export class CreateMidiEventsCommand extends KGCommand {
|
||||
targetRegion.addPitchBend(newPitchBend);
|
||||
this.createdPitchBends.push({ pitchBend: newPitchBend, regionId: pitchBendData.regionId });
|
||||
}
|
||||
|
||||
for (const controllerEventData of this.controllerEventCreationData) {
|
||||
const targetRegion = this.resolveRegion(tracks, controllerEventData.regionId);
|
||||
const newControllerEvent = new KGMidiControllerEvent(
|
||||
controllerEventData.controllerEventId!,
|
||||
controllerEventData.beat,
|
||||
controllerEventData.value
|
||||
);
|
||||
targetRegion.addControllerEvent(controllerEventData.controller, newControllerEvent);
|
||||
this.createdControllerEvents.push({
|
||||
controller: controllerEventData.controller,
|
||||
controllerEvent: newControllerEvent,
|
||||
regionId: controllerEventData.regionId,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
@@ -91,19 +126,40 @@ export class CreateMidiEventsCommand extends KGCommand {
|
||||
core.removeSelectedItem(selectedPitchBend);
|
||||
}
|
||||
}
|
||||
|
||||
for (const data of this.createdControllerEvents) {
|
||||
const region = this.resolveRegion(tracks, data.regionId);
|
||||
region.removeControllerEvent(data.controller, data.controllerEvent.getId());
|
||||
const selectedControllerEvent = core.getSelectedItems().find(
|
||||
item => item instanceof KGMidiControllerEvent && item.getId() === data.controllerEvent.getId()
|
||||
);
|
||||
if (selectedControllerEvent) {
|
||||
core.removeSelectedItem(selectedControllerEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getDescription(): string {
|
||||
const noteCount = this.noteCreationData.length;
|
||||
const pitchBendCount = this.pitchBendCreationData.length;
|
||||
const controllerEventCount = this.controllerEventCreationData.length;
|
||||
|
||||
if (noteCount > 0 && pitchBendCount > 0) {
|
||||
return `Create ${noteCount} note${noteCount === 1 ? '' : 's'} and ${pitchBendCount} pitch bend${pitchBendCount === 1 ? '' : 's'}`;
|
||||
const parts: string[] = [];
|
||||
if (noteCount > 0) {
|
||||
parts.push(`${noteCount} note${noteCount === 1 ? '' : 's'}`);
|
||||
}
|
||||
if (pitchBendCount > 0) {
|
||||
return pitchBendCount === 1 ? 'Create pitch bend' : `Create ${pitchBendCount} pitch bends`;
|
||||
parts.push(`${pitchBendCount} pitch bend${pitchBendCount === 1 ? '' : 's'}`);
|
||||
}
|
||||
return noteCount === 1 ? 'Create note' : `Create ${noteCount} notes`;
|
||||
if (controllerEventCount > 0) {
|
||||
parts.push(`${controllerEventCount} controller event${controllerEventCount === 1 ? '' : 's'}`);
|
||||
}
|
||||
|
||||
if (parts.length === 0) {
|
||||
return 'Create MIDI events';
|
||||
}
|
||||
|
||||
return `Create ${parts.join(' and ')}`;
|
||||
}
|
||||
|
||||
public getNoteCreationData(): NoteCreationData[] {
|
||||
@@ -118,6 +174,10 @@ export class CreateMidiEventsCommand extends KGCommand {
|
||||
return this.createdPitchBends;
|
||||
}
|
||||
|
||||
public getCreatedControllerEvents(): Array<{ controller: number; controllerEvent: KGMidiControllerEvent; regionId: string }> {
|
||||
return this.createdControllerEvents;
|
||||
}
|
||||
|
||||
public getCreatedNoteIds(): string[] {
|
||||
return this.noteCreationData.map(data => data.noteId!);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { KGCommand } from '../KGCommand';
|
||||
import { KGCore } from '../../KGCore';
|
||||
import { KGMidiControllerEvent } from '../../midi/KGMidiControllerEvent';
|
||||
import { KGMidiNote } from '../../midi/KGMidiNote';
|
||||
import { KGMidiPitchBend } from '../../midi/KGMidiPitchBend';
|
||||
import { KGMidiRegion } from '../../region/KGMidiRegion';
|
||||
@@ -16,16 +17,26 @@ interface DeletedPitchBendData {
|
||||
originalIndex: number;
|
||||
}
|
||||
|
||||
interface DeletedControllerEventData {
|
||||
controller: number;
|
||||
controllerEvent: KGMidiControllerEvent;
|
||||
regionId: string;
|
||||
originalIndex: number;
|
||||
}
|
||||
|
||||
export class DeleteMidiEventsCommand extends KGCommand {
|
||||
private noteIds: string[];
|
||||
private pitchBendIds: string[];
|
||||
private controllerEventIds: string[];
|
||||
private deletedNoteData: DeletedNoteData[] = [];
|
||||
private deletedPitchBendData: DeletedPitchBendData[] = [];
|
||||
private deletedControllerEventData: DeletedControllerEventData[] = [];
|
||||
|
||||
constructor(noteIds: string[] = [], pitchBendIds: string[] = []) {
|
||||
constructor(noteIds: string[] = [], pitchBendIds: string[] = [], controllerEventIds: string[] = []) {
|
||||
super();
|
||||
this.noteIds = noteIds;
|
||||
this.pitchBendIds = pitchBendIds;
|
||||
this.controllerEventIds = controllerEventIds;
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
@@ -34,6 +45,7 @@ export class DeleteMidiEventsCommand extends KGCommand {
|
||||
|
||||
this.deletedNoteData = [];
|
||||
this.deletedPitchBendData = [];
|
||||
this.deletedControllerEventData = [];
|
||||
|
||||
for (const noteId of this.noteIds) {
|
||||
for (const track of tracks) {
|
||||
@@ -71,12 +83,35 @@ export class DeleteMidiEventsCommand extends KGCommand {
|
||||
}
|
||||
}
|
||||
|
||||
if (this.deletedNoteData.length === 0 && this.deletedPitchBendData.length === 0) {
|
||||
for (const controllerEventId of this.controllerEventIds) {
|
||||
for (const track of tracks) {
|
||||
for (const region of track.getRegions()) {
|
||||
if (!(region instanceof KGMidiRegion)) continue;
|
||||
|
||||
const flattened = region.getAllControllerEventsFlattened();
|
||||
const flattenedIndex = flattened.findIndex(({ event }) => event.getId() === controllerEventId);
|
||||
if (flattenedIndex === -1) continue;
|
||||
|
||||
const { controller, event } = flattened[flattenedIndex];
|
||||
const originalIndex = region.getControllerEvents(controller).findIndex(candidate => candidate.getId() === controllerEventId);
|
||||
this.deletedControllerEventData.push({
|
||||
controller,
|
||||
controllerEvent: event,
|
||||
regionId: region.getId(),
|
||||
originalIndex,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this.deletedNoteData.length === 0 && this.deletedPitchBendData.length === 0 && this.deletedControllerEventData.length === 0) {
|
||||
throw new Error('No MIDI events found to delete');
|
||||
}
|
||||
|
||||
this.deletedNoteData.sort((a, b) => b.originalIndex - a.originalIndex);
|
||||
this.deletedPitchBendData.sort((a, b) => b.originalIndex - a.originalIndex);
|
||||
this.deletedControllerEventData.sort((a, b) => b.originalIndex - a.originalIndex);
|
||||
|
||||
for (const data of this.deletedNoteData) {
|
||||
const region = this.resolveRegion(tracks, data.regionId);
|
||||
@@ -99,6 +134,18 @@ export class DeleteMidiEventsCommand extends KGCommand {
|
||||
core.removeSelectedItem(selectedPitchBend);
|
||||
}
|
||||
}
|
||||
|
||||
for (const data of this.deletedControllerEventData) {
|
||||
const region = this.resolveRegion(tracks, data.regionId);
|
||||
region.removeControllerEvent(data.controller, data.controllerEvent.getId());
|
||||
|
||||
const selectedControllerEvent = core.getSelectedItems().find(
|
||||
item => item instanceof KGMidiControllerEvent && item.getId() === data.controllerEvent.getId()
|
||||
);
|
||||
if (selectedControllerEvent) {
|
||||
core.removeSelectedItem(selectedControllerEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
@@ -125,19 +172,39 @@ export class DeleteMidiEventsCommand extends KGCommand {
|
||||
region.addPitchBend(data.pitchBend);
|
||||
}
|
||||
}
|
||||
|
||||
for (const data of [...this.deletedControllerEventData].sort((a, b) => a.originalIndex - b.originalIndex)) {
|
||||
const region = this.resolveRegion(tracks, data.regionId);
|
||||
const controllerEvents = region.getControllerEvents(data.controller);
|
||||
if (data.originalIndex >= 0 && data.originalIndex <= controllerEvents.length) {
|
||||
controllerEvents.splice(data.originalIndex, 0, data.controllerEvent);
|
||||
region.setControllerEvents(data.controller, controllerEvents);
|
||||
} else {
|
||||
region.addControllerEvent(data.controller, data.controllerEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getDescription(): string {
|
||||
const noteCount = this.noteIds.length;
|
||||
const pitchBendCount = this.pitchBendIds.length;
|
||||
|
||||
if (noteCount > 0 && pitchBendCount > 0) {
|
||||
return `Delete ${noteCount} note${noteCount === 1 ? '' : 's'} and ${pitchBendCount} pitch bend${pitchBendCount === 1 ? '' : 's'}`;
|
||||
const controllerEventCount = this.controllerEventIds.length;
|
||||
const parts: string[] = [];
|
||||
if (noteCount > 0) {
|
||||
parts.push(`${noteCount} note${noteCount === 1 ? '' : 's'}`);
|
||||
}
|
||||
if (pitchBendCount > 0) {
|
||||
return pitchBendCount === 1 ? 'Delete pitch bend' : `Delete ${pitchBendCount} pitch bends`;
|
||||
parts.push(`${pitchBendCount} pitch bend${pitchBendCount === 1 ? '' : 's'}`);
|
||||
}
|
||||
return noteCount === 1 ? 'Delete note' : `Delete ${noteCount} notes`;
|
||||
if (controllerEventCount > 0) {
|
||||
parts.push(`${controllerEventCount} controller event${controllerEventCount === 1 ? '' : 's'}`);
|
||||
}
|
||||
|
||||
if (parts.length === 0) {
|
||||
return 'Delete MIDI events';
|
||||
}
|
||||
|
||||
return `Delete ${parts.join(' and ')}`;
|
||||
}
|
||||
|
||||
private resolveRegion(tracks: Array<{ getRegions(): unknown[] }>, regionId: string): KGMidiRegion {
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
import { KGCommand } from '../KGCommand';
|
||||
import { KGCore } from '../../KGCore';
|
||||
import { KGMidiControllerEvent } from '../../midi/KGMidiControllerEvent';
|
||||
import { KGMidiRegion } from '../../region/KGMidiRegion';
|
||||
import { KGTrack } from '../../track/KGTrack';
|
||||
|
||||
interface ControllerEventSnapshot {
|
||||
controllerEventId: string;
|
||||
controller: number;
|
||||
beat: number;
|
||||
value: number;
|
||||
}
|
||||
|
||||
interface ControllerEventUpdate {
|
||||
controllerEventId: string;
|
||||
controller?: number;
|
||||
beat?: number;
|
||||
value?: number;
|
||||
}
|
||||
|
||||
export class UpdateControllerEventPropertiesCommand extends KGCommand {
|
||||
private regionId: string;
|
||||
private snapshots: ControllerEventSnapshot[];
|
||||
private updates: ControllerEventUpdate[];
|
||||
private targetRegion: KGMidiRegion | null = null;
|
||||
private parentTrack: KGTrack | null = null;
|
||||
|
||||
constructor(regionId: string, snapshots: ControllerEventSnapshot[], updates: ControllerEventUpdate[]) {
|
||||
super();
|
||||
this.regionId = regionId;
|
||||
this.snapshots = [...snapshots];
|
||||
this.updates = [...updates];
|
||||
}
|
||||
|
||||
execute(): void {
|
||||
const tracks = KGCore.instance().getCurrentProject().getTracks();
|
||||
|
||||
for (const track of tracks) {
|
||||
const region = track.getRegions().find(r => r.getId() === this.regionId) as KGMidiRegion | undefined;
|
||||
if (region) {
|
||||
this.targetRegion = region;
|
||||
this.parentTrack = track;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.targetRegion) {
|
||||
throw new Error(`Region with ID ${this.regionId} not found`);
|
||||
}
|
||||
|
||||
for (const update of this.updates) {
|
||||
const currentController = this.snapshots.find(snapshot => snapshot.controllerEventId === update.controllerEventId)?.controller;
|
||||
if (currentController === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const event = this.findControllerEvent(currentController, update.controllerEventId);
|
||||
if (!event) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (update.controller !== undefined && update.controller !== currentController) {
|
||||
this.targetRegion.removeControllerEvent(currentController, event.getId());
|
||||
this.targetRegion.addControllerEvent(update.controller, event);
|
||||
}
|
||||
|
||||
if (update.beat !== undefined) event.setBeat(update.beat);
|
||||
if (update.value !== undefined) event.setValue(update.value);
|
||||
}
|
||||
}
|
||||
|
||||
undo(): void {
|
||||
if (!this.targetRegion) {
|
||||
throw new Error('Cannot undo: command was not executed');
|
||||
}
|
||||
|
||||
this.snapshots.forEach(snapshot => {
|
||||
const existing = this.findControllerEventAcrossBuckets(snapshot.controllerEventId);
|
||||
if (!existing) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing.controller !== snapshot.controller) {
|
||||
this.targetRegion!.removeControllerEvent(existing.controller, existing.event.getId());
|
||||
this.targetRegion!.addControllerEvent(snapshot.controller, existing.event);
|
||||
}
|
||||
|
||||
existing.event.setBeat(snapshot.beat);
|
||||
existing.event.setValue(snapshot.value);
|
||||
});
|
||||
}
|
||||
|
||||
getDescription(): string {
|
||||
const count = this.snapshots.length;
|
||||
return count === 1 ? 'Update controller event properties' : `Update ${count} controller events' properties`;
|
||||
}
|
||||
|
||||
public getParentTrack(): KGTrack | null {
|
||||
return this.parentTrack;
|
||||
}
|
||||
|
||||
private findControllerEvent(controller: number, controllerEventId: string): KGMidiControllerEvent | undefined {
|
||||
return this.targetRegion?.getControllerEvents(controller).find(candidate => candidate.getId() === controllerEventId);
|
||||
}
|
||||
|
||||
private findControllerEventAcrossBuckets(controllerEventId: string): { controller: number; event: KGMidiControllerEvent } | null {
|
||||
if (!this.targetRegion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const { controller, event } of this.targetRegion.getAllControllerEventsFlattened()) {
|
||||
if (event.getId() === controllerEventId) {
|
||||
return { controller, event };
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { KGCommand } from '../KGCommand';
|
||||
import { KGCore } from '../../KGCore';
|
||||
import { KGMidiRegion } from '../../region/KGMidiRegion';
|
||||
import { KGMidiControllerEvent } from '../../midi/KGMidiControllerEvent';
|
||||
import { KGMidiNote } from '../../midi/KGMidiNote';
|
||||
import { KGMidiPitchBend } from '../../midi/KGMidiPitchBend';
|
||||
import { KGTrack } from '../../track/KGTrack';
|
||||
@@ -22,6 +23,11 @@ interface RegionSnapshot {
|
||||
beat: number;
|
||||
value: number;
|
||||
}>;
|
||||
controllerEventsByType: Array<Array<{
|
||||
id: string;
|
||||
beat: number;
|
||||
value: number;
|
||||
}>>;
|
||||
}
|
||||
|
||||
interface ResolvedRegion {
|
||||
@@ -47,6 +53,14 @@ function clonePitchBend(pitchBend: KGMidiPitchBend, beat: number): KGMidiPitchBe
|
||||
);
|
||||
}
|
||||
|
||||
function cloneControllerEvent(controllerEvent: KGMidiControllerEvent, beat: number): KGMidiControllerEvent {
|
||||
return new KGMidiControllerEvent(
|
||||
controllerEvent.getId(),
|
||||
beat,
|
||||
controllerEvent.getValue()
|
||||
);
|
||||
}
|
||||
|
||||
export class MergeMidiRegionsCommand extends KGCommand {
|
||||
private readonly regionIdsToMerge: string[];
|
||||
private targetTrack: KGTrack | null = null;
|
||||
@@ -121,6 +135,13 @@ export class MergeMidiRegionsCommand extends KGCommand {
|
||||
beat: pitchBend.getBeat(),
|
||||
value: pitchBend.getValue(),
|
||||
})),
|
||||
controllerEventsByType: region.getControllerEventsByType().map(events => (
|
||||
events.map(event => ({
|
||||
id: event.getId(),
|
||||
beat: event.getBeat(),
|
||||
value: event.getValue(),
|
||||
}))
|
||||
)),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -136,6 +157,7 @@ export class MergeMidiRegionsCommand extends KGCommand {
|
||||
|
||||
const mergedNotes = [...this.survivingRegion.getNotes()];
|
||||
const mergedPitchBends = [...this.survivingRegion.getPitchBends()];
|
||||
const mergedControllerEventsByType = this.survivingRegion.getControllerEventsByType().map(events => [...events]);
|
||||
for (const { region } of resolvedRegions.slice(1)) {
|
||||
const regionStart = region.getStartFromBeat();
|
||||
region.getNotes().forEach(note => {
|
||||
@@ -153,11 +175,20 @@ export class MergeMidiRegionsCommand extends KGCommand {
|
||||
regionStart + pitchBend.getBeat() - survivingRegionStart
|
||||
));
|
||||
});
|
||||
region.getControllerEventsByType().forEach((events, controller) => {
|
||||
events.forEach(event => {
|
||||
mergedControllerEventsByType[controller].push(cloneControllerEvent(
|
||||
event,
|
||||
regionStart + event.getBeat() - survivingRegionStart
|
||||
));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
this.survivingRegion.setLength(mergedEndBeat - survivingRegionStart);
|
||||
this.survivingRegion.setNotes(mergedNotes);
|
||||
this.survivingRegion.setPitchBends(mergedPitchBends);
|
||||
this.survivingRegion.setControllerEventsByType(mergedControllerEventsByType);
|
||||
|
||||
const removedRegionIds = new Set(this.removedRegions.map(({ region }) => region.getId()));
|
||||
const nextRegions = resolvedTargetTrack.getRegions().filter(region => !removedRegionIds.has(region.getId()));
|
||||
@@ -197,6 +228,13 @@ export class MergeMidiRegionsCommand extends KGCommand {
|
||||
pitchBend.beat,
|
||||
pitchBend.value
|
||||
)));
|
||||
this.survivingRegion.setControllerEventsByType(survivingSnapshot.controllerEventsByType.map(events => (
|
||||
events.map(event => new KGMidiControllerEvent(
|
||||
event.id,
|
||||
event.beat,
|
||||
event.value
|
||||
))
|
||||
)));
|
||||
|
||||
for (const { region } of this.removedRegions) {
|
||||
const snapshot = this.originalRegionSnapshots.get(region.getId());
|
||||
@@ -217,6 +255,13 @@ export class MergeMidiRegionsCommand extends KGCommand {
|
||||
pitchBend.beat,
|
||||
pitchBend.value
|
||||
)));
|
||||
region.setControllerEventsByType(snapshot.controllerEventsByType.map(events => (
|
||||
events.map(event => new KGMidiControllerEvent(
|
||||
event.id,
|
||||
event.beat,
|
||||
event.value
|
||||
))
|
||||
)));
|
||||
}
|
||||
|
||||
const regions = [...this.targetTrack.getRegions()];
|
||||
|
||||
@@ -2,6 +2,7 @@ import { KGCommand } from '../KGCommand';
|
||||
import { KGCore } from '../../KGCore';
|
||||
import { KGRegion } from '../../region/KGRegion';
|
||||
import { KGMidiRegion } from '../../region/KGMidiRegion';
|
||||
import { KGMidiControllerEvent } from '../../midi/KGMidiControllerEvent';
|
||||
import { KGMidiNote } from '../../midi/KGMidiNote';
|
||||
import { KGMidiPitchBend } from '../../midi/KGMidiPitchBend';
|
||||
import { KGTrack } from '../../track/KGTrack';
|
||||
@@ -90,6 +91,15 @@ export class PasteRegionsCommand extends KGCommand {
|
||||
pitchBend.getValue()
|
||||
));
|
||||
});
|
||||
originalRegion.getControllerEventsByType().forEach((events, controller) => {
|
||||
events.forEach(controllerEvent => {
|
||||
(newRegion as KGMidiRegion).addControllerEvent(controller, new KGMidiControllerEvent(
|
||||
generateUniqueId('KGMidiControllerEvent'),
|
||||
controllerEvent.getBeat(),
|
||||
controllerEvent.getValue()
|
||||
));
|
||||
});
|
||||
});
|
||||
|
||||
console.log(`Created MIDI region "${newRegion.getName()}" with ${originalNotes.length} notes`);
|
||||
} else {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { KGCore } from '../../KGCore';
|
||||
import { KGRegion } from '../../region/KGRegion';
|
||||
import { KGMidiRegion } from '../../region/KGMidiRegion';
|
||||
import { KGAudioRegion } from '../../region/KGAudioRegion';
|
||||
import { KGMidiControllerEvent } from '../../midi/KGMidiControllerEvent';
|
||||
import { KGMidiNote } from '../../midi/KGMidiNote';
|
||||
import { KGMidiPitchBend } from '../../midi/KGMidiPitchBend';
|
||||
|
||||
@@ -28,6 +29,11 @@ export class ResizeRegionCommand extends KGCommand {
|
||||
pitchBendId: string;
|
||||
originalBeat: number;
|
||||
}> = [];
|
||||
private controllerEventAdjustments: Array<{
|
||||
controller: number;
|
||||
controllerEventId: string;
|
||||
originalBeat: number;
|
||||
}> = [];
|
||||
|
||||
// Audio region clip offset support
|
||||
private newClipStartOffsetSeconds?: number;
|
||||
@@ -93,6 +99,16 @@ export class ResizeRegionCommand extends KGCommand {
|
||||
});
|
||||
pitchBend.setBeat(pitchBend.getBeat() - beatOffset);
|
||||
});
|
||||
targetRegion.getControllerEventsByType().forEach((events, controller) => {
|
||||
events.forEach((controllerEvent: KGMidiControllerEvent) => {
|
||||
this.controllerEventAdjustments.push({
|
||||
controller,
|
||||
controllerEventId: controllerEvent.getId(),
|
||||
originalBeat: controllerEvent.getBeat(),
|
||||
});
|
||||
controllerEvent.setBeat(controllerEvent.getBeat() - beatOffset);
|
||||
});
|
||||
});
|
||||
|
||||
console.log(`Adjusted ${notes.length} notes by offset ${-beatOffset} beats to maintain absolute positions`);
|
||||
}
|
||||
@@ -143,6 +159,16 @@ export class ResizeRegionCommand extends KGCommand {
|
||||
}
|
||||
});
|
||||
}
|
||||
if (this.controllerEventAdjustments.length > 0 && this.targetRegion instanceof KGMidiRegion) {
|
||||
const midiRegion = this.targetRegion;
|
||||
this.controllerEventAdjustments.forEach(adjustment => {
|
||||
const controllerEvent = midiRegion.getControllerEvents(adjustment.controller)
|
||||
.find(candidate => candidate.getId() === adjustment.controllerEventId);
|
||||
if (controllerEvent) {
|
||||
controllerEvent.setBeat(adjustment.originalBeat);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Restore clip offset for audio regions
|
||||
if (this.targetRegion instanceof KGAudioRegion && this.newClipStartOffsetSeconds !== undefined) {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { KGCore } from '../../KGCore';
|
||||
import { KGRegion } from '../../region/KGRegion';
|
||||
import { KGMidiRegion } from '../../region/KGMidiRegion';
|
||||
import { KGAudioRegion } from '../../region/KGAudioRegion';
|
||||
import { KGMidiControllerEvent } from '../../midi/KGMidiControllerEvent';
|
||||
import { KGMidiNote } from '../../midi/KGMidiNote';
|
||||
import { KGMidiPitchBend } from '../../midi/KGMidiPitchBend';
|
||||
import { KGTrack } from '../../track/KGTrack';
|
||||
@@ -131,6 +132,22 @@ export class SplitRegionCommand extends KGCommand {
|
||||
}
|
||||
}
|
||||
|
||||
for (const { controller, event } of originalRegion.getAllControllerEventsFlattened()) {
|
||||
if (event.getBeat() < splitOffsetBeats) {
|
||||
region1.addControllerEvent(controller, new KGMidiControllerEvent(
|
||||
generateUniqueId('KGMidiControllerEvent'),
|
||||
event.getBeat(),
|
||||
event.getValue()
|
||||
));
|
||||
} else {
|
||||
region2.addControllerEvent(controller, new KGMidiControllerEvent(
|
||||
generateUniqueId('KGMidiControllerEvent'),
|
||||
event.getBeat() - splitOffsetBeats,
|
||||
event.getValue()
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
this.region1 = region1;
|
||||
this.region2 = region2;
|
||||
|
||||
|
||||
@@ -30,6 +30,12 @@ interface PitchBendAdjustment {
|
||||
originalBeat: number;
|
||||
}
|
||||
|
||||
interface ControllerEventAdjustment {
|
||||
controller: number;
|
||||
controllerEventId: string;
|
||||
originalBeat: number;
|
||||
}
|
||||
|
||||
const EPSILON = 1e-9;
|
||||
|
||||
function getRegionById(tracks: KGTrack[], regionId: string): { region: KGRegion; track: KGTrack } | null {
|
||||
@@ -174,6 +180,7 @@ export class ResizeMultipleRegionsCommand extends KGCommand {
|
||||
private targetRegions: KGRegion[] = [];
|
||||
private noteAdjustments = new Map<string, NoteAdjustment[]>();
|
||||
private pitchBendAdjustments = new Map<string, PitchBendAdjustment[]>();
|
||||
private controllerEventAdjustments = new Map<string, ControllerEventAdjustment[]>();
|
||||
|
||||
constructor(
|
||||
primaryRegionId: string,
|
||||
@@ -272,6 +279,8 @@ export class ResizeMultipleRegionsCommand extends KGCommand {
|
||||
}));
|
||||
this.targetRegions = resolvedRegions.map(({ region }) => region);
|
||||
this.noteAdjustments.clear();
|
||||
this.pitchBendAdjustments.clear();
|
||||
this.controllerEventAdjustments.clear();
|
||||
|
||||
projectedStates.forEach(projectedState => {
|
||||
const region = projectedState.region;
|
||||
@@ -295,6 +304,16 @@ export class ResizeMultipleRegionsCommand extends KGCommand {
|
||||
region.getPitchBends().forEach(pitchBend => {
|
||||
pitchBend.setBeat(pitchBend.getBeat() - beatOffset);
|
||||
});
|
||||
this.controllerEventAdjustments.set(region.getId(), region.getAllControllerEventsFlattened().map(({ controller, event }) => ({
|
||||
controller,
|
||||
controllerEventId: event.getId(),
|
||||
originalBeat: event.getBeat(),
|
||||
})));
|
||||
region.getControllerEventsByType().forEach(events => {
|
||||
events.forEach(event => {
|
||||
event.setBeat(event.getBeat() - beatOffset);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (region instanceof KGAudioRegion && projectedState.clipStartOffsetSeconds !== undefined) {
|
||||
@@ -335,6 +354,14 @@ export class ResizeMultipleRegionsCommand extends KGCommand {
|
||||
pitchBend.setBeat(adjustment.originalBeat);
|
||||
}
|
||||
});
|
||||
const controllerEventAdjustments = this.controllerEventAdjustments.get(region.getId()) ?? [];
|
||||
controllerEventAdjustments.forEach(adjustment => {
|
||||
const controllerEvent = region.getControllerEvents(adjustment.controller)
|
||||
.find(candidate => candidate.getId() === adjustment.controllerEventId);
|
||||
if (controllerEvent) {
|
||||
controllerEvent.setBeat(adjustment.originalBeat);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (region instanceof KGAudioRegion && originalState.clipStartOffsetSeconds !== undefined) {
|
||||
|
||||
@@ -29,6 +29,7 @@ export class KGMidiInput {
|
||||
private onRecordNoteOn: ((pitch: number, velocity: number) => void) | null = null;
|
||||
private onRecordNoteOff: ((pitch: number) => void) | null = null;
|
||||
private onRecordPitchBend: ((value: number) => void) | null = null;
|
||||
private onRecordControlChange: ((controller: number, value: number) => void) | null = null;
|
||||
private liveNoteTrackOwnership: Map<number, string[]> = new Map();
|
||||
private sustainPolarityInverted: boolean | null = null;
|
||||
|
||||
@@ -288,13 +289,17 @@ export class KGMidiInput {
|
||||
}
|
||||
|
||||
if (controller === KGMidiInput.CONTROL_CHANGE_SUSTAIN) {
|
||||
const isPressed = this.normalizeSustainPedalValue(value);
|
||||
this.onRecordControlChange?.(controller, isPressed ? 127 : 0);
|
||||
audioInterface.setLiveMidiSustain(
|
||||
selectedTrackId,
|
||||
this.normalizeSustainPedalValue(value)
|
||||
isPressed
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
this.onRecordControlChange?.(controller, value);
|
||||
|
||||
if (
|
||||
controller === KGMidiInput.CONTROL_CHANGE_MODULATION ||
|
||||
controller === KGMidiInput.CONTROL_CHANGE_BREATH ||
|
||||
@@ -381,11 +386,13 @@ export class KGMidiInput {
|
||||
public setRecordingCallbacks(
|
||||
onNoteOn: ((pitch: number, velocity: number) => void) | null,
|
||||
onNoteOff: ((pitch: number) => void) | null,
|
||||
onPitchBend: ((value: number) => void) | null = null
|
||||
onPitchBend: ((value: number) => void) | null = null,
|
||||
onControlChange: ((controller: number, value: number) => void) | null = null
|
||||
): void {
|
||||
this.onRecordNoteOn = onNoteOn;
|
||||
this.onRecordNoteOff = onNoteOff;
|
||||
this.onRecordPitchBend = onPitchBend;
|
||||
this.onRecordControlChange = onControlChange;
|
||||
}
|
||||
|
||||
// ===== GETTERS =====
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { KGMidiControllerEvent } from './KGMidiControllerEvent';
|
||||
|
||||
describe('KGMidiControllerEvent', () => {
|
||||
it('stores beat and raw controller value', () => {
|
||||
const event = new KGMidiControllerEvent('cc-1', 1.5, 64);
|
||||
|
||||
expect(event.getId()).toBe('cc-1');
|
||||
expect(event.getBeat()).toBe(1.5);
|
||||
expect(event.getValue()).toBe(64);
|
||||
expect(event.getCurrentType()).toBe('KGMidiControllerEvent');
|
||||
});
|
||||
|
||||
it('supports selection state', () => {
|
||||
const event = new KGMidiControllerEvent('cc-1', 0, 127);
|
||||
|
||||
expect(event.isSelected()).toBe(false);
|
||||
event.select();
|
||||
expect(event.isSelected()).toBe(true);
|
||||
event.deselect();
|
||||
expect(event.isSelected()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Expose } from 'class-transformer';
|
||||
import type { Selectable } from '../../components/interfaces';
|
||||
|
||||
export class KGMidiControllerEvent implements Selectable {
|
||||
@Expose()
|
||||
private id: string = '';
|
||||
|
||||
@Expose()
|
||||
private beat: number = 0;
|
||||
|
||||
@Expose()
|
||||
private value: number = 0;
|
||||
|
||||
@Expose()
|
||||
private selected: boolean = false;
|
||||
|
||||
constructor(id: string, beat: number = 0, value: number = 0) {
|
||||
this.id = id;
|
||||
this.beat = beat;
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public getId(): string {
|
||||
return this.id;
|
||||
}
|
||||
|
||||
public getBeat(): number {
|
||||
return this.beat;
|
||||
}
|
||||
|
||||
public getValue(): number {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
public setId(id: string): void {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public setBeat(beat: number): void {
|
||||
this.beat = beat;
|
||||
}
|
||||
|
||||
public setValue(value: number): void {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
public select(): void {
|
||||
this.selected = true;
|
||||
}
|
||||
|
||||
public deselect(): void {
|
||||
this.selected = false;
|
||||
}
|
||||
|
||||
public isSelected(): boolean {
|
||||
return this.selected;
|
||||
}
|
||||
|
||||
public getRootType(): string {
|
||||
return 'KGMidiControllerEvent';
|
||||
}
|
||||
|
||||
public getCurrentType(): string {
|
||||
return 'KGMidiControllerEvent';
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { upgradeToV5 } from './upgradeToV5';
|
||||
import { upgradeToV6 } from './upgradeToV6';
|
||||
import { upgradeToV7 } from './upgradeToV7';
|
||||
import { upgradeToV8 } from './upgradeToV8';
|
||||
import { upgradeToV9 } from './upgradeToV9';
|
||||
|
||||
/**
|
||||
* Upgrade the given project to the latest structure version, one version at a time.
|
||||
@@ -58,6 +59,10 @@ export function upgradeProjectToLatest(project: KGProject): KGProject {
|
||||
workingProject = upgradeToV8(workingProject);
|
||||
break;
|
||||
}
|
||||
case 9: {
|
||||
workingProject = upgradeToV9(workingProject);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
// If an upgrader is missing, throw to prevent loading incompatible structures
|
||||
throw new Error(`No upgrader found for project structure version ${nextVersion}`);
|
||||
|
||||
@@ -57,7 +57,8 @@ describe('upgradeToV8', () => {
|
||||
|
||||
const upgraded = upgradeProjectToLatest(project);
|
||||
|
||||
expect(upgraded.getProjectStructureVersion()).toBe(8);
|
||||
expect(upgraded.getProjectStructureVersion()).toBe(9);
|
||||
expect((upgraded.getTracks()[0].getRegions()[0] as KGMidiRegion).getPitchBends()).toEqual([]);
|
||||
expect((upgraded.getTracks()[0].getRegions()[0] as KGMidiRegion).getControllerEventsByType()).toHaveLength(128);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { KGProject } from '../KGProject';
|
||||
import { KGMidiRegion } from '../region/KGMidiRegion';
|
||||
|
||||
export function upgradeToV9(project: KGProject): KGProject {
|
||||
try {
|
||||
for (const track of project.getTracks()) {
|
||||
for (const region of track.getRegions()) {
|
||||
if (region instanceof KGMidiRegion) {
|
||||
const candidate = (region as unknown as { controllerEventsByType?: unknown }).controllerEventsByType;
|
||||
if (!Array.isArray(candidate) || candidate.length !== 128) {
|
||||
region.setControllerEventsByType([]);
|
||||
} else {
|
||||
region.setControllerEventsByType(candidate as never);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
project.setProjectStructureVersion(9);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { KGMidiRegion } from './KGMidiRegion';
|
||||
import { KGRegion } from './KGRegion';
|
||||
import { KGMidiNote } from '../midi/KGMidiNote';
|
||||
import { KGMidiPitchBend } from '../midi/KGMidiPitchBend';
|
||||
import { KGMidiControllerEvent } from '../midi/KGMidiControllerEvent';
|
||||
import { createMockMidiNote } from '../../test/utils/mock-data';
|
||||
|
||||
describe('KGMidiRegion', () => {
|
||||
@@ -249,6 +250,40 @@ describe('KGMidiRegion', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('controller event management', () => {
|
||||
let controllerEvent1: KGMidiControllerEvent;
|
||||
let controllerEvent2: KGMidiControllerEvent;
|
||||
|
||||
beforeEach(() => {
|
||||
controllerEvent1 = new KGMidiControllerEvent('cc-1', 0.5, 127);
|
||||
controllerEvent2 = new KGMidiControllerEvent('cc-2', 1.5, 32);
|
||||
});
|
||||
|
||||
it('adds and returns controller events by controller number', () => {
|
||||
region.addControllerEvent(11, controllerEvent1);
|
||||
region.addControllerEvent(11, controllerEvent2);
|
||||
|
||||
expect(region.getControllerEvents(11)).toEqual([controllerEvent1, controllerEvent2]);
|
||||
});
|
||||
|
||||
it('removes controller events by id within a controller bucket', () => {
|
||||
region.setControllerEvents(11, [controllerEvent1, controllerEvent2]);
|
||||
region.removeControllerEvent(11, 'cc-1');
|
||||
|
||||
expect(region.getControllerEvents(11)).toEqual([controllerEvent2]);
|
||||
});
|
||||
|
||||
it('flattens controller events with their controller numbers for UI use', () => {
|
||||
region.addControllerEvent(2, controllerEvent1);
|
||||
region.addControllerEvent(11, controllerEvent2);
|
||||
|
||||
expect(region.getAllControllerEventsFlattened()).toEqual([
|
||||
{ controller: 2, event: controllerEvent1 },
|
||||
{ controller: 11, event: controllerEvent2 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('inheritance from KGRegion', () => {
|
||||
it('should inherit all base region properties', () => {
|
||||
expect(region.getId()).toBe('test-region-1');
|
||||
@@ -388,6 +423,7 @@ describe('KGMidiRegion', () => {
|
||||
it('preserves pitch bends through class-transformer serialization', () => {
|
||||
region.addNote(createMockMidiNote({ id: 'note-1', pitch: 60, startBeat: 0, endBeat: 1 }));
|
||||
region.addPitchBend(new KGMidiPitchBend('bend-1', 0.5, 12288));
|
||||
region.addControllerEvent(11, new KGMidiControllerEvent('cc-1', 0.25, 96));
|
||||
|
||||
const plain = instanceToPlain(region);
|
||||
const restored = plainToInstance(KGMidiRegion, plain);
|
||||
@@ -396,6 +432,9 @@ describe('KGMidiRegion', () => {
|
||||
expect(restored.getPitchBends()).toHaveLength(1);
|
||||
expect(restored.getPitchBends()[0]).toBeInstanceOf(KGMidiPitchBend);
|
||||
expect(restored.getPitchBends()[0].getValue()).toBe(12288);
|
||||
expect(restored.getControllerEvents(11)).toHaveLength(1);
|
||||
expect(restored.getControllerEvents(11)[0]).toBeInstanceOf(KGMidiControllerEvent);
|
||||
expect(restored.getControllerEvents(11)[0].getValue()).toBe(96);
|
||||
});
|
||||
|
||||
it('defaults missing legacy pitch bend data to an empty array', () => {
|
||||
@@ -411,6 +450,7 @@ describe('KGMidiRegion', () => {
|
||||
});
|
||||
|
||||
expect(restored.getPitchBends()).toEqual([]);
|
||||
expect(restored.getControllerEventsByType()).toHaveLength(128);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,22 @@ import { Expose, Type } from 'class-transformer';
|
||||
import { KGRegion } from './KGRegion';
|
||||
import { KGMidiNote } from '../midi/KGMidiNote';
|
||||
import { KGMidiPitchBend } from '../midi/KGMidiPitchBend';
|
||||
import { KGMidiControllerEvent } from '../midi/KGMidiControllerEvent';
|
||||
|
||||
export interface FlattenedControllerEvent {
|
||||
controller: number;
|
||||
event: KGMidiControllerEvent;
|
||||
}
|
||||
|
||||
const MIDI_CONTROLLER_COUNT = 128;
|
||||
|
||||
function createEmptyControllerBuckets(): KGMidiControllerEvent[][] {
|
||||
return Array.from({ length: MIDI_CONTROLLER_COUNT }, () => []);
|
||||
}
|
||||
|
||||
function normalizeController(controller: number): number {
|
||||
return Math.max(0, Math.min(MIDI_CONTROLLER_COUNT - 1, Math.floor(controller)));
|
||||
}
|
||||
|
||||
/**
|
||||
* KGMidiRegion - Class representing a MIDI region in the DAW
|
||||
@@ -19,6 +35,10 @@ export class KGMidiRegion extends KGRegion {
|
||||
@Type(() => KGMidiPitchBend)
|
||||
protected pitchBends: KGMidiPitchBend[] = [];
|
||||
|
||||
@Expose()
|
||||
@Type(() => KGMidiControllerEvent)
|
||||
protected controllerEventsByType: KGMidiControllerEvent[][] = createEmptyControllerBuckets();
|
||||
|
||||
constructor(id: string, trackId: string, trackIndex: number, name: string, startFromBeat: number = 0, length: number = 0) {
|
||||
super(id, trackId, trackIndex, name, startFromBeat, length);
|
||||
this.__type = 'KGMidiRegion';
|
||||
@@ -48,6 +68,54 @@ export class KGMidiRegion extends KGRegion {
|
||||
this.pitchBends = pitchBends ?? [];
|
||||
}
|
||||
|
||||
public getControllerEventsByType(): KGMidiControllerEvent[][] {
|
||||
if (!Array.isArray(this.controllerEventsByType) || this.controllerEventsByType.length !== MIDI_CONTROLLER_COUNT) {
|
||||
this.setControllerEventsByType(this.controllerEventsByType ?? []);
|
||||
}
|
||||
|
||||
return this.controllerEventsByType;
|
||||
}
|
||||
|
||||
public setControllerEventsByType(controllerEventsByType: KGMidiControllerEvent[][]): void {
|
||||
const normalizedBuckets = createEmptyControllerBuckets();
|
||||
if (Array.isArray(controllerEventsByType)) {
|
||||
controllerEventsByType.forEach((bucket, controller) => {
|
||||
if (controller < 0 || controller >= MIDI_CONTROLLER_COUNT || !Array.isArray(bucket)) {
|
||||
return;
|
||||
}
|
||||
|
||||
normalizedBuckets[controller] = bucket;
|
||||
});
|
||||
}
|
||||
|
||||
this.controllerEventsByType = normalizedBuckets;
|
||||
}
|
||||
|
||||
public getControllerEvents(controller: number): KGMidiControllerEvent[] {
|
||||
return this.getControllerEventsByType()[normalizeController(controller)];
|
||||
}
|
||||
|
||||
public setControllerEvents(controller: number, events: KGMidiControllerEvent[]): void {
|
||||
this.getControllerEventsByType()[normalizeController(controller)] = events ?? [];
|
||||
}
|
||||
|
||||
public addControllerEvent(controller: number, event: KGMidiControllerEvent): void {
|
||||
this.getControllerEvents(controller).push(event);
|
||||
}
|
||||
|
||||
public removeControllerEvent(controller: number, controllerEventId: string): void {
|
||||
this.setControllerEvents(
|
||||
controller,
|
||||
this.getControllerEvents(controller).filter(event => event.getId() !== controllerEventId)
|
||||
);
|
||||
}
|
||||
|
||||
public getAllControllerEventsFlattened(): FlattenedControllerEvent[] {
|
||||
return this.getControllerEventsByType().flatMap((events, controller) => (
|
||||
events.map(event => ({ controller, event }))
|
||||
));
|
||||
}
|
||||
|
||||
// Add a single note
|
||||
public addNote(note: KGMidiNote): void {
|
||||
this.getNotes().push(note);
|
||||
|
||||
Reference in New Issue
Block a user