diff --git a/MaiChartManager.Tests/ChartSplitting/ChartSplitProgressTests.cs b/MaiChartManager.Tests/ChartSplitting/ChartSplitProgressTests.cs new file mode 100644 index 00000000..b355aa50 --- /dev/null +++ b/MaiChartManager.Tests/ChartSplitting/ChartSplitProgressTests.cs @@ -0,0 +1,66 @@ +using System.IO.Compression; +using MaiChartManager.Services.ChartSplitting; + +namespace MaiChartManager.Tests.ChartSplitting; + +public class ChartSplitProgressTests +{ + private static readonly SplitCaller Caller = new("A000", 10123, 3, "127.0.0.1", ""); + private sealed class Clock : TimeProvider + { + public DateTimeOffset Now = DateTimeOffset.UtcNow; + public override DateTimeOffset GetUtcNow() => Now; + } + + [Fact] + public void OnlyMatchingTokenRouteAndCallerCanReadAndReplayNeverOverwritesReceipt() + { + var store = new ChartSplitProgressStore(TimeProvider.System); var id = Guid.NewGuid(); + Assert.True(ChartSplitProgressStore.ValidToken(id.ToString("D"), out var parsed)); Assert.Equal(id, parsed); + Assert.False(ChartSplitProgressStore.ValidToken(Guid.Empty.ToString(), out _)); + Assert.False(ChartSplitProgressStore.ValidToken("../A000", out _)); + Assert.Null(store.Read(id, Caller)); var w = store.TryStart(id, Caller, 3, out var duplicate)!; Assert.False(duplicate); + w.Step("encoding", 2, 32, 107); var s = store.Read(id, Caller)!; Assert.Equal("encoding", s.Stage); Assert.Equal(32, s.Completed); Assert.Equal(107, s.Total); Assert.Equal(3, s.Parts); Assert.Null(s.Outcome); + Assert.Null(store.Read(id, Caller with { Level = 2 })); Assert.Null(store.Read(id, Caller with { Address = "::2" })); Assert.Null(store.Read(id, Caller with { Principal = "other" })); + store.Finish(w, "installed"); Assert.Null(store.TryStart(id, Caller, 4, out duplicate)); Assert.True(duplicate); Assert.Equal("installed", store.Read(id, Caller)!.Outcome); + } + + [Fact] + public void RetentionIsBoundedActiveWorkDoesNotExpireAndPollsCannotExtendReceiptLifetime() + { + var clock = new Clock(); var store = new ChartSplitProgressStore(clock, 1); var id = Guid.NewGuid(); var work = store.TryStart(id, Caller, 2, out _)!; + clock.Now += TimeSpan.FromHours(1); Assert.NotNull(store.Read(id, Caller)); Assert.Null(store.TryStart(Guid.NewGuid(), Caller, 2, out _)); + store.Finish(work, "failed", "没有读取或安装权限。"); clock.Now += TimeSpan.FromMinutes(9); Assert.Equal("failed", store.Read(id, Caller)!.Outcome); + clock.Now += TimeSpan.FromMinutes(1); Assert.Null(store.Read(id, Caller)); Assert.NotNull(store.TryStart(Guid.NewGuid(), Caller, 2, out _)); + } + + [Theory] + [InlineData(5, true)] + [InlineData(19, true)] + [InlineData(1314, true)] + [InlineData(1, false)] + [InlineData(13, false)] + [InlineData(30, false)] + public void NativePermissionAndReadOnlyErrorsAreNotServerErrors(int errno, bool windows) + => Assert.IsType(ChartSplitPublisher.NativeError(errno, windows, "无法创建暂存目录。")); + + [Fact] + public void RecheckAndPublishAreNotTerminalUntilAtomicRenameReturns() + { + var root = Directory.CreateTempSubdirectory("chart-progress-test-"); + try + { + var streaming = Path.Combine(root.FullName, "Sinmai_Data", "StreamingAssets"); + var a000 = Directory.CreateDirectory(Path.Combine(streaming, "A000")); + File.WriteAllText(Path.Combine(a000.FullName, "DataConfig.xml"), "70"); + var dest = Path.Combine(streaming, "A999"); var plan = new ChartSplitPlan("A999", "test", ["one", "two"], 1, 1, [18000, 18001], dest, true, "", [], []); + var store = new ChartSplitProgressStore(TimeProvider.System); var id = Guid.NewGuid(); var w = store.TryStart(id, Caller, 2, out _)!; + using var memory = new MemoryStream(); using (var z = new ZipArchive(memory, ZipArchiveMode.Create, true)) { z.CreateEntry("A999/fixture.txt"); } + memory.Position = 0; + ChartSplitPublisher.Publish(plan, memory, () => { Assert.False(Directory.Exists(dest)); var status = store.Read(id, Caller)!; Assert.Equal("rechecking", status.Stage); Assert.Null(status.Outcome); }, default, w); + Assert.True(File.Exists(Path.Combine(dest, "fixture.txt"))); Assert.Equal("publishing", store.Read(id, Caller)!.Stage); + store.Finish(w, "installed"); Assert.Equal("done", store.Read(id, Caller)!.Stage); + } + finally { root.Delete(true); } + } +} diff --git a/MaiChartManager.Tests/ChartSplitting/Ma2SplitChartTests.cs b/MaiChartManager.Tests/ChartSplitting/Ma2SplitChartTests.cs new file mode 100644 index 00000000..18d33183 --- /dev/null +++ b/MaiChartManager.Tests/ChartSplitting/Ma2SplitChartTests.cs @@ -0,0 +1,124 @@ +using MaiChartManager.Services.ChartSplitting; + +namespace MaiChartManager.Tests.ChartSplitting; + +public class Ma2SplitChartTests +{ + private const string Header = """ + VERSION 0.00.00 1.05.00 + FES_MODE 0 + BPM_DEF 120 120 240 120 + MET_DEF 4 4 + RESOLUTION 384 + CLK_DEF 384 + COMPATIBLE_CODE MA2 + """; + private static Ma2SplitChart Parse(string body) => Ma2SplitChart.Parse(Header + "\n" + body); + + [Fact] + public void ZeroImplicitClocksSurvivesAndOnlyInteriorExplicitClocksAreShifted() + { + var c = Ma2SplitChart.Parse(Header.Replace("CLK_DEF 384", "CLK_DEF 0") + + "\nCLK 0 0\nCLK 0 96\nCLK 0 192\nNMTAP 0 96 0\nNMTAP 0 192 1"); + var sliced = c.Slice(96, 192, 24); + var lines = sliced.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries); + Assert.Contains("CLK_DEF\t0", lines); + Assert.Equal(new[] { "CLK\t0\t24" }, lines.Where(l => l.StartsWith("CLK\t")).ToArray()); + Assert.Equal(24L, Assert.Single(Ma2SplitChart.Parse(sliced).Notes).Tick); + } + + [Fact] + public void TempoIntegrationAndHalfOpenCutAreAlignedToAudioLead() + { + var c = Parse(""" + BPM 0 0 120 + BPM 0 192 240 + MET 0 192 8 3 + BPM 1 0 160 + MET 1 0 12 11 + CLK 1 0 + NMTAP 0 0 0 + NMTAP 0 192 1 + NMTAP 1 96 2 + NMTAP 1 192 3 + T_NUM_ALL 987 + """); + Assert.Equal(1.875, c.SecondsAt(480), 9); + long lead = c.LeadTicks(192, 0.25); Assert.Equal(96L, lead); + var text = c.Slice(192, 576, lead); var part = Ma2SplitChart.Parse(text); + Assert.Equal(new Ma2TempoPoint(0, 240), part.Tempos[0]); Assert.Equal(new Ma2TempoPoint(288, 160), part.Tempos[1]); + Assert.Equal(new Ma2MeterPoint(0, 3, 8), part.Meters[0]); Assert.Equal(new Ma2MeterPoint(288, 11, 12), part.Meters[1]); + Assert.Equal(2, part.Notes.Count); Assert.Equal(96L, part.Notes[0].Tick); Assert.Equal(384L, part.Notes[1].Tick); + Assert.Equal(c.SecondsAt(480) - c.SecondsAt(192) + 0.25, part.SecondsAt(384), 9); + Assert.Contains("CLK\t0\t288", text); Assert.Contains("T_NUM_ALL\t2", text); + } + + [Fact] + public void RejectsEitherBoundaryInsideHoldOrEntireConnectedSlideIncludingWait() + { + var c = Parse(""" + NMHLD 0 0 5 96 + NMSTR 0 96 0 + NMSI_ 0 96 0 24 72 3 + CNSCR 0 192 3 0 48 4 + NMTAP 0 240 4 + """); + var slide = c.Notes.Single(n => n.Kind == "NMSI_"); + Assert.Equal(120L, slide.SlideStartTick); // 96+24; the later CN does not replace the initial wait + Assert.Equal(240L, slide.EndTick); + Assert.All(c.Notes.Where(n => n != slide), n => Assert.Null(n.SlideStartTick)); + foreach (var t in new long[] { 48, 100, 160, 192, 200 }) + { + Assert.Throws(() => c.Slice(0, t, 0)); + Assert.Throws(() => c.Slice(t, c.EndTick, 0)); + } + var text = c.Slice(96, 240, 48); Assert.Contains("CNSCR\t0\t144\t3\t0\t48\t4", text); + Assert.Contains("T_NUM_ALL\t2", text); Assert.Contains("T_NUM_SLD\t1", text); Assert.DoesNotContain("NMTAP", text); + Assert.Equal(1, Ma2SplitChart.Parse(c.Slice(0, 96, 0)).Notes.Count); + } + + [Fact] + public void RebuildsStatisticsFromNativeRecordsIncludingModifiersAndTempoDependentHoldJudges() + { + var c = Parse(""" + BPM 0 0 120 + BPM 0 48 240 + BRTAP 0 0 0 + BXHLD 0 0 1 144 + NMTTP 0 96 0 C 1 M1 + NMTHO 0 144 0 96 C 0 L1 + """); + var text = c.Slice(0, c.EndTick, 0); + foreach (string line in new[] { "T_REC_BXH\t1", "T_NUM_BRK\t2", "T_NUM_HLD\t1", "T_NUM_TAP\t1", "T_JUDGE_HLD\t3", "T_JUDGE_TAP\t2", "TTM_EACHPAIRS\t1", "TTM_SCR_SS\t6500", "TTM_SCR_ALL\t6700", "TTM_RAT_ACV\t10307" }) Assert.Contains(line + Environment.NewLine, text); + } + + [Fact] + public void Legacy103DoesNotUpgradeRowsOrAddModernStats() + { + var c = Ma2SplitChart.Parse(Header.Replace("1.05.00", "1.03.00") + "\nSTR 0 0 1\nSI_ 0 0 1 96 24 3\nXHO 1 0 7 96"); + var text = c.Slice(0, 120, 0); Assert.Contains("T_REC_SLD\t1", text); Assert.DoesNotContain("T_REC_BSL", text); + Assert.Equal(120L, Ma2SplitChart.Parse(text).Notes[1].EndTick); + } + + [Theory] + [InlineData("SEF 0 96 1")] + [InlineData("T_REC_UNKNOWN 0")] + [InlineData("NMTAP 0 0 8")] + [InlineData("NMTAP 0 384 1")] + [InlineData("NMSI_ 0 0 0 -1 12 3")] + [InlineData("NMSI_ 0 0 0 0 0 3")] + [InlineData("NMHLD 0 0 0 1 trailing")] + [InlineData("CNSI_ 0 0 0 0 48 2")] + [InlineData("NMTTP 0 0 0 Q 3 XXL")] + [InlineData("BPM 0 96 NaN")] + [InlineData("BPM 0 0 100\nBPM 0 0 120")] + public void RefusesUnsupportedOrMalformedInput(string row) => Assert.Throws(() => Parse("NMTAP 1 0 0\n" + row)); + + [Fact] + public void RefusesEmptySegmentAndOutOfRangeArguments() + { + var c = Parse("NMTAP 1 0 7"); Assert.Throws(() => c.Slice(0, 96, 0)); + Assert.Throws(() => c.Slice(0, 386, 0)); Assert.Throws(() => c.Slice(384, 384, 0)); + Assert.Throws(() => c.Slice(384, 385, -1)); Assert.Throws(() => c.LeadTicks(0, double.PositiveInfinity)); + } +} diff --git a/MaiChartManager.Tests/ChartSplitting/PracticeCodecProgressTests.cs b/MaiChartManager.Tests/ChartSplitting/PracticeCodecProgressTests.cs new file mode 100644 index 00000000..5bd8fe14 --- /dev/null +++ b/MaiChartManager.Tests/ChartSplitting/PracticeCodecProgressTests.cs @@ -0,0 +1,38 @@ +using MaiChartManager.Utils; +using NAudio.Wave; +using VGAudio; +using VGAudio.Cli; +namespace MaiChartManager.Tests.ChartSplitting; + +public class PracticeCodecProgressTests +{ + [Fact] + public async Task OverlappingLoopedCueAndPracticeEncodesMatchTheirSerialResults() + { + using var wave = new MemoryStream(); + using (var raw = new RawSourceWaveStream(new MemoryStream(new byte[44100 * 2]), new WaveFormat(44100, 16, 1))) + WaveFileWriter.WriteWavFileToStream(wave, raw); + var bytes = wave.ToArray(); + byte[] Looped() { using var w = new MemoryStream(bytes); return Audio.ConvertFile(w, FileType.Wave, FileType.Hca, true); } + byte[] Practice(Action? cb = null) { using var w = new MemoryStream(bytes); return PracticeHca.Encode(w, default, cb); } + var expectedLooped = Looped(); var expectedPractice = Practice(); + using var started = new ManualResetEventSlim(); using var ordinaryStarted = new ManualResetEventSlim(); + var practice = Task.Run(() => Practice((_, _) => { started.Set(); Assert.True(ordinaryStarted.Wait(TimeSpan.FromSeconds(10))); })); + var ordinary = Task.Run(() => { Assert.True(started.Wait(TimeSpan.FromSeconds(10))); ordinaryStarted.Set(); return Looped(); }); + await Task.WhenAll(practice, ordinary); + Assert.Equal(expectedPractice, await practice); Assert.Equal(expectedLooped, await ordinary); + } + + [Fact] + public void RealFrameCountsAndByteIdenticalAudio() + { + using var wav = new MemoryStream(); + var samples = new byte[44100 * 2]; + for (int i = 0; i < samples.Length; i += 2) BitConverter.TryWriteBytes(samples.AsSpan(i), (short)(8000 * Math.Sin(i * .023))); + using (var raw = new RawSourceWaveStream(new MemoryStream(samples), new WaveFormat(44100, 16, 1))) WaveFileWriter.WriteWavFileToStream(wav, raw); + wav.Position = 0; var expected = Audio.ConvertFile(wav, FileType.Wave, FileType.Hca, false, 9170825592834449000); wav.Position = 0; + var reports = new List<(int done, int total)>(); var actual = PracticeHca.Encode(wav, default, (d, t) => reports.Add((d, t))); + Assert.Equal(expected, actual); Assert.True(reports[0].total > 1); Assert.Equal(0, reports[0].done); Assert.Equal(reports[^1].total, reports[^1].done); + Assert.All(reports, r => Assert.InRange(r.done, 0, r.total)); + } +} diff --git a/MaiChartManager.Tests/ChartSplitting/PracticeDifficultyTests.cs b/MaiChartManager.Tests/ChartSplitting/PracticeDifficultyTests.cs new file mode 100644 index 00000000..80ac80b5 --- /dev/null +++ b/MaiChartManager.Tests/ChartSplitting/PracticeDifficultyTests.cs @@ -0,0 +1,29 @@ +using System.Xml; +using MaiChartManager.Services.ChartSplitting; + +namespace MaiChartManager.Tests.ChartSplitting; + +public class PracticeDifficultyTests +{ + [Fact] + public void SplitKeepsSourceLevelBadgeAndOnlyZerosTheClonedConstants() + { + var src = new XmlDocument(); + var difficulties = string.Concat(Enumerable.Range(0, 6).Select(i => $"source.ma2{10 + i}9{17 + i}48true")); + src.LoadXml($"original1SourceSOURCE1801Source1Source{difficulties}"); + var before = src.OuterXml; + // A section can start at a fractional MA2 tempo; the song list reads its display BPM as Int32. + var result = ChartSplitExportService.BuildXml(src, 18000, 1, 3, 12, 57.333); + Assert.Equal(180, XmlConvert.ToInt32(result.DocumentElement!["bpm"]!.InnerText)); + var notes = result.SelectNodes("/MusicData/notesData/Notes")!.Cast().ToArray(); + Assert.Equal(6, notes.Length); + for (int i = 0; i < notes.Length; i++) + { + Assert.Equal((17 + i).ToString(), notes[i]["musicLevelID"]!.InnerText); + Assert.Equal("0", notes[i]["level"]!.InnerText); + Assert.Equal("0", notes[i]["levelDecimal"]!.InnerText); + Assert.Equal(i == 3 ? "true" : "false", notes[i]["isEnable"]!.InnerText); + } + Assert.Equal(before, src.OuterXml); + } +} diff --git a/MaiChartManager.Tests/ChartSplitting/PracticeRangeTests.cs b/MaiChartManager.Tests/ChartSplitting/PracticeRangeTests.cs new file mode 100644 index 00000000..a471bb4a --- /dev/null +++ b/MaiChartManager.Tests/ChartSplitting/PracticeRangeTests.cs @@ -0,0 +1,15 @@ +using MaiChartManager.Services.ChartSplitting; +namespace MaiChartManager.Tests.ChartSplitting; + +public class PracticeRangeTests +{ + [Theory] + [InlineData(123, 8999)] + [InlineData(10123, 18999)] + public void LastSlotThenRefuseRatherThanWrap(int source, int last) + { + var taken = Enumerable.Range(8000, 999).ToArray(); + Assert.Equal(new[] { last }, ChartSplitExportService.AllocateIds(source, taken, 1)); + Assert.Throws(() => ChartSplitExportService.AllocateIds(source, taken, 2)); + } +} diff --git a/MaiChartManager.Tests/Controllers/Charts/ChartSplitExportTests.cs b/MaiChartManager.Tests/Controllers/Charts/ChartSplitExportTests.cs new file mode 100644 index 00000000..e23c09a2 --- /dev/null +++ b/MaiChartManager.Tests/Controllers/Charts/ChartSplitExportTests.cs @@ -0,0 +1,146 @@ +using System.IO.Compression; +using System.Xml; +using MaiChartManager.Services.ChartSplitting; +using MaiChartManager.Utils; +using NAudio.Wave; + +namespace MaiChartManager.Tests.Controllers.Charts; + +public class ChartSplitExportTests +{ + private static readonly ChartSplitRequest Request = new([384], 2, 2, 8, 8); + + [Fact] + public void WindowsClipToActualSourceAndFadesNeverTouchChart() + { + Assert.Equal(new SplitWindow(0, 2, .25, .25, .5), ChartSplitExportService.Window(.25, 1.5, 60, 120, 2, Request)); + Assert.Equal(new SplitWindow(1, 4.5, 1, 1, .5), ChartSplitExportService.Window(2, 4, 120, 240, 10, Request)); + Assert.Equal(0, ChartSplitExportService.Window(1, 4, 120, 120, 3.9, Request).FadeOut); + Assert.Equal(new long[]{0,384,450}, ChartSplitExportService.Boundaries(Request, 450)); + foreach (long[] cuts in new long[][] { [], [0], [450], [10,10], [20,10] }) + Assert.Throws(() => ChartSplitExportService.Boundaries(Request with { Cuts = cuts }, 450)); + Assert.Throws(() => ChartSplitExportService.Boundaries(Request with { PreBeats = double.NaN }, 450)); + } + + [Theory] + [InlineData("../A000", 1, 3)] + [InlineData("A000/", 1, 3)] + [InlineData("A000", -1, 3)] + [InlineData("A000", 1, 6)] + public void InvalidRouteKeysAreRejectedBeforeLibraryLookup(string asset, int song, int level) + { + Assert.Throws(() => ChartSplitExportService.Resolve(null!, asset, song, level)); + } + + [Fact] + public void IdAllocatorReservesSourceAndAllSharedSoundSuffixes() + { + Assert.Equal(new[]{18004,18005}, ChartSplitExportService.AllocateIds(18000, [8001,18002,108003], 2)); + Assert.Throws(() => ChartSplitExportService.AllocateIds(22, Enumerable.Range(1,9999), 1)); + } + + private static MemoryStream AudioFixture(int seconds, int rate = 16000) + { + var bytes = new byte[seconds * rate * 2]; + for (int i = 0; i < bytes.Length; i += 2) { bytes[i] = 0x10; bytes[i + 1] = 0x27; } // 10000 + using var raw = new RawSourceWaveStream(new MemoryStream(bytes), new WaveFormat(rate,16,1)); + var wav = new MemoryStream(); WaveFileWriter.WriteWavFileToStream(wav, raw); wav.Position = 0; return wav; + } + + [Theory] + [InlineData(2, false)] [InlineData(4, false)] [InlineData(8, true)] + public void ReadOnlyBankFallbackKeepsPointerWidthsAndAlternateNames(int width, bool alternate) + { + var dir = Directory.CreateTempSubdirectory("mcm-awb-reader-"); + try + { + var acbPath = Path.Combine(dir.FullName, "cue.acb"); + var template = Audio.LoadCueTemplate(Path.Combine(AppContext.BaseDirectory, "nopreview.acb")); + var wrapper = new Xv2CoreLib.ACB.ACB_Wrapper(template); + using var wav = AudioFixture(1); + var hca = PracticeHca.Encode(wav, default, null); + wrapper.Cues[0].AddTrackToCue(hca, true, false, Xv2CoreLib.ACB.EncodeType.HCA); + wrapper.AcbFile.Save(acbPath); + var mainBank = Path.ChangeExtension(acbPath, ".awb"); + var expected = Audio.AcbToWav(acbPath); + var id = Assert.Single(Xv2CoreLib.AFS2.AFS2_File.LoadFromStream(mainBank).Entries).ID; + File.Delete(mainBank); + var bank = alternate ? Path.Combine(dir.FullName, "cue_streamfiles.awb") : mainBank; + // A one-entry AFS2 fixture; a 64-bit pointer table need not contain gigabytes of PCM. + using (var output = new BinaryWriter(File.Create(bank))) + { + output.Write("AFS2"u8); output.Write((byte)1); output.Write((byte)width); + output.Write((short)2); output.Write(1); output.Write(1); output.Write((ushort)id); + void Pointer(long n) { if (width == 2) output.Write(checked((ushort)n)); else if(width == 4) output.Write((uint)n); else output.Write(n); } + var first=18+2*width; Pointer(first); Pointer(first+hca.Length); output.Write(hca); + } + var bankOriginal = File.ReadAllBytes(bank); + using var readOnlyHandle = new FileStream(bank, FileMode.Open, FileAccess.Read, FileShare.Read); + Assert.Equal(expected, Audio.AcbToWav(acbPath)); + var staged = Audio.LoadReadOnlyCue(acbPath); + var waveform = staged.GetWaveformsFromCue(staged.Cues[0])[0]; + Assert.Equal(hca, staged.GetAfs2Entry(waveform.AwbId).bytes); + Assert.Equal(bankOriginal, File.ReadAllBytes(bank)); + } + finally { dir.Delete(true); } + } + + [Fact] + public void PcmFadeIsAudibleOnlyOutsidePracticeRegion() + { + using var source = new WaveFileReader(AudioFixture(2)); + using var slice = ChartSplitExportService.Crop(source, new SplitWindow(.25,1.75,.25,.25,.5), default); + using var wave = new WaveFileReader(slice); + Assert.Equal(1.5, wave.TotalTime.TotalSeconds, 6); + short At(int frame) { wave.Position = frame * 2; var b = new byte[2]; wave.ReadExactly(b); return BitConverter.ToInt16(b); } + Assert.Equal(0, At(0)); Assert.Equal(5000, At(2000)); Assert.Equal(10000, At(4000)); + Assert.Equal(10000, At(15999)); Assert.Equal(0, At(23999)); + } + + [Fact] + public void RealOptZipContainsTwoDecodableBanksAndIndependentCharts() + { + var chart = Ma2SplitChart.Parse(""" + VERSION 0.00.00 1.03.00 + BPM_DEF 120 120 120 120 + MET_DEF 4 4 + RESOLUTION 384 + CLK_DEF 384 + COMPATIBLE_CODE MA2 + TAP 0 0 0 + TAP 1 0 1 + TAP 1 96 2 + """); + var xml = new XmlDocument(); + xml.LoadXml("31Original3131ORIGmusic00003112083" + string.Concat(Enumerable.Repeat("old.ma2true99",6)) + ""); + var original = xml.OuterXml; + using var source = new WaveFileReader(AudioFixture(4,44100)); + string path; + using (var payload = ChartSplitExportService.BuildZip(chart,3,Request,[0,384,chart.EndTick],[18000,18001],"A998",null,xml,source,default)) + { + path = payload.Name; + using var zip = new ZipArchive(payload, ZipArchiveMode.Read); + Assert.Equal(8,zip.Entries.Count); + var scratch = Directory.CreateTempSubdirectory("split-test-"); + try + { + for(int i=0;i<2;i++) + { + var music = $"A998/music/music{18000+i:D6}/"; + var doc = new XmlDocument(); using(var stream = zip.GetEntry(music+"Music.xml")!.Open()) doc.Load(stream); + Assert.Equal(1, doc.SelectNodes("//Notes[isEnable='true']")!.Count); + Assert.Equal($"{i+1}", doc.SelectSingleNode("//Notes[isEnable='true']/maxNotes")!.InnerText); + Assert.Equal("83",doc.SelectSingleNode("//rightsInfoName/id")!.InnerText); + using var reader = new StreamReader(zip.GetEntry(music+$"{18000+i:D6}_03.ma2")!.Open()); + Assert.Equal(i+1,Ma2SplitChart.Parse(reader.ReadToEnd()).Notes.Count); + var stem = $"music{8000+i:D6}"; + foreach(var ext in new[]{".acb",".awb"}) zip.GetEntry($"A998/SoundData/{stem}{ext}")!.ExtractToFile(Path.Combine(scratch.FullName,stem+ext)); + using var decoded = new WaveFileReader(new MemoryStream(Audio.AcbToWav(Path.Combine(scratch.FullName,stem+".acb")))); + Assert.InRange(decoded.TotalTime.TotalSeconds, i == 0 ? 2.95 : 2.45, i == 0 ? 3.05 : 2.56); + } + } + finally { scratch.Delete(true); } + } + Assert.False(File.Exists(path)); Assert.Equal(original,xml.OuterXml); + } +} diff --git a/MaiChartManager.Tests/Controllers/Charts/ChartSplitInstallTests.cs b/MaiChartManager.Tests/Controllers/Charts/ChartSplitInstallTests.cs new file mode 100644 index 00000000..64036590 --- /dev/null +++ b/MaiChartManager.Tests/Controllers/Charts/ChartSplitInstallTests.cs @@ -0,0 +1,77 @@ +using System.IO.Compression; +using System.Text; +using System.Xml.Linq; +using MaiChartManager.Services.ChartSplitting; + +namespace MaiChartManager.Tests.Controllers.Charts; + +public sealed class ChartSplitInstallTests:IDisposable +{ + private readonly DirectoryInfo temp=Directory.CreateTempSubdirectory("mcm-test-opt-"); + private string Root=>temp.FullName; + private string Option=>Path.Combine(Root,"option"); + private string Streaming=>Path.Combine(Root,"Sinmai_Data","StreamingAssets"); + private string Marker=>Path.Combine(Streaming,"A000","DataConfig.xml"); + private const string MarkerXml="1700"; + public ChartSplitInstallTests(){Directory.CreateDirectory(Path.GetDirectoryName(Marker)!);File.WriteAllText(Marker,MarkerXml);} + public void Dispose()=>temp.Delete(true); + private static ChartSplitRequest Req=>new([384],2,2,1,1); + private ChartSplitPlan Plan(ChartSplitRequest? request=null){var cat=ChartSplitCatalog.Scan(Root,default);var (g,v)=cat.Practice.Resolve();return cat.Plan(10100,"曲",g,v,[new(g,"练习分区")],[new(v,"练习分区")],2,request);} + private static MemoryStream Pack(ChartSplitPlan plan){var ms=new MemoryStream();using(var z=new ZipArchive(ms,ZipArchiveMode.Create,true))ChartSplitPractice.AddDefinitions(z,plan.OptName,plan.GenreId,plan.VersionId);ms.Position=0;return ms;} + private void Song(string pkg,int id,int cue,string title) { + var dir=Directory.CreateDirectory(Path.Combine(pkg,"music",$"music{id:D6}")).FullName; + var x=new XElement("MusicData",new XElement("name",new XElement("id",id),new XElement("str",title)),new XElement("cueName",new XElement("id",cue)),new XElement("movieName",new XElement("id",cue)));x.Save(Path.Combine(dir,"Music.xml")); + } + [Fact]public void OldLibraryAndUnloadedOptionReservePathsIdsTitlesAndLooseBanks(){ + var a=Path.Combine(Streaming,"A999");Song(a,18000,8001,"Already installed");var z=Path.Combine(Option,"A998");Song(z,18002,8111,"SONG"); + var sound=Directory.CreateDirectory(Path.Combine(z,"SoundData")).FullName;File.WriteAllText(Path.Combine(sound,"music008003.awb"),"stub"); + var jacket=Directory.CreateDirectory(Path.Combine(z,"AssetBundleImages","jacket_s")).FullName;File.WriteAllText(Path.Combine(jacket,"ui_jacket_008004_s.ab"),"stub"); + var p=Plan();Assert.True(p.CanInstall);Assert.Equal("A997",p.OptName);Assert.Equal(new[]{18005,18006},p.Ids);Assert.Equal("Sinmai_Data/StreamingAssets",p.TargetRoot);Assert.Equal(Path.Combine(Streaming,"A997"),p.Destination); + Assert.Throws(()=>Plan(Req with{SegmentTitles=["song","next"]})); + Assert.Throws(()=>Plan(Req with{SegmentTitles=["No.1"," NO.1 "]})); + Assert.Throws(()=>Plan(Req with{OptName="A998"})); + Assert.Throws(()=>Plan(Req with{Ids=[18111,18888]})); + Assert.Throws(()=>Plan(Req with{OptName="../A012"})); + Assert.Empty(Directory.GetDirectories(Streaming,".mcm-stage-*")); + } + [Theory][InlineData(false)][InlineData(true)] + public void InstallDoesNotRequireOptionOrFollowSegatoolsVfs(bool hasIni){ + if(hasIni)File.WriteAllText(Path.Combine(Root,"segatools.ini"),"[vfs]\noption=unrelated\n"); + var p=Plan();Assert.True(p.CanInstall);Assert.Equal(Path.Combine(Streaming,"A999"),p.Destination); + using var zip=Pack(p);ChartSplitPublisher.Publish(p,zip,()=>{},default); + Assert.True(Directory.Exists(p.Destination));Assert.False(Directory.Exists(Option));Assert.False(Directory.Exists(Path.Combine(Root,"unrelated"))); + } + [Fact]public void SegatoolsAndLegacyOptionCannotSubstituteForMissingA000DataConfig(){ + File.Delete(Marker);Directory.CreateDirectory(Option);File.WriteAllText(Path.Combine(Root,"segatools.ini"),"[vfs]\noption=option\n"); + var p=Plan();Assert.False(p.CanInstall); + using var zip=Pack(p);Assert.Throws(()=>ChartSplitPublisher.Publish(p,zip,()=>{},default)); + Assert.False(Directory.Exists(p.Destination));Assert.Empty(Directory.GetDirectories(Streaming,".mcm-stage-*"));Assert.Empty(Directory.EnumerateFileSystemEntries(Option)); + } + [Fact]public void ExistingEmptyTargetCannotBeReplacedEvenAfterSuccessfulFinalCheck(){ + var p=Plan();using var zip=Pack(p); + Assert.Throws(()=>ChartSplitPublisher.Publish(p,zip,()=>Directory.CreateDirectory(p.Destination),default)); + Assert.True(Directory.Exists(p.Destination));Assert.Empty(Directory.EnumerateFileSystemEntries(p.Destination));Assert.Empty(Directory.GetDirectories(Streaming,".mcm-stage-*")); + } + [Fact]public void FinalCatalogConflictRollsBackStageWithoutPublishing(){ + var p=Plan();using var zip=Pack(p);var held=Req with{OptName=p.OptName,Ids=p.Ids,SegmentTitles=p.SegmentTitles}; + Assert.Throws(()=>ChartSplitPublisher.Publish(p,zip,()=>{Song(Path.Combine(Option,"A010"),p.Ids[0],p.Ids[0]%10000,"Other");Plan(held);},default)); + Assert.False(Directory.Exists(p.Destination));Assert.Empty(Directory.GetDirectories(Streaming,".mcm-stage-*"));Assert.True(Directory.Exists(Path.Combine(Option,"A010"))); + } + [Fact]public void PracticePackReusesOwnedDefinitionsAndDoesNotDependOnFirstPack(){ + var p=Plan();using(var zip=Pack(p)) ChartSplitPublisher.Publish(p,zip,()=>{},default); + var q=Plan();Assert.NotEqual(p.Destination,q.Destination);Assert.Equal(p.GenreId,q.GenreId);Assert.Equal(p.VersionId,q.VersionId);using(var zip=Pack(q)) ChartSplitPublisher.Publish(q,zip,()=>{},default); + foreach(var f in Directory.EnumerateFiles(p.Destination,"*",SearchOption.AllDirectories)){var twin=Path.Combine(q.Destination,Path.GetRelativePath(p.Destination,f));Assert.Equal(File.ReadAllBytes(f),File.ReadAllBytes(twin));} + Directory.Delete(p.Destination,true);Assert.Equal(q.GenreId,Plan().GenreId);File.WriteAllText(Path.Combine(q.Destination,ChartSplitPractice.Marker),"unrelated");Assert.Throws(()=>Plan()); + } + [Fact]public void CreatesOneStreamingSiblingAndPreservesExistingPackagesAndLegacyOption(){ + var a000=Path.GetDirectoryName(Marker)!;var a001=Directory.CreateDirectory(Path.Combine(Streaming,"A001")).FullName; + var legacy=Directory.CreateDirectory(Path.Combine(Option,"A123")).FullName; + foreach(var existing in new[]{a000,a001,legacy})File.WriteAllText(Path.Combine(existing,"sentinel.txt"),existing); + var p=Plan();using var zip=Pack(p);ChartSplitPublisher.Publish(p,zip,()=>{},default); + Assert.Equal(new[]{"A000","A001","A999"},Directory.EnumerateFileSystemEntries(Streaming).Select(Path.GetFileName).Order().ToArray()); + Assert.Equal(new[]{legacy},Directory.GetFileSystemEntries(Option));Assert.Equal(MarkerXml,File.ReadAllText(Marker)); + foreach(var existing in new[]{a000,a001,legacy}){Assert.Equal(existing,File.ReadAllText(Path.Combine(existing,"sentinel.txt")));Assert.Empty(Directory.GetDirectories(existing));} + Assert.True(File.Exists(Path.Combine(Streaming,"A999","Common","Sprites","Tab","Title",ChartSplitPractice.Texture+".png"))); + Assert.Throws(()=>Plan(Req with{OptName=p.OptName})); + } +} diff --git a/MaiChartManager.Tests/Integration/PracticeSongFlowTests.cs b/MaiChartManager.Tests/Integration/PracticeSongFlowTests.cs new file mode 100644 index 00000000..602bc7b8 --- /dev/null +++ b/MaiChartManager.Tests/Integration/PracticeSongFlowTests.cs @@ -0,0 +1,147 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using System.Xml; +using System.Xml.Linq; +using MaiChartManager.Models; +using MaiChartManager.Services.ChartSplitting; +using MaiChartManager.Utils; +using Microsoft.Extensions.Logging.Abstractions; +using NAudio.Wave; +using Xv2CoreLib.ACB; + +namespace MaiChartManager.Tests.Integration; + +[Collection("Static settings")] +public class PracticeSongFlowTests +{ + private const int SongId = 10123, Difficulty = 3; + private const long Cut = 384; + + [Fact] + public void ExportAndInstallTwoBatchesWithoutLosingFractionalTempoOrOverwritingAnExistingPack() + { + var temp = Directory.CreateTempSubdirectory("practice-flow-"); + var previous = (StaticSettings.GamePath, StaticSettings.AcbAwb, StaticSettings.AssetBundleJacketMap, + StaticSettings.PseudoAssetBundleJacketMap, StaticSettings.MovieDataMap); + var errors = StaticSettings.StartupErrorsList.ToArray(); + try + { + // Start without booting mod configuration; invoke the actual scanners on the fixture below. + StaticSettings.GamePath = ""; + var settings = new StaticSettings(NullLogger.Instance, null!); + StaticSettings.GamePath = temp.FullName; + StaticSettings.AcbAwb = []; StaticSettings.AssetBundleJacketMap = []; + StaticSettings.PseudoAssetBundleJacketMap = []; StaticSettings.MovieDataMap = []; + Assert.Equal(Path.Combine(temp.FullName, "LocalAssets"), StaticSettings.ImageAssetsDir); + var source = Directory.CreateDirectory(Path.Combine(StaticSettings.StreamingAssets, "A000")).FullName; + WriteSource(source); + var original = Snapshot(source); + settings.ScanMusicList(); + settings.ScanSoundData(); + var (song, chart) = ChartSplitExportService.Resolve(settings, "A000", SongId, Difficulty); + ChartSplitPlan Plan() => ChartSplitExportService.Plan(settings, song, 2, null, default); + ChartSplitPlan Install(ChartSplitPlan p) => ChartSplitExportService.Install(settings, song, chart, Difficulty, Confirm(p), default); + + var first = Plan(); + Assert.True(first.CanInstall); + Assert.Equal(Path.Combine(StaticSettings.StreamingAssets, first.OptName), first.Destination); + var extracted = Path.Combine(temp.FullName, "export"); + using (var stream = ChartSplitExportService.Export(settings, song, chart, Difficulty, Confirm(first), default)) + using (var zip = new ZipArchive(stream, ZipArchiveMode.Read)) zip.ExtractToDirectory(extracted); + Assert.False(Directory.Exists(first.Destination)); + VerifySongs(Path.Combine(extracted, first.OptName), first, chart); + + Install(first); + VerifySongs(first.Destination, first, chart); + var installed = Snapshot(first.Destination); + Assert.Throws(() => Install(first)); + var next = Plan(); + Assert.NotEqual(first.OptName, next.OptName); + Assert.Empty(first.Ids.Intersect(next.Ids)); + Assert.Equal((first.GenreId, first.VersionId), (next.GenreId, next.VersionId)); + Install(next); + VerifySongs(next.Destination, next, chart); + Assert.Equal(installed, Snapshot(first.Destination)); + Assert.Equal(original, Snapshot(source)); + Assert.False(Directory.Exists(Path.Combine(temp.FullName, "option"))); + } + finally + { + (StaticSettings.GamePath, StaticSettings.AcbAwb, StaticSettings.AssetBundleJacketMap, + StaticSettings.PseudoAssetBundleJacketMap, StaticSettings.MovieDataMap) = previous; + StaticSettings.StartupErrorsList.Clear(); StaticSettings.StartupErrorsList.AddRange(errors); + temp.Delete(true); + } + } + + private static ChartSplitRequest Confirm(ChartSplitPlan p) => new([Cut], 0, 0, 0, 0, p.OptName, + p.BaseTitle, p.SegmentTitles, p.GenreId, p.VersionId, p.Ids, p.Destination); + + private static void WriteSource(string source) + { + File.WriteAllText(Path.Combine(source, "DataConfig.xml"), "1"); + var music = MusicXml.CreateNew(SongId, StaticSettings.GamePath, "A000"); + var xml = XElement.Load(music.FilePath); + xml.Element("name")!.SetElementValue("str", "Fixture"); + xml.SetElementValue("bpm", 120); + var notes = xml.Element("notesData")!.Elements("Notes").ElementAt(Difficulty); + notes.SetElementValue("isEnable", "true"); notes.SetElementValue("musicLevelID", 19); + notes.SetElementValue("level", 13); notes.SetElementValue("levelDecimal", 4); + xml.Save(music.FilePath); + File.WriteAllText(Path.Combine(Path.GetDirectoryName(music.FilePath)!, music.Charts[Difficulty].Path), """ + VERSION 0.00.00 1.03.00 + BPM_DEF 120 120 120 83.75 + MET_DEF 4 4 + RESOLUTION 384 + CLK_DEF 384 + COMPATIBLE_CODE MA2 + BPM 0 0 120 + BPM 1 0 83.75 + TAP 0 0 0 + TAP 1 0 1 + TAP 1 48 2 + """); + + // No jacket (thus no game bundle template), ffmpeg or external game resources. + const int rate = 44100; + var pcm = new byte[rate * 4 * sizeof(short)]; + for (int i = 0; i < pcm.Length; i += 2) BitConverter.TryWriteBytes(pcm.AsSpan(i), (short)(8000 * Math.Sin(i * .02))); + using var raw = new RawSourceWaveStream(new MemoryStream(pcm), new WaveFormat(rate, 16, 1)); + using var wav = new MemoryStream(); + WaveFileWriter.WriteWavFileToStream(wav, raw); wav.Position = 0; + var bank = new ACB_Wrapper(ACB_File.Load(File.ReadAllBytes(Path.Combine(AppContext.BaseDirectory, "nopreview.acb")), null)); + bank.Cues[0].AddTrackToCue(PracticeHca.Encode(wav, default, null), true, false, EncodeType.HCA); + var sound = Directory.CreateDirectory(Path.Combine(source, "SoundData")).FullName; + bank.AcbFile.Save(Path.Combine(sound, $"music{SongId % 10000:D6}.acb")); + } + + private static void VerifySongs(string pack, ChartSplitPlan plan, Ma2SplitChart source) + { + for (int i = 0; i < 2; i++) + { + int id = plan.Ids[i]; + var dir = Path.Combine(pack, "music", $"music{id:D6}"); + var music = XElement.Load(Path.Combine(dir, "Music.xml")); + Assert.Equal(120, XmlConvert.ToInt32(music.Element("bpm")!.Value)); // game XML contract, not MA2 tempo + Assert.Equal(plan.SegmentTitles[i], (string?)music.Element("name")!.Element("str")); + Assert.Equal(plan.GenreId, (int)music.Element("genreName")!.Element("id")!); + Assert.Equal(plan.VersionId, (int)music.Element("AddVersion")!.Element("id")!); + var enabled = Assert.Single(music.Element("notesData")!.Elements("Notes").Where(n => (bool)n.Element("isEnable")!)); + Assert.Equal(19, (int)enabled.Element("musicLevelID")!); + Assert.Equal((0, 0), ((int)enabled.Element("level")!, (int)enabled.Element("levelDecimal")!)); + var chart = Ma2SplitChart.Parse(File.ReadAllText(Path.Combine(dir, enabled.Element("file")!.Element("path")!.Value))); + Assert.Equal(i == 0 ? 120 : 83.75, chart.Tempos[0].Bpm); + Assert.Equal(i + 1, chart.Notes.Count); + int cue = (int)music.Element("cueName")!.Element("id")!; + Assert.Equal(id % 10000, cue); + var acb = Path.Combine(pack, "SoundData", $"music{cue:D6}.acb"); + using var decoded = new WaveFileReader(new MemoryStream(Audio.AcbToWav(acb))); + var seconds = i == 0 ? source.SecondsAt(Cut) : source.SecondsAt(source.EndTick) - source.SecondsAt(Cut); + Assert.InRange(decoded.TotalTime.TotalSeconds, seconds - .05, seconds + .05); + } + } + + private static string[] Snapshot(string root) => Directory.EnumerateFiles(root, "*", SearchOption.AllDirectories) + .Select(f => $"{Path.GetRelativePath(root, f)}:{Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(f)))}") + .Order(StringComparer.Ordinal).ToArray(); +} diff --git a/MaiChartManager/Controllers/Charts/ChartSplitController.cs b/MaiChartManager/Controllers/Charts/ChartSplitController.cs new file mode 100644 index 00000000..21c10bc9 --- /dev/null +++ b/MaiChartManager/Controllers/Charts/ChartSplitController.cs @@ -0,0 +1,128 @@ +using MaiChartManager.Services.ChartSplitting; +using Microsoft.AspNetCore.Mvc; + +namespace MaiChartManager.Controllers.Charts; + +[ApiController] +[Route("MaiChartManagerServlet/[action]Api/{assetDir}/{songId:int}/{level:int}")] +public sealed class ChartSplitController(StaticSettings settings, ILogger logger) : ControllerBase +{ + // The HCA codec is memory intensive. Reject concurrent jobs rather than queue unlimited requests. + private static readonly SemaphoreSlim ExportSlot = new(1); + private static readonly SemaphoreSlim TimelineSlots = new(2); + private static readonly ChartSplitProgressStore Progress = new(TimeProvider.System); + private SplitCaller Caller(string assetDir,int songId,int level) => new(assetDir,songId,level, + HttpContext.Connection.RemoteIpAddress?.ToString() ?? "", HttpContext.User.Identity?.Name ?? ""); + + [HttpGet, ResponseCache(NoStore=true,Location=ResponseCacheLocation.None)] + public IActionResult ChartSplitProgress(string assetDir,int songId,int level,[FromQuery] string? operationId) + { + if(!ChartSplitProgressStore.ValidToken(operationId,out var id))return NotFound(); + var status=Progress.Read(id,Caller(assetDir,songId,level)); + return status is null ? NotFound() : Ok(status); + } + + [HttpGet] + public IActionResult ChartSplitTimeline(string assetDir, int songId, int level) + { + if (!TimelineSlots.Wait(0)) return StatusCode(429, "时间轴正在加载,请稍后再试。"); + try + { + var (music, chart) = ChartSplitExportService.Resolve(settings, assetDir, songId, level); + int? audioId; + try { audioId = ChartSplitExportService.ResolveAudio(music).Id; } + catch (FileNotFoundException) { audioId = null; } // Missing audio need not hide the chart timeline. + return Ok(new { chart.Resolution, chart.EndTick, chart.Tempos, chart.Meters, chart.Notes, AudioId = audioId }); + } + catch (Exception e) { return Failure(e); } + finally { TimelineSlots.Release(); } + } + + [HttpGet] + public IActionResult ChartSplitRecommend(string assetDir,int songId,int level,[FromQuery] int parts=2,CancellationToken cancellationToken=default) + { + if(!TimelineSlots.Wait(0))return StatusCode(429,"正在检查曲库,请稍后再试。"); + try{var (music,_)=ChartSplitExportService.Resolve(settings,assetDir,songId,level);return Ok(ChartSplitExportService.Plan(settings,music,parts,null,cancellationToken));} + catch(OperationCanceledException) when(cancellationToken.IsCancellationRequested){throw;} + catch(Exception e){return Failure(e);}finally{TimelineSlots.Release();} + } + + [HttpPost,RequestSizeLimit(65536)] + public IActionResult ChartSplitPreflight(string assetDir,int songId,int level,[FromBody] ChartSplitRequest request,CancellationToken cancellationToken) + { + if(!TimelineSlots.Wait(0))return StatusCode(429,"正在检查曲库,请稍后再试。"); + try{var (music,chart)=ChartSplitExportService.Resolve(settings,assetDir,songId,level);ChartSplitExportService.ValidateCuts(chart,request); ChartSplitExportService.ResolveAudio(music); + return Ok(ChartSplitExportService.Plan(settings,music,request.Cuts.Length+1,request,cancellationToken));} + catch(OperationCanceledException) when(cancellationToken.IsCancellationRequested){throw;} + catch(Exception e){return Failure(e);}finally{TimelineSlots.Release();} + } + + [HttpPost,RequestSizeLimit(65536)] + public async Task ChartSplitInstall(string assetDir,int songId,int level,[FromBody] ChartSplitRequest request,CancellationToken cancellationToken,[FromQuery] string? operationId=null) + { + var ip=HttpContext.Connection.RemoteIpAddress; + if(ip==null||!System.Net.IPAddress.IsLoopback(ip.IsIPv4MappedToIPv6?ip.MapToIPv4():ip))return StatusCode(403,"直接安装仅允许在本机操作。"); +#if WINDOWS + if(IapManager.License!=IapManager.LicenseStatus.Active)return StatusCode(403,"安装需要已激活的许可。"); +#endif + return await Run(assetDir,songId,level,request,operationId,true,cancellationToken); + } + + [HttpPost, RequestSizeLimit(65536)] + public async Task ChartSplitExport(string assetDir, int songId, int level, + [FromBody] ChartSplitRequest request, CancellationToken cancellationToken,[FromQuery] string? operationId=null) + { +#if WINDOWS + if (IapManager.License != IapManager.LicenseStatus.Active) + return StatusCode(403, "谱面拆分导出需要已激活的许可。"); +#endif + return await Run(assetDir,songId,level,request,operationId,false,cancellationToken); + } + + private async Task Run(string assetDir,int songId,int level,ChartSplitRequest request,string? operationId,bool install,CancellationToken token) + { + Guid id=default; + if(operationId!=null&&!ChartSplitProgressStore.ValidToken(operationId,out id))return BadRequest("无效的操作令牌。"); + if(!await ExportSlot.WaitAsync(0,token))return StatusCode(429,"另一个拆分操作正在进行。"); + ChartSplitWork? work=null; + try { + if(operationId!=null){ + // Register before semantic validation: a rejected cut list still has a queryable failed receipt. + int parts=request.Cuts is { Length: >=1 and <=31 } cuts ? cuts.Length+1 : 0; + work=Progress.TryStart(id,Caller(assetDir,songId,level),parts,out bool duplicate); + if(work==null)return duplicate ? Conflict("该操作令牌已使用。") : StatusCode(429,"操作记录已满,请稍后再试。"); + } + // CPU-heavy HCA conversion and the catalog scan are synchronous. One dedicated worker + // (bounded by ExportSlot) lets ASP.NET handle status polls, without a detached job/retry. + var result=await Task.Factory.StartNew(()=>{ + token.ThrowIfCancellationRequested(); + var (music,chart)=ChartSplitExportService.Resolve(settings,assetDir,songId,level); + return install ? ChartSplitExportService.Install(settings,music,chart,level,request,token,work) : + ChartSplitExportService.ExportTracked(settings,music,chart,level,request,token,null,work); + },token,TaskCreationOptions.LongRunning,TaskScheduler.Default); + // Install returned only after the atomic rename; exported means server ZIP is ready, + // not that a browser has already received its bytes. FileStreamResult owns disposal. + Progress.Finish(work,install?"installed":"exported"); + return install ? Ok((ChartSplitPlan)result) : File((FileStream)result,"application/zip",$"chart-split-{songId:D6}.zip"); + }catch(OperationCanceledException) when(token.IsCancellationRequested){Progress.Finish(work,"cancelled","操作已取消。");throw;} + catch(Exception e){Progress.Finish(work,"failed",e switch { + UnauthorizedAccessException => "没有读取或安装权限。", SplitConflict => "曲库或安装目标冲突。", + FileNotFoundException or DirectoryNotFoundException => "缺少曲目资源。",InvalidDataException => "谱面或分段设置无效。",_ => "处理失败,请查看后端日志。"});return Failure(e);} + finally{ExportSlot.Release();} + } + + private IActionResult Failure(Exception e) + { + if (e is SplitConflict) return Conflict(e.Message); + if (e is InvalidDataException) return BadRequest(e.Message); + if (e is UnauthorizedAccessException) return StatusCode(403,"无法安全读取曲库或写入新 Opt;未覆盖已有文件。"); + if (e is FileNotFoundException or DirectoryNotFoundException) return NotFound("未找到曲目、谱面或对应资源。"); + // Some portable Windows hosts lack permission to register/write an EventLog source. + // A broken logging provider must not replace the API's JSON/text error with a reset connection. + try { logger.LogError(e,"Chart split failed"); } + catch(Exception loggingError) when(loggingError is AggregateException or InvalidOperationException or UnauthorizedAccessException) { + System.Diagnostics.Debug.WriteLine($"Chart split failed ({e.GetType().Name}); logging failed ({loggingError.GetType().Name})."); + } + return StatusCode(500, "拆分失败,请查看后端日志。"); + } +} diff --git a/MaiChartManager/Front/package.json b/MaiChartManager/Front/package.json index 1e0c505b..7582a0da 100644 --- a/MaiChartManager/Front/package.json +++ b/MaiChartManager/Front/package.json @@ -7,6 +7,8 @@ "dev:expose": "vite --host", "build": "vite build", "preview": "vite preview", + "test:chart-split": "node --experimental-transform-types --test tests/chart-split*.test.mjs", + "test:chart-split:browser": "node tests/chart-split-output-browser.mjs", "genClient": "tsx genClient", "typecheck": "tsc -p tsconfig.json && tsc -p tsconfig.node.json" }, diff --git a/MaiChartManager/Front/src/router.ts b/MaiChartManager/Front/src/router.ts index 9b0e7738..c29e135e 100644 --- a/MaiChartManager/Front/src/router.ts +++ b/MaiChartManager/Front/src/router.ts @@ -9,6 +9,7 @@ const router = createRouter({ routes: [ { path: '/', component: Index }, { path: '/chart-preview', component: ChartPreviewPage }, + { path: '/chart-split', component: () => import('@/views/ChartSplit') }, { path: '/fancy-tool', component: FancyTool }, { path: '/oobe', component: Oobe, name: 'oobe' }, { path: '/server', component: Oobe, name: 'server' }, diff --git a/MaiChartManager/Front/src/views/ChartPreviewPage.tsx b/MaiChartManager/Front/src/views/ChartPreviewPage.tsx index eae98a28..a1c8db7a 100644 --- a/MaiChartManager/Front/src/views/ChartPreviewPage.tsx +++ b/MaiChartManager/Front/src/views/ChartPreviewPage.tsx @@ -1,4 +1,7 @@ -import { defineComponent } from "vue"; +import { defineComponent, onUnmounted } from "vue"; +import { installUnityClock } from './ChartSplit/unityClock'; +import { createUnityControls } from './ChartSplit/unityControls'; +import { tellEditor, type PreviewWindow } from './ChartSplit/embed'; import UnityWebgl from "unity-webgl"; import dataUrl from './Charts/MusicEdit/majdata-wasm/Build.bin?url'; import frameworkUrl from './Charts/MusicEdit/majdata-wasm/Build.framework.js?url'; @@ -8,7 +11,8 @@ import UnityVue from 'unity-webgl/vue'; import { getUrl } from "@/client/api"; import { useRoute } from 'vue-router'; import { useTitle } from '@vueuse/core'; -import { t } from '@/locales'; +import { locale, t } from '@/locales'; +import { splitText } from './ChartSplit/labels'; export default defineComponent({ setup() { @@ -19,6 +23,20 @@ export default defineComponent({ const level = route.query.level as string ?? ''; const side = route.query.side === 'L' || route.query.side === 'R' ? route.query.side : undefined; + const embedded = route.query.embed === 'split' && window.parent !== window && window.parent.origin === location.origin; + const host = window as PreviewWindow; + if (embedded && location.hostname === 'mcm.invalid' && !globalThis.backendUrl) { + globalThis.backendUrl = (parent as Window & {backendUrl?:string}).backendUrl; + } + const audioId = embedded && /^\d+$/.test(String(route.query.audioId)) ? String(route.query.audioId) : songId; + let lastPlaying = false; + const disposeClock = embedded ? installUnityClock(Number(route.query.duration), state => { + lastPlaying = state.playing; tellEditor({kind:'clock',state}); + }) : undefined; + const onKey = (e:KeyboardEvent) => { if(e.code === 'KeyM' && !e.repeat && !e.ctrlKey && !e.metaKey && !e.altKey) { e.preventDefault(); tellEditor({kind:'mark'}); } }; + const onPointer = () => { if (!lastPlaying) tellEditor({kind:'position-unknown'}); }; + if (embedded) { window.addEventListener('keydown', onKey, true); window.addEventListener('pointerdown', onPointer, true); } + onUnmounted(() => { disposeClock?.(); delete host.mcmSplitActions; window.removeEventListener('keydown',onKey,true); window.removeEventListener('pointerdown',onPointer,true); }); const unityContext = new UnityWebgl({ dataUrl, frameworkUrl, @@ -32,17 +50,23 @@ export default defineComponent({ if (side) chartUrl.searchParams.set('side', side); unityContext.send("HandleJSMessages", "ReceiveMessage", [ chartUrl.toString(), - getUrl(`GetMusicWavApi/${assetDir}/${songId}`), + getUrl(`GetMusicWavApi/${assetDir}/${audioId}`), getUrl(`GetJacketApi/${assetDir}/${songId}`), '', 'lv0' ].join('\n')); + if (embedded) { host.mcmSplitActions = createUnityControls((o:string,m:string,v?:number)=>unityContext.sendMessage(o,m,v)); tellEditor({kind:'ready'}); } }, 500); }); return () => (
- + {route.query.canSplit === '1' && !side && } +
); }, diff --git a/MaiChartManager/Front/src/views/ChartSplit/OutputPanel.tsx b/MaiChartManager/Front/src/views/ChartSplit/OutputPanel.tsx new file mode 100644 index 00000000..d3ca06ee --- /dev/null +++ b/MaiChartManager/Front/src/views/ChartSplit/OutputPanel.tsx @@ -0,0 +1,162 @@ +import {computed,defineComponent,onUnmounted,reactive,ref,shallowRef,watch,type PropType} from 'vue'; +import {getUrl} from '@/client/api'; +import {locale} from '@/locales'; +import {outputText} from './outputText'; +import ProgressStatus from './ProgressStatus'; +import {canRelease,createOperation,OutputTracker,validOperation,type Kind,type ProgressView} from './outputProgress'; +import {InstallGate,rangeKey,settingsFrom,titlesFor,validOpt,validSettings,type OutputRequest,type OutputSettings,type Recommendation,type SegmentRange,type SplitPlan} from './installPlan'; +import type {Margins} from './timing'; + +// The in-game practice category and this badge share one asset. A source checkout +// without generated category artwork still provides the functional text badge. +const artwork=Object.values(import.meta.glob('../../../../Resources/ChartSplitPractice/Practice.png',{eager:true,query:'?url',import:'default'}))[0]; +class ApiError extends Error { constructor(readonly status:number,text:string) { super(text || `HTTP ${status}`); } } +const errorText=(e:unknown)=>e instanceof Error?e.message:String(e); +export default defineComponent({ + props:{path:{type:String,required:true},song:{type:String,required:true},level:{type:String,required:true},cuts:{type:Array as PropType,required:true},segments:{type:Array as PropType,required:true},margins:{type:Object as PropType,required:true}}, + emits:{busy:(_busy:boolean)=>true}, + setup(props,{emit}) { + const s=computed(()=>outputText(locale.value)); + const rec=shallowRef(), check=shallowRef(), receipt=shallowRef(); + const changedNames=reactive>({}), base=ref(''),opt=ref(''); + const pending=ref<''|'zip'|'check'|'install'>(''), recLoading=ref(false), recError=ref(''), error=ref(''), download=ref(''); + const needsNewIds=ref(false), abort=new AbortController(), gate=new InstallGate(); let lookup=0, recAbort:AbortController|undefined; + let lastSuggestion:Recommendation|undefined; + const tracking=shallowRef(),storageKey=`mcm.chartSplit.pending.v1:${props.path}`; + const unresolved=computed(()=>tracking.value?.phase==='unknown' && tracking.value.op.kind==='install'); + const forget=(id:string)=>{try{if(JSON.parse(sessionStorage.getItem(storageKey)||'null')?.id===id)sessionStorage.removeItem(storageKey);}catch{/* browser storage optional */}}; + const tracker=new OutputTracker(async(id,signal)=>{ + const r=await fetch(getUrl(`ChartSplitProgressApi/${props.path}?operationId=${encodeURIComponent(id)}`),{signal,cache:'no-store'}); + if(r.status===404)return null;if(!r.ok)throw Error(`HTTP ${r.status}`);return r.json(); + },v=>{ + tracking.value=v; + if(v && v.op.kind==='install' && v.phase!=='working' && v.phase!=='unknown'){ + forget(v.op.id);needsNewIds.value=true; + if(v.phase==='installed')error.value=''; + } + }); + try {const saved:unknown=JSON.parse(sessionStorage.getItem(storageKey)||'null'); + if(validOperation(saved) && saved.kind==='install'){needsNewIds.value=true;tracker.start(saved,true);} + }catch{/* no persisted operation */} + function startTracking(kind:Kind,destination?:string){const op=createOperation(kind,props.segments.length,destination); + if(kind==='install'){try{sessionStorage.setItem(storageKey,JSON.stringify(op));}catch{/* in-memory protection still applies */}} + tracker.start(op);return `?operationId=${encodeURIComponent(op.id)}`; + } + function release(){const v=tracking.value;if(!canRelease(v)||!v)return;forget(v.op.id);tracker.clear();discardCheck();needsNewIds.value=true;error.value=s.value.uncertain;} + + const names=computed(()=>rec.value?titlesFor(props.segments,base.value,rec.value,changedNames):[]); + const settings=computed(()=>rec.value?{optName:opt.value.trim(),baseTitle:base.value.trim(),segmentTitles:names.value,genreId:rec.value.genreId,versionId:rec.value.versionId,ids:rec.value.ids}:undefined); + const valid=computed(()=>!!settings.value && validSettings(settings.value,props.segments.length)); + const usable=computed(()=>props.cuts.length>0 && !props.segments.some(part=>part.empty)); + const request=computed(()=>({cuts:[...props.cuts],...props.margins,...(settings.value?settingsFrom(settings.value):{})})); + const nameFor=(list:{id:number;name:string}[],id:number)=>list.find(c=>c.id===id)?.name ?? `#${id}`; + function discardCheck(){gate.clear();check.value=undefined;} + function clearDownload(){if(download.value) URL.revokeObjectURL(download.value);download.value='';} + function clearOutput(){discardCheck();clearDownload();error.value='';} + const filename=()=>`practice-${props.song}-${props.level}.zip`; + let locked=false; + function lock(action:'zip'|'check'|'install') {if(locked || unresolved.value)return false;locked=true;pending.value=action;error.value='';emit('busy',true);return true;} + function unlock(){locked=false;pending.value='';emit('busy',false);} + async function api(action:string,body?:object,signal:AbortSignal|null=abort.signal,query=''){ + const init:RequestInit={signal};if(body){init.method='POST';init.headers={'Content-Type':'application/json'};init.body=JSON.stringify(body);} + const r=await fetch(getUrl(`ChartSplit${action}Api/${props.path}${query}`),init); + if(!r.ok) throw new ApiError(r.status,(await r.text()).slice(0,600)); return r; + } + async function recommend(manual=false){ + const old=lastSuggestion;const serial=++lookup;recAbort?.abort();recAbort=new AbortController(); + rec.value=undefined;recError.value='';recLoading.value=false;clearOutput(); + if(!props.cuts.length)return; + recLoading.value=true; + try { + const next:Recommendation=await (await api('Recommend',undefined,recAbort.signal,`?parts=${props.segments.length}`)).json(); + if(serial!==lookup||abort.signal.aborted)return; + if(!old || base.value===old.baseTitle) base.value=next.baseTitle; + if(!old || manual || opt.value===old.optName) opt.value=next.optName; + lastSuggestion=rec.value=next;needsNewIds.value=false; + } catch(e) {if(serial===lookup&&!abort.signal.aborted)recError.value=errorText(e);} + finally{if(serial===lookup)recLoading.value=false;} + } + // Marking rapidly must not launch a full catalogue scan for each intermediate cut. + watch(()=>props.segments.length,(_n,_prev,cleanup)=>{ + ++lookup;recAbort?.abort();rec.value=undefined;recError.value='';recLoading.value=props.cuts.length>0;clearOutput(); + if(!props.cuts.length)return; + const timer=setTimeout(()=>void recommend(),250);cleanup(()=>clearTimeout(timer)); + },{immediate:true}); + watch(()=>props.segments.map(rangeKey),keys=>{for(const k of Object.keys(changedNames))if(!keys.includes(k))delete changedNames[k];}); + watch(request,clearOutput,{flush:'sync'}); + onUnmounted(()=>{tracker.dispose();abort.abort();recAbort?.abort();discardCheck();clearDownload();}); + function report(e:unknown,installing=false){ + if(abort.signal.aborted)return; + const reason=errorText(e); error.value=e instanceof ApiError&&e.status===409?`${s.value.changed} ${reason}`:installing&&!(e instanceof ApiError&&e.status<500)?`${s.value.uncertain} ${reason}`:reason; + if((e instanceof ApiError&&e.status===409)||installing) needsNewIds.value=true; + } + async function zip(){ + if(!usable.value || recLoading.value || !rec.value || !valid.value || !lock('zip')) return; + discardCheck();clearDownload(); + try{ + const query=startTracking('zip');const response=await api('Export',request.value,abort.signal,query);if (!response.headers.get('content-type')?.includes('application/zip'))throw Error('Invalid ZIP response');const blob=await response.blob();if(abort.signal.aborted)return; + download.value=URL.createObjectURL(blob);const link=document.createElement('a');link.href=download.value;link.download=filename();link.click();tracker.responseSuccess(); + }catch(e){if(!abort.signal.aborted){report(e);tracker.responseFailure(e instanceof ApiError && [400,401,403,404,409,413,422,429].includes(e.status));}}finally{unlock();} + } + async function inspect(){ + if(!usable.value||!valid.value||!rec.value?.canInstall||needsNewIds.value||!lock('check'))return; + discardCheck(); + try{check.value=await gate.inspect(request.value, async body=>(await api('Preflight',body)).json());} + catch(e){report(e);}finally{unlock();} + } + async function install(){ + if(!check.value||!usable.value||!valid.value||!rec.value?.canInstall||needsNewIds.value||!lock('install'))return; + const plan=check.value,body=gate.take(request.value);check.value=undefined;receipt.value=undefined; + try{ + if(!body)throw Error(s.value.stale); + const query=startTracking('install',plan.destination), id=tracker.view!.op.id; + const transport=new AbortController(); + const response=api('Install',body,transport.signal,query).then(async r=>{ + const installed:SplitPlan=await r.json(); + if(!installed || installed.destination!==plan.destination || installed.optName!==plan.optName || JSON.stringify(installed.ids)!==JSON.stringify(plan.ids) || JSON.stringify(installed.segmentTitles)!==JSON.stringify(plan.segmentTitles))throw Error('Invalid installation receipt'); + // The original response may arrive after the UI has entered GET-only recovery. + if(!abort.signal.aborted && tracker.view?.op.id===id && tracker.view.phase==='unknown'){receipt.value=installed;tracker.responseSuccess();} + return installed; + }); + try {const installed=await tracker.installationReceipt(response,plan);if(abort.signal.aborted)return; + receipt.value=installed;needsNewIds.value=true;tracker.responseSuccess(); + } finally {if(tracker.view?.op.id===id && tracker.view.snapshot?.outcome)transport.abort();} + }catch(e){if(!abort.signal.aborted){if(!['failed','cancelled'].includes(tracker.view?.phase??''))report(e,true);if(body)tracker.responseFailure(e instanceof ApiError && [400,401,403,404,409,413,422,429].includes(e.status));}}finally{unlock();} + } + const suggestedOpt=computed(()=>rec.value?.optName===opt.value.trim()); + const displayDestination=computed(()=>{const r=rec.value; if(!r)return ''; if(suggestedOpt.value)return r.destination; + // Display only: the client never chooses a root. Confirmation uses the full path returned by preflight. + if(!validOpt(opt.value.trim())||!r.destination.endsWith(r.optName))return ''; + return r.destination.slice(0,-r.optName.length)+opt.value.trim(); + }); + return ()=>{const t=s.value,r=rec.value,p=check.value,done=receipt.value,disabled=!!pending.value||unresolved.value;return
+

{t.title}

{t.desc}

+ {!props.cuts.length?{t.needCuts}:<> + {recLoading.value&&

{t.loading}

} + {recError.value&&

{t.fallback} {recError.value}

} + {r&&
+ + + {artwork?Practice:Practice}{t.genre}:{nameFor(r.genres,r.genreId)}{t.version}:{nameFor(r.versions,r.versionId)} +
{t.default} +

{t.names}

{t.nameHint}
{props.segments.map((part,i)=>{ + const key=rangeKey(part),override=changedNames[key]!==undefined; + return ; + })}
} + {!recLoading.value&&} + {r&&!valid.value&&

{t.invalid}

} + {!usable.value&&

{t.unsaved}

} + {r&&

{t.where}:{displayDestination.value&&{displayDestination.value}}{!suggestedOpt.value&&{t.verifyWhere}}
{r.loaderNotice}

} + {r&&!r.canInstall&&

{t.blocked}

} +
{download.value&&{t.save}}{t.zipHint}
+
{t.checking}
+ {p&&

{t.confirmTitle}

{t.previewOnly} {t.confirmHint}

{t.where}:{p.destination}
Opt: {p.optName} · {t.genre}: {nameFor(r?.genres??[],p.genreId)} · {t.version}: {nameFor(r?.versions??[],p.versionId)}

    {p.segmentTitles.map((v,i)=>
  1. {v} · #{p.ids[i]}
  2. )}
{p.loaderNotice}
} + } + {tracking.value&&void tracker.query()} onRelease={release}/>} + {error.value&&

{error.value}

} + {done&&
{t.done} · {done.optName}

{done.destination}

{done.segmentTitles.length} {t.names} · {t.id}: {done.ids.join(', ')}

{t.restart}

{done.loaderNotice}
} +
;}; + }, +}); diff --git a/MaiChartManager/Front/src/views/ChartSplit/ProgressStatus.tsx b/MaiChartManager/Front/src/views/ChartSplit/ProgressStatus.tsx new file mode 100644 index 00000000..168eb778 --- /dev/null +++ b/MaiChartManager/Front/src/views/ChartSplit/ProgressStatus.tsx @@ -0,0 +1,19 @@ +import {defineComponent,type PropType} from 'vue'; +import {locale} from '@/locales'; +import {canRelease,elapsedLabel,messageKey,progressBar,type ProgressView} from './outputProgress'; + +const zh={zip:'生成 ZIP',install:'安装练习曲',waiting:'等待后端接收请求',validating:'检查设置、曲号与目标目录',decoding:'解码原曲音频',chart:'生成分段谱面',cropping:'裁切音频并应用淡入淡出',encoding:'编码游戏音频',jacket:'生成封面资源',packing:'写入 ZIP',unpacking:'写入安装暂存目录',rechecking:'再次核对曲目和编号冲突',publishing:'发布到最终 Opt 目录',receiving:'压缩包已生成,等待接收下载数据',receipt:'后端已发布,正在读取安装回执',installed:'已安装到游戏',downloaded:'文件已就绪,可下载 ZIP',exported:'后端已生成 ZIP,但浏览器未确认收到下载数据',failed:'请求失败;若已确认安装,请检查目标目录',cancelled:'后端报告已取消;请检查目标目录',unknown:'未收到完整回执,结果尚未确认;不要重复提交',elapsed:'已用时',part:'当前段',parts:'总段数',files:'本阶段文件',frames:'本段编码帧',done:'后端已完成',indeterminate:'此阶段耗时不可预估',missing:'尚无可读进度记录(后端可能仍在登记,或是旧版本)。',offline:'暂时读不到进度;以下为最后已知状态,不代表任务已停止。',last:'最后阶段',verify:'只查询进度',release:'已人工核对目标目录,解除保护并重新预检',reference:'操作编号',sec:'(分:秒)'}; +const tw:typeof zh={zip:'產生 ZIP',install:'安裝練習曲',waiting:'等待後端接收請求',validating:'檢查設定、曲號與目標目錄',decoding:'解碼原曲音訊',chart:'產生分段譜面',cropping:'裁切音訊並套用淡入淡出',encoding:'編碼遊戲音訊',jacket:'產生封面資源',packing:'寫入 ZIP',unpacking:'寫入安裝暫存目錄',rechecking:'再次核對曲目及編號衝突',publishing:'發佈至最終 Opt 目錄',receiving:'壓縮包已產生,等待接收下載資料',receipt:'後端已發佈,正在讀取安裝回執',installed:'已安裝到遊戲',downloaded:'檔案已就緒,可下載 ZIP',exported:'後端已產生 ZIP,但瀏覽器未確認收到下載資料',failed:'請求失敗;若已確認安裝,請檢查目標目錄',cancelled:'後端報告已取消;請檢查目標目錄',unknown:'未收到完整回執,結果尚未確認;請勿重複提交',elapsed:'已用時',part:'當前段',parts:'總段數',files:'本階段檔案',frames:'本段編碼影格',done:'後端已完成',indeterminate:'此階段耗時無法預估',missing:'尚無可讀進度記錄(後端可能正在登記,或是舊版本)。',offline:'暫時無法讀取進度;以下為最後已知狀態,不代表工作已停止。',last:'最後階段',verify:'僅查詢進度',release:'已人工核對目標目錄,解除保護並重新預檢',reference:'操作編號',sec:'(分:秒)'}; +const en:typeof zh={zip:'Build ZIP',install:'Install practice songs',waiting:'Waiting for server',validating:'Checking settings, IDs and destination',decoding:'Decoding original audio',chart:'Creating segment chart',cropping:'Cropping audio and applying fades',encoding:'Encoding game audio',jacket:'Building jackets',packing:'Writing ZIP',unpacking:'Writing installation staging directory',rechecking:'Rechecking catalogue conflicts',publishing:'Publishing final Opt directory',receiving:'Archive generated; receiving download data',receipt:'Published; receiving installation receipt',installed:'Installation confirmed',downloaded:'ZIP ready for download',exported:'ZIP generated on server; browser download not confirmed',failed:'Request failed; check destination if installation was confirmed',cancelled:'Server reports cancellation; check destination',unknown:'Receipt incomplete; result unconfirmed. Do not resubmit.',elapsed:'Elapsed',part:'Segment',parts:'Total segments',files:'Files this stage',frames:'Encoded frames this segment',done:'Server finished',indeterminate:'Stage duration is not predictable',missing:'No status record available yet; registration may be pending or the server may not support progress.',offline:'Cannot read progress; last known state is shown. This does not mean the operation stopped.',last:'Last stage',verify:'Query progress only',release:'I checked the destination; unlock for a fresh preflight',reference:'Operation ID',sec:' (min:sec)'}; +export default defineComponent({props:{state:{type:Object as PropType,required:true}},emits:['verify','release'],setup(props,{emit}){return ()=>{ + const s=props.state,t=locale.value==='zh'?zh:locale.value==='zh-TW'?tw:en,active=s.phase==='working'||s.phase==='unknown',snap=s.snapshot; + const bar=s.connection==='ok' && s.phase==='working'?progressBar(snap):{}; + return
+ {t[s.op.kind]} · {t[messageKey(s)]} +
{t.elapsed}{t.sec}: {elapsedLabel(s.elapsed)} · {snap?.part?`${t.part}: ${snap.part}/${snap.parts}`:`${t.parts}: ${s.op.parts}`}
+ {active && <>
{s.connection==='offline'?t.offline:s.connection==='missing'?t.missing:''} {s.phase==='unknown'&&snap?`${t.last}: ${t[snap.stage]}. `:''}{bar.max?`${snap?.stage==='encoding'?t.frames:t.files}: ${bar.value}/${bar.max}`:t.indeterminate}
} + {s.op.destination &&
{s.op.destination}
} + {(active || s.phase==='exported') && {t.reference}: {s.op.id}} + {s.phase==='unknown'&&
{canRelease(s)&&}
} +
; +};}}); diff --git a/MaiChartManager/Front/src/views/ChartSplit/draft.ts b/MaiChartManager/Front/src/views/ChartSplit/draft.ts new file mode 100644 index 00000000..053edea1 --- /dev/null +++ b/MaiChartManager/Front/src/views/ChartSplit/draft.ts @@ -0,0 +1,12 @@ +import {cutIssue,type Margins,type Timeline} from './timing'; +export interface DraftSource {assetDir:string; songId:number; levelIndex:number; resolution:number; endTick:number} +const keys=['preBeats','postBeats','fadeInBeats','fadeOutBeats'] as const; +export function makeDraft(source:DraftSource,cuts:readonly number[],m:Margins){return {format:'mcm-practice-split-preset/v1',source,cuts:[...cuts],preBeats:m.preBeats,postBeats:m.postBeats,fadeInBeats:m.fadeInBeats,fadeOutBeats:m.fadeOutBeats};} +export function parseDraft(value:unknown,source:DraftSource,t:Timeline){ + const v=value as ReturnType | null; + if(!v||v.format!=='mcm-practice-split-preset/v1'||!v.source||Object.entries(source).some(([k,x])=>v.source[k as keyof DraftSource]!==x))throw Error('切点备份与当前谱面不匹配。'); + if(!Array.isArray(v.cuts)||v.cuts.length>31||keys.some(k=>!Number.isFinite(v[k])||v[k]<0||v[k]>32))throw Error('切点备份的分段或拍数无效。'); + const verified:number[]=[]; + for(const tick of v.cuts){if(!Number.isSafeInteger(tick)||tick<=(verified.at(-1)??0)||cutIssue(t,tick,verified))throw Error('备份切点无效或会切断长音符。');verified.push(tick);} + return makeDraft(source,verified,v); +} diff --git a/MaiChartManager/Front/src/views/ChartSplit/embed.ts b/MaiChartManager/Front/src/views/ChartSplit/embed.ts new file mode 100644 index 00000000..8d9bf308 --- /dev/null +++ b/MaiChartManager/Front/src/views/ChartSplit/embed.ts @@ -0,0 +1,10 @@ +// Same-origin communication only between the existing preview page and its split editor. +// No audio is created here: song playback and all judgement sounds belong to Majdata. +export const splitPreviewChannel = 'mcm-split-preview-v1'; +export interface PreviewTime {time: number; playing: boolean} +export type PreviewNotice = {kind:'clock'; state:PreviewTime} | {kind:'mark'} | {kind:'ready'} | {kind:'position-unknown'} | {kind:'error'; text:string}; +export interface NativePreviewActions { toggle():void; stop():void; seek?(seconds:number, resume:boolean):boolean | Promise } +export type PreviewWindow = Window & {mcmSplitActions?:NativePreviewActions}; +export function tellEditor(event:PreviewNotice) { + if (window.parent !== window) window.parent.postMessage({channel:splitPreviewChannel, ...event},location.origin); +} diff --git a/MaiChartManager/Front/src/views/ChartSplit/index.tsx b/MaiChartManager/Front/src/views/ChartSplit/index.tsx new file mode 100644 index 00000000..3d1bd695 --- /dev/null +++ b/MaiChartManager/Front/src/views/ChartSplit/index.tsx @@ -0,0 +1,185 @@ +import { computed, defineComponent, nextTick, onMounted, onUnmounted, reactive, ref, shallowRef, watch } from 'vue'; +import { useRoute } from 'vue-router'; +import { getUrl, isWebView } from '@/client/api'; +import { locale } from '@/locales'; +import { splitText } from './labels'; +import { cutIssue, formatTime, timing, type Timeline, type Margins, type WindowSpec } from './timing'; +import { SplitPlayer } from './player'; +import { splitPreviewChannel, type PreviewNotice, type PreviewWindow } from './embed'; +import { useElementSize } from '@vueuse/core'; +import { headFill, rollNotes, starPoints } from './rollNotes'; +import OutputPanel from './OutputPanel'; +import {makeDraft,parseDraft,type DraftSource} from './draft'; +import './style.css'; + +async function checked(url: string, init: RequestInit) { + const r = await fetch(getUrl(url), init); + if (!r.ok) throw Error((await r.text()).slice(0, 600) || `HTTP ${r.status}`); + return r; +} +const message = (e: unknown) => e instanceof Error ? e.message : String(e); +export default defineComponent({setup() { + const route = useRoute(), l = computed(() => splitText(locale.value)); + const asset = encodeURIComponent(String(route.query.assetDir ?? '')), song = String(route.query.songId ?? ''), level = String(route.query.level ?? ''); + const path = `${asset}/${encodeURIComponent(song)}/${encodeURIComponent(level)}`; + const data = shallowRef(), duration = ref(0), time = ref(0), playing = ref(false), loading = ref(true), error = ref(''); + const frameEl = ref(), audioId = ref(song), nativeReady = ref(false), nativeView = ref(true), positionKnown = ref(true); + const nativeActions = () => (frameEl.value?.contentWindow as PreviewWindow | null)?.mcmSplitActions; + const frameUrl = computed(() => `#/chart-preview?${new URLSearchParams({assetDir:String(route.query.assetDir ?? ''),songId:song,level,embed:'split',audioId:audioId.value,duration:String(duration.value)})}`); + const nativeLabel = computed(() => locale.value.startsWith('zh') ? '原版谱面预览' : 'Original chart preview'); + const nativeTip = computed(() => locale.value.startsWith('zh') ? '拖动下方长进度条,松开后原版播放器会跳到同一位置。播放时按 M 标记。' : 'Drag the long seek bar below and release to move the original player. Press M to mark.'); + const syncTip = computed(() => locale.value.startsWith('zh') ? '上方拖动后请播放一下以同步,或点下方时间线指定切点。' : 'Play once after scrubbing to sync, or select a cut on the timeline.'); + const cuts = ref([]), division = ref(1), busy = ref(false), preview = ref(null); + const margins = reactive({preBeats:2,postBeats:2,fadeInBeats:1,fadeOutBeats:1}); + const marginsKeys = Object.keys(margins) as (keyof Margins)[]; + const draftKey=`mcm.chartSplit.draft.v1:${path}`, restored=ref(''); + let draftSource:DraftSource|undefined; + function saveDraft(){if(!draftSource)return;try{localStorage.setItem(draftKey,JSON.stringify(makeDraft(draftSource,cuts.value,margins)));}catch{/* storage is optional */}} + watch([cuts,margins],saveDraft,{deep:true,flush:'sync'}); + async function restoreDraft(t:Timeline){ + const source={assetDir:String(route.query.assetDir),songId:Number(song),levelIndex:Number(level),resolution:t.resolution,endTick:t.endTick}; + const preset=route.query.preset;let json:unknown; + try { + if(preset!==undefined){ + if(typeof preset!=='string'||!/^[a-z0-9][a-z0-9-]{0,79}$/.test(preset))throw Error('切点备份名称无效。'); + const r=await fetch(`./split-presets/${preset}.json`,{signal:abort.signal,cache:'no-store'}); + if(!r.ok)throw Error('未找到切点备份。'); json=await r.json(); + }else{const raw=localStorage.getItem(draftKey);if(raw)json=JSON.parse(raw);} + if(json){const v=parseDraft(json,source,t);if(abort.signal.aborted)return;cuts.value=v.cuts;for(const k of marginsKeys)margins[k]=v[k];restored.value=locale.value.startsWith('zh')?'已恢复切点配置':'Split settings restored';} + draftSource=source;if(json)saveDraft(); + }catch(e){if(!abort.signal.aborted){error.value=message(e);draftSource=source;}} + } + const clock = computed(() => data.value && timing(data.value)); + const ticks = computed(() => [0,...cuts.value,data.value?.endTick ?? 0]); + const sections = computed(() => ticks.value.slice(1).map((to,i) => ({from:ticks.value[i],to, empty: !data.value?.notes.some(n => n.tick >= ticks.value[i] && n.tick < to)}))); + const abort = new AbortController(); let ctx: AudioContext | undefined, player: SplitPlayer | undefined, frame = 0, attempt = 0; + const update = () => { time.value = player?.position ?? 0; playing.value = !!player?.playing; if (!playing.value) preview.value = null; }; + const animate = () => {update(); if (playing.value) frame = requestAnimationFrame(animate);}; + const pause = () => { attempt++; cancelAnimationFrame(frame); player?.stop(); update(); }; + const scrub = ref(null), seeking = ref(false); + const shownTime = computed(() => scrub.value ?? time.value); + let manualCursor = false, queuedSeek: number | null = null; + async function seek(sec:number) { + const target = Math.max(0, Math.min(duration.value, sec)); + if (!Number.isFinite(target)) return; + if (!nativeView.value) { scrub.value=null; pause(); player?.seek(target); update(); positionKnown.value=true; return; } + const actions=nativeActions(); + if (!actions?.seek) { scrub.value=null; error.value=syncTip.value; return; } + scrub.value=queuedSeek=target; + if (seeking.value) return; + const resume = playing.value; + seeking.value=true; + try { + while (queuedSeek !== null && !abort.signal.aborted && nativeView.value) { + const requested:number=queuedSeek; queuedSeek=null; + if (!await actions.seek(requested,resume)) throw Error(locale.value.startsWith('zh')?'原播放器未能定位,请稍后重试。':'The original preview could not seek.'); + time.value=requested; positionKnown.value=true; manualCursor=!resume; error.value=''; + } + } catch(e) { error.value=message(e); } + finally { seeking.value=false; scrub.value=null; } + } + function receive(e:MessageEvent) { + if (!nativeView.value || e.origin !== location.origin || !frameEl.value || e.source !== frameEl.value.contentWindow || e.data?.channel !== splitPreviewChannel) return; + const v = e.data as PreviewNotice; + if (v.kind === 'mark') mark(); + if (v.kind === 'ready') nativeReady.value = true; + if (v.kind === 'error') error.value = v.text; + if (v.kind === 'position-unknown') { positionKnown.value=false; manualCursor=false; } + if (v.kind === 'clock' && Number.isFinite(v.state.time)) { + if (v.state.playing) { manualCursor = false; positionKnown.value=true; } + if (!seeking.value && !manualCursor && (v.state.playing || playing.value)) time.value=Math.max(0,Math.min(duration.value,v.state.time)); + playing.value=v.state.playing; + } + } + function returnToPreview() { pause(); manualCursor=false; time.value=0; positionKnown.value=true; nativeReady.value=false; nativeView.value=true; } + + async function play(w: WindowSpec, index: number | null = null) { + if (!ctx || !player) return; + // Segment audition renders the exported audio envelope, not a second simultaneous music track. + // Stop and discard the native document before starting Web Audio (also stops all Unity hit sounds). + if (nativeView.value) { nativeActions()?.stop?.(); nativeView.value=false; nativeReady.value=false; await nextTick(); } + pause(); const token = attempt; + try {await ctx.resume(); if (token !== attempt || abort.signal.aborted) return; + player.play(w); preview.value = index; animate(); + } catch(e) {error.value = message(e);} + } + function toggle() { + if (nativeView.value) nativeActions()?.toggle?.(); + else if (playing.value) pause(); + else returnToPreview(); + } + const cursor = computed(() => clock.value?.atSecond(shownTime.value) ?? 0); + function mark() { + const c = clock.value, d = data.value; if (!player || !c || !d || busy.value || seeking.value || scrub.value !== null) return; + if (nativeView.value && !positionKnown.value) {error.value=syncTip.value; return;} + const tick = c.snap(c.atSecond(nativeView.value ? time.value : player.position),division.value), issue = cutIssue(d,tick,cuts.value); + if (issue) {error.value = l.value[issue]; return;} + cuts.value = [...cuts.value,tick].sort((a,b) => a-b); error.value = ''; + } + function step(direction: number) { + const c = clock.value; if (!c) return; + const tick = c.snap(cursor.value,division.value) + direction*c.quarter/division.value; + seek(c.atTick(Math.max(0, Math.round(tick)))); + } + function keyboard(e: KeyboardEvent) { + if (!player || e.repeat || e.ctrlKey || e.metaKey || e.altKey || (e.target instanceof HTMLElement && e.target.closest('input,select,textarea,[contenteditable=true]'))) return; + if (e.code === 'KeyM') mark(); else if (e.code === 'ArrowLeft') step(-1); else if (e.code === 'ArrowRight') step(1); else if (e.code === 'Space' && !(e.target instanceof HTMLButtonElement)) toggle(); else return; + e.preventDefault(); + } + watch([cuts,margins], () => {if (preview.value !== null) pause();}, {deep:true}); + async function load() { + loading.value = true; error.value = ''; + try { + if (!asset || !/^\d+$/.test(song) || !/^[0-4]$/.test(level)) throw Error('Invalid chart selection'); + // 子窗口创建时 WebView2 的后端地址是异步送达的。 + for (let i = 0; isWebView && !globalThis.backendUrl && i < 100 && !abort.signal.aborted; i++) await new Promise(r => setTimeout(r,50)); + const opts = {signal:abort.signal}; + const d: Timeline & {audioId?: number} = await (await checked(`ChartSplitTimelineApi/${path}`,opts)).json(); + timing(d); audioId.value = String(d.audioId ?? song); + const raw = await (await checked(`GetMusicWavApi/${asset}/${encodeURIComponent(d.audioId ?? song)}`,opts)).arrayBuffer(); + if (abort.signal.aborted) return; + ctx ??= new AudioContext(); const buf = await ctx.decodeAudioData(raw); if (abort.signal.aborted) return; + player = new SplitPlayer(ctx,buf); duration.value = buf.duration; await restoreDraft(d); if (!abort.signal.aborted) data.value = d; + } catch(e) {if (!abort.signal.aborted) error.value = message(e);} finally {loading.value = false;} + } + onMounted(() => {document.title = l.value.title; window.addEventListener('keydown',keyboard); window.addEventListener('message',receive); void load();}); + onUnmounted(() => {abort.abort(); pause(); void ctx?.close(); window.removeEventListener('keydown',keyboard); window.removeEventListener('message',receive);}); + const glyphs = computed(() => rollNotes(data.value?.notes ?? [])); + const rollBox = ref(); + const {width: rollWidth} = useElementSize(rollBox); + function roll() { + const c = clock.value!; + // SVG is displayed 160px high with 128 logical units. Match the X scale so stars stay regular. + const viewWidth = rollWidth.value > 0 ? rollWidth.value*128/160 : 960; + const width = c.quarter * 12, left = Math.max(0,cursor.value-width/3), right = left+width; + const x = (tick:number) => (tick-left)/width*viewWidth; + const y = (lane:number) => lane*16+8; + const selected = preview.value === null ? undefined : sections.value[preview.value]; + const visible = glyphs.value.filter(n => n.tick <= right && n.endTick >= left && (!selected || (n.tick >= selected.from && n.tick < selected.to))); + const lines = []; + for (let n = Math.ceil(left/c.quarter); n*c.quarter <= right; n++) lines.push(); + return
{ + const rect = (e.currentTarget as SVGSVGElement).getBoundingClientRect(); seek(c.atTick(c.snap(left+(e.clientX-rect.left)/rect.width*width,division.value))); + }}> + {lines}{Array.from({length:8},(_,i) => )} + {visible.map(n=>n.moveTick !== null && + {n.moveTick>n.tick && n.moveTick>left && } + {n.moveTick<=right && } + )} + {visible.map(n=>n.hold && n.marker && {n.kind} · {n.lane+1})} + {visible.map(n=>!n.hold && n.marker && {n.kind} · {n.lane+1}{n.marker==='star' ? : })} + {cuts.value.filter(t => t>=left && t<=right).map(t => )} + +
; + } + return () => { const s = l.value,c = clock.value; return

{s.title}

#{song}{restored.value&&{restored.value}}
+ {loading.value &&

{s.load}

}{error.value &&

{error.value}

}{!c && !loading.value && } + {c && <>

{nativeLabel.value}

{nativeView.value ?