Files
alex c80e3f5567 Portierung der Python/Tkinter-Vorlage nach C++17/Qt6
Die fuer Debian 13 geschriebene Fassung (Python + Tkinter + matplotlib)
laeuft jetzt als Windows-Anwendung mit Qt 6. Oberflaeche, Bedienlogik und
alle DSP-Verfahren sind unveraendert uebernommen.

- core/   DSP, Audio-IO und Export ohne GUI-Abhaengigkeit
- ui/     Hauptfenster, eigene Wellenform-Anzeige, Uebersichtsleiste,
          ffplay-Wiedergabe, Hintergrund-Worker
- tools/  Selbsttest gegen die Python-Vorlage, Ende-zu-Ende-Test der
          ffmpeg-Kette, Messwerkzeuge fuer den Geschwindigkeitsvergleich
- chopper/  unveraenderte Vorlage als Referenz fuer die Pruefungen

Verifikation: verify.ps1 vergleicht den Auslieferungsbau gegen die Vorlage
(alle diskreten Ergebnisse identisch) und zusaetzlich einen double-Bau
gegen eine float64-Referenz (260 Werte innerhalb von 1e-9).

Die 14 Commits der Python-Vorlage liegen als chopper-history.bundle bei
(chopper/ war unter Debian ein eigenes Repository).
2026-09-11 09:56:14 +02:00

64 lines
29 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## What this is
A single-file Python/Tkinter desktop GUI (`sample_chopper4.py`) for removing silence from audio files and chopping them into segments at detected transients, using FFmpeg for all decode/export work. All UI text and comments in the source are in German.
There is no build system, package manifest, or test suite — the whole app is one script.
## Running
```
python3 sample_chopper4.py
```
Dependencies (not pinned anywhere, install manually):
- `ffmpeg` in `PATH` — required for decoding and export; `ffplay` (ships with ffmpeg) enables in-app playback
- `python3-tk` — GUI toolkit (`apt install python3-tk`)
- `numpy`, `matplotlib` — analysis/waveform display (`pip install numpy matplotlib`)
- `scipy` — optional, only for `scipy.fft`. If importable (and its `rfft` accepts `workers=`, probed once at import), `spectral_flux` transforms in float32 across all cores, roughly 3× faster than `numpy.fft`, which always upcasts to float64. Without it the code takes a `numpy.fft` fallback that is bit-identical to the pre-scipy behaviour — never a correctness dependency, only speed.
- `tkinterdnd2` — optional, enables drag-and-drop file adding; the app degrades gracefully to an "Add" button if it's not importable (see `DND_OK` check at the top of the file)
There is no linter or test runner configured in this repo.
## Architecture
The file is organized top-to-bottom into four layers, in this order:
1. **FFmpeg/Audio-IO** (`ffmpeg_available`, `ffplay_available`, `decode_mono`, `decode_stereo`) — decodes any input file to float32 PCM via a raw `ffmpeg` subprocess call, at `ANALYSIS_SR` (22050 Hz) for analysis/display, or `ZC_SR` (48000 Hz) for zero-crossing snapping. `decode_stereo` forces 2-channel output (`-ac 2`) and returns separate left/right arrays — mono sources come back with identical left/right (ffmpeg duplicates the single channel). The GUI's "combined" reference signal used for detection by default is `0.5*(left+right)`, matching ffmpeg's own stereo→mono downmix, so switching from the old mono-only decode didn't change default detection behavior.
2. **DSP** (`frame_rms`, `keep_segments`, `spectral_flux`, `onset_data`/`detect_onsets`, `detect_region_starts`, `pitch_track`/`detect_pitch_changes`, `detect_cuts`, `enforce_length_constraints`, `cap_by_strength`, `select_phrase_cuts`, `finalize_cuts`, `waveform_peaks*`) — pure numpy functions, no GUI or subprocess dependency. Three independent detectors feed the "chop point" logic, and they are freely combinable — `mode` is a set, not one choice (see `DETECTORS`/`parse_mode`/`mode_to_str`; `settings["mode"]` persists as a sorted `+`-joined string, and `parse_mode` still accepts the old `off`/`transient`/`onset`/`both` values):
- **Transient mode**: spectral-flux onset detection with an adaptive (locally-averaged) threshold — good for percussive hits. `onset_data` log-compresses the flux (`log1p`) and normalizes it to robust statistics (median → 0, 98th percentile → 1) rather than to the global maximum, so a single loud hit can't push a quiet passage below the threshold; the price is that relative normalization would manufacture peaks in material with no real dynamics, so a degenerate span (`span <= 0.25 * p98`, measured ~0.05–0.11 for pure noise vs. ~0.9 for real material) short-circuits to "no onsets". The adaptive threshold gets a sensitivity-dependent absolute floor for the same reason. Peak-picking is vectorized; only the min-gap pass loops, over peaks rather than frames. `spectral_flux` itself frames the signal as a `sliding_window_view` and transforms it in blocks of 256 frames, because the obvious version — an `(n_frames × frame)` fancy-index array plus the whole windowed frame matrix — allocated ~450 MB on a 5-minute file and was bound by memory bandwidth rather than by the FFT; blockwise, the working set stays near 1 MB and in cache. The `prev` magnitude spectrum carried across the block boundary is what keeps the result identical to the one-shot version.
- **Onset/"Einsätze" mode**: start-of-region detection reusing the silence-segment logic — good for swelling sounds without a sharp attack.
- **Pitch/"Tonwechsel" mode** (`pitch_track` + `detect_pitch_changes`): for material that sounds continuously and only changes note — a legato bass or synth, where neither of the other two fires because there is no attack and no pause. `pitch_track` is a YIN-style tracker: squared difference function via FFT autocorrelation, cumulative-mean normalized, minimum searched in the lag window `sr/fmax … sr/fmin`. Two details are load-bearing. It takes the **first** minimum below `YIN_THRESH`, not the global one — d′ has minima at every multiple of the true period and the later ones are often deeper, so a global `argmin` returns sub-octaves (measured: 440 Hz read as 49 Hz); after crossing the threshold it descends to the actual trough, otherwise f0 reads consistently high. And `times` marks the window *centre*: the ~90 ms window already contains a note change before it starts at it, so without that correction every cut lands ~45 ms early. `detect_pitch_changes` compares the median of the `PITCH_SPAN_FRAMES` frames *before* against those *after*, not adjacent frames — the analysis window smears a pitch step across several frames, so frame-to-frame deltas stay under the threshold (measured: 20 of 31 changes found that way, all 31 with the window comparison). Frames below `PITCH_MIN_CONF` or under the silence threshold count as unvoiced, so noise between phrases can't register as a note change.
- `detect_cuts` merges/dedupes whichever detectors are active (empty set = no auto cuts).
- `keep_segments` is the silence-removal core: thresholds the RMS envelope, drops silence runs shorter than a minimum duration, then pads and merges the surviving segments. This same function backs both the "remove silence" export path and the "onset" chop-detection path.
- `enforce_length_constraints` post-processes the merged cut list against `min_len`/`max_len`: segments shorter than `min_len` are merged forward into their neighbor (the cut that created them is dropped); segments longer than `max_len` get extra, evenly-spaced cut points inserted so every resulting piece stays under the cap. `cap_by_strength` then optionally truncates the list to the N cuts with the highest nearby spectral-flux magnitude (looked up via `onset_data`'s flux array, regardless of whether the cut came from transient/onset detection or was placed manually) when a "Maximale Chops" limit is set.
- **Phrase mode** ("Phrasen statt Einzeltöne", per file) replaces the `min_len` half of `enforce_length_constraints` with `select_phrase_cuts`: instead of merging forward — which always keeps the *earliest* cut of a too-dense cluster no matter how weak it is — cuts are taken in descending `cut_scores` order and kept if they're at least `min_len` from every already-kept point (non-maximum suppression). `cut_scores` = normalized flux strength + a bonus for the pause immediately preceding the cut (`pause_before_cuts`, probed `lookback_ms` *before* the cut because the 20 ms RMS window sitting right at a cut already overlaps the attack and would report a pause of 0; cuts within `HEAD_S` of the file start get the full bonus unconditionally, since the file start *is* the first phrase's start), so a note after a breath outranks a note mid-run. Manual cuts are passed as `protected`: always kept, and they suppress neighbors themselves. Only the file *end* acts as an extra blocker — the start deliberately does not, because a cut is a chop *start* (`export_chops`: `bounds = onsets + [dur]`) and the audio before the first cut is discarded, so an early first cut rescues the opening phrase instead of creating a short chop. `min_len` is therefore the density control in phrase mode: raise it and you get fewer, longer chops.
- `analyze_material` derives a whole `settings` dict from the audio itself (the "Auto-Einstellungen" button): silence threshold from the noise floor (`max(p10 + 8 dB, p90 − 38 dB)` — the second term keeps decaying note tails from counting as signal and swallowing the pauses between phrases), `minsil` from the silence-run distribution, sensitivity from `stable_sensitivity` (samples 16 sensitivities on the already-computed flux and takes the middle of the widest plateau in onset count — the count that's robust to threshold changes is the material's real event count, no arbitrary target needed), the active detector set from measured evidence (see below), and `min_len`/`phrase` from the region spacing (target `"phrases"`) or the note IOI (target `"hits"`). `rise_times` measures 20 %→90 % of the first peak **from region starts, not from flux onsets** — on swelling material the flux onset only fires near the end of the swell, which would measure a rise time of 0 and misclassify a pad as percussive. Since 20 %→90 % of a linear ramp is 0.7× the true attack, `RISE_SWELL_MS = 100` corresponds to a ~150 ms attack; the lower bound `RISE_TRANSIENT_MS = 45` is set by `frame_rms`'s 20 ms window (a hard drum hit measures ~15 ms). The split of `onset_data` into `flux_envelope` + `onsets_from_flux` exists so the sensitivity sweep reuses one FFT pass; `analyze_material` runs in ~0.25 s for a 60 s file. That same split is what every other caller must respect: only `flux_envelope` is expensive and it does *not* depend on sensitivity, so anything that varies sensitivity (the GUI's Chop-Intensität slider, `stable_sensitivity`) must cache the envelope and re-run only `onsets_from_flux`. `detect_cuts` therefore takes optional `flux_data=(times, flux)`, `envelope=(times, rms)` and `pitch_data=(times, f0, conf)` arguments; callers that already hold those cached (the GUI, `_export_worker`) pass them in, and only a caller with neither computes them itself. `pitch_track` is the most expensive analysis in the app and obeys the same rule — it depends on neither the sensitivity nor the semitone threshold, so both sliders must run off a cached curve. As a result nothing on a hot path calls `onset_data`/`detect_onsets` any more — they survive as the one-call convenience wrapper (`detect_onsets` currently has no caller at all, like `waveform_peaks` next to `waveform_peaks_range`); new code wanting onsets at a given sensitivity should go through `flux_envelope` + `onsets_from_flux` so the envelope stays reusable.
**Choosing the detectors** used to hinge on median rise time alone, picking exactly one mode. That failed because it never checked whether the chosen mode produces anything — "Einsätze" needs pauses and finds nothing in continuous material. Each detector is now switched on from its own evidence: *onset* when there are real pauses (≥3 regions and a meaningful silence fraction), *pitch* when the material is tonal and continuous and the pitch actually moves, *transient* on a sharp attack when the flux finds more than the region count alone. The last one carries an exception worth keeping: sustained clearly-tonal material (`voiced_frac ≥ 0.8`, almost no silence) has no attacks at all, the flux merely reacts to harmonics, and enabling it scattered 359 chops across a legato bass instead of its 35 note changes — so it stays off there when pitch is already active. If nothing qualifies, the old rise-time rule is the fallback. The measured evidence goes into `info` and is shown in the status line, so a surprising choice can be traced.
- `finalize_cuts` is the single entry point for all of the above (min_len via phrase mode or forward-merge, then max_len, then `cap_by_strength`); it takes a lazy `flux_provider` callable so the GUI keeps using its cached envelope and the export computes at most one FFT pass per file — in `_export_worker` that provider is created *before* `detect_cuts` and handed to it as `flux_data`, so transient detection and the phrase/max-chops scoring share the single pass rather than each running their own. It's called identically from `_effective_cuts()` (GUI) and `_export_worker` (export) so what you see matches what gets exported.
3. **Export via FFmpeg** (`snap_to_zero_crossing`, `_pan_filter`, `_measure_peak`, `export_silence_removed`, `export_chops`) — turns the segment/cut-point lists from layer 2 into actual output files. `export_silence_removed` builds an `atrim`+`concat` `-filter_complex_script` to splice the kept segments into one file; `export_chops` runs one `ffmpeg -ss/-t` extraction per chop into separate WAVs. Both take a `channel_mode` (`"stereo"` / `"l"` / `"r"` / `"combined"`) applied via `_pan_filter` — for `export_silence_removed` this is appended as a final stage inside the filter_complex graph (an `-af` after `-filter_complex` is rejected by ffmpeg), for `export_chops` it's folded into a plain `-af` alongside the normalize gain. `export_chops` can optionally peak-normalize each chop individually to 0 dBFS via `-af volume=<gain>dB`; the gain is computed by `_measure_peak` from the already-decoded `left_ref`/`right_ref` arrays (not a second ffmpeg pass), measuring the peak of whichever channel(s) the export's `channel_mode` actually outputs (e.g. only the right channel's peak for `"r"`, the louder of the two for `"stereo"`) so the gain matches what's really being exported. `export_chops` also accepts `name_prefix` to replace the source filename in the output name (`{name_prefix}_{k:03d}.wav` vs. the default `{base}_chop_{k:03d}.wav`) — this is the per-file "Chop-Titel" field. Both export functions can optionally snap cut points to the nearest zero-crossing (via `snap_to_zero_crossing`) against a *separate*, higher-sample-rate mono decode (`ZC_SR = 48000` in the export worker) to avoid clicks — this is distinct from the 22050 Hz array used for analysis/display.
4. **GUI** (`class App`) — Tkinter/ttk + embedded matplotlib waveform. Key points if modifying it:
- `self.cache[path]` holds per-file state: `samples` (combined `0.5*(left+right)`), `left`, `right`, `times`, `rms`, `dur` (populated lazily on first select via `decode_stereo`), plus `manual` (manual cut list), `excluded_auto` (auto-cut positions permanently suppressed because the user dragged or right-clicked them away — see below), `cuts_cache`/`onsets_cache` (memoized detection results keyed by rounded parameter tuples *and* the active detection channel, so slider drags and arrow-key chop navigation stay responsive; both are cleared wholesale once they pass a size cap, since a long slider drag would otherwise accumulate an entry per step), `flux_cache` (the `flux_envelope` result per detection channel — keyed by channel *only*, deliberately not by sensitivity: this is the one cache that holds the FFT, and `_flux_for` is the single place it is filled. `onsets_cache` entries reference its arrays rather than copying them, and `_cuts_for`/`_onset_data_for` both read through it, so moving the Chop-Intensität slider costs a threshold pass and peak-picking instead of a full FFT), `pitch_cache` (the `pitch_track` result per detection channel, filled only by `_pitch_for` — same contract as `flux_cache`, and it matters more here because it is the slowest analysis), `chan_rms` (lazily-computed `frame_rms` per single channel, see below), and `settings` (that file's own DSP slider values — thresh/minsil/pad/sens/mode/min_len_ms/max_len_ms/max_chops/title/phrase/semitones). `settings` is seeded with `DEFAULT_SETTINGS` as soon as a file is added (`_add_files`), independent of decoding. Every DSP slider is a single global Tk variable shared by the whole app, so `_on_select` explicitly saves the outgoing file's slider values into its `settings` (`_save_current_settings`) and loads the incoming file's `settings` into the sliders (`_load_settings_for`) on every file switch — this is what makes each file's silence/chop parameters independent rather than one shared global config. Export (`_export`/`_export_worker`) reads `settings_by_file`/`manual_by_file`/`excluded_by_file` per file rather than one shared parameter set.
- **Channel selection** is split into four independent concerns, each with its own combobox: **Anzeige-Kanal** (`self.v_view_channel_label`, global, default "LR-Combined") controls only what's plotted in the waveform (`_view_channel_code()` → `l`/`r`/`combined`, indexing into `c["left"]`/`c["right"]`/`c["samples"]`); **Erkennung folgt Anzeige-Kanal** (`self.v_detect_follow`, global checkbox, default off) makes silence/transient detection follow that same selection instead of always using the combined signal — `_detect_channel_code()`/`_detection_arrays()` resolve this and feed `_current_segments`/`_cuts_for`/`_onset_data_for`, all of which now key their caches on the channel too; **Export-Kanal** (`self.v_export_channel_label`, global, default "Stereo Interleaved", values also include L-Mono/R-Mono/Mono Combined) is what actually gets written to disk, via `channel_mode` passed through to `export_silence_removed`/`export_chops`; **Monitoring** (`self.v_monitor_channel`, global, default "Folgt Anzeige") only affects `ffplay` playback (`_monitor_af_args()`, folded into every `_start_ffplay` call). Its default couples it to the Anzeige-Kanal so you hear the channel you see — `_monitor_channel_code()` resolves "Folgt Anzeige" to the view channel, mapping LR-Combined to `"stereo"` rather than the mono sum so the default case sounds like the original; the other values (Stereo/L-Mono/R-Mono) pin it independently of the display. The resulting code goes through the same `_pan_filter` used by the export path. Channel changes take effect on a *running* ffplay: `_start_ffplay` records `_last_play_args`/`_last_play_channel` (cleared by `_stop_playback`), and `_restart_monitoring` — wired to both comboboxes, for the view channel via `_on_view_channel_change` alongside the debounced redraw — re-launches the same command with the new filter, but only when the effective monitor channel actually changed (so switching the display while Monitoring is pinned doesn't interrupt playback). The restart resets playback to the start of the segment/file, which is why it's gated that tightly. None of the four are per-file — they're treated as "how am I working right now" preferences, unlike the DSP sliders.
- The **Min./Max. Chop-Länge** controls are plain `ttk.Entry` fields (`_ms_entry`), not sliders — chop lengths vary too much for coarse slider steps, so they're typed in milliseconds directly (0 = off), committed on Enter/focus-out via `_refresh_ms_entries`. The **Chop-Erkennung** row is three independent checkboxes (`self.v_detectors`, one per entry in `DETECTORS`) rather than a single-choice combobox, so the detectors combine freely and the auto-analysis can enable each on its own; `_mode()` reads them back as a frozenset and `_set_mode` writes one. The **Tonwechsel ab** slider (`self.v_semitones`) is the interval that counts as a note change — vibrato and glissando need a different value than clearly separated notes. The **"Phrasen statt Einzeltöne"** checkbox (`self.v_phrase`) sits below them and is per-file like the sliders; since it only changes *how* `min_len` is enforced, `_on_phrase_toggle` seeds `min_len` with 800 ms when it's still 0 so ticking the box does something visible.
- The **Auto-Analyse row** ("⚙ Auto-Einstellungen" / "alle Dateien" / "↶ zurücknehmen" + a "Ziel" combobox) wraps `analyze_material`. The **Ziel** selection (`phrases`/`hits`) is the one thing the analysis genuinely cannot measure — a drum loop and a bass run look alike structurally, only the intent differs — so it stays a user choice, defaulting to "Phrasen". `_auto_current` works off the cached arrays of the selected file (synchronous, sub-second); `_auto_all` runs `_auto_worker` in a thread that decodes uncached files and posts an `("auto", (results, errors))` message, applied in `_poll_queue` like every other worker result. `_apply_auto` stashes each file's previous `settings` in `self._auto_backup` so `_auto_undo` can restore them — a whole batch is one undo step. The per-file **Chop-Titel** is deliberately carried over rather than reset, since the analysis can't know it.
- Manual chop points (added via double-click, removed via right-click, or created by dragging an auto-detected chop line — see below) live in `cache[path]["manual"]` and are merged with auto-detected cuts in `_effective_cuts()`/at export time via `_dedup_sorted`, then passed through `finalize_cuts` (see layer 2) before being used for display, navigation, or export — where they're also handed in as `protected`, so phrase mode never drops a hand-placed point. `_effective_cuts()`'s memo key includes `manual` and `excluded_auto` as tuples, not just the slider values: those two change on a bare mouse click, and the click handlers call `_redraw()` directly rather than `_schedule_redraw()` (which is what clears the cache). Without them in the key, a deleted chop kept being served from the cache and stayed drawn until some slider was touched.
- Chop lines are draggable: `_on_press`/`_on_motion`/`_on_release` (bound to `button_press_event`/`motion_notify_event`/`button_release_event`) implement a click-vs-drag state machine — a plain click/double-click/right-click (no pointer movement past a small pixel threshold) falls through to `_handle_static_click`. A static click that *hit a line* toggles that chop's selection (`_press_hit_t` carries the hit from `_on_press` through to the release) and deliberately does not play; a click that missed deselects and plays from there. Every chop also carries its running number, thinned to whatever stays legible (`NUM_MIN_PX`, same `px_per_s` trick as the normalize labels) and with the selected one drawn as a separate white `vlines` on top. The grab radius comes from `_grab_tol()` and is measured in **pixels** (`GRAB_PX`), not as a fraction of the visible span — 1 % of the span is nearly a second when zoomed out and milliseconds when zoomed in, so the old formula felt different at every zoom level and, with click-to-select, would have made almost every click count as a line hit. Dragging an already-manual line just moves its value in `manual`; dragging an auto-detected line records its original time in `cache[path]["excluded_auto"]` (so `_effective_cuts`/export don't resurrect it there) and adds the new position to `manual`. Right-click deletes the nearest chop outright regardless of origin — for a manual point it's removed from `manual`; for an auto-detected point its time is added to `excluded_auto` with no replacement (unlike drag, which adds one). The move itself lives in `_move_cut`, shared by dragging and `Shift+←/→` (`_nudge_selected_chop`, one pixel of the current zoom per step, taken from the `_px_per_s` that `_redraw` records).
- The file listbox uses `selectmode="extended"` so multiple files can be shift/ctrl-selected at once, primarily for `_remove_selected` (bulk delete); `_on_select` still only previews the first selected file's waveform when several are selected.
- The "Chops normalisieren (Peak 0 dB)" checkbox (`self.v_normalize`) is a global export option, applied only in `export_chops` (not the silence-removed export) — each chop is individually gained (based on the **Export-Kanal** setting, via `_measure_peak`) so its loudest sample hits 0 dBFS. When checked, `_redraw()` doesn't just draw a `+X.X dB` text label per chop — it re-plots each chop segment's waveform shape scaled by its own gain, so the peak visually reaches the top/bottom of the plot exactly as it would after normalization; `peak`/`ylim` are pinned to `1.0` in that mode since every segment now maxes out by construction. The per-segment shapes are concatenated with `NaN` separators into a *single* `fill_between` — one call per segment meant hundreds of `PolyCollection`s per redraw and was by far the most expensive thing the app did. Each segment is also bucketed to its own on-screen width (`px_per_s`, measured once per redraw off `ax.get_window_extent()`) instead of a flat 2000 buckets, and the `+X.X dB` labels are skipped for chops narrower than `LABEL_MIN_PX` — at a few hundred chops in view they overlapped into an illegible bar anyway, and they reappear on zoom. `_seg_peak` memoizes `_measure_peak` per (file, export channel, bounds) so zooming and panning don't re-measure unchanged chops.
- **Window layout** is order-sensitive in two places. `status_frame` is packed **first** in `_build_ui`, before the left and right columns: Tk hands out space in packing order, so packing it last left it competing with the editing area and shrinking the waveform whenever a longer message appeared. Its label also carries `width=1` so the text length can't drive the window's requested width, and `_set_status` truncates at `STATUS_MAX_CHARS`. Second, the waveform and posbar live in their own `wave_host`, *not* in the scrollable control column — that column's inner frame shrink-wraps to its children, so `expand=True` on the canvas there did nothing and the plot was stuck at `figsize` forever. `_split_height` divides the height on `<Configure>`, giving `WAVE_MIN_H` to the waveform before the controls grow past `CTRL_PANEL_MIN_H`, so a 768 px display keeps the size it had while a taller window lets the plot grow.
- Long-running work (analysis decode, export) runs in background `threading.Thread`s that push `(kind, payload)` tuples onto `self.msg_q`; `_poll_queue` (polled via `root.after`) is the only place GUI state is touched from those results — don't touch Tk widgets directly from a worker thread.
- Waveform redraws are debounced through `_schedule_redraw` (`root.after(120, ...)`) so continuous slider drags and chop dragging don't redraw on every event.
- **Playhead**: the current playback position is shown twice — as a pink vertical line in the waveform and in the `posbar` (a plain `tk.Canvas` strip under the figure that always shows the *whole* file, with the zoom window and the elapsed portion marked, so you stay oriented while zoomed in). The position comes from ffplay itself: `_start_ffplay` adds `-stats`, and `_read_play_pos` parses the ` 3.96 M-A: … fd=` lines off stderr in a daemon thread (`PLAY_STATS_RE`) — this is exact, unlike extrapolating from wall clock, which would be ~0.37 s off because of ffplay's startup latency (that measured constant is only the fallback if a build emits no stats). ffplay reports *absolute* stream time, so `-ss` needs no correction. `_start_ffplay`'s `timeline` argument says how that clock maps back to the source file: `("span", start, end)` for direct playback, `("keeps", segs)` for the "Stille entfernt" preview, whose timeline lacks the removed silence and is mapped back through the cumulative keep lengths in `_play_position`. A `root.after(PLAY_TICK_MS, …)` ticker (`_play_tick`) drives it and stops itself when the process exits.
- Drawing the playhead deliberately bypasses `_redraw` (which does `fig.clear()` and rebuilds every artist): the lines are created with `animated=True`, so they're excluded from normal draws, and `_blit_playhead` restores a background captured after each real draw (`_on_mpl_draw` → `copy_from_bbox`) and blits just the line. Any full redraw invalidates `_ph_bg`, and the next `draw_event` re-captures it and re-blits — so a frame may be skipped after a redraw, never drawn onto a stale background. `_follow_view` pages the zoom window forward when playback runs off the right edge (DAW-style, position lands at 10 % into the new window); that path *does* call `_redraw`, and `_play_tick` skips its own blit for that tick.
- Zoom/pan state (`self._view`) is separate from the underlying `dur`; `waveform_peaks_range` recomputes min/max buckets for just the visible window so zooming stays fast on long files. Zooming is available via mouse scroll (`_on_scroll`), the +/− buttons, and +/− keyboard shortcuts — all three funnel through the shared `_zoom_by(factor, center_t)` helper, added because scroll-wheel events don't reliably reach matplotlib/Tk on every Linux setup. `_zoom_by` also takes `recenter`: the keyboard zoom (`←`/`→`) puts `_zoom_anchor()` — the selected chop's start, else the mouse pointer — in the *middle* of the new window, while the wheel keeps the point under the cursor where it is, which is what a wheel is expected to do.
All four arrow-key behaviours hang off the same two keys and are decided in one place, `_on_arrow`, from the modifier bits (`Shift` 0x0001, `Control` 0x0004, `Alt` 0x0008): bare = zoom, `Shift` = move the selected chop, `Control` = previous/next chop, `Alt` = scroll. The modifier variants have to be bound explicitly in `_build_ui` — a bare `<Left>` binding does not fire for `<Shift-Left>`. Keep `_show_hotkeys` and `self.play_hint` in step with any change here. `_zoom_by` and `_on_pan` go through `_schedule_redraw(invalidate=False)` rather than calling `_redraw` directly: a single wheel gesture or scrollbar drag emits a burst of events, and each one would otherwise rebuild the whole figure. The `invalidate=False` flag is the point of the parameter — only the visible window changed, so the memoized cut points stay valid and don't need another `finalize_cuts` pass. Anything that changes a DSP parameter must use the default `invalidate=True`, because `_cuts_cache`'s key does not cover manual cuts or `excluded_auto`.