using System.Diagnostics; using System.IO; using System.Reflection; using System.Text.Json; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Threading; using XFEToolBox.Tools.VideoStudio; namespace VideoStudio.Validation; internal static partial class Program { // Run this mode in a fresh process, before other tests create MediaPlayer or // warm the editor. It covers the user's initial drop, not a warmed import. private static async Task FirstImportTests(string path, bool diagnose) { Check(File.Exists(path), "first-import source exists"); var original = new FileInfo(path); long size = original.Length; var written = original.LastWriteTimeUtc; var measurements = new List(); var watch = Stopwatch.StartNew(); double last = 0, maximumGap = 0; int ticks = 0, renders = 0; var operations = new Dictionary(); var slowOperations = new List(); var methodField = typeof(DispatcherOperation).GetField("_method", BindingFlags.NonPublic | BindingFlags.Instance); void OperationStarted(object? sender, DispatcherHookEventArgs e) => operations[e.Operation] = Stopwatch.GetTimestamp(); void OperationCompleted(object? sender, DispatcherHookEventArgs e) { if (!operations.Remove(e.Operation, out long started)) return; double milliseconds = Stopwatch.GetElapsedTime(started).TotalMilliseconds; if (milliseconds < 50) return; var method = methodField?.GetValue(e.Operation) as Delegate; var sample = new { at = watch.Elapsed.TotalMilliseconds, milliseconds, priority = e.Operation.Priority.ToString(), method = method?.Method.ToString(), target = method?.Target?.GetType().FullName }; slowOperations.Add(sample); if (diagnose) Console.WriteLine(JsonSerializer.Serialize(sample, Json)); } Dispatcher.CurrentDispatcher.Hooks.OperationStarted += OperationStarted; Dispatcher.CurrentDispatcher.Hooks.OperationCompleted += OperationCompleted; // Input priority measures the latency of actual editor interactions; // Background work may deliberately wait while the native player prerolls. var heartbeat = new DispatcherTimer(DispatcherPriority.Input) { Interval = TimeSpan.FromMilliseconds(15) }; heartbeat.Tick += (_, _) => { double now = watch.Elapsed.TotalMilliseconds; maximumGap = Math.Max(maximumGap, now - last); last = now; ticks++; }; void Rendering(object? sender, EventArgs e) => renders++; CompositionTarget.Rendering += Rendering; heartbeat.Start(); MainPage? page = null; MainPageViewModel? model = null; Window? window = null; void Stage(string name) { maximumGap = Math.Max(maximumGap, watch.Elapsed.TotalMilliseconds - last); measurements.Add(new { stage = name, elapsedMs = watch.Elapsed.TotalMilliseconds, maximumUiGapMs = maximumGap, ticks, renders, openCount = page?.Playback.OpenCount }); Console.WriteLine(JsonSerializer.Serialize(measurements[^1], Json)); maximumGap = last = 0; ticks = renders = 0; watch.Restart(); } try { page = new MainPage(); model = (MainPageViewModel)page.DataContext; model.FfmpegPath = ffmpeg; model.FfprobePath = ffprobe; page.Playback.IsMuted = true; window = TestWindow(page); window.Show(); await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); Stage("Cold editor startup"); await page.HandleMaterialDropAsync(new DataObject(DataFormats.FileDrop, new[] { path }), null); Check(model.Assets.Count == 1 && model.Clips.Any(c => c.Kind == MediaKind.Video), "first Explorer-format drop imports and automatically inserts the first video"); await WaitUntil(() => page.Playback.ReadySourceCount == 1, "first native decoder opens without precomposing a movie", 20); await model.WaitForAssetPreviewsAsync(); await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); double dropGap = maximumGap; Stage("First drop, thumbnail and native initialization"); Check(page.Playback.OpenCount == 1 && !page.Playback.IsPlaying, "first linked video/audio uses one paused original decoder"); var preview = (SourcePreviewSurface)page.FindName("SourcePreview"); int layouts = 0; void LayoutUpdated(object? sender, EventArgs e) => layouts++; preview.LayoutUpdated += LayoutUpdated; await Task.Delay(400); preview.LayoutUpdated -= LayoutUpdated; Check(layouts < 20, $"paused first preview settles instead of entering an arrange/render loop ({layouts} layout passes)"); Stage("Paused preview settles"); int corrections = 0; double previousCorrection = -1; var sourceSamples = new List(); var sessionsField = typeof(SourcePlaybackController).GetField("sessions", BindingFlags.NonPublic | BindingFlags.Instance)!; model.TogglePlaybackCommand.Execute(null); for (int i = 0; i < 32; i++) { await Task.Delay(250); var layer = page.Playback.ActiveLayers.First(l => l.Clip.Kind == MediaKind.Video); var sessions = (System.Collections.IDictionary)sessionsField.GetValue(page.Playback)!; var session = sessions.Values.Cast().Single(); double correction = (double)session.GetType().GetField("LastCorrection")!.GetValue(session)!; if (previousCorrection >= 0 && correction != previousCorrection) corrections++; previousCorrection = correction; sourceSamples.Add(new { sequence = page.Playback.Position, source = page.Playback.SourcePosition(layer), correction }); } page.Playback.Pause(); double playingGap = maximumGap; Stage("First eight seconds of original 4K playback"); measurements.Add(new { seekCorrections = corrections, sourceSamples }); Check(page.Playback.Position > 7 && page.Playback.OpenCount == 1, "first playback advances using the same original decoder"); Check(!model.Status.Contains("失败") && !model.Status.Contains("无法直接播放"), "first-import playback remains successful"); if (!diagnose) { Check(dropGap < 1000, $"cold first drop avoids a one-second UI stall (maximum gap {dropGap:0.0} ms)"); Check(playingGap < 250, $"first playback keeps UI responsive (maximum gap {playingGap:0.0} ms)"); Check(corrections <= 2, $"first playback avoids repeated decoder seek resets ({corrections} corrections)"); } original.Refresh(); Check(original.Length == size && original.LastWriteTimeUtc == written, "original recording remains unchanged"); } finally { heartbeat.Stop(); CompositionTarget.Rendering -= Rendering; Dispatcher.CurrentDispatcher.Hooks.OperationStarted -= OperationStarted; Dispatcher.CurrentDispatcher.Hooks.OperationCompleted -= OperationCompleted; if (model is not null) model.HasUnsavedChanges = false; window?.Close(); await File.WriteAllTextAsync(Path.Combine(Root, "first-import-metrics.json"), JsonSerializer.Serialize(new { source = path, size, measurements, slowOperations }, Json)); } } }