Skip to content

instruments sample editor

Aisjam edited this page Nov 15, 2026 · 1 revision

Sample Editor: trim, loop, slice and process

Home · Section index

Working manual · 0.0.1-alpha · source snapshot 16 November 2026

Open INST, focus EDIT on a usable sample, and press A. Selection bounds identify the region to process; loop bounds define playback repetition. They are separate. Keep a source copy before using OVERWRITE.

INST sample rows retain their Save/ZipFolder/Cross status icons. Right focuses EDIT; A opens the selected usable slot. Missing and empty slots cannot open. Windows can click EDIT. The overlay uses the supplied Dialog_9s_SampleEdit.ctg and its bank snapshot, baked through the existing semantic nine-slice pipeline.

Controls and layout

The editor uses a centred 568 x 456 panel (four 12-pixel cells taller). A shared UI title and right-aligned duration/format metadata sit above the waveform. Rename, selection and loop positions use normal-size text across the full width. Add Slice, Process and Degrade share a single compact button row; Process uses Signal Secondary and Degrade uses Flash Secondary. Save, Overwrite, New Sample and To Inst are compact buttons; Save uses Pulse Secondary and Overwrite uses Core Secondary. Shared UI buttons and dropdowns provide actions, format choices and processing. Instrument volume, pan, tuning, finetune and loop mode remain outside this editor. Existing sample metadata is retained.

Control Action
D-pad Move between rows and fields
A + D-pad Edit selection/loop positions, horizontal 1 ms, vertical 10 ms
L2 + A + D-pad Frame precision, horizontal 1 frame, vertical 10
Left/right stick X Move selection start/end continuously; LOOP POS focus moves LS/LE instead
R2 + sticks Move loop start/end
L1/R1 Zoom out/in
L2 + L1/R1 Scroll waveform
X Select all
Start Toggle selection preview on/off, including current degrader settings
Select + Start Stop audition
Y Open the single action radial; choose a direction and release Y
Select + Y Undo
B / Escape Close the topmost popup; closing the editor confirms unsaved changes

PROCESS opens SELECT PROCESS with four groups: EDIT, LEVEL, TIME / SLICE and EFFECTS. Left/right selects a column; up/down scrolls through processor rows; A opens it. Holy Trinity, Crop and Remove DC apply immediately. Other processors expose at most four values and reachable APPLY and CANCEL actions. Up/down selects a row; left/right edits. Hold A+Up/Down for ten numeric steps or A+Left/Right for one; choice fields always advance one option. A on APPLY commits; A on CANCEL or B cancels. Start renders and auditions the pending result without modifying the draft or history; another Start stops it, including pending preview work. Select+Start also stops audition. Apply reuses a completed preview when settings and tempo are unchanged.

Group Processors
EDIT Holy Trinity, Crop, Reverse (selection/slices), Trim Silence, Depop, Remove DC
LEVEL Gain, Normalise, Fade (in/out/both), Compressor, Limiter
TIME / SLICE Stretch, Pitch Shift, Loop Crossfade, Loop Render, Even Slice, Auto Slice
EFFECTS Reverb, Delay, Filter, Saturate / Clip, Colour, EQ, Tape, Granule

All audio processors operate on the selection. Crop keeps only that selection; other length-changing operations splice the result between the unchanged prefix and suffix, remapping loop/slice markers. Slice creation tools retain their existing whole-sample scope. Reverse in SLICES mode reverses each intersecting slice portion while preserving boundaries and order. Fade lengths are percentages of the selection, independently adjustable for the two ends. Reverse edge fades and Depop lengths use milliseconds. Gain previews predicted peak and rejects clipping rather than silently saturating. DC removal subtracts each channel's mean and also rejects overload. Silent Trim/Holy Trinity operations are no-ops.

Holy Trinity is one press and one Undo: trim both edges at -60 dB (10 ms minimum silence, 2 ms padding), depop the resulting edges over 3 ms, then normalise to -3 dB. The job runs outside audio and never saves automatically. Failed processes do not add history or discard Redo.

Stretch combines TIME (25-400%) / BEAT (1-256 beats), amount, Legacy/Smooth algorithm and grain (5-100 ms). Beat fitting uses project BPM and preserves exact rounded frame length; it does not quantise transients. Pitch Shift combines the shared clean PCM resampler with OLA/WSOLA to preserve duration. It offers semitones, cents, algorithm and grain; extreme shifts can produce audible artefacts. Loop Render repeats the selection forwards or ping-pong into a chosen beat length, with adjustable seam smoothing and final fade.

Loop Crossfade offers AUTO/EXISTING points, internal crossfade milliseconds, entry/release crossfade milliseconds and linear/equal-power/smooth curves. Auto search compares bounded stereo waveform windows, rejects weak matches, and reserves attack/release material inside the selection. Existing points must also leave enough room. It bakes the wrap, entry and release joins and sets a forward LS/LE region without changing duration. Start previews attack, two sustain passes and release (one pass if another would exceed the preview memory limit). Forward sample loops with trailing audio now leave the loop at its next boundary on note-off and play the release tail; full-region and ping-pong loops retain ordinary release. Hard cut still cuts immediately. Existing instrument envelopes remain active. Detection is heuristic; preview the result before applying.

Effects reuse the existing Effect factory and MasterProcessor, not duplicate DSP. Reverb/delay expose wet/dry; their tails fit within the selection, so include silence after a hit when needed. The final 3 ms blends processed audio back into the original boundary without touching outside samples. Delay is in milliseconds; filter cutoff and EQ mid-frequency use the effects' logarithmic percentage maps. Colour uses a master colour preset, amount, high-band tone offset and output gain. Compressor Response pairs attack/release: Punch 30/80 ms, Balanced 15/120 ms, Smooth 3/250 ms. Limiter input gain is applied before its existing lookahead and latency compensation. Granule retains the existing live effect's capture/delay behavior, so high Position values require a sufficiently long selection.

The compact DEGRADE button opens a separate overlay using the supplied Dialog_9s_SampleEditSmall.ctg artwork. ON/OFF and the RATE, BITS and CHANNEL dropdowns live there; B/Escape returns to the sample editor. INST sample rows also have compact EDIT and DEGRADE buttons (Right once/twice, then A). Opening DEGRADE directly hides the sample editor and saves settings to the instrument on B/Escape. Undo remains available through Select+Y and the radial. The final action row is SAVE, OVERWRITE, NEW SAMPLE, NEW SAMPLE TO INSTRUMENT. Y opens the same radial from any main field: Process, Overwrite, New Sample, Pack/Unpack, New Sample to Instrument, Revert, Undo and Stop.

Mouse clicks use the same fields and dropdowns. Left/right waveform dragging moves selection start/end, or LS/LE when LOOP POS is focused; the wheel zooms over the waveform and navigates fields elsewhere. Focus loss/disconnect clears held axes. Physical handheld input and latency still require hardware verification.

RATE, BITS and CHANNEL use compact dropdown headers. Their lists open upward from the existing controls over the degrader overlay, with the original dropdown list skin and no additional dialog backdrop. A/click commits, B/Escape cancels, and clicking the open header closes it. Option order remains top-to-bottom.

Working state and processing

Selection and loop bounds are independent half-open native-frame ranges. LS/LE are the tone-coloured loop markers, S/E are the core-coloured selection markers. The waveform combines stereo extrema, preserving either channel's transient. Its hierarchical 64-frame min/max cache supplies exact partial-block peaks; the 520-column, 120-pixel-high viewport is rebuilt only when PCM, zoom or scroll changes.

The original file is untouched until an explicit save. Each operation publishes a new immutable working buffer. Up to eight undo states share unchanged PCM; unique history PCM is bounded to 32 MiB, with one previous buffer retained. Working PCM is limited to 32 MiB, separately from prepared audio banks. Revert restores the last committed draft. Processing and saving run in a background job; the modal stays visible while editing is temporarily disabled. No callback does filesystem work, processing allocation or ownership destruction.

Stretch runs offline through the existing OLA/WSOLA algorithms. Legacy is S950-inspired, not exact emulation. Operations leave audio outside the selection unchanged, except Crop which removes it. Crop/stretch remap loops and slices; reverse mirrors contained loop ranges and slice points.

The shared DSP interface is MasterProcessor: prepare(rate) initializes its bounded state, configure(settings, true) sets offline parameters immediately, and processStage(frame, stage) runs Colour (0), Saturation (1), Dynamics (2) or Limiter (3) independently. latencyFrames() supplies the limiter flush/trim length. MasterBus retains the full realtime chain through this same processor; offline edits do not create a mixer, audio device or second DSP implementation.

DEGRADE opens the conversion controls; A on ON/OFF toggles conversion for audition and audio export. RATE/BITS/CHANNEL use the existing degrader settings and algorithms. Rate and channel conversion apply to the whole sample, because a WAV cannot contain different rates/channels in one contiguous buffer. Existing degrader rate/depth limits apply: choices cap the source rate/depth rather than upsampling it. Start uses a temporary converted buffer when enabled; saved PCM is marked baked per slot so instrument-wide degradation is not applied a second time.

SLICES adds selection boundaries (and frame 0) without discarding existing points. Enabling SLICE requires confirmation. Runtime SLICE uses sample slot 00, with C4 selecting the first slice and subsequent notes selecting subsequent slices at native pitch. Other slots must first be extracted to their own instrument. No silent KIT/ROUND conversion occurs.

Authored waveform markers

Selection and loop boundaries use SelectHead_L/R and LoopHead_L/R; slices use SliceHead with a small one-based hexadecimal label (S1-SFF). Markers outside the zoomed viewport are hidden. Position editing and audition controls are unchanged. The imported compositions share one Playhead.ctb bank snapshot under Asset/Glyphs/Playhead; source artwork is retained separately from generated data. Regenerate src/render/PlayheadArtworkData.hpp using ContourBakeDialogSkins with Asset/Glyphs/Playhead, src/Editor/glyphEditor/assets/Bescii-All.bmp, the output header path, and --playheads. The existing semantic nine-slice renderer stretches stems without stretching the caps or doing filesystem work in the frame loop.

Tracker modularity: application/Playhead.hpp holds presentation-only Song, Chain and Sequence followers. Song and Chain have per-lane followers; Roll uses one spanning head or separate lane heads during independent playback. Phrase uses a Sequence follower. UI::playhead shares authored PlayHead drawing across Song, Chain, Roll, Phrase and Table. Table uses one head spanning its graph and step data. Sample boundaries share artwork rendering, but are editor positions rather than transport followers.

Validation: build Contour and ContourSampleEditorTests, then run ctest --test-dir build -C Release -R "^sample_editor$" --output-on-failure. The test writes build/sample-editor-tests/sample-editor.bmp for visual inspection.

Even Slice and Auto Slice

PROCESSES > TIME / SLICE contains EVEN SLICE and AUTO SLICE. Both operate on the entire sample in slot 00, using the existing Slice instrument semantics. Other slots must first be extracted to their own instrument.

The lower overlay leaves the waveform visible. Up/down selects values and Cancel/Confirm; left/right edits values or selects a button. L2 changes values by ten. A advances from a value or activates a button. B/Escape discards the preview. Other sample-editing inputs are captured until the overlay closes.

Even Slice offers 1-255 regions (default: existing marker count, otherwise 16). Starts use floor(index * frames / count), with a 64-bit intermediate. Samples shorter than the requested count produce one region per frame.

Auto Slice defaults to 65% sensitivity, 45 ms minimum length and 3 ms pre-roll. An asynchronous preparation worker shares immutable PCM, computes independent channel RMS rises and positive spectral flux using Hann-windowed FFTs, then ranks local novelty peaks against an adaptive mean and global silence floor. The cached result is tied to PCM identity. Parameter changes filter ranked candidates without another FFT. Pre-roll precedes boundary and minimum-spacing validation, including the final region. Up to 254 strongest valid attacks join the initial frame-zero slice. Silence retains one region. Cancellation/closure cannot publish a stale result; worker shutdown is cooperative.

Preview markers replace committed markers visually. Confirm replaces the draft layout and enables Slice mode in one undo step; PCM, selection and loops stay unchanged. As with manual slices, SAVE persists the draft and updates instrument playback mapping, with the existing separate confirmation for shared WAV cues. Opening/Confirm does not write the source audio file.

Markers reuse the existing SliceHead artwork and sample-head renderer, alongside the loop and selection heads. Labels are ordered S1-SFF; crowded labels are omitted without moving their stems. Zoom/scroll use native frame coordinates. CTP/CTL v50 and embedded CTI data preserve the expanded capacity; see file format (repository reference: file-formats/project-v50.md).

Validation: transient_detector covers generated drum-loop attacks, sustained tone, silence, short buffers, opposite-phase stereo, pre-roll, spacing and strongest-candidate capacity. sample_editor covers previews, cancel/confirm, undo, input isolation, WAV/CTP/CTI round trips and playback mapping, and emits sample-even-slice.bmp and sample-auto-slice.bmp. Hardware responsiveness and physical controller/audio behavior still require Anbernic H700 verification.

Tracker heads retain the 12-pixel authored cap and repeat the stem vertically. Short lane stems clip the repeated region without shrinking the cap. The source Signal ink maps to the semantic Playhead role, and caller clipping is preserved. The original per-lane transport followers and visibility rules are unchanged.

Implementation files

  • src/scene/SampleEditor.hpp, src/scene/SampleEditor.cpp: modal lifecycle, cached worker, preview replacement, controller input, undo and labels.
  • src/core/audio/analysis/TransientDetector.hpp, src/core/audio/analysis/TransientDetector.cpp: reusable slice analysis.
  • src/core/audio/analysis/Fft.hpp, src/core/audio/osc/WaveformBank.cpp: shared existing preparation FFT.
  • src/core/instruments/SampleProperties.hpp, src/core/audio/Synth/_INST/InstDefinition.hpp, src/application/PlaybackPreparation.cpp, src/core/tracker/FxRegistry.hpp: expanded metadata, WAV loading, playback mapping and SLICE FX range.
  • src/core/save/ProjectSerializer.hpp, src/core/save/ProjectSerializer.cpp, src/core/provenance/CreativeContent.cpp: explicit v50 gating and frozen encoding audit guard.
  • tests/TransientDetectorTests.cpp, tests/SampleEditorTests.cpp, CMakeLists.txt: portable analysis and integrated regression coverage.
  • README.md, ARCHITECTURE.md, docs/sample-editor.md, docs/file-formats/project-v50.md: controls, ownership and compatibility.

Run cmake --build build --config Debug, then ctest --test-dir build -C Debug -R "^(transient_detector|sample_editor|save|tracker_fx|oscillators|publication)$" --output-on-failure.

For deterministic active tracker-head screenshots, run Contour with --snapshot, --playhead-demo, --preview-step 5 and one of --song, --chain, --roll, --phrase or --table. The demo is restricted to isolated snapshots; normal audio is unchanged. Validate the shared renderer with the playheads and ui_toolkit_render CTest cases.

Validation completed in the isolated build/slice-validation Release tree: Contour built successfully; publication, transient_detector, sample_editor, save, tracker_fx and oscillators all passed (6/6). Both slice dialog BMPs were visually inspected at 640x480. PublicationTests retained the existing project and PCM known-answer hashes. Physical H700 controller responsiveness, analysis latency on long recordings, and audible output remain hardware checks.

What should be here

Documentation still to add
Annotated current-build screenshots and a recorded controller walkthrough for this topic.

Evidence and verification

Repository sources used for this page:

  • docs/sample-editor.md

This is a documentation/source review, not a new runtime or hardware test. Physical response, screenshots and listening examples still need verification on a recorded build.

Clone this wiki locally