"""Original generated fixtures only; no installed kit, factory song or network needed.""" import hashlib import os import shutil import uuid from collections.abc import Iterator from fractions import Fraction from pathlib import Path from unittest.mock import Mock import pytest from pydantic import ValidationError from riff_groove_builder.articulations import compile_score from riff_groove_builder.errors import ( NativeFormatUnavailableError, OutputExistsError, OutputIOError, SerializationError, ) from riff_groove_builder.formats import sdp from riff_groove_builder.profiles import InstrumentProfile, load_profile_registry from riff_groove_builder.schemas import ( ControlChangeEvent, EventPlan, NoteOffEvent, NoteOnEvent, ProfileSelection, Score, ) ROOT = Path(__file__).resolve().parents[2] TEMPLATE = ROOT / "tests" / "fixtures" / "sd3" / "original-template.sd3p" def original_plan(*, ppq: int = 960) -> tuple[EventPlan, InstrumentProfile]: profile = load_profile_registry().select( ["drums"], ProfileSelection(drums="toontrack.sd3.3.4.4.core.v1") )["drums"] score = Score.model_validate_json(TEMPLATE.with_name("original-score.json").read_bytes()) return compile_score(score, {"drums": profile}, ppq=ppq), profile @pytest.fixture def workspace() -> Iterator[Path]: path = ROOT / ".test-artifacts" / f"sd3p-{uuid.uuid4().hex}" path.mkdir(parents=True) try: yield path finally: shutil.rmtree(path) def test_real_writer_and_independent_packed_readback_preserve_operator_state( workspace: Path, ) -> None: plan, profile = original_plan() before = TEMPLATE.stat() raw = TEMPLATE.read_bytes() template = sdp.parse_sdp_project(raw) assert len(template.source_notes) == 1 info = sdp.inspect_sdp_template(TEMPLATE) assert info.version == "3.4.4" and info.track_count == info.event_count == 1 assert info.sha256 == hashlib.sha256(raw).hexdigest() assert sdp.check_sdp_capability("drums", profile, template=TEMPLATE).available path = workspace / "original.sd3p" assert sdp.write_sdp(path, plan, "drums", profile, template=TEMPLATE) == path saved = sdp.validate_sdp_file(path, plan, "drums", profile, template=TEMPLATE) assert (saved.tempo_bpm, saved.meter, saved.start, saved.end) == ( Fraction(275, 2), (7, 8), Fraction(0), Fraction(7, 2), ) assert [(n.channel, n.pitch, n.velocity, n.start, n.end) for n in saved.notes] == [ (9, 36, 1, Fraction(0), Fraction(1, 8)), (9, 42, 64, Fraction(1, 4), Fraction(3, 8)), (9, 38, 127, Fraction(3), Fraction(25, 8)), ] actual = path.read_bytes() # Independent arithmetic, not the codec's packer/decoder. events = next( line.split()[1:] for line in actual.decode().splitlines() if line.startswith("Events ") ) assert [int(events[i]) for i in range(0, len(events), 3)] == [0x012499, 0x402A99, 0x7F2699] assert int(events[6]) & 255 == 0x99 assert 8332944 == 0x7F2690 # Independently verified genuine message, not its sequence. assert ((8332944 >> 8) & 127, (8332944 >> 16) & 127) == (38, 127) assert sdp.parse_sdp_project(actual).non_song_bytes == template.non_song_bytes assert b"original-source.mid" not in actual assert b"Original source song" not in actual assert b"Offset 0" in actual and b"Offset 2" not in actual assert TEMPLATE.read_bytes() == raw after = TEMPLATE.stat() assert (before.st_ino, before.st_size, before.st_mtime_ns) == ( after.st_ino, after.st_size, after.st_mtime_ns, ) assert sorted(p.name for p in workspace.iterdir()) == ["original.sd3p"] def test_optional_missing_template_is_the_only_target_capability_limitation( workspace: Path, ) -> None: plan, profile = original_plan() assert sdp.check_sdp_capability("drums", profile).reason == "sdp_template_required" for operation in ( lambda: sdp.require_sdp_capability("drums", profile), lambda: sdp.write_sdp(workspace / "absent.sd3p", plan, "drums", profile), ): with pytest.raises(NativeFormatUnavailableError) as error: operation() assert error.value.details["reason"] == "sdp_template_required" with pytest.raises(OutputIOError): sdp.check_sdp_capability("drums", profile, template=workspace / "absent.sd3p") assert not list(workspace.iterdir()) @pytest.mark.parametrize("ending", [b"", b"\0"]) @pytest.mark.parametrize("crlf", [False, True]) def test_quotes_braces_escapes_unicode_nul_and_line_endings( workspace: Path, ending: bytes, crlf: bool ) -> None: raw = TEMPLATE.read_bytes().replace(b"\r\n", b"\n") raw = raw.replace(b"Not song data", "Original café {state}".encode()) if crlf: raw = raw.replace(b"\n", b"\r\n") raw += ending template = workspace / "template.sd3p" template.write_bytes(raw) plan, profile = original_plan() output = workspace / "new.sd3p" sdp.write_sdp(output, plan, "drums", profile, template=template) assert sdp.parse_sdp_project(output.read_bytes()).non_song_bytes == ( sdp.parse_sdp_project(raw).non_song_bytes ) assert output.read_bytes().endswith(ending or (b"\r\n" if crlf else b"\n")) def test_replace_all_contiguous_source_tracks_and_clips(workspace: Path) -> None: raw = TEMPLATE.read_bytes() project = sdp.parse_sdp_project(raw) fields = project.tracks[0].children assert fields is not None loop = next(n for n in fields if n.key == "MidiLoop") old_loop = project.text[loop.start : loop.end].encode() raw = raw.replace( old_loop, old_loop + b"\n" + old_loop.replace(b"MidiLoop 0", b"MidiLoop 1").replace(b"Offset 2", b"Offset 8"), ) project = sdp.parse_sdp_project(raw) track = project.tracks[0] old = project.text[track.start : track.end].encode() raw = raw.replace(old, old + b"\n" + old.replace(b"SongTrack 0", b"SongTrack 1")) raw = raw.replace(b"SetCurrentSongTrack 0", b"SetCurrentSongTrack 1") template = workspace / "multi.sd3p" template.write_bytes(raw) assert sdp.inspect_sdp_template(template).track_count == 2 assert sdp.inspect_sdp_template(template).event_count == 4 plan, profile = original_plan() path = workspace / "single.sd3p" sdp.write_sdp(path, plan, "drums", profile, template=template) saved = sdp.parse_sdp_project(path.read_bytes()) assert len(saved.tracks) == 1 and len(saved.source_notes) == 3 assert saved.non_song_bytes == sdp.parse_sdp_project(raw).non_song_bytes @pytest.mark.parametrize( ("old", "new"), [ (b"3.4.4", b"3.4.5"), (b"3.4.4", b"4.0.0"), (b"PlugVersion", b"UnknownVersion"), (b"SongTrack 0", b"SongTrack 1"), (b"SetCurrentSongTrack 0", b"SetCurrentSongTrack 2"), (b"ClearTracksFirst\n", b""), (b"ClearTrackFirst\n", b""), (b"Tempo 100 0 0", b"Tempo 100 1 0"), (b"Tempo 100 0 0", b"Tempo nan 0 0"), (b"TimeSig 4 4 0", b"TimeSig 4 3 0"), (b"TrackLength 16", b"TrackLength -1"), (b"Offset 2", b"Offset -2"), (b"StartTime 0", b"StartTime 5"), (b"Events 4203664 0 0.25", b"Events 4203664 0"), (b"Events 4203664 0 0.25", b"Events 4203664 -1 0.25"), (b"Events 4203664 0 0.25", b"Events 4203664 0 0"), (b"Events 4203664 0 0.25", b"Events 4203664 0 5"), (b"Events 4203664 0 0.25", b"Events 4203664 0 1/4"), (b"Events 4203664 0 0.25", b"Events 4203696 0 0.25"), # CC. (b"Events 4203664 0 0.25", b"Events 4203648 0 0.25"), # Explicit note-off. (b"Events 4203664 0 0.25", b"Events 9360 0 0.25"), # Zero on-velocity. (b"Events 4203664 0 0.25", b"Events 8388752 0 0.25"), # Velocity 128. (b"Events 4203664 0 0.25", b"Events 4227216 0 0.25"), # Pitch 128. (b"Events 4203664 0 0.25", b"Events 4203664 0 0.1234567890"), (b"TrackLength 16", b"TrackLength 16\nTrackLength 16"), (b"MidiEvents {", b"MidiEvents 1 {"), (b'OriginalLabel "Not song data"', b'OriginalLabel "unterminated'), (b'OriginalLabel "Not song data"', b"SongTrack 0 {\n}"), (b"SyncToHost 1", b"}\nSyncToHost 1"), (b"SyncToHost 1", b"{\nSyncToHost 1"), (b"SyncToHost 1", b"SyncToHost \0 1"), (b"SyncToHost 1", b"SyncToHost \xff 1"), ], ) def test_corrupt_unsupported_and_ambiguous_project_inputs(old: bytes, new: bytes) -> None: with pytest.raises(SerializationError): raw = TEMPLATE.read_bytes().replace(b"\r\n", b"\n") assert old in raw sdp.parse_sdp_project(raw.replace(old, new)) @pytest.mark.parametrize( ("old", "new"), [ (b'"SL-DFH"', b'"other-library"'), (b"alias kickR 36", b"alias kickR 35"), (b"alias snareR 38", b"alias snareSL 38"), (b"alias hatsTP 42", b"alias hatsTP 42\nalias other 42"), (b"pad kickR {", b"pad other {"), (b"MidiInChannel -1", b"MidiInChannel 0"), (b"midilearn {", b"midilearn {\nOriginalRemap 36 37"), ], ) def test_template_mapping_mismatch_errors_not_fallback( workspace: Path, old: bytes, new: bytes ) -> None: path = workspace / "bad.sd3p" path.write_bytes(TEMPLATE.read_bytes().replace(old, new)) _, profile = original_plan() with pytest.raises(SerializationError): sdp.check_sdp_capability("drums", profile, template=path) @pytest.mark.parametrize("bound", ["bytes", "depth", "events", "tokens"]) def test_parser_resource_bounds(monkeypatch: pytest.MonkeyPatch, bound: str) -> None: raw = TEMPLATE.read_bytes() if bound == "bytes": monkeypatch.setattr(sdp, "MAX_BYTES", 10) elif bound == "depth": monkeypatch.setattr(sdp, "MAX_DEPTH", 2) elif bound == "events": monkeypatch.setattr(sdp, "MAX_EVENTS", 0) else: monkeypatch.setattr(sdp, "MAX_TOKENS", 10) with pytest.raises(SerializationError): sdp.parse_sdp_project(raw) @pytest.mark.parametrize( "case", ["cc", "off_velocity", "wrong_channel", "plan_pitch", "preroll", "tail", "mutated"], ) def test_unrepresentable_plan_semantics_fail_before_write(workspace: Path, case: str) -> None: plan, profile = original_plan() if case == "cc": plan.tracks[0].events.append( ControlChangeEvent( part="drums", channel=9, tick=0, priority=10, sequence=100, controller=4, value=127, ) ) elif case == "off_velocity": next(e for e in plan.tracks[0].events if isinstance(e, NoteOffEvent)).velocity = 10 elif case == "wrong_channel": for event in plan.tracks[0].events: event.channel = 0 elif case == "plan_pitch": for event in plan.tracks[0].events: if isinstance(event, NoteOnEvent | NoteOffEvent) and event.note == 36: event.note = 35 elif case == "preroll": plan.musical_start_tick = 1 elif case == "tail": plan.end_tick += 1 else: plan.score.intent.tempo_bpm = float("nan") with pytest.raises(SerializationError): sdp.write_sdp(workspace / "bad.sd3p", plan, "drums", profile, template=TEMPLATE) assert not list(workspace.iterdir()) @pytest.mark.parametrize("ppq", [960, 480, 96]) def test_exact_quarter_beats_not_assumed_ppq(workspace: Path, ppq: int) -> None: plan, profile = original_plan(ppq=ppq) path = workspace / "original.sd3p" sdp.write_sdp(path, plan, "drums", profile, template=TEMPLATE) assert sdp.validate_sdp_file(path, plan, "drums", profile, template=TEMPLATE).notes[ 1 ].start == (Fraction(1, 4)) @pytest.mark.parametrize("denominator", [3, 128]) def test_nonterminating_or_overprecision_timing_is_rejected( workspace: Path, denominator: int ) -> None: plan, profile = original_plan() data = plan.score.model_dump() data["tracks"][0]["notes"][0]["duration"] = {"numerator": 1, "denominator": denominator} plan = compile_score(Score.model_validate(data), {"drums": profile}, ppq=3840) with pytest.raises(SerializationError) as error: sdp.write_sdp(workspace / "bad.sd3p", plan, "drums", profile, template=TEMPLATE) assert error.value.details["reason"] == "sd3_timing_not_representable" assert not list(workspace.iterdir()) @pytest.mark.parametrize( ("old", "new"), [ (b"OriginalGain 0.375", b"OriginalGain 0.5"), (b'trackstuff "', b'trackstuff "corrupt-'), (b"TrackLength 3.5", b"TrackLength 4"), (b"Offset 0", b"Offset 1"), (b"Velocity 0", b"Velocity 1"), (b"Mute 0", b"Mute 1"), (b"137.5", b"140"), (b"TimeSig 7 8", b"TimeSig 4 4"), (b"Events 74905", b"Events 140441"), (b"74905 0 0.125", b"74905 0 0.25"), (b"ClearNotes", b'ClearNotes\nFileName "unexpected-source.mid"'), (b'TrackName "', b'UnknownTrackName "'), (b"Type 1", b"Type 2"), (b"ClearSongParts", b"ClearSongParts\nMidiLoop 1 {\n}"), ], ) def test_saved_file_corruption_is_a_named_serialization_failure( workspace: Path, old: bytes, new: bytes ) -> None: plan, profile = original_plan() path = workspace / "saved.sd3p" sdp.write_sdp(path, plan, "drums", profile, template=TEMPLATE) raw = path.read_bytes() assert old in raw path.write_bytes(raw.replace(old, new)) with pytest.raises(SerializationError): sdp.validate_sdp_file(path, plan, "drums", profile, template=TEMPLATE) def test_suffix_exclusive_writes_template_identity_and_io_errors( workspace: Path, monkeypatch: pytest.MonkeyPatch ) -> None: plan, profile = original_plan() for suffix in ("sdp", "mid", "SD3P"): with pytest.raises(SerializationError): sdp.write_sdp(workspace / f"wrong.{suffix}", plan, "drums", profile, template=TEMPLATE) copy = workspace / "operator.sd3p" copy.write_bytes(TEMPLATE.read_bytes()) before = copy.read_bytes() with pytest.raises(OutputExistsError): sdp.write_sdp(copy, plan, "drums", profile, template=copy) assert copy.read_bytes() == before with pytest.raises(OutputIOError): sdp.write_sdp(workspace / "missing" / "out.sd3p", plan, "drums", profile, template=copy) with monkeypatch.context() as guard: guard.setattr(Path, "open", Mock(side_effect=PermissionError("private path"))) with pytest.raises(OutputIOError) as error: sdp.inspect_sdp_template(copy) assert "private" not in str(error.value.details) with monkeypatch.context() as guard: guard.setattr(os, "fsync", Mock(side_effect=OSError)) with pytest.raises(OutputIOError): sdp.write_sdp(workspace / "io.sd3p", plan, "drums", profile, template=copy) def test_writer_checks_actual_saved_bytes_not_only_its_buffer( workspace: Path, monkeypatch: pytest.MonkeyPatch ) -> None: plan, profile = original_plan() actual = sdp._replace_song monkeypatch.setattr( sdp, "_replace_song", lambda project, song: actual(project, song).replace(b"Offset 0", b"Offset 1"), ) with pytest.raises(SerializationError): sdp.write_sdp(workspace / "bad.sd3p", plan, "drums", profile, template=TEMPLATE) @pytest.mark.parametrize("channel", [0, 15]) @pytest.mark.parametrize("pitch", [0, 127]) @pytest.mark.parametrize("velocity", [1, 127]) def test_packed_message_byte_boundaries(channel: int, pitch: int, velocity: int) -> None: packed = (velocity * 65536) + (pitch * 256) + 144 + channel raw = TEMPLATE.read_bytes().replace(b"4203664 0 0.25", f"{packed} 0 0.25".encode()) (note,) = sdp.parse_sdp_project(raw).source_notes assert (note.channel, note.pitch, note.velocity) == (channel, pitch, velocity) def test_template_change_during_write_is_detected( workspace: Path, monkeypatch: pytest.MonkeyPatch ) -> None: template = workspace / "operator.sd3p" raw = TEMPLATE.read_bytes() template.write_bytes(raw) plan, profile = original_plan() def changed(_: int) -> None: template.write_bytes(raw.replace(b"OriginalGain 0.375", b"OriginalGain 0.5")) monkeypatch.setattr(os, "fsync", changed) with pytest.raises(SerializationError) as error: sdp.write_sdp(workspace / "failed.sd3p", plan, "drums", profile, template=template) assert error.value.details["reason"] == "sd3_template_changed" def test_empty_non_regular_and_versioned_templates_never_create_output(workspace: Path) -> None: plan, profile = original_plan() path = workspace / "invalid.sd3p" output = workspace / "never-created.sd3p" for raw in (b"", TEMPLATE.read_bytes().replace(b"3.4.4", b"3.5.0"), b"MThd"): path.write_bytes(raw) with pytest.raises(SerializationError): sdp.write_sdp(output, plan, "drums", profile, template=path) assert not output.exists() path.unlink() path.mkdir() with pytest.raises(OutputIOError): sdp.write_sdp(output, plan, "drums", profile, template=path) assert not output.exists() @pytest.mark.parametrize( "field", ["version", "voices", "library", "channel", "default_type", "actions", "velocity", "status"], ) def test_subset_profile_rejects_unsupported_promotions(field: str) -> None: _, profile = original_plan() data = profile.model_dump() if field == "version": data["sdp"]["layout_version"] = "3.4.5" elif field == "voices": data["drum_voices"][0]["note"] = 35 elif field == "library": data["sdp"]["sound_library"] = "SL-SD3" elif field == "channel": data["channel"] = 0 elif field == "default_type": data["default"] = "yes" elif field == "actions": data["articulations"][0]["mode"] = "momentary" elif field == "velocity": data["articulations"][0]["layers"][0]["velocity_high"] = 126 else: data["provenance"]["status"] = "verified" with pytest.raises(ValidationError): InstrumentProfile.model_validate(data)