Take management: move takes onto the clip instance

Take management should be per clip instance — deleting a take from one
half of a comped split shouldn't pull it out from under the other half.
That's cleanest if the takes themselves live on the instance rather than
the clip, so they do now.

AudioClipType::TakeFolder is gone entirely. A clip is plain Sampled/Midi
content again, and an instance with a non-empty `takes` list simply
OVERRIDES it with whichever take is active. Splitting already clones the
instance, so each half gets its own take list for free — no index
remapping across instances, no copy-on-write, no shared-state surprise —
and comping still works, because the halves can still each select a
different take. It collapsed machinery too: resolve() moved from the clip
to the instance, and owns_audio_pool_index went back to a one-liner.

Management (DeleteTakeAction, DeleteUnusedTakesAction, RenameTakeAction):
- Right-click a clip with more than one take: `Delete "<active take>"`
  and "Delete Unused Takes". Deletion is named after the take that's
  PLAYING rather than being a generic entry, so you pick the victim by
  selecting it — one clear act instead of hunting a small trash icon in a
  list (which is where this started, and it was fiddly).
- Double-click a take in the dropdown to rename it in place.
- What happens to the selection on delete is the subtle part, and there's
  a test per case: deleting a take BELOW the active one shifts the
  selection down so you keep hearing the same take; deleting the ACTIVE
  take lands on whatever slid into its place (not silently back to take
  1); deleting the LAST take steps back one. The only take can't be
  deleted at all — the menu item isn't offered.
- Deleted takes' audio stays in the pool: undo has to put it back, and
  the other half of a split may still be playing it.

Fixes:
- A recording that stopped before the loop came round wasn't joining an
  existing take list — it landed as a separate overlapping clip. Trigger-
  on-wrap is right for the FIRST recording, but once takes exist there,
  a further run is plainly another take however short. The engine can't
  know that (it's document state), so the editor passes `force_takes`
  with the start-recording command and the run is cut and padded to the
  region even with zero wraps. This forced cycle_loop_len and `wrapped`
  apart on the MIDI side: the region length has to be known from the
  start, but the clip should only pin to full-region length AFTER a pass
  completes, or the bar jumps to full width the moment you hit record.
- Recording a second take left BOTH sounding. append_cycle_takes tore
  down the recording's backend clip by looking it up in
  clip_instance_to_backend_map — but on the audio path the recording
  instance isn't in that map yet; it's only added during promotion, which
  the append path skips. The event already carries the engine's clip id,
  so it's handed over explicitly now.
- The take badge is hidden when there's only one take — no choice to make.
This commit is contained in:
Skyler Lehmkuhl
2026-07-14 12:58:33 -04:00
parent c62164c365
commit 6924fc0ffe
19 changed files with 905 additions and 337 deletions
@@ -76,7 +76,7 @@ impl BackendContext<'_> {
.get(layer_id)
.ok_or_else(|| format!("Layer {} not mapped to backend track", layer_id))?;
let resolved = clip.resolve(instance.active_take);
let resolved = instance.resolve(clip);
let content = clip.content_duration();
let internal_start = instance.trim_start;
let internal_end = instance
@@ -9,17 +9,16 @@
//! plays, which has to be repointed at the newly-active take.
use crate::action::{Action, BackendClipInstanceId, BackendContext};
use crate::clip::{AudioClipType, AudioTake};
use crate::clip::AudioTake;
use crate::document::Document;
use crate::layer::AnyLayer;
use uuid::Uuid;
/// Action that appends takes to a take-folder clip and selects the last of them.
/// Action that appends takes to an instance's take list and selects the last of them.
pub struct AppendTakesAction {
layer_id: Uuid,
/// The instance whose folder is being extended (and whose active take changes).
/// The instance whose take list is being extended (and whose active take changes).
instance_id: Uuid,
clip_id: Uuid,
/// The takes to add, in recording order.
new_takes: Vec<AudioTake>,
@@ -30,11 +29,10 @@ pub struct AppendTakesAction {
}
impl AppendTakesAction {
pub fn new(layer_id: Uuid, instance_id: Uuid, clip_id: Uuid, new_takes: Vec<AudioTake>) -> Self {
pub fn new(layer_id: Uuid, instance_id: Uuid, new_takes: Vec<AudioTake>) -> Self {
Self {
layer_id,
instance_id,
clip_id,
new_takes,
old_take_count: 0,
old_active_take: None,
@@ -71,32 +69,11 @@ impl AppendTakesAction {
impl Action for AppendTakesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let clip = document
.audio_clips
.get_mut(&self.clip_id)
.ok_or_else(|| format!("Audio clip {} not found", self.clip_id))?;
let AudioClipType::TakeFolder { takes, .. } = &mut clip.clip_type else {
return Err("Can only append takes to a take folder".to_string());
};
// Only record the pre-state on the first execute; a redo must not overwrite it with the
// post-state left behind by the previous run.
if !self.executed {
self.old_take_count = takes.len();
}
takes.extend(self.new_takes.iter().cloned());
// Renumber so the names stay in step with the take indices the badge shows.
for (i, take) in takes.iter_mut().enumerate() {
take.name = format!("Take {}", i + 1);
}
let new_active = takes.len() - 1;
let layer = document
.get_layer_mut(&self.layer_id)
.ok_or_else(|| format!("Layer {} not found", self.layer_id))?;
let AnyLayer::Audio(audio_layer) = layer else {
return Err("Take folders only exist on audio layers".to_string());
return Err("Takes only exist on audio layers".to_string());
};
let instance = audio_layer
.clip_instances
@@ -104,31 +81,38 @@ impl Action for AppendTakesAction {
.find(|ci| ci.id == self.instance_id)
.ok_or_else(|| format!("Clip instance {} not found", self.instance_id))?;
// Only record the pre-state on the first execute; a redo must not overwrite it with the
// post-state left behind by the previous run.
if !self.executed {
self.old_take_count = instance.takes.len();
self.old_active_take = instance.active_take;
}
// Number the new takes on from what's already there. Existing names are left alone — the
// user may well have renamed them, and renumbering would clobber that.
let base = instance.takes.len();
for (i, take) in self.new_takes.iter().enumerate() {
let mut take = take.clone();
if take.name.is_empty() {
take.name = format!("Take {}", base + i + 1);
}
instance.takes.push(take);
}
// Land on the take just recorded, GarageBand-style.
instance.active_take = Some(new_active);
instance.active_take = Some(instance.takes.len() - 1);
self.executed = true;
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
if let Some(clip) = document.audio_clips.get_mut(&self.clip_id) {
if let AudioClipType::TakeFolder { takes, .. } = &mut clip.clip_type {
takes.truncate(self.old_take_count);
for (i, take) in takes.iter_mut().enumerate() {
take.name = format!("Take {}", i + 1);
}
}
}
if let Some(AnyLayer::Audio(audio_layer)) = document.get_layer_mut(&self.layer_id) {
if let Some(instance) = audio_layer
.clip_instances
.iter_mut()
.find(|ci| ci.id == self.instance_id)
{
instance.takes.truncate(self.old_take_count);
instance.active_take = self.old_active_take;
}
}
@@ -141,7 +141,7 @@ impl LoopClipInstancesAction {
let external_start = instance.timeline_start - left_duration;
let get_backend_clip_id = |inst_id: &Uuid| -> Result<u32, String> {
match &clip.resolve(instance.active_take) {
match &instance.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => Ok(*midi_clip_id),
ResolvedContent::Audio { .. } => {
let backend_id = backend.clip_instance_to_backend_map.get(inst_id)
@@ -0,0 +1,419 @@
//! Take management: delete and rename the takes on a clip instance.
//!
//! Takes live on the INSTANCE, so both of these are naturally scoped to the one the user clicked —
//! deleting a take from one half of a comped split leaves the other half's list alone.
use crate::action::{Action, BackendClipInstanceId, BackendContext};
use crate::clip::{AudioTake, ClipInstance};
use crate::document::Document;
use crate::layer::AnyLayer;
use uuid::Uuid;
/// The instance a take action targets, looked up mutably.
fn instance_mut<'a>(
document: &'a mut Document,
layer_id: &Uuid,
instance_id: &Uuid,
) -> Result<&'a mut ClipInstance, String> {
let layer = document
.get_layer_mut(layer_id)
.ok_or_else(|| format!("Layer {} not found", layer_id))?;
let AnyLayer::Audio(audio_layer) = layer else {
return Err("Takes only exist on audio layers".to_string());
};
audio_layer
.clip_instances
.iter_mut()
.find(|ci| ci.id == *instance_id)
.ok_or_else(|| format!("Clip instance {} not found", instance_id))
}
/// Swap an instance's backend clip to whatever take the document now says is active.
///
/// The same remove + re-add as `SetActiveTakeAction` — there's no in-place pool-swap command.
fn resync(
backend: &mut BackendContext,
document: &Document,
layer_id: &Uuid,
instance_id: &Uuid,
) -> Result<(), String> {
let instance = document
.get_layer(layer_id)
.and_then(|l| match l {
AnyLayer::Audio(al) => al.clip_instances.iter().find(|ci| ci.id == *instance_id),
_ => None,
})
.cloned()
.ok_or_else(|| format!("Clip instance {} not found", instance_id))?;
let existing: Option<BackendClipInstanceId> = backend
.clip_instance_to_backend_map
.get(instance_id)
.copied();
let track_id = backend.layer_to_track_map.get(layer_id).copied();
if let (Some(backend_id), Some(track_id)) = (existing, track_id) {
backend.remove_clip_instance(track_id, backend_id, *instance_id);
}
backend.add_clip_instance(document, layer_id, &instance)?;
Ok(())
}
/// Remove a take from an instance's take list.
///
/// The take's recorded audio/MIDI stays in the backend pool — undo has to be able to put it back,
/// and other instances (the other half of a split, say) may still be playing it.
pub struct DeleteTakeAction {
layer_id: Uuid,
instance_id: Uuid,
take_index: usize,
// Stored during execute for rollback.
removed: Option<AudioTake>,
old_active_take: Option<usize>,
}
impl DeleteTakeAction {
pub fn new(layer_id: Uuid, instance_id: Uuid, take_index: usize) -> Self {
Self {
layer_id,
instance_id,
take_index,
removed: None,
old_active_take: None,
}
}
}
impl Action for DeleteTakeAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
if self.take_index >= instance.takes.len() {
return Err(format!("Take {} does not exist", self.take_index + 1));
}
// An instance with no takes at all would fall back to the clip's own content, which for a
// cycle recording is a take we may just have deleted. Refuse rather than strand it.
if instance.takes.len() == 1 {
return Err("Can't delete the only take".to_string());
}
self.old_active_take = instance.active_take;
self.removed = Some(instance.takes.remove(self.take_index));
// Everything above the removed take shifts down one, so the selection has to move with it.
// Deleting the *active* take lands on the one that took its place (or the new last take, if
// it was at the end) — that keeps the clip sounding rather than silently picking take 1.
let active = instance.active_take.unwrap_or(0);
instance.active_take = Some(if active > self.take_index {
active - 1
} else if active == self.take_index {
self.take_index.min(instance.takes.len() - 1)
} else {
active
});
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let Some(take) = self.removed.take() else {
return Ok(());
};
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
let at = self.take_index.min(instance.takes.len());
instance.takes.insert(at, take);
instance.active_take = self.old_active_take;
Ok(())
}
fn description(&self) -> String {
format!("Delete take {}", self.take_index + 1)
}
fn execute_backend(
&mut self,
backend: &mut BackendContext,
document: &Document,
) -> Result<(), String> {
resync(backend, document, &self.layer_id, &self.instance_id)
}
fn rollback_backend(
&mut self,
backend: &mut BackendContext,
document: &Document,
) -> Result<(), String> {
resync(backend, document, &self.layer_id, &self.instance_id)
}
}
/// Throw away every take except the one that's playing.
///
/// The tidy-up once you've picked your keeper. Scoped to this instance, so on a comped split it
/// prunes the half you clicked and leaves the other half's alternatives intact.
pub struct DeleteUnusedTakesAction {
layer_id: Uuid,
instance_id: Uuid,
// Stored during execute for rollback.
old_takes: Vec<AudioTake>,
old_active_take: Option<usize>,
}
impl DeleteUnusedTakesAction {
pub fn new(layer_id: Uuid, instance_id: Uuid) -> Self {
Self {
layer_id,
instance_id,
old_takes: Vec::new(),
old_active_take: None,
}
}
}
impl Action for DeleteUnusedTakesAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
if instance.takes.len() < 2 {
return Err("Nothing to delete".to_string());
}
let keep = instance.active_take_index();
self.old_takes = instance.takes.clone();
self.old_active_take = instance.active_take;
let kept = instance.takes.remove(keep);
instance.takes.clear();
instance.takes.push(kept);
instance.active_take = Some(0);
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
instance.takes = std::mem::take(&mut self.old_takes);
instance.active_take = self.old_active_take;
Ok(())
}
fn description(&self) -> String {
"Delete unused takes".to_string()
}
// The take that plays doesn't change, so the backend clip is already correct.
}
/// Rename a take. Document-only — which take *plays* doesn't change, so the backend is untouched.
pub struct RenameTakeAction {
layer_id: Uuid,
instance_id: Uuid,
take_index: usize,
new_name: String,
old_name: String,
}
impl RenameTakeAction {
pub fn new(layer_id: Uuid, instance_id: Uuid, take_index: usize, new_name: String) -> Self {
Self {
layer_id,
instance_id,
take_index,
new_name,
old_name: String::new(),
}
}
}
impl Action for RenameTakeAction {
fn execute(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
let take = instance
.takes
.get_mut(self.take_index)
.ok_or_else(|| format!("Take {} does not exist", self.take_index + 1))?;
self.old_name = std::mem::replace(&mut take.name, self.new_name.clone());
Ok(())
}
fn rollback(&mut self, document: &mut Document) -> Result<(), String> {
let instance = instance_mut(document, &self.layer_id, &self.instance_id)?;
if let Some(take) = instance.takes.get_mut(self.take_index) {
take.name = self.old_name.clone();
}
Ok(())
}
fn description(&self) -> String {
format!("Rename take to \"{}\"", self.new_name)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::clip::TakeContent;
use crate::layer::AudioLayer;
/// A document with one audio layer holding one instance with 4 takes (pools 10..13).
fn doc_with_takes() -> (Document, Uuid, Uuid) {
let mut document = Document::new("Test");
let clip = crate::clip::AudioClip::new_sampled("Cycle rec", 10, 2.0);
let clip_id = document.add_audio_clip(clip);
let mut instance = ClipInstance::new(clip_id);
instance.takes = (10..14)
.map(|pool| AudioTake {
name: format!("Take {}", pool - 9),
content: TakeContent::Audio { audio_pool_index: pool },
})
.collect();
let instance_id = instance.id;
let mut layer = AudioLayer::new("Layer");
layer.clip_instances.push(instance);
let layer_id = document.root.add_child(AnyLayer::Audio(layer));
(document, layer_id, instance_id)
}
fn takes_of(document: &Document, layer_id: &Uuid, instance_id: &Uuid) -> ClipInstance {
let AnyLayer::Audio(al) = document.get_layer(layer_id).unwrap() else { panic!() };
al.clip_instances.iter().find(|ci| ci.id == *instance_id).unwrap().clone()
}
#[test]
fn deleting_a_take_below_the_active_one_shifts_the_selection_down() {
// Everything above the removed take shifts down one, so a selection above it has to move
// with it — otherwise the instance silently starts playing a different take.
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(3); // playing pool 13
}
DeleteTakeAction::new(layer_id, instance_id, 1)
.execute(&mut document)
.expect("delete");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.takes.len(), 3);
assert_eq!(inst.active_take, Some(2), "index shifted down with the take");
assert_eq!(
inst.takes[inst.active_take_index()].content,
TakeContent::Audio { audio_pool_index: 13 },
"still playing the same take it was",
);
}
#[test]
fn deleting_the_active_take_lands_on_its_replacement() {
// Deleting what you're listening to should hand you the take that took its place, not
// silently jump you back to take 1.
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(1); // playing pool 11
}
DeleteTakeAction::new(layer_id, instance_id, 1)
.execute(&mut document)
.expect("delete");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.active_take, Some(1));
assert_eq!(
inst.takes[1].content,
TakeContent::Audio { audio_pool_index: 12 },
"the take that slid into the deleted one's place",
);
}
#[test]
fn deleting_the_last_take_in_the_list_steps_back() {
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(3);
}
DeleteTakeAction::new(layer_id, instance_id, 3)
.execute(&mut document)
.expect("delete");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.active_take, Some(2), "there is no take 4 to land on");
}
#[test]
fn the_only_take_cannot_be_deleted() {
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].takes.truncate(1);
}
assert!(DeleteTakeAction::new(layer_id, instance_id, 0)
.execute(&mut document)
.is_err());
}
#[test]
fn undoing_a_delete_puts_the_take_back_where_it_was() {
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(2);
}
let mut action = DeleteTakeAction::new(layer_id, instance_id, 1);
action.execute(&mut document).expect("delete");
action.rollback(&mut document).expect("undo");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.takes.len(), 4);
assert_eq!(
inst.takes[1].content,
TakeContent::Audio { audio_pool_index: 11 },
"restored at its original index",
);
assert_eq!(inst.active_take, Some(2), "and the selection with it");
}
#[test]
fn deleting_unused_takes_keeps_the_one_thats_playing() {
let (mut document, layer_id, instance_id) = doc_with_takes();
{
let AnyLayer::Audio(al) = document.get_layer_mut(&layer_id).unwrap() else { panic!() };
al.clip_instances[0].active_take = Some(2); // pool 12 — the keeper
}
let mut action = DeleteUnusedTakesAction::new(layer_id, instance_id);
action.execute(&mut document).expect("prune");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.takes.len(), 1);
assert_eq!(inst.active_take, Some(0));
assert_eq!(
inst.takes[0].content,
TakeContent::Audio { audio_pool_index: 12 },
"the take that was playing survives, and nothing else",
);
action.rollback(&mut document).expect("undo");
let inst = takes_of(&document, &layer_id, &instance_id);
assert_eq!(inst.takes.len(), 4);
assert_eq!(inst.active_take, Some(2), "back to what was playing before");
}
#[test]
fn renaming_a_take_round_trips() {
let (mut document, layer_id, instance_id) = doc_with_takes();
let mut action =
RenameTakeAction::new(layer_id, instance_id, 2, "The good one".to_string());
action.execute(&mut document).expect("rename");
assert_eq!(takes_of(&document, &layer_id, &instance_id).takes[2].name, "The good one");
action.rollback(&mut document).expect("undo");
assert_eq!(takes_of(&document, &layer_id, &instance_id).takes[2].name, "Take 3");
}
}
@@ -16,6 +16,7 @@ pub mod paint_bucket;
pub mod remove_effect;
pub mod set_cycle_region;
pub mod append_takes;
pub mod manage_takes;
pub mod set_active_take;
pub mod set_document_properties;
pub mod set_instance_properties;
@@ -55,6 +56,7 @@ pub mod resize_text_box;
pub use add_clip_instance::AddClipInstanceAction;
pub use set_cycle_region::SetCycleRegionAction;
pub use append_takes::AppendTakesAction;
pub use manage_takes::{DeleteTakeAction, DeleteUnusedTakesAction, RenameTakeAction};
pub use set_active_take::SetActiveTakeAction;
pub use add_effect::AddEffectAction;
pub use add_layer::AddLayerAction;
@@ -247,7 +247,7 @@ impl Action for MoveClipInstancesAction {
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
// Handle move based on clip type
match &clip.resolve(instance.active_take) {
match &instance.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => {
// For MIDI: move_clip expects the pool clip ID
controller.move_clip(*track_id, *midi_clip_id, *new_start);
@@ -332,7 +332,7 @@ impl Action for MoveClipInstancesAction {
.ok_or_else(|| format!("Audio clip {} not found", instance.clip_id))?;
// Handle move based on clip type (restore old position)
match &clip.resolve(instance.active_take) {
match &instance.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => {
// For MIDI: move_clip expects the pool clip ID
controller.move_clip(*track_id, *midi_clip_id, *old_start);
@@ -364,7 +364,7 @@ impl Action for SplitClipInstanceAction {
.ok_or_else(|| "Audio clip not found".to_string())?;
use crate::clip::ResolvedContent;
if matches!(clip.resolve(original_instance.active_take), ResolvedContent::Recording) {
if matches!(original_instance.resolve(clip), ResolvedContent::Recording) {
return Err("Cannot split a clip that is currently recording".to_string());
}
@@ -455,7 +455,7 @@ impl Action for SplitClipInstanceAction {
// Restore based on clip type
use crate::clip::ResolvedContent;
match &clip.resolve(instance.active_take) {
match &instance.resolve(clip) {
ResolvedContent::Midi { .. } => {
if let Some(crate::action::BackendClipInstanceId::Midi(orig_backend_id)) =
backend.clip_instance_to_backend_map.get(&self.instance_id)
@@ -487,7 +487,7 @@ impl Action for TrimClipInstancesAction {
.unwrap_or(ContentTime(clip.content_duration().native()));
// Handle trim based on clip type
match &clip.resolve(instance.active_take) {
match &instance.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => {
// For MIDI: trim_clip expects the pool clip ID
controller.trim_clip(*track_id, *midi_clip_id, clip.trim_range(internal_start, internal_end));
@@ -584,7 +584,7 @@ impl Action for TrimClipInstancesAction {
};
// Handle trim based on clip type
match &clip.resolve(instance.active_take) {
match &instance.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => {
// For MIDI: trim_clip expects the pool clip ID
controller.trim_clip(*track_id, *midi_clip_id, clip.trim_range(internal_start, internal_end));
+152 -162
View File
@@ -472,39 +472,20 @@ pub enum AudioClipType {
/// Placeholder for a clip that is currently being recorded.
/// The audio_pool_index will be assigned when recording stops.
Recording,
/// A folder of alternate takes, produced by cycle recording.
///
/// Each pass of the transport around the cycle region becomes one take. Every take spans the
/// **full** cycle region (partial passes are padded with silence at capture time), so all takes
/// are the same length and share this clip's `duration` — which in turn means switching takes
/// never changes the clip's geometry, and splitting a take-folder instance yields two halves
/// whose takes still line up. Which take actually sounds is per-*instance*
/// ([`ClipInstance::active_take`]), not per-clip, so a split can play take 1 on the left and
/// take 3 on the right. That's comping.
TakeFolder {
/// The takes, in the order they were recorded. Never empty in practice.
takes: Vec<AudioTake>,
/// The cycle region's length in beats at the time of recording.
///
/// Audio takes are segmented geometrically (by sample count), so they're only meaningful
/// against the tempo they were cut at. Keeping the recorded length lets a future
/// time-stretch/conform feature reconcile the takes if the tempo changes underneath them.
recorded_loop_beats: Beats,
},
}
/// One take in a [`AudioClipType::TakeFolder`].
/// One take of a cycle recording — see [`ClipInstance::takes`].
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct AudioTake {
/// Display name, e.g. "Take 1".
/// Display name, e.g. "Take 1". User-editable.
pub name: String,
/// The recorded content this take points at.
pub content: TakeContent,
}
/// What a take actually holds. A folder's takes are all the same kind — one cycle-record session
/// What a take actually holds. An instance's takes are all the same kind — one cycle-record session
/// captures either audio or MIDI, never a mix.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub enum TakeContent {
/// Sampled audio: index into the audio pool.
Audio { audio_pool_index: usize },
@@ -608,18 +589,8 @@ impl AudioClip {
}
/// Whether this clip's `duration` is measured in beats (MIDI) rather than seconds.
///
/// A take folder inherits the domain of its takes, which are all the same kind — one
/// cycle-record session captures either audio or MIDI, never a mix. An empty folder can't
/// happen in practice; call it seconds so the fallback is the common case.
fn is_midi_domain(&self) -> bool {
match &self.clip_type {
AudioClipType::Midi { .. } => true,
AudioClipType::Sampled { .. } | AudioClipType::Recording => false,
AudioClipType::TakeFolder { takes, .. } => {
matches!(takes.first().map(|t| &t.content), Some(TakeContent::Midi { .. }))
}
}
matches!(self.clip_type, AudioClipType::Midi { .. })
}
/// Create a new sampled audio clip
@@ -706,34 +677,11 @@ impl AudioClip {
}
}
/// The clip's takes, if it's a take folder.
pub fn takes(&self) -> Option<&[AudioTake]> {
match &self.clip_type {
AudioClipType::TakeFolder { takes, .. } => Some(takes),
_ => None,
}
}
/// The take an instance's `active_take` actually selects.
/// The clip's own content, ignoring takes.
///
/// `None` means take 0, which is also what an out-of-range index falls back to — an index can
/// go stale (an old `.beam`, an undo that shrank the folder), and silently playing the first
/// take beats refusing to play anything.
fn take_for(&self, active_take: Option<usize>) -> Option<&AudioTake> {
let takes = self.takes()?;
takes
.get(active_take.unwrap_or(0))
.or_else(|| takes.first())
}
/// What this clip plays *for a given instance*, with take folders collapsed to the instance's
/// active take.
///
/// This is the sanctioned way to ask "what content do I hand the backend for this instance?".
/// Matching on `clip_type` directly will see a `TakeFolder` and have to handle it separately;
/// matching on this won't, because a folder is never a distinct case here — it's just an audio
/// or MIDI clip whose identity depends on which take is active.
pub fn resolve(&self, active_take: Option<usize>) -> ResolvedContent {
/// Callers that are handing content to the backend want [`ClipInstance::resolve`] instead — an
/// instance with takes overrides the clip's content with whichever take is active.
pub fn resolve(&self) -> ResolvedContent {
match &self.clip_type {
AudioClipType::Sampled { audio_pool_index } => ResolvedContent::Audio {
audio_pool_index: *audio_pool_index,
@@ -742,17 +690,6 @@ impl AudioClip {
midi_clip_id: *midi_clip_id,
},
AudioClipType::Recording => ResolvedContent::Recording,
AudioClipType::TakeFolder { .. } => match self.take_for(active_take).map(|t| &t.content) {
Some(TakeContent::Audio { audio_pool_index }) => ResolvedContent::Audio {
audio_pool_index: *audio_pool_index,
},
Some(TakeContent::Midi { midi_clip_id }) => ResolvedContent::Midi {
midi_clip_id: *midi_clip_id,
},
// An empty folder has nothing to play. Treat it like a recording placeholder:
// the backend gets nothing, rather than a bogus pool index.
None => ResolvedContent::Recording,
},
}
}
@@ -787,49 +724,19 @@ impl AudioClip {
}
}
/// Whether this clip owns the given audio pool index — either as a plain sampled clip, or as
/// *any* take of a take folder. Reverse lookups (backend resource → document clip) must use
/// this: a folder owns one pool file per take, not just the active one.
/// Whether this clip's own content is the given audio pool index.
pub fn owns_audio_pool_index(&self, pool_index: usize) -> bool {
match &self.clip_type {
AudioClipType::Sampled { audio_pool_index } => *audio_pool_index == pool_index,
AudioClipType::TakeFolder { takes, .. } => takes.iter().any(|t| {
matches!(t.content, TakeContent::Audio { audio_pool_index } if audio_pool_index == pool_index)
}),
_ => false,
}
self.audio_pool_index() == Some(pool_index)
}
/// Whether this clip owns the given backend MIDI clip ID. See [`Self::owns_audio_pool_index`].
/// Whether this clip's own content is the given backend MIDI clip ID.
pub fn owns_midi_clip_id(&self, id: u32) -> bool {
match &self.clip_type {
AudioClipType::Midi { midi_clip_id } => *midi_clip_id == id,
AudioClipType::TakeFolder { takes, .. } => takes.iter().any(|t| {
matches!(t.content, TakeContent::Midi { midi_clip_id } if midi_clip_id == id)
}),
_ => false,
}
}
/// The audio pool index this *instance* should play. See [`Self::resolve`].
pub fn resolved_audio_pool_index(&self, active_take: Option<usize>) -> Option<usize> {
match self.resolve(active_take) {
ResolvedContent::Audio { audio_pool_index } => Some(audio_pool_index),
_ => None,
}
}
/// The backend MIDI clip ID this *instance* should play. See [`Self::resolve`].
pub fn resolved_midi_clip_id(&self, active_take: Option<usize>) -> Option<u32> {
match self.resolve(active_take) {
ResolvedContent::Midi { midi_clip_id } => Some(midi_clip_id),
_ => None,
}
self.midi_clip_id() == Some(id)
}
}
/// What a clip instance actually plays, once take folders are resolved to their active take.
/// Produced by [`AudioClip::resolve`].
/// What a clip instance actually plays, once takes are resolved to the active one.
/// Produced by [`ClipInstance::resolve`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ResolvedContent {
Audio { audio_pool_index: usize },
@@ -942,14 +849,34 @@ pub struct ClipInstance {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub loop_before: Option<Beats>,
/// Which take of a [`AudioClipType::TakeFolder`] clip this instance plays.
/// Alternate takes from cycle recording. Empty = an ordinary instance with no takes.
///
/// Per-instance rather than per-clip so two instances of the same folder — e.g. the two halves
/// of a split — can play different takes. That's how comping works. `None` means take 0;
/// meaningless (and ignored) on non-folder clips.
/// The takes live on the INSTANCE, not the clip, so managing them is per-instance: deleting or
/// renaming a take on one instance leaves every other instance alone. Splitting clones the list
/// along with the rest of the instance, so the two halves get independent take lists — and,
/// since they can each select a different take, comping still falls out for free.
///
/// Every take spans the full cycle region (partial passes are padded with silence at capture
/// time), so they're all the same length as the clip's own content. That uniformity is what lets
/// a take switch leave the instance's geometry untouched.
///
/// When non-empty, these OVERRIDE the clip's own content — see [`Self::resolve`].
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub takes: Vec<AudioTake>,
/// Which of [`Self::takes`] plays. `None` (or a stale index) means take 0.
/// Default: None
#[serde(default, skip_serializing_if = "Option::is_none")]
pub active_take: Option<usize>,
/// The cycle region's length in beats when these takes were recorded.
///
/// Audio takes are cut geometrically (by sample count), so they're only meaningful against the
/// tempo they were recorded at. Keeping the recorded length lets a future time-stretch/conform
/// feature reconcile them if the tempo moves underneath, and lets a new recording tell whether
/// it belongs in this take list or a fresh one.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub recorded_loop_beats: Option<Beats>,
}
/// High 64-bit sentinel used to identify UUIDs that encode a backend audio clip instance ID.
@@ -1008,7 +935,9 @@ impl ClipInstance {
playback_speed: 1.0,
gain: 1.0,
loop_before: None,
takes: Vec::new(),
active_take: None,
recorded_loop_beats: None,
}
}
@@ -1027,7 +956,9 @@ impl ClipInstance {
playback_speed: 1.0,
gain: 1.0,
loop_before: None,
takes: Vec::new(),
active_take: None,
recorded_loop_beats: None,
}
}
@@ -1087,6 +1018,55 @@ impl ClipInstance {
self
}
/// The take this instance plays, if it has any.
///
/// A `None`/stale `active_take` falls back to take 0 — an index can go stale (an undo that
/// shrank the list, an old `.beam`), and silently playing the first take beats playing nothing.
pub fn active_take(&self) -> Option<&AudioTake> {
self.takes
.get(self.active_take.unwrap_or(0))
.or_else(|| self.takes.first())
}
/// The index [`Self::active_take`] actually resolves to, clamped into range.
pub fn active_take_index(&self) -> usize {
let i = self.active_take.unwrap_or(0);
if i < self.takes.len() { i } else { 0 }
}
/// What this instance plays: its active take if it has takes, otherwise the clip's own content.
///
/// This is the sanctioned way to ask "what content do I hand the backend for this instance?".
/// Takes are never a distinct *case* at the call site — an instance with takes is just an audio
/// or MIDI instance whose identity depends on which take is live.
pub fn resolve(&self, clip: &AudioClip) -> ResolvedContent {
match self.active_take().map(|t| &t.content) {
Some(TakeContent::Audio { audio_pool_index }) => ResolvedContent::Audio {
audio_pool_index: *audio_pool_index,
},
Some(TakeContent::Midi { midi_clip_id }) => ResolvedContent::Midi {
midi_clip_id: *midi_clip_id,
},
None => clip.resolve(),
}
}
/// The audio pool index this instance plays. See [`Self::resolve`].
pub fn resolved_audio_pool_index(&self, clip: &AudioClip) -> Option<usize> {
match self.resolve(clip) {
ResolvedContent::Audio { audio_pool_index } => Some(audio_pool_index),
_ => None,
}
}
/// The backend MIDI clip ID this instance plays. See [`Self::resolve`].
pub fn resolved_midi_clip_id(&self, clip: &AudioClip) -> Option<u32> {
match self.resolve(clip) {
ResolvedContent::Midi { midi_clip_id } => Some(midi_clip_id),
_ => None,
}
}
/// Content window (`trim_end - trim_start`) in the clip's own content domain.
/// Used for internal looping calculations.
pub fn content_window(&self, clip_content: ClipDuration) -> ClipDuration {
@@ -1328,79 +1308,89 @@ mod tests {
assert_eq!(instance.gain, 0.8);
}
/// Build a take folder of `n` audio takes with the given pool indices.
fn take_folder(pool_indices: &[usize]) -> AudioClip {
let mut clip = AudioClip::new_sampled("Cycle rec", 0, 2.0);
clip.clip_type = AudioClipType::TakeFolder {
takes: pool_indices
.iter()
.enumerate()
.map(|(i, &audio_pool_index)| AudioTake {
name: format!("Take {}", i + 1),
content: TakeContent::Audio { audio_pool_index },
})
.collect(),
recorded_loop_beats: Beats(8.0),
};
clip
/// A clip whose own content is pool 10, plus an instance carrying takes over the given pools.
fn with_takes(pool_indices: &[usize]) -> (AudioClip, ClipInstance) {
let clip = AudioClip::new_sampled("Cycle rec", pool_indices[0], 2.0);
let mut instance = ClipInstance::new(clip.id);
instance.takes = pool_indices
.iter()
.enumerate()
.map(|(i, &audio_pool_index)| AudioTake {
name: format!("Take {}", i + 1),
content: TakeContent::Audio { audio_pool_index },
})
.collect();
instance.recorded_loop_beats = Some(Beats(8.0));
(clip, instance)
}
#[test]
fn active_take_selects_the_pool_file() {
let clip = take_folder(&[10, 11, 12]);
assert_eq!(clip.resolved_audio_pool_index(Some(0)), Some(10));
assert_eq!(clip.resolved_audio_pool_index(Some(2)), Some(12));
let (clip, mut instance) = with_takes(&[10, 11, 12]);
instance.active_take = Some(0);
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(10));
instance.active_take = Some(2);
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(12));
// None means take 0.
assert_eq!(clip.resolved_audio_pool_index(None), Some(10));
instance.active_take = None;
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(10));
}
#[test]
fn out_of_range_take_falls_back_to_the_first() {
// An index can go stale (an old .beam, an undo that shrank the folder). Playing the first
// take beats playing nothing.
let clip = take_folder(&[10, 11]);
assert_eq!(clip.resolved_audio_pool_index(Some(99)), Some(10));
// An index can go stale (an undo that shrank the list, an old .beam). Playing the first take
// beats playing nothing.
let (clip, mut instance) = with_takes(&[10, 11]);
instance.active_take = Some(99);
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(10));
assert_eq!(instance.active_take_index(), 0);
}
#[test]
fn take_folder_owns_every_takes_pool_file() {
// Reverse lookups (backend resource -> document clip) must find the folder via ANY take,
// not just the active one.
let clip = take_folder(&[10, 11, 12]);
assert!(clip.owns_audio_pool_index(10));
assert!(clip.owns_audio_pool_index(12));
assert!(!clip.owns_audio_pool_index(13));
fn an_instance_without_takes_plays_the_clips_own_content() {
let clip = AudioClip::new_sampled("Plain", 42, 2.0);
let instance = ClipInstance::new(clip.id);
assert!(instance.takes.is_empty());
assert_eq!(instance.resolved_audio_pool_index(&clip), Some(42));
}
#[test]
fn midi_take_folder_measures_duration_in_beats() {
// A folder inherits its takes' domain: MIDI takes mean the duration is beats, not seconds.
let mut clip = AudioClip::new_sampled("Cycle rec", 0, 4.0);
clip.clip_type = AudioClipType::TakeFolder {
takes: vec![AudioTake {
name: "Take 1".into(),
content: TakeContent::Midi { midi_clip_id: 7 },
}],
recorded_loop_beats: Beats(4.0),
};
fn midi_takes_resolve_to_midi_content() {
let clip = AudioClip::new_midi("Cycle rec", 7, Beats(4.0));
let mut instance = ClipInstance::new(clip.id);
instance.takes = vec![AudioTake {
name: "Take 1".into(),
content: TakeContent::Midi { midi_clip_id: 7 },
}];
assert_eq!(clip.content_duration(), ClipDuration::Beats(Beats(4.0)));
assert_eq!(clip.resolved_midi_clip_id(Some(0)), Some(7));
assert_eq!(clip.resolved_audio_pool_index(Some(0)), None);
assert_eq!(instance.resolved_midi_clip_id(&clip), Some(7));
assert_eq!(instance.resolved_audio_pool_index(&clip), None);
}
#[test]
fn takes_are_per_instance_so_a_split_can_comp() {
// The whole point of putting active_take on the instance: two instances of the same folder
// (which is what a split produces) can play different takes.
let clip = take_folder(&[10, 11, 12]);
let mut left = ClipInstance::new(clip.id);
let mut right = left.clone();
fn splitting_gives_each_half_an_independent_take_list() {
// Takes live on the INSTANCE, so a split (which clones the instance) hands each half its own
// list. Two consequences, both wanted: the halves can select different takes (comping), and
// deleting a take from one leaves the other alone.
let (clip, left_src) = with_takes(&[10, 11, 12]);
let mut left = left_src.clone();
let mut right = left_src.clone();
right.id = Uuid::new_v4();
left.active_take = Some(0);
right.active_take = Some(2);
assert_eq!(left.resolved_audio_pool_index(&clip), Some(10));
assert_eq!(right.resolved_audio_pool_index(&clip), Some(12));
assert_eq!(clip.resolved_audio_pool_index(left.active_take), Some(10));
assert_eq!(clip.resolved_audio_pool_index(right.active_take), Some(12));
// Delete take 2 (pool 11) from the left half only.
left.takes.remove(1);
assert_eq!(left.takes.len(), 2);
assert_eq!(right.takes.len(), 3, "the other half keeps its own takes");
assert_eq!(
right.resolved_audio_pool_index(&clip),
Some(12),
"and its selection still points where it did",
);
}
#[test]
@@ -944,31 +944,27 @@ impl Document {
/// would break the uniform-take invariant comping depends on.
///
/// `exclude` is the in-progress recording's own instance, which is on the layer but isn't a
/// candidate. Returns (instance id, clip id).
/// candidate. Returns the instance id.
pub fn take_folder_at(
&self,
layer_id: &Uuid,
loop_start: Beats,
loop_len: Beats,
exclude: &Uuid,
) -> Option<(Uuid, Uuid)> {
) -> Option<Uuid> {
let Some(AnyLayer::Audio(audio_layer)) = self.get_layer(layer_id) else {
return None;
};
const EPS: f64 = 1e-6;
audio_layer.clip_instances.iter().find_map(|ci| {
if ci.id == *exclude || (ci.timeline_start - loop_start).beats_to_f64().abs() > EPS {
if ci.id == *exclude
|| ci.takes.is_empty()
|| (ci.timeline_start - loop_start).beats_to_f64().abs() > EPS
{
return None;
}
let clip = self.audio_clips.get(&ci.clip_id)?;
match clip.clip_type {
crate::clip::AudioClipType::TakeFolder { recorded_loop_beats, .. }
if (recorded_loop_beats - loop_len).beats_to_f64().abs() < EPS =>
{
Some((ci.id, ci.clip_id))
}
_ => None,
}
let recorded = ci.recorded_loop_beats?;
((recorded - loop_len).beats_to_f64().abs() < EPS).then_some(ci.id)
})
}