Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Add support of midi files
Egor Khindikaynenadf06ff4dd87
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f38b4651..261a4ead 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,12 @@ created, and the build-and-publish run starts.Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.### Added+- Import MIDI files. `.mid` files now show up in the browser's Files tab, and you can drag+ them from there or straight from Finder / Explorer. Drop one on the arrangement and it+ becomes a MIDI clip at that spot. A file with several parts spreads out: the first part+ goes on the track you dropped on, and each of the others gets its own new track (drum+ parts get a Nota Rhythm). Drop one on a session slot and the whole file becomes that+ slot's clip. Double-clicking a MIDI file in the browser puts it on a new track.- Preview presets before loading them. The browser's player now also sits under theInstruments, Audio Effects, MIDI Effects and Presets tabs. Select a preset, a drum kit or abuilt-in device and press Space or Play to hear it; turn on Auto there to hear each one as@@ -92,6 +98,9 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Changed+- The browser's preview player stays out of the way until you use it. It is hidden at+ launch, appears once you click or arrow through a list (or press Space there), and hides+ again when you drag or double-click an item into the project.- ⌘A now selects all clips in the arrangement. Automation mode moved to ⌘⇧A.- Nota Arp has a new look and two sizes: a full card and a small 260-pixel one. Switchbetween them with S / L in the card's header. Both sizes share the same presets, and thediff --git a/src/managed/Nota.App/BrowserView.cs b/src/managed/Nota.App/BrowserView.csindex bad985a7..7306c36d 100644--- a/src/managed/Nota.App/BrowserView.cs+++ b/src/managed/Nota.App/BrowserView.cs@@ -47,8 +47,8 @@ public sealed class BrowserView : UserControlpublic static bool IsBrowserDrag => CurrentDrag is not null;// --- external file drops (from Finder / other programs) ------------------ // Audio extensions Nota can import as a clip / sample. Anything else in an- // external drag is ignored.+ // Audio extensions Nota can import as a clip / sample; MIDI files (MidiFileReader)+ // import as MIDI clips. Anything else in an external drag is ignored.private static readonly HashSet<string> AudioExts = new(StringComparer.OrdinalIgnoreCase){ ".wav", ".wave", ".aif", ".aiff", ".flac", ".mp3", ".ogg", ".m4a", ".aac" };@@ -58,9 +58,9 @@ public sealed class BrowserView : UserControlpublic static bool IsAcceptableDrag(DragEventArgs e)=> IsBrowserDrag || e.DataTransfer.Contains(DataFormat.File);- /// <summary>Local paths of the audio files carried by an external drag (empty if- /// none / not a file drag).</summary>- private static List<string> ExternalAudioFiles(DragEventArgs e)+ /// <summary>Local paths of the audio / MIDI files carried by an external drag (empty+ /// if none / not a file drag).</summary>+ private static List<string> ExternalFiles(DragEventArgs e){var paths = new List<string>();if (!e.DataTransfer.Contains(DataFormat.File)) return paths;@@ -69,23 +69,25 @@ public sealed class BrowserView : UserControlforeach (var f in files){var p = f.TryGetLocalPath();- if (!string.IsNullOrEmpty(p) && AudioExts.Contains(System.IO.Path.GetExtension(p))) paths.Add(p!);+ if (!string.IsNullOrEmpty(p)+ && (AudioExts.Contains(System.IO.Path.GetExtension(p)) || Nota.Application.Midi.MidiFileReader.IsMidiFile(p)))+ paths.Add(p!);}return paths;}/// <summary>The items a drop should load: the internal browser item (any kind), or- /// one synthesized Sample item per external audio file. Empty when there's nothing- /// we can use (e.g. a non-audio external file). Callers that take one use [0].</summary>+ /// one synthesized Sample / MidiFile item per external file. Empty when there's nothing+ /// we can use (e.g. an unsupported external file). Callers that take one use [0].</summary>public static IReadOnlyList<BrowserItem> DroppedItems(DragEventArgs e){if (CurrentDrag is { } item) return new[] { item };var list = new List<BrowserItem>();- foreach (var p in ExternalAudioFiles(e))+ foreach (var p in ExternalFiles(e))list.Add(new BrowserItem{Name = System.IO.Path.GetFileNameWithoutExtension(p),- Kind = BrowserItemKind.Sample,+ Kind = Nota.Application.Midi.MidiFileReader.IsMidiFile(p) ? BrowserItemKind.MidiFile : BrowserItemKind.Sample,Path = p,});return list;@@ -190,6 +192,10 @@ public sealed class BrowserView : UserControl// Pinned preview footer + the status line under it.private readonly PreviewPlayer _previewFooter; // sample / preset auditioner — list tabs+ // The player stays hidden until the user works a list (click, arrow keys, Space) and hides+ // again once a row is dragged or double-clicked onto the project.+ private bool _previewShown;+ private bool _listPointerDown; // a single click is in progress on a list rowprivate readonly Border _statusBar;private readonly TextBlock _statusText;@@ -320,7 +326,7 @@ public sealed class BrowserView : UserControl_chipsPanel = new ChipStrip(_overflowChip, _overflowText);_chipsHost = new Border { Margin = new Thickness(8, 0, 8, 7), Child = _chipsPanel };- _previewFooter = new PreviewPlayer();+ _previewFooter = new PreviewPlayer { IsVisible = false };_previewFooter.SetContext(files: _active == FilesTab);// Status line: what the active tab is showing, counted.@@ -603,7 +609,7 @@ public sealed class BrowserView : UserControl// The auditioner follows the list tabs: samples in Files, presets and built-in devices// in Instr / FX / MIDI / Presets. It picks up the new tab's selection.bool auditions = index <= PresetsTab;- _previewFooter.IsVisible = auditions;+ UpdatePreviewVisibility();_previewFooter.SetContext(files: index == FilesTab);if (auditions) SyncPreview(_pages[index]);// Favorite/tag filter chips apply only to the device tabs.@@ -839,7 +845,7 @@ public sealed class BrowserView : UserControl{BrowserItemKind.Folder => "",BrowserItemKind.Preset => it.Depth > 0 ? "" : it.Sub,- BrowserItemKind.Sample => System.IO.Path.GetExtension(it.Path).TrimStart('.').ToLowerInvariant(),+ BrowserItemKind.Sample or BrowserItemKind.MidiFile => System.IO.Path.GetExtension(it.Path).TrimStart('.').ToLowerInvariant(),// A column of "project" down a tab that is only projects says nothing.BrowserItemKind.Project => "",_ => it.Sub,@@ -959,10 +965,26 @@ public sealed class BrowserView : UserControl{if (_active > PresetsTab || !_previewFooter.HasSample) return false;for (var c = source as StyledElement; c is not null; c = c.Parent)- if (c == _pages[_active] || c == _previewFooter) { _previewFooter.Toggle(); return true; }+ if (c == _pages[_active] || c == _previewFooter) { ShowPreview(true); _previewFooter.Toggle(); return true; }return false;}+ private void ShowPreview(bool shown)+ {+ _previewShown = shown;+ UpdatePreviewVisibility();+ }++ private void UpdatePreviewVisibility() => _previewFooter.IsVisible = _previewShown && _active <= PresetsTab;++ // A row left the browser for the project: stop its audition and put the player away.+ private void DismissPreview()+ {+ _listPointerDown = false;+ _previewFooter.StopPlayback();+ ShowPreview(false);+ }+// Hands the player a list's selection and the row below it (which the player pre-renders,// so arrowing down plays at once).private void SyncPreview(ListBox list)@@ -992,14 +1014,23 @@ public sealed class BrowserView : UserControlif (list.SelectedItem is not BrowserItem { IsGroup: false } item) return;// Folders (sample dirs, preset categories) are navigation: double-click opens them.if (item.Kind == BrowserItemKind.Folder) _vm?.ToggleExpand(item);- else { _previewFooter.StopAudition(); ItemActivated?.Invoke(item); }+ else { DismissPreview(); ItemActivated?.Invoke(item); }};list.SelectionChanged += (_, _) =>{// Section headers are chrome: never let one become the selection.if (list.SelectedItem is BrowserItem { IsGroup: true }) { list.SelectedItem = null; return; }- if (_active <= PresetsTab && list == _pages[_active]) SyncPreview(list);+ if (_active <= PresetsTab && list == _pages[_active])+ {+ SyncPreview(list);+ // Keyboard navigation reveals at once; a click waits for release, so a row+ // pressed only to be dragged away doesn't flash the player.+ if (!_listPointerDown) ShowPreview(true);+ }};+ list.AddHandler(InputElement.PointerPressedEvent, (object? _, PointerPressedEventArgs e) =>+ _listPointerDown = e.ClickCount < 2 && e.GetCurrentPoint(list).Properties.IsLeftButtonPressed,+ RoutingStrategies.Tunnel, handledEventsToo: true);// Drag source (M7-5): start a copy-drag when the pointer leaves the row.// Must use handledEventsToo — ListBoxItem marks PointerPressed as Handled for// selection, so a plain `+=` (handled=false) never fires and the drag never@@ -1007,7 +1038,12 @@ public sealed class BrowserView : UserControllist.AddHandler(InputElement.PointerPressedEvent, OnRowPressed, RoutingStrategies.Bubble, handledEventsToo: true);list.AddHandler(InputElement.PointerMovedEvent, OnRowMoved, RoutingStrategies.Bubble, handledEventsToo: true);list.AddHandler(InputElement.PointerReleasedEvent,- (object? _, PointerReleasedEventArgs _) => { _pressedItem = null; _pressArgs = null; },+ (object? _, PointerReleasedEventArgs _) =>+ {+ _pressedItem = null; _pressArgs = null;+ if (_listPointerDown && _active <= PresetsTab && list == _pages[_active]) ShowPreview(true);+ _listPointerDown = false;+ },RoutingStrategies.Bubble, handledEventsToo: true);// Right-click / context menu: favorites + tags on device rows, reveal on files,// open / reveal / delete on projects.@@ -1041,6 +1077,7 @@ public sealed class BrowserView : UserControlvar item = _pressedItem;var args = _pressArgs;_pressedItem = null; _pressArgs = null; // start the drag once+ DismissPreview();// Single native pasteboard item (one format → one drag image → one// pasteboard item: macOS is satisfied). The payload rides CurrentDrag.@@ -1284,6 +1321,7 @@ public sealed class BrowserView : UserControlswitch (item.Kind){case BrowserItemKind.Sample:+ case BrowserItemKind.MidiFile:// A saved preset file on disk. Synthetic rows (factory presets, drum kits)// carry a scheme instead of a path and have nothing to reveal.case BrowserItemKind.Preset when System.IO.Path.IsPathRooted(item.Path):diff --git a/src/managed/Nota.App/Controls/ChamberViews.cs b/src/managed/Nota.App/Controls/ChamberViews.csindex 15fdfb7e..4a72bc6d 100644--- a/src/managed/Nota.App/Controls/ChamberViews.cs+++ b/src/managed/Nota.App/Controls/ChamberViews.cs@@ -137,7 +137,7 @@ internal sealed class ChamberIrView : Control{_hover = false; InvalidateVisual();foreach (var it in BrowserView.DroppedItems(e))- if (it.Path is { Length: > 0 } p) { FileDropped?.Invoke(p); break; }+ if (it.Kind != Nota.Presentation.BrowserItemKind.MidiFile && it.Path is { Length: > 0 } p) { FileDropped?.Invoke(p); break; }e.Handled = true;});}diff --git a/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs b/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.csindex ca49fbe8..469a45bf 100644--- a/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs+++ b/src/managed/Nota.App/DeviceCards/Instruments/RhythmInstrumentCard.cs@@ -224,7 +224,7 @@ internal sealed class RhythmInstrumentCard : IInstrumentCard{hover(false);foreach (var it in BrowserView.DroppedItems(e))- if (it.Path is { Length: > 0 } p && engine.SetRhythmVoiceSample(track, voice, p))+ if (it.Kind != Nota.Presentation.BrowserItemKind.MidiFile && it.Path is { Length: > 0 } p && engine.SetRhythmVoiceSample(track, voice, p)){Loaded(voice);ctx.NotifyChanged(); ctx.RequestRebuild();diff --git a/src/managed/Nota.App/MainWindow.Browser.cs b/src/managed/Nota.App/MainWindow.Browser.csindex 345c228b..a3f0beec 100644--- a/src/managed/Nota.App/MainWindow.Browser.cs+++ b/src/managed/Nota.App/MainWindow.Browser.cs@@ -207,6 +207,10 @@ public partial class MainWindowcase BrowserItemKind.Sample:_ = ImportAudioInBackgroundAsync(item.Path, -1, 0.0);break;+ case BrowserItemKind.MidiFile:+ ImportMidiFileToArrangement(item, -1, 0.0);+ Timeline.Refresh();+ break;case BrowserItemKind.Project:OpenProject(item.Path);return; // OpenProject rebuilds everything itselfdiff --git a/src/managed/Nota.App/MainWindow.Dnd.cs b/src/managed/Nota.App/MainWindow.Dnd.csindex af154385..0c895c08 100644--- a/src/managed/Nota.App/MainWindow.Dnd.cs+++ b/src/managed/Nota.App/MainWindow.Dnd.cs@@ -33,6 +33,9 @@ public partial class MainWindow// Decodes in the background; the track shows a filling placeholder meanwhile._ = ImportAudioInBackgroundAsync(item.Path, TrackIsAudio(trackId) ? trackId : -1, beat);break;+ case BrowserItemKind.MidiFile:+ ImportMidiFileToArrangement(item, trackId, beat);+ break;case BrowserItemKind.BuiltinInstrument:{// Dropped on an existing (non-rack) instrument track → swap its instrument;@@ -95,6 +98,9 @@ public partial class MainWindowif (Engine.AddSessionAudioFile(trackId, scene, item.Path))_vm.StatusText = $"Added {item.Name} to slot";break;+ case BrowserItemKind.MidiFile:+ ImportMidiFileToSlot(item, trackId, scene, instrumentTrack);+ break;case BrowserItemKind.BuiltinEffect:case BrowserItemKind.PluginEffect:case BrowserItemKind.Preset:@@ -222,6 +228,9 @@ public partial class MainWindowcase BrowserItemKind.Sample:_vm.StatusText = "Drop samples onto the arrangement.";break;+ case BrowserItemKind.MidiFile:+ _vm.StatusText = "Drop MIDI files onto the arrangement or a session slot.";+ break;default: // effects + presetsRouteToTrack(item, t);break;diff --git a/src/managed/Nota.App/MainWindow.MidiImport.cs b/src/managed/Nota.App/MainWindow.MidiImport.csnew file mode 100644index 00000000..5b459f09--- /dev/null+++ b/src/managed/Nota.App/MainWindow.MidiImport.cs@@ -0,0 +1,100 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// MIDI file import (.mid from the browser's Files tab or dragged in from Finder / Explorer).+// In the arrangement each note-bearing part of the file becomes a clip: the first lands on+// the dropped-on instrument track, the rest each get a new track below — the same spread the+// multi-file audio drop uses. A session slot takes the whole file merged into one clip.++using System;+using System.IO;+using Nota.Application;+using Nota.Application.Midi;+using Nota.Presentation;++namespace Nota.App;++public partial class MainWindow+{+ private void ImportMidiFileToArrangement(BrowserItem item, int trackId, double beat)+ {+ if (_vm is null || ReadMidiFile(item) is not { } file) return;+ string baseName = Path.GetFileNameWithoutExtension(item.Path);+ bool multi = file.Parts.Count > 1;+ int firstTrack = -1;+ Engine.BeginUndoGroup(); // tracks + clips + notes undo as one step+ try+ {+ for (int i = 0; i < file.Parts.Count; i++)+ {+ var part = file.Parts[i];+ bool reuse = i == 0 && IsPlainInstrumentTrack(trackId);+ int t = reuse ? trackId : AddTrackForMidiPart(part, multi ? PartName(part, i) : baseName);+ if (t <= 0) continue;+ int clip = Engine.AddMidiClip(t, beat, file.LengthBeats);+ if (clip < 0) continue;+ Engine.SetClipNotes(t, clip, part.Notes.ToArray());+ Engine.SetClipName(t, clip, multi ? $"{baseName} · {PartName(part, i)}" : baseName);+ if (firstTrack < 0) firstTrack = t;+ }+ }+ finally { Engine.EndUndoGroup(); }+ if (firstTrack > 0) _lastInstrumentTrackId = firstTrack;+ _vm.StatusText = multi ? $"Imported {item.Name} ({file.Parts.Count} parts)" : $"Imported {item.Name}";+ }++ private void ImportMidiFileToSlot(BrowserItem item, int trackId, int scene, bool instrumentTrack)+ {+ if (_vm is null) return;+ if (!instrumentTrack) { _vm.StatusText = "Drop MIDI files onto instrument slots."; return; }+ if (ReadMidiFile(item) is not { } file) return;+ Engine.BeginUndoGroup();+ try+ {+ Engine.AddSessionMidiClip(trackId, scene, file.LengthBeats);+ Engine.SetSessionNotes(trackId, scene, file.AllNotes().ToArray());+ }+ finally { Engine.EndUndoGroup(); }+ _vm.StatusText = $"Added {item.Name} to slot";+ }++ // Parses the file, reporting a bad / empty one in the status bar instead of throwing.+ private MidiFileData? ReadMidiFile(BrowserItem item)+ {+ try+ {+ var file = MidiFileReader.Read(item.Path);+ if (file.Parts.Count > 0) return file;+ _vm!.StatusText = $"{item.Name} has no notes.";+ }+ catch (Exception ex) { _vm!.StatusText = $"Couldn't read {item.Name}: {ex.Message}"; }+ return null;+ }++ private static string PartName(MidiFilePart part, int index)+ => part.Name.Length > 0 ? part.Name : $"Part {index + 1}";++ // A drum part (GM channel 10) gets a Rhythm on its factory kit, anything else the default synth.+ private int AddTrackForMidiPart(MidiFilePart part, string name)+ {+ int t;+ if (part.IsDrums)+ {+ t = Engine.AddRhythmTrack();+ _kits.LoadInto(Engine, t, _kits.DefaultRhythmKit, out _);+ }+ else t = Engine.AddInstrumentTrack();+ if (t > 0 && name.Length > 0) Engine.SetTrackName(t, name);+ return t;+ }++ private bool IsPlainInstrumentTrack(int trackId)+ {+ if (trackId <= 0) return false;+ int n = Engine.TrackCount;+ for (int i = 0; i < n; i++)+ if (Engine.TryGetTrackInfo(i, out var ti) && ti.Id == trackId)+ return ti.IsInstrument && !ti.IsGroup;+ return false;+ }+}diff --git a/src/managed/Nota.App/PreviewPlayer.cs b/src/managed/Nota.App/PreviewPlayer.csindex 3f249b5f..44dc7603 100644--- a/src/managed/Nota.App/PreviewPlayer.cs+++ b/src/managed/Nota.App/PreviewPlayer.cs@@ -338,6 +338,13 @@ public sealed class PreviewPlayer : UserControl_playWhenReady = null;}+ /// <summary>Stops whatever is playing (the browser is hiding the player).</summary>+ public void StopPlayback()+ {+ _playWhenReady = null;+ if (_playing) Stop();+ }+private static AuditionSubject? SubjectOf(BrowserItem? item) => item switch{{ IsGroup: true } => null,diff --git a/src/managed/Nota.Application/Midi/MidiFileReader.cs b/src/managed/Nota.Application/Midi/MidiFileReader.csnew file mode 100644index 00000000..6c2ceb8f--- /dev/null+++ b/src/managed/Nota.Application/Midi/MidiFileReader.cs@@ -0,0 +1,180 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Standard MIDI File (.mid / .midi) import: formats 0, 1 and 2, PPQ timing. Only notes+// survive — tempo, controllers and program changes are dropped (Nota's clips hold notes+// only; the project keeps its own tempo). Times come out in quarter-note beats.++using System.Text;++namespace Nota.Application.Midi;++/// <summary>One note-bearing part of a MIDI file: a file track, or — for a format-0 file+/// that packs several instruments into one track — one MIDI channel of it.</summary>+public sealed class MidiFilePart+{+ public string Name { get; init; } = "";+ /// <summary>Every note sits on MIDI channel 10 (the General MIDI drum channel).</summary>+ public bool IsDrums { get; init; }+ public List<NotaNote> Notes { get; } = new();+}++public sealed class MidiFileData+{+ /// <summary>Parts that carry at least one note, in file order.</summary>+ public List<MidiFilePart> Parts { get; } = new();++ /// <summary>End of the last note, rounded up to a whole 4/4 bar (at least one bar).</summary>+ public double LengthBeats { get; set; }++ /// <summary>Every part merged into one sorted note list.</summary>+ public List<NotaNote> AllNotes()+ {+ var all = new List<NotaNote>();+ foreach (var p in Parts) all.AddRange(p.Notes);+ return MidiToolUtil.Sorted(all);+ }+}++public static class MidiFileReader+{+ public static readonly string[] Extensions = { ".mid", ".midi", ".smf" };++ public static bool IsMidiFile(string path)+ {+ var ext = Path.GetExtension(path);+ foreach (var e in Extensions)+ if (string.Equals(e, ext, StringComparison.OrdinalIgnoreCase)) return true;+ return false;+ }++ public static MidiFileData Read(string path) => Parse(File.ReadAllBytes(path));++ public static MidiFileData Parse(byte[] data)+ {+ int pos = 0;+ if (data.Length < 14 || Encoding.ASCII.GetString(data, 0, 4) != "MThd")+ throw new InvalidDataException("Not a standard MIDI file.");+ int hdrLen = (int)ReadU32(data, 4);+ int format = ReadU16(data, 8);+ int ntracks = ReadU16(data, 10);+ int division = ReadU16(data, 12);+ if ((division & 0x8000) != 0)+ throw new InvalidDataException("SMPTE-timed MIDI files aren't supported.");+ double ppq = division > 0 ? division : 480;+ pos = 8 + hdrLen;++ var result = new MidiFileData();+ double end = 0;+ for (int t = 0; t < ntracks && pos + 8 <= data.Length; t++)+ {+ string id = Encoding.ASCII.GetString(data, pos, 4);+ int len = (int)ReadU32(data, pos + 4);+ pos += 8;+ int trackEnd = Math.Min(data.Length, pos + len);+ if (id == "MTrk")+ foreach (var part in ReadTrack(data, pos, trackEnd, ppq, splitChannels: format == 0))+ {+ result.Parts.Add(part);+ foreach (var n in part.Notes) end = Math.Max(end, n.StartBeat + n.LengthBeats);+ }+ pos = trackEnd; // unknown chunks are skipped+ }+ result.LengthBeats = Math.Max(4.0, Math.Ceiling(end / 4.0 - 1e-9) * 4.0);+ return result;+ }++ private static IEnumerable<MidiFilePart> ReadTrack(byte[] d, int pos, int end, double ppq, bool splitChannels)+ {+ string name = "";+ long tick = 0;+ int running = 0;+ // Open notes keyed by channel*128 + pitch; queued so overlapping same-pitch notes pair FIFO.+ var open = new Dictionary<int, Queue<(long tick, int vel)>>();+ var byChannel = new SortedDictionary<int, List<NotaNote>>();++ void Close(int ch, int pitch, long at)+ {+ if (!open.TryGetValue(ch * 128 + pitch, out var q) || q.Count == 0) return;+ var (on, vel) = q.Dequeue();+ double start = on / ppq, lenBeats = Math.Max(MidiToolUtil.MinLength, (at - on) / ppq);+ if (!byChannel.TryGetValue(ch, out var list)) byChannel[ch] = list = new();+ list.Add(new NotaNote(pitch, start, lenBeats, vel / 127f));+ }++ while (pos < end)+ {+ tick += ReadVarLen(d, ref pos, end);+ if (pos >= end) break;+ int status = d[pos];+ if (status == 0xFF)+ {+ if (pos + 1 >= end) break;+ int type = d[pos + 1];+ pos += 2;+ int len = (int)ReadVarLen(d, ref pos, end);+ if (type == 0x03 && name.Length == 0 && pos + len <= end)+ name = Encoding.Latin1.GetString(d, pos, len).Trim('\0', ' ');+ pos += len;+ if (type == 0x2F) break;+ continue;+ }+ if (status is 0xF0 or 0xF7)+ {+ pos++;+ pos += (int)ReadVarLen(d, ref pos, end);+ continue;+ }+ if ((status & 0x80) != 0) { running = status; pos++; }+ else if (running == 0) break; // data byte with no running status: corrupt+ int kind = running & 0xF0, ch = running & 0x0F;+ int dataLen = kind is 0xC0 or 0xD0 ? 1 : 2;+ if (pos + dataLen > end) break;+ int a = d[pos], b = dataLen > 1 ? d[pos + 1] : 0;+ pos += dataLen;+ if (kind == 0x90 && b > 0)+ {+ int key = ch * 128 + (a & 0x7F);+ if (!open.TryGetValue(key, out var q)) open[key] = q = new();+ q.Enqueue((tick, b));+ }+ else if (kind == 0x80 || (kind == 0x90 && b == 0))+ Close(ch, a & 0x7F, tick);+ }+ // Notes never released: end them at the track's last event.+ foreach (var (key, q) in open)+ while (q.Count > 0) Close(key / 128, key % 128, Math.Max(tick, q.Peek().tick + (long)ppq / 4));++ if (!splitChannels || byChannel.Count <= 1)+ {+ var part = new MidiFilePart { Name = name, IsDrums = byChannel.Count == 1 && byChannel.ContainsKey(9) };+ foreach (var list in byChannel.Values) part.Notes.AddRange(list);+ if (part.Notes.Count == 0) yield break;+ part.Notes.Sort(static (x, y) => x.StartBeat.CompareTo(y.StartBeat));+ yield return part;+ yield break;+ }+ foreach (var (ch, list) in byChannel)+ {+ var part = new MidiFilePart { Name = ch == 9 ? "Drums" : $"Ch {ch + 1}", IsDrums = ch == 9 };+ part.Notes.AddRange(list);+ part.Notes.Sort(static (x, y) => x.StartBeat.CompareTo(y.StartBeat));+ yield return part;+ }+ }++ private static long ReadVarLen(byte[] d, ref int pos, int end)+ {+ long v = 0;+ for (int i = 0; i < 4 && pos < end; i++)+ {+ byte b = d[pos++];+ v = (v << 7) | (uint)(b & 0x7F);+ if ((b & 0x80) == 0) break;+ }+ return v;+ }++ private static int ReadU16(byte[] d, int p) => (d[p] << 8) | d[p + 1];+ private static uint ReadU32(byte[] d, int p) => (uint)((d[p] << 24) | (d[p + 1] << 16) | (d[p + 2] << 8) | d[p + 3]);+}diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.csindex 2163bc22..1da585ea 100644--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs@@ -19,6 +19,8 @@ public enum BrowserItemKind/// <summary>A section header row (BUILT-IN / PLUG-INS) inside a flattened list — never/// selectable, draggable or activatable.</summary>Group,+ /// <summary>A Standard MIDI File (.mid) — drops as MIDI clip(s).</summary>+ MidiFile,}/// <summary>Active library filter for the device tabs (Instr / FX / MIDI).</summary>@@ -512,8 +514,8 @@ public sealed partial class BrowserViewModel : ObservableObject|| it.Sub.Contains(q, StringComparison.OrdinalIgnoreCase);/// <summary>Scans the configured samples folder into a navigable folder tree (M7-4a).- /// Folders become expandable parent nodes; audio files are leaves. Only folders on a- /// path to an audio file appear.</summary>+ /// Folders become expandable parent nodes; audio and MIDI files are leaves. Only folders+ /// on a path to such a file appear.</summary>public void RebuildSamples(){_sampleTree.Clear();@@ -524,7 +526,8 @@ public sealed partial class BrowserViewModel : ObservableObject// Folder nodes keyed by absolute directory path (reused while placing files).var folders = new Dictionary<string, BrowserItem>(StringComparer.OrdinalIgnoreCase);foreach (var path in EnumerateFilesSafe(root)- .Where(p => SampleExts.Contains(Path.GetExtension(p).ToLowerInvariant()))+ .Where(p => SampleExts.Contains(Path.GetExtension(p).ToLowerInvariant())+ || Nota.Application.Midi.MidiFileReader.IsMidiFile(p)).OrderBy(p => p, StringComparer.OrdinalIgnoreCase).Take(MaxSamples)){@@ -533,7 +536,7 @@ public sealed partial class BrowserViewModel : ObservableObjectparentChildren.Add(new BrowserItem{Name = Path.GetFileName(path),- Kind = BrowserItemKind.Sample,+ Kind = Nota.Application.Midi.MidiFileReader.IsMidiFile(path) ? BrowserItemKind.MidiFile : BrowserItemKind.Sample,Sub = "",Path = path,Depth = depth,