XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
返回提交历史

XFEstudio/XFEToolBox

引入回归验证与控件生命周期优化

新增 VideoStudio.Validation 回归测试工程,覆盖导入、剪辑、导出、WPF 渲染等 96 项断言,支持 1.3.0/1.4.0 行为对比。控件动画生命周期行为改进,防止内存泄漏,进度条样式与动画精确控制。轮播图与工具目录性能优化,减少无效重建与内存分配。完善测试、产物与错误处理,提升健壮性与可追溯性。

4314bef
XFE工作室室长 <mail@xfegzs.com>
提交于

代码差异

12 个文件 +943 -32
Added XFEToolBox.Client.Wpf.Test/PageNavigationLifetimeTests.cs +210 -0
@@ -0,0 +1,210 @@
1 using System.Diagnostics;
2 using System.Reflection;
3 using System.Windows;
4 using System.Windows.Controls;
5 using System.Windows.Media;
6 using System.Windows.Media.Imaging;
7 using System.Windows.Threading;
8 using XFEToolBox.Client.Views.Pages;
9 using XFEToolBox.Core.Tools;
10 using XFEToolBox.WpfCore.Controls;
11
12 namespace XFEToolBox.Client.Wpf.Test;
13
14 public static class PageNavigationLifetimeTests
15 {
16 [Test]
17 [NonParallel]
18 [Isolated]
19 public static void UnchangedToolCatalogReusesRowsWithoutSerializingIcons() => RunSta(() =>
20 {
21 using var application = new TestApplication();
22 var pending = new TaskCompletionSource<ToolPackageSummary[]>();
23 var page = new ToolBoxPage((_, _) => pending.Task);
24 var original = Summary();
25 page.ApplyTools([original]);
26 var rows = page.ToolCards.ItemsSource;
27 for (var index = 0; index < 100; index++)
28 page.ApplyTools([Summary()]);
29 Ensure(ReferenceEquals(rows, page.ToolCards.ItemsSource), "未变化的工具目录仍重建了虚拟化列表。");
30
31 // Comparing a catalog snapshot must not serialize its potentially megabyte-sized data URI.
32 var left = Summary(icon: new string('a', 100_000));
33 var right = Summary(icon: new string('a', 100_000));
34 ToolBoxPage.ToolSummariesEquivalent(left, right);
35 var before = GC.GetAllocatedBytesForCurrentThread();
36 for (var index = 0; index < 100; index++)
37 Ensure(ToolBoxPage.ToolSummariesEquivalent(left, right), "相同的工具摘要比较失败。");
38 Ensure(GC.GetAllocatedBytesForCurrentThread() - before < 100_000,
39 "工具摘要比较仍分配了与图标内容大小成倍增长的内存。");
40
41 page.ApplyTools([Summary(name: "已更新的工具")]);
42 Ensure(!ReferenceEquals(rows, page.ToolCards.ItemsSource), "目录变化没有刷新工具卡片。");
43 page.ApplyTools([]);
44 Ensure(page.ToolCards.Items.Count == 0, "目录移除后仍显示旧工具。");
45 });
46
47 [Test]
48 [NonParallel]
49 [Isolated]
50 public static void ToolCatalogResponseAfterLeavingPageDoesNotRebuildHiddenList() => RunSta(() =>
51 {
52 using var application = new TestApplication();
53 var pending = new TaskCompletionSource<ToolPackageSummary[]>(TaskCreationOptions.RunContinuationsAsynchronously);
54 var calls = 0;
55 var page = new ToolBoxPage((_, _) => { calls++; return pending.Task; });
56 SetField(page, "_cacheLoaded", true);
57 SetField(page, "_hasCachedCatalog", true);
58 SetField(page, "_cachedCatalog", new[] { Summary() });
59 var host = new Frame { NavigationUIVisibility = System.Windows.Navigation.NavigationUIVisibility.Hidden, Content = page };
60 using var window = new TestWindow(host);
61 PumpUntil(() => calls == 1 && page.IsLoaded);
62 var rows = page.ToolCards.ItemsSource;
63 var home = new Page { Content = new TextBlock { Text = "主页" } };
64 host.Content = home;
65 PumpUntil(() => !page.IsLoaded && home.IsLoaded);
66
67 pending.SetResult([Summary(name: "延迟返回的新目录")]);
68 PumpFor(TimeSpan.FromMilliseconds(150));
69 Ensure(ReferenceEquals(rows, page.ToolCards.ItemsSource), "工具页卸载后,旧请求仍重建隐藏的工具列表。");
70 Ensure(ReferenceEquals(host.Content, home), "迟到的工具目录响应改变了当前页面。");
71 });
72
73 [Test]
74 [NonParallel]
75 public static void HiddenAndUnloadedProgressBarsReleaseAnimationClocks() => RunSta(() =>
76 {
77 var progress = new ProgressBar { IsIndeterminate = true, Width = 200, Height = 8 };
78 var host = new ContentControl { Content = progress };
79 using var window = new TestWindow(host);
80 PumpUntil(() => progress.IsLoaded && progress.Template is not null);
81 var transform = (TranslateTransform)progress.Template.FindName("IndeterminateTransform", progress);
82 Ensure(transform.HasAnimatedProperties, "可见进度条没有开始动画。");
83 for (var index = 0; index < 5; index++)
84 {
85 progress.Visibility = Visibility.Collapsed;
86 PumpFor(TimeSpan.FromMilliseconds(20));
87 Ensure(!transform.HasAnimatedProperties, "隐藏的进度条仍持有无限动画时钟。");
88 progress.Visibility = Visibility.Visible;
89 PumpFor(TimeSpan.FromMilliseconds(20));
90 Ensure(transform.HasAnimatedProperties, "再次显示进度条时没有恢复动画。");
91 }
92 host.Content = null;
93 PumpUntil(() => !progress.IsLoaded);
94 Ensure(!transform.HasAnimatedProperties, "页面卸载后,进度条仍持有动画时钟。");
95 host.Content = progress;
96 PumpUntil(() => progress.IsLoaded);
97 transform = (TranslateTransform)progress.Template.FindName("IndeterminateTransform", progress);
98 Ensure(transform.HasAnimatedProperties, "页面重新加载后,进度动画没有恢复。");
99 });
100
101 [Test]
102 [NonParallel]
103 public static void LeavingDuringCarouselTransitionReleasesPreviousImageAndClocks() => RunSta(() =>
104 {
105 var carousel = new Carousel { IsLoading = false, AutoPlay = false, Height = 220 };
106 var items = Enumerable.Range(0, 2).Select(index =>
107 {
108 var bitmap = BitmapSource.Create(8, 8, 96, 96, PixelFormats.Bgra32, null, new byte[256], 32);
109 bitmap.Freeze();
110 return new CarouselImageItem { Image = bitmap, Title = $"封面 {index}" };
111 }).ToArray();
112 carousel.SetItems(items);
113 var host = new ContentControl { Content = carousel };
114 using var window = new TestWindow(host);
115 PumpUntil(() => carousel.IsLoaded);
116 var front = (Image)carousel.FindName("ImageFront");
117 var back = (Image)carousel.FindName("ImageBack");
118 var navigate = typeof(Carousel).GetMethod("NavigateTo", BindingFlags.Instance | BindingFlags.NonPublic)!;
119 navigate.Invoke(carousel, [1, false]);
120 Ensure(front.HasAnimatedProperties && back.Source is not null, "测试未进入轮播图切换状态。");
121 host.Content = null;
122 PumpUntil(() => !carousel.IsLoaded);
123 Ensure(!front.HasAnimatedProperties && !back.HasAnimatedProperties && back.Source is null,
124 "离开主页后,轮播过渡仍持有图片或动画时钟。");
125 host.Content = carousel;
126 PumpUntil(() => carousel.IsLoaded);
127 Ensure(ReferenceEquals(front.Source, items[1].Image) && front.Opacity == 1, "返回主页后没有恢复当前封面。");
128 navigate.Invoke(carousel, [0, false]);
129 PumpFor(TimeSpan.FromMilliseconds(450));
130 Ensure(!front.HasAnimatedProperties && !back.HasAnimatedProperties && back.Source is null && front.Opacity == 1,
131 "轮播过渡完成后没有释放动画时钟。");
132 });
133
134 private static ToolPackageSummary Summary(string name = "测试工具", string? icon = null) => new()
135 {
136 Id = "navigation-test", Name = name, Description = "目录刷新测试", Author = "Test",
137 Category = "测试", LatestVersion = "1.0.0", Tags = ["test"], IconDataUrl = icon
138 };
139
140 private static void SetField(object instance, string name, object value) =>
141 instance.GetType().GetField(name, BindingFlags.Instance | BindingFlags.NonPublic)!.SetValue(instance, value);
142
143 private sealed class TestApplication : IDisposable
144 {
145 private readonly Application application = new() { ShutdownMode = ShutdownMode.OnExplicitShutdown };
146 public TestApplication() => application.Resources.MergedDictionaries.Add(new ResourceDictionary
147 {
148 Source = new Uri("/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml", UriKind.Relative)
149 });
150 public void Dispose() => application.Shutdown();
151 }
152
153 private sealed class TestWindow : IDisposable
154 {
155 private readonly Window window;
156 public TestWindow(object content)
157 {
158 window = new Window
159 {
160 Content = content, Width = 900, Height = 600, Left = -10_000, Top = -10_000,
161 ShowActivated = false, ShowInTaskbar = false, WindowStartupLocation = WindowStartupLocation.Manual
162 };
163 window.Resources.MergedDictionaries.Add(new ResourceDictionary
164 {
165 Source = new Uri("/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml", UriKind.Relative)
166 });
167 window.Show();
168 }
169 public void Dispose() { window.Close(); PumpFor(TimeSpan.FromMilliseconds(20)); }
170 }
171
172 private static void PumpUntil(Func<bool> condition)
173 {
174 var clock = Stopwatch.StartNew();
175 do
176 {
177 PumpFor(TimeSpan.FromMilliseconds(10));
178 Ensure(clock.Elapsed < TimeSpan.FromSeconds(5), "等待页面生命周期变化超时。");
179 } while (!condition());
180 }
181
182 private static void PumpFor(TimeSpan duration)
183 {
184 var frame = new DispatcherFrame();
185 var timer = new DispatcherTimer(DispatcherPriority.Background) { Interval = duration };
186 timer.Tick += (_, _) => { timer.Stop(); frame.Continue = false; };
187 timer.Start();
188 Dispatcher.PushFrame(frame);
189 }
190
191 private static void RunSta(Action action)
192 {
193 Exception? failure = null;
194 var thread = new Thread(() =>
195 {
196 try { action(); }
197 catch (Exception exception) { failure = exception; }
198 finally { Dispatcher.CurrentDispatcher.InvokeShutdown(); }
199 }) { IsBackground = true };
200 thread.SetApartmentState(ApartmentState.STA);
201 thread.Start();
202 Ensure(thread.Join(TimeSpan.FromSeconds(15)), "页面导航生命周期测试超时。");
203 if (failure is not null) throw new InvalidOperationException($"页面导航生命周期回归失败:{failure}", failure);
204 }
205
206 private static void Ensure(bool condition, string message)
207 {
208 if (!condition) throw new InvalidOperationException(message);
209 }
210 }
Added XFEToolBox.WpfCore/Behaviors/AnimationLifecycle.cs +44 -0
@@ -0,0 +1,44 @@
1 using System.Windows;
2
3 namespace XFEToolBox.WpfCore.Behaviors;
4
5 /// <summary>Lets template animations run only while their control is loaded and visible.</summary>
6 public static class AnimationLifecycle
7 {
8 public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached(
9 "IsEnabled", typeof(bool), typeof(AnimationLifecycle), new PropertyMetadata(false, OnIsEnabledChanged));
10
11 private static readonly DependencyPropertyKey IsActivePropertyKey = DependencyProperty.RegisterAttachedReadOnly(
12 "IsActive", typeof(bool), typeof(AnimationLifecycle), new PropertyMetadata(false));
13 public static readonly DependencyProperty IsActiveProperty = IsActivePropertyKey.DependencyProperty;
14
15 public static bool GetIsEnabled(DependencyObject target) => (bool)target.GetValue(IsEnabledProperty);
16 public static void SetIsEnabled(DependencyObject target, bool value) => target.SetValue(IsEnabledProperty, value);
17 public static bool GetIsActive(DependencyObject target) => (bool)target.GetValue(IsActiveProperty);
18
19 private static void OnIsEnabledChanged(DependencyObject target, DependencyPropertyChangedEventArgs e)
20 {
21 if (target is not FrameworkElement element) return;
22 if ((bool)e.NewValue)
23 {
24 element.Loaded += OnLoaded;
25 element.Unloaded += OnUnloaded;
26 element.IsVisibleChanged += OnIsVisibleChanged;
27 Update(element);
28 }
29 else
30 {
31 element.Loaded -= OnLoaded;
32 element.Unloaded -= OnUnloaded;
33 element.IsVisibleChanged -= OnIsVisibleChanged;
34 element.SetValue(IsActivePropertyKey, false);
35 }
36 }
37
38 private static void OnLoaded(object sender, RoutedEventArgs e) => Update((FrameworkElement)sender);
39 private static void OnUnloaded(object sender, RoutedEventArgs e) =>
40 ((FrameworkElement)sender).SetValue(IsActivePropertyKey, false);
41 private static void OnIsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) => Update((FrameworkElement)sender);
42 private static void Update(FrameworkElement element) =>
43 element.SetValue(IsActivePropertyKey, element.IsLoaded && element.IsVisible);
44 }
Modified XFEToolBox.WpfCore/Controls/Carousel.xaml.cs +21 -6
@@ -19,6 +19,7 @@ public partial class Carousel : UserControl, INotifyPropertyChanged
19 19 private readonly DispatcherTimer timer;
20 20 private readonly HashSet<CarouselImageItem> subscribedItems = [];
21 21 private int currentIndex = -1;
22 private int transitionVersion;
22 23 private CarouselImageItem? currentItem;
23 24
24 25 #region Dependency properties
@@ -209,9 +210,17 @@ public partial class Carousel : UserControl, INotifyPropertyChanged
209 210 RestartTimer();
210 211 }
211 212
212 private void Carousel_Unloaded(object sender, RoutedEventArgs e) => timer.Stop();
213 private void Carousel_Unloaded(object sender, RoutedEventArgs e)
214 {
215 timer.Stop();
216 ShowImmediately(CurrentImageSource);
217 }
213 218
214 private void Carousel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) => RestartTimer();
219 private void Carousel_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
220 {
221 if (!IsVisible) ShowImmediately(CurrentImageSource);
222 RestartTimer();
223 }
215 224
216 225 private void ImageViewport_SizeChanged(object sender, SizeChangedEventArgs e)
217 226 {
@@ -323,8 +332,7 @@ public partial class Carousel : UserControl, INotifyPropertyChanged
323 332 CurrentImageSource = null;
324 333 CurrentTitle = string.Empty;
325 334 CurrentBadge = string.Empty;
326 ImageFront.Source = null;
327 ImageBack.Source = null;
335 ShowImmediately(null);
328 336 NotifyStateChanged();
329 337 return;
330 338 }
@@ -351,6 +359,7 @@ public partial class Carousel : UserControl, INotifyPropertyChanged
351 359
352 360 private void ShowImmediately(ImageSource? image)
353 361 {
362 ++transitionVersion;
354 363 ImageFront.BeginAnimation(OpacityProperty, null);
355 364 ImageBack.BeginAnimation(OpacityProperty, null);
356 365 ImageFront.Source = image;
@@ -361,9 +370,16 @@ public partial class Carousel : UserControl, INotifyPropertyChanged
361 370
362 371 private void BeginCrossFade(ImageSource? image)
363 372 {
373 if (!IsLoaded || !IsVisible)
374 {
375 ShowImmediately(image);
376 return;
377 }
378
364 379 ImageFront.BeginAnimation(OpacityProperty, null);
365 380 ImageBack.BeginAnimation(OpacityProperty, null);
366 381
382 var version = ++transitionVersion;
367 383 ImageBack.Source = ImageFront.Source;
368 384 ImageBack.Opacity = ImageBack.Source is null ? 0 : 1;
369 385 ImageFront.Source = image;
@@ -376,8 +392,7 @@ public partial class Carousel : UserControl, INotifyPropertyChanged
376 392
377 393 fadeOut.Completed += (_, _) =>
378 394 {
379 ImageBack.Source = null;
380 ImageBack.Opacity = 0;
395 if (version == transitionVersion) ShowImmediately(image);
381 396 };
382 397
383 398 ImageBack.BeginAnimation(OpacityProperty, fadeOut, HandoffBehavior.SnapshotAndReplace);
Modified XFEToolBox.WpfCore/Resources/Style/UnifiedControlsStyle.xaml +14 -8
@@ -1,11 +1,13 @@
1 1 <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
2 2 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
3 xmlns:controls="clr-namespace:XFEToolBox.WpfCore.Controls">
3 xmlns:controls="clr-namespace:XFEToolBox.WpfCore.Controls"
4 xmlns:behaviors="clr-namespace:XFEToolBox.WpfCore.Behaviors">
4 5
5 6 <BooleanToVisibilityConverter x:Key="TimePickerBooleanToVisibilityConverter"/>
6 7
7 8 <!-- 统一进度控件。 -->
8 9 <Style x:Key="UnifiedProgressBarStyle" TargetType="ProgressBar">
10 <Setter Property="behaviors:AnimationLifecycle.IsEnabled" Value="True"/>
9 11 <Setter Property="Height" Value="8"/>
10 12 <Setter Property="MinWidth" Value="80"/>
11 13 <Setter Property="Foreground" Value="{DynamicResource MainColor}"/>
@@ -27,10 +29,14 @@
27 29 </Grid>
28 30 </controls:RoundedClipBorder>
29 31 <ControlTemplate.Triggers>
30 <Trigger Property="IsIndeterminate" Value="True">
32 <MultiTrigger>
33 <MultiTrigger.Conditions>
34 <Condition Property="IsIndeterminate" Value="True"/>
35 <Condition Property="behaviors:AnimationLifecycle.IsActive" Value="True"/>
36 </MultiTrigger.Conditions>
31 37 <Setter TargetName="PART_Indicator" Property="Visibility" Value="Collapsed"/>
32 38 <Setter TargetName="IndeterminateBar" Property="Visibility" Value="Visible"/>
33 <Trigger.EnterActions>
39 <MultiTrigger.EnterActions>
34 40 <BeginStoryboard x:Name="IndeterminateStoryboard">
35 41 <Storyboard>
36 42 <DoubleAnimation Storyboard.TargetName="IndeterminateTransform"
@@ -38,11 +44,11 @@
38 44 Duration="0:0:1.35" RepeatBehavior="Forever"/>
39 45 </Storyboard>
40 46 </BeginStoryboard>
41 </Trigger.EnterActions>
42 <Trigger.ExitActions>
43 <StopStoryboard BeginStoryboardName="IndeterminateStoryboard"/>
44 </Trigger.ExitActions>
45 </Trigger>
47 </MultiTrigger.EnterActions>
48 <MultiTrigger.ExitActions>
49 <RemoveStoryboard BeginStoryboardName="IndeterminateStoryboard"/>
50 </MultiTrigger.ExitActions>
51 </MultiTrigger>
46 52 <Trigger Property="IsEnabled" Value="False">
47 53 <Setter Property="Opacity" Value="0.48"/>
48 54 </Trigger>
Modified XFEToolBox/Views/Pages/ToolBoxPage.xaml +1 -1
@@ -2,7 +2,7 @@
2 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
3 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
4 4 xmlns:controls="clr-namespace:XFEToolBox.WpfCore.Controls;assembly=XFEToolBox.WpfCore"
5 Background="Transparent" Title="" Loaded="Page_Loaded">
5 Background="Transparent" Title="" Loaded="Page_Loaded" Unloaded="Page_Unloaded">
6 6 <Page.Resources>
7 7 <Style x:Key="CategoryComboBoxItemStyle" TargetType="ComboBoxItem">
8 8 <Setter Property="Padding" Value="9,7"/>
Modified XFEToolBox/Views/Pages/ToolBoxPage.xaml.cs +32 -16
@@ -25,6 +25,7 @@ public partial class ToolBoxPage : Page
25 25 {
26 26 private static readonly ImageSource DefaultToolIcon = CreateDefaultIcon();
27 27 private static readonly JsonSerializerOptions CacheJsonOptions = new(JsonSerializerDefaults.Web);
28 private readonly Func<string, string, Task<ToolPackageSummary[]>> requestCatalog;
28 29 private readonly List<ToolCardViewModel> _tools = [];
29 30 private ToolCatalogRowViewModel[] _toolRows = [];
30 31 private int _visibleCategoryCount;
@@ -36,15 +37,21 @@ public partial class ToolBoxPage : Page
36 37
37 38 public static ToolBoxPage Current { get; private set; } = new();
38 39
39 public ToolBoxPage()
40 public ToolBoxPage() : this(RequestCatalogAsync)
40 41 {
41 42 Current = this;
43 }
44
45 internal ToolBoxPage(Func<string, string, Task<ToolPackageSummary[]>> requestCatalog)
46 {
47 this.requestCatalog = requestCatalog;
42 48 InitializeComponent();
43 49 CategoryFilter.Items.Add("全部分类");
44 50 CategoryFilter.SelectedIndex = 0;
45 51 }
46 52
47 53 private async void Page_Loaded(object sender, RoutedEventArgs e) => await RefreshAsync(refreshFullCatalog: true);
54 private void Page_Unloaded(object sender, RoutedEventArgs e) => ++_refreshGeneration;
48 55 private async void RefreshButton_Click(object sender, RoutedEventArgs e) => await RefreshAsync(refreshFullCatalog: true);
49 56 private async void SearchButton_Click(object sender, RoutedEventArgs e) => await RefreshAsync(updateCategories: false);
50 57
@@ -84,16 +91,8 @@ public partial class ToolBoxPage : Page
84 91 {
85 92 var requestQuery = refreshFullCatalog ? string.Empty : query;
86 93 var requestCategory = refreshFullCatalog ? string.Empty : category;
87 var response = await ClientSession.Requester.Request<ToolPackageSummary[]>(
88 "catalogTools", requestQuery, requestCategory);
94 var tools = await requestCatalog(requestQuery, requestCategory);
89 95 if (refreshGeneration != _refreshGeneration) return;
90 if (response.StatusCode != HttpStatusCode.OK)
91 {
92 ShowRefreshFailure(response.Message);
93 return;
94 }
95
96 var tools = response.Result ?? [];
97 96 if (refreshFullCatalog || string.IsNullOrWhiteSpace(query) && string.IsNullOrWhiteSpace(category))
98 97 {
99 98 _cachedCatalog = tools;
@@ -127,6 +126,14 @@ public partial class ToolBoxPage : Page
127 126 }
128 127 }
129 128
129 private static async Task<ToolPackageSummary[]> RequestCatalogAsync(string query, string category)
130 {
131 var response = await ClientSession.Requester.Request<ToolPackageSummary[]>("catalogTools", query, category);
132 if (response.StatusCode != HttpStatusCode.OK)
133 throw new InvalidOperationException(response.Message);
134 return response.Result ?? [];
135 }
136
130 137 private void EnsureCacheLoaded()
131 138 {
132 139 if (_cacheLoaded) return;
@@ -157,7 +164,7 @@ public partial class ToolBoxPage : Page
157 164 || tool.Tags?.Any(tag => Contains(tag, query)) == true))
158 165 .ToArray();
159 166
160 private void ApplyTools(IReadOnlyList<ToolPackageSummary> tools)
167 internal void ApplyTools(IReadOnlyList<ToolPackageSummary> tools)
161 168 {
162 169 var desiredCards = tools.Select(tool =>
163 170 {
@@ -168,9 +175,14 @@ public partial class ToolBoxPage : Page
168 175 return CreateToolCard(tool);
169 176 }).ToArray();
170 177
171 _tools.Clear();
172 _tools.AddRange(desiredCards);
173 RebuildCatalogRows();
178 // A page is reused when navigating back. Keep its containers, image bindings and scroll state
179 // when the catalog has not changed instead of rebuilding the virtualized list on every visit.
180 if (!_tools.SequenceEqual(desiredCards))
181 {
182 _tools.Clear();
183 _tools.AddRange(desiredCards);
184 RebuildCatalogRows();
185 }
174 186 EmptyState.Visibility = _tools.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
175 187 ToolCountText.Text = FormatToolCount();
176 188 }
@@ -242,8 +254,12 @@ public partial class ToolBoxPage : Page
242 254 private static bool Contains(string? value, string query) =>
243 255 value?.Contains(query, StringComparison.CurrentCultureIgnoreCase) == true;
244 256
245 private static bool ToolSummariesEquivalent(ToolPackageSummary left, ToolPackageSummary right) =>
246 JsonSerializer.Serialize(left, CacheJsonOptions) == JsonSerializer.Serialize(right, CacheJsonOptions);
257 internal static bool ToolSummariesEquivalent(ToolPackageSummary left, ToolPackageSummary right) =>
258 ReferenceEquals(left, right) ||
259 left.Id == right.Id && left.Name == right.Name && left.Description == right.Description &&
260 left.IconDataUrl == right.IconDataUrl && left.Author == right.Author && left.Category == right.Category &&
261 left.LatestVersion == right.LatestVersion && left.RequiresAdministrator == right.RequiresAdministrator &&
262 left.UpdatedAtUtc == right.UpdatedAtUtc && (left.Tags ?? []).SequenceEqual(right.Tags ?? []);
247 263
248 264 private static string[] GetCatalogCategories(IEnumerable<ToolPackageSummary> tools) =>
249 265 tools.Select(tool => NormalizeCategory(tool.Category))
Modified XFEToolBox/XFEToolBox.Client.csproj +1 -1
@@ -8,7 +8,7 @@
8 8 <UseWPF>true</UseWPF>
9 9 <ApplicationManifest>app.manifest</ApplicationManifest>
10 10 <ApplicationIcon>Resources\Icon\XFEToolBoxIcon.ico</ApplicationIcon>
11 <Version>1.2.1</Version>
11 <Version>1.2.2</Version>
12 12 <AssemblyTitle>XFEToolBox</AssemblyTitle>
13 13 <AssemblyName>XFEToolBox</AssemblyName>
14 14 </PropertyGroup>
Added tests/VideoStudio.Validation/AccelerationTests.cs +160 -0
@@ -0,0 +1,160 @@
1 using System.Diagnostics;
2 using System.Globalization;
3 using System.IO;
4 using System.Text.Json;
5 using System.Windows;
6 using System.Windows.Threading;
7 using XFEToolBox.Tools.VideoStudio;
8
9 namespace VideoStudio.Validation;
10
11 internal static partial class Program
12 {
13 private static bool Near(double x, double y) => Math.Abs(x - y) < .000001;
14 private static void TrimTests(string video)
15 {
16 using var vm = new MainPageViewModel { SourcePath = video, SourceDurationSeconds = 6, FramesPerSecond = 25, HasAudio = true };
17 vm.Clips.Add(new TimelineClip("trim", 1, 5) { AudioVolume = 37 }); vm.SelectedClip = vm.Clips[0];
18 Check(vm.BeginTrim(vm.Clips[0], ClipEdge.Start) && vm.IsTrimming && !vm.CanEdit, "start-edge gesture locks other editing actions");
19 for (int i = 0; i < 40; i++) vm.UpdateTrim(1.137);
20 Check(Near(vm.Clips[0].StartSeconds, 2.12) && Near(vm.Clips[0].EndSeconds, 5) && vm.Clips[0].AudioVolume == 37, "start-edge drag snaps to frames and preserves linked audio settings");
21 vm.EndTrim(true); vm.UndoCommand.Execute(null);
22 Check(Near(vm.Clips[0].StartSeconds, 1) && !vm.UndoCommand.CanExecute(null), "forty drag updates produce exactly one undo step");
23 vm.RedoCommand.Execute(null); Check(Near(vm.Clips[0].StartSeconds, 2.12), "redo restores entire trim gesture"); vm.UndoCommand.Execute(null);
24 vm.BeginTrim(vm.Clips[0], ClipEdge.End); vm.UpdateTrim(40); vm.EndTrim(true);
25 Check(Near(vm.Clips[0].EndSeconds, 6), "end-edge extension is clamped to source end"); vm.UndoCommand.Execute(null);
26 vm.BeginTrim(vm.Clips[0], ClipEdge.Start); vm.UpdateTrim(-100); vm.EndTrim(true);
27 Check(Near(vm.Clips[0].StartSeconds, 0), "start-edge extension is clamped to source beginning"); vm.UndoCommand.Execute(null);
28 vm.BeginTrim(vm.Clips[0], ClipEdge.Start); vm.UpdateTrim(100);
29 Check(Near(vm.Clips[0].DurationSeconds, .04), "drag cannot trim a clip below one frame");
30 vm.EndTrim(false); Check(Near(vm.Clips[0].StartSeconds, 1) && vm.RedoCommand.CanExecute(null), "cancel restores bounds without destroying redo history");
31 vm.BeginTrim(vm.Clips[0], ClipEdge.End); vm.UpdateTrim(-100); vm.EndTrim(true);
32 Check(Near(vm.Clips[0].DurationSeconds, .04), "end-edge crossing clamps to one frame"); vm.UndoCommand.Execute(null);
33 vm.BeginTrim(vm.Clips[0], ClipEdge.End); vm.UpdateTrim(double.NaN); vm.EndTrim(true);
34 Check(Near(vm.Clips[0].EndSeconds, 5) && !vm.UndoCommand.CanExecute(null), "NaN and no-op gestures do not add undo entries");
35 vm.IsBusy = true; Check(!vm.BeginTrim(vm.Clips[0], ClipEdge.Start), "export in progress rejects trim gestures"); vm.IsBusy = false;
36 vm.ToggleExportModeCommand.Execute(null); Check(vm.ExportMode == ExportEncodingMode.Cpu, "toolbar can explicitly select optimized CPU export");
37 vm.ToggleExportModeCommand.Execute(null); Check(vm.ExportMode == ExportEncodingMode.Automatic, "automatic GPU selection is the default export mode");
38 }
39
40 private static async Task GestureTests(MainPageViewModel vm, TimelineSurface surface, FrameworkElement page)
41 {
42 var first = vm.Clips[0]; double scale = surface.XAt(1);
43 var tail = new Point(surface.XAt(2) - 4, 76);
44 Check(surface.EdgeAt(tail) is { Edge: ClipEdge.End } hit && hit.Clip == first, "video right handle hit-test belongs to preceding clip");
45 Check(surface.EdgeAt(new Point(surface.XAt(2) + 3, 164)) is { Edge: ClipEdge.Start } audio && audio.Clip == vm.Clips[1], "audio left handle hit-test belongs to following clip");
46 Check(surface.EdgeAt(new Point(surface.XAt(1), 10)) is null && surface.EdgeAt(new Point(surface.XAt(1), 76)) is null, "ruler and clip body are not trim handles");
47 surface.BeginDrag(tail); surface.MoveDrag(new Point(tail.X - .4 * scale, tail.Y)); await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
48 surface.MoveDrag(new Point(tail.X - .4 * scale, tail.Y));
49 Check(Near(first.EndSeconds, 1.6) && Near(surface.XAt(1), scale) && vm.Clips.Count == 3, "drag uses frozen scale despite live ripple duration changes");
50 surface.FinishDrag(new Point(tail.X - .4 * scale, tail.Y));
51 Check(!vm.IsTrimming && Near(vm.TimelineDuration, 5.6), "pointer release commits video/audio trim without reordering"); vm.UndoCommand.Execute(null);
52 await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
53 var head = new Point(surface.XAt(2) + 3, 164); scale = surface.XAt(1);
54 surface.BeginDrag(head); surface.MoveDrag(new Point(head.X + .28 * scale, head.Y));
55 Check(Near(vm.Clips[1].StartSeconds, 2.28), "audio-track start handle edits linked video boundary"); surface.CancelDrag();
56 Check(!vm.IsTrimming && Near(vm.Clips[1].StartSeconds, 2), "lost capture / Escape cancellation restores the linked clip");
57 vm.Zoom = 2; await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
58 var lastTail = new Point(surface.XAt(6) - 4, 164); scale = surface.XAt(1);
59 surface.BeginDrag(lastTail); surface.MoveDrag(new Point(lastTail.X - .36 * scale, lastTail.Y)); surface.FinishDrag(new Point(lastTail.X - .36 * scale, lastTail.Y));
60 Check(Near(vm.Clips[^1].EndSeconds, 5.64), "last audio tail handle trims accurately on zoomed timeline"); vm.UndoCommand.Execute(null); vm.FitTimelineCommand.Execute(null);
61 Save(page, "trim-handles.png");
62 }
63
64 private static async Task AccelerationTests(MediaProcessingService media, string source)
65 {
66 var clips = new[] { new TimelineClip("A", 1, 2), new TimelineClip("B", 3, 5) { AudioVolume = 50 } };
67 string gpu = Path.Combine(Root, "accelerated.mp4"); var messages = new CollectedProgress();
68 var result = await media.ExportTimelineAsync(ffmpeg, source, clips, gpu, messages, default, ffprobe);
69 Check(result.Batches == 1 && result.RenderSegments == 2 && !result.StreamCopy, "multi-clip edited sequence uses one encoding pass without intermediate media");
70 Check(result.UsedGpu && result.Encoder.Contains("NVIDIA"), "actual RTX 5090 NVENC export selected after capability smoke encode");
71 Check(messages.Values.Any(m => m.Message.Contains("NVIDIA")) && messages.Values.Last().Value == 1, "export progress reports actual encoder and completion");
72 string cpu = Path.Combine(Root, "optimized-cpu.mp4");
73 var cpuResult = await media.ExportTimelineAsync(ffmpeg, source, clips, cpu, null, default, ffprobe, new(ExportEncodingMode.Cpu));
74 Check(!cpuResult.UsedGpu && !cpuResult.StreamCopy, "CPU mode bypasses GPU probing and still uses single-pass pipeline");
75 Check(await FrameError(source, 3.2, cpu, 1.2) < 9, "optimized CPU output preserves exact cut frames");
76 var adjacent = new[] { new TimelineClip("split1", 0, 2), new TimelineClip("split2", 2, 4), new TimelineClip("split3", 4, 6) };
77 string copied = Path.Combine(Root, "smart-copy.mp4");
78 var smart = await media.ExportTimelineAsync(ffmpeg, source, adjacent, copied, null, default, ffprobe);
79 Check(smart.StreamCopy && smart.RenderSegments == 1 && adjacent[0].EndSeconds == 2, "contiguous unmodified splits coalesce to lossless smart copy without mutating edits");
80 async Task<string> StreamHash(string file, string type) { var r = await new ProcessRunner().RunAsync(ffmpeg, ["-v", "error", "-i", file, "-map", type, "-c", "copy", "-f", "hash", "-hash", "sha256", "-"], Root, null, null, default); if (!r.Success) throw new InvalidOperationException(r.CombinedOutput); return r.StandardOutput.Trim(); }
81 Check(await StreamHash(source, "0:v:0") == await StreamHash(copied, "0:v:0") && await StreamHash(source, "0:a:0") == await StreamHash(copied, "0:a:0"), "smart-copy audio and video compressed payloads are bit-identical");
82 Check(MediaProcessingService.Coalesce([new("a", 0, 1), new("b", 1, 2) { AudioEnabled = false }]).Length == 2, "coalescer does not merge different audio gains");
83 Check(MediaProcessingService.Coalesce([new("a", 0, 1), new("gap", 1.04, 2)]).Length == 2, "coalescer preserves removed frames and source gaps");
84 string fallback = Path.Combine(Root, "fallback.mp4");
85 var failingGpu = new MediaProcessingService { EncoderResolver = (_, _) => Task.FromResult(new VideoEncoder("h264_nonexistent_test_encoder", "injected GPU failure", true, [])) };
86 var recovered = await failingGpu.ExportTimelineAsync(ffmpeg, source, clips, fallback, null, default, ffprobe);
87 Check(recovered.FellBack && !recovered.UsedGpu && (await media.ProbeAsync(ffprobe, fallback, default)).Width == 640, "real FFmpeg encoder failure falls back to working CPU output");
88 await Ffmpeg(["-xerror", "-i", fallback, "-f", "null", "-"]); Check(true, "fallback output fully decodes");
89 // Nine distinct slices force multiple bounded batches; last slice has different source mapping and gain.
90 var many = Enumerable.Range(0, 9).Select(i => new TimelineClip($"batch{i}", i % 2 == 0 ? 1 : 3, i % 2 == 0 ? 1.2 : 3.2) { AudioVolume = i == 8 ? 25 : 100 }).ToArray();
91 string batched = Path.Combine(Root, "batched.mp4");
92 var batchResult = await media.ExportTimelineAsync(ffmpeg, source, many, batched, null, default, ffprobe);
93 Check(batchResult.Batches == 2 && Math.Abs((await media.ProbeAsync(ffprobe, batched, default)).DurationSeconds - 1.8) < .09, "large timeline uses bounded batches with correct final duration");
94 await Ffmpeg(["-xerror", "-i", batched, "-f", "null", "-"]); Check(true, "batched GPU output fully decodes across batch join");
95 Check(await FrameError(source, 1.08, batched, 1.68) < 9, "last batch frame mapping survives video stream-copy join");
96 double ratio = await Rms(batched, 1.64, .12) / await Rms(source, 1.04, .12);
97 Check(ratio > .15 && ratio < .35, "batched audio is encoded once with expected last-clip gain");
98 async Task<int> FrameCount(string path)
99 {
100 var counted = await new ProcessRunner().RunAsync(ffprobe, ["-v", "error", "-count_frames", "-select_streams", "v:0", "-show_entries", "stream=nb_read_frames", "-of", "csv=p=0", path], Root, null, null, default);
101 return int.Parse(counted.StandardOutput.Trim(), CultureInfo.InvariantCulture);
102 }
103 Check(await FrameCount(batched) == 45, "bounded-batch join neither duplicates nor loses frames");
104 var unstable = VideoEncoder.Hardware[0] with { Options = VideoEncoder.Hardware[0].Options.ToArray() };
105 var lateFailure = new MediaProcessingService { EncoderResolver = (_, _) => Task.FromResult(unstable) };
106 bool invalidated = false;
107 var invalidator = new CallbackProgress(p => { if (!invalidated && p.Value > .7 && p.Message.Contains("正在渲染:")) { unstable.Options[1] = "invalid_preset_for_late_failure_test"; invalidated = true; } });
108 string late = Path.Combine(Root, "late-fallback.mp4");
109 var lateResult = await lateFailure.ExportTimelineAsync(ffmpeg, source, many, late, invalidator, default, ffprobe);
110 Check(invalidated && lateResult.FellBack && !lateResult.UsedGpu && lateResult.Batches == 2, "GPU failure after a completed batch restarts all batches with one CPU encoder");
111 await Ffmpeg(["-xerror", "-i", late, "-f", "null", "-"]);
112 Check(await FrameCount(late) == 45, "late GPU fallback has consistent H.264 headers and complete frames");
113 byte[] previousOutput = File.ReadAllBytes(late);
114 var brokenEncoder = new MediaProcessingService { EncoderResolver = (_, _) => Task.FromResult(new VideoEncoder("nonexistent_cpu_encoder", "expected test failure", false, [])) };
115 await Reject(() => brokenEncoder.ExportTimelineAsync(ffmpeg, source, clips, late, null, default, ffprobe), "unrecoverable encoder failure is surfaced");
116 Check(previousOutput.SequenceEqual(File.ReadAllBytes(late)), "unrecoverable failure preserves the user's previous destination bytes");
117 string fractional = Path.Combine(Root, "fractional.mp4"), fractionalOut = Path.Combine(Root, "fractional-edited.mp4");
118 await Ffmpeg(["-f", "lavfi", "-i", "testsrc2=s=320x180:r=30000/1001:d=2", "-f", "lavfi", "-i", "sine=duration=2", "-c:v", "libx264", "-c:a", "aac", "-shortest", fractional]);
119 double frame = 1001d / 30000;
120 await media.ExportTimelineAsync(ffmpeg, fractional, [new("first", 3 * frame, 11 * frame), new("second", 24 * frame, 33 * frame)], fractionalOut, null, default, ffprobe);
121 Check(await FrameCount(fractionalOut) == 17, "fractional 29.97fps non-keyframe trims preserve exact frame count");
122 Check(Math.Abs((await media.ProbeAsync(ffprobe, fractionalOut, default)).FramesPerSecond - 30000d / 1001) < .001, "fractional frame rate survives accelerated export");
123 Check(!Directory.EnumerateDirectories(Root, ".xfe-video-*").Any(), "successful and fallback exports clean all private staging directories");
124 }
125
126 private sealed class CollectedProgress : IProgress<ExportProgress>
127 {
128 private readonly List<ExportProgress> values = [];
129 public ExportProgress[] Values { get { lock (values) return values.ToArray(); } }
130 public void Report(ExportProgress value) { lock (values) values.Add(value); }
131 }
132 private sealed class CallbackProgress(Action<ExportProgress> callback) : IProgress<ExportProgress> { public void Report(ExportProgress value) => callback(value); }
133
134 private static async Task Benchmark()
135 {
136 string source = Path.Combine(Root, "benchmark-1080p.mp4");
137 await Ffmpeg(["-f", "lavfi", "-i", "testsrc2=s=1920x1080:r=30:d=24", "-f", "lavfi", "-i", "sine=frequency=880:sample_rate=48000:duration=24", "-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-threads", "12", "-c:a", "aac", "-shortest", source]);
138 var clips = new[] { new TimelineClip("1", 1, 5), new TimelineClip("2", 9, 13) { AudioVolume = 60 }, new TimelineClip("3", 5, 9), new TimelineClip("4", 18, 22) { AudioEnabled = false }, new TimelineClip("5", 14, 18), new TimelineClip("6", 0, 4) };
139 var legacy = new LegacyExporter(); var optimized = new MediaProcessingService();
140 var rows = new List<object>(); var times = new Dictionary<string, List<double>>();
141 // Two rounds in different orders reduce cache/thermal ordering bias. Fixture creation is not timed.
142 foreach (var mode in new[] { "legacy", "cpu", "gpu", "gpu", "cpu", "legacy" })
143 {
144 string output = Path.Combine(Root, $"{mode}-{rows.Count}.mp4"); var watch = Stopwatch.StartNew(); string encoder = "CPU · x264 medium (legacy)";
145 if (mode == "legacy") await legacy.ExportTimelineAsync(ffmpeg, source, clips, output, null, default, ffprobe);
146 else { var result = await optimized.ExportTimelineAsync(ffmpeg, source, clips, output, null, default, ffprobe, new(mode == "cpu" ? ExportEncodingMode.Cpu : ExportEncodingMode.Automatic, false)); encoder = result.Encoder; if (mode == "gpu") Check(result.UsedGpu, "benchmark actually used GPU hardware"); }
147 watch.Stop();
148 var probe = await optimized.ProbeAsync(ffprobe, output, default);
149 Check(Math.Abs(probe.DurationSeconds - 24) < .09 && probe.Width == 1920 && probe.Height == 1080 && probe.HasAudio, $"{mode} benchmark dimensions/duration/audio");
150 await Ffmpeg(["-xerror", "-i", output, "-f", "null", "-"]);
151 Check(await Rms(output, 12.5, .5) < .00005, $"{mode} benchmark muted segment");
152 if (!times.TryGetValue(mode, out var list)) times[mode] = list = []; list.Add(watch.Elapsed.TotalSeconds);
153 rows.Add(new { mode, encoder, seconds = watch.Elapsed.TotalSeconds, bytes = new FileInfo(output).Length, output });
154 Console.WriteLine($"BENCHMARK {mode}: {watch.Elapsed.TotalSeconds:0.000}s / {encoder}");
155 }
156 var averages = times.ToDictionary(p => p.Key, p => p.Value.Average());
157 var report = new { input = "testsrc2 1920x1080 30fps 24s + sine; six 4-second noncontiguous/reordered clips; one gain=60%, one muted", cpu = "AMD Ryzen 9 9950X3D", gpu = "NVIDIA RTX 5090", rounds = rows, averageSeconds = averages, cpuSpeedup = averages["legacy"] / averages["cpu"], gpuSpeedup = averages["legacy"] / averages["gpu"] };
158 string json = JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true }); await File.WriteAllTextAsync(Path.Combine(Root, "benchmark.json"), json); Console.WriteLine(json);
159 }
160 }
Added tests/VideoStudio.Validation/LegacyExporter.cs +245 -0
@@ -0,0 +1,245 @@
1 // Frozen VideoStudio 1.3.0 export baseline. Test-only: keep algorithms and encoder options unchanged.
2 using System.Globalization;
3 using System.IO;
4 using System.Text;
5 using System.Text.Json;
6
7 using XFEToolBox.Tools.VideoStudio;
8 namespace VideoStudio.Validation;
9
10 public sealed class LegacyExporter
11 {
12 private readonly ProcessRunner processRunner = new();
13
14 public async Task<MediaProbeResult> ProbeAsync(
15 string ffprobePath,
16 string sourcePath,
17 CancellationToken cancellationToken)
18 {
19 var result = await processRunner.RunAsync(
20 ffprobePath,
21 ["-v", "error", "-show_streams", "-show_format", "-of", "json", sourcePath],
22 Path.GetDirectoryName(sourcePath),
23 null,
24 null,
25 cancellationToken);
26 if (!result.Success)
27 throw CreateProcessException("FFprobe 读取媒体信息失败", result);
28
29 using var document = JsonDocument.Parse(result.StandardOutput);
30 var root = document.RootElement;
31 JsonElement? videoStream = null;
32 var hasAudio = false;
33 if (root.TryGetProperty("streams", out var streams))
34 {
35 foreach (var stream in streams.EnumerateArray())
36 {
37 var codecType = ReadString(stream, "codec_type");
38 if (codecType == "video" && videoStream is null)
39 videoStream = stream.Clone();
40 else if (codecType == "audio")
41 hasAudio = true;
42 }
43 }
44
45 var duration = 0d;
46 var formatName = string.Empty;
47 if (root.TryGetProperty("format", out var format))
48 {
49 duration = ReadDouble(format, "duration");
50 formatName = ReadString(format, "format_long_name");
51 if (formatName.Length == 0)
52 formatName = ReadString(format, "format_name");
53 }
54 if (duration <= 0 && videoStream is { } durationStream)
55 duration = ReadDouble(durationStream, "duration");
56
57 var width = videoStream is { } widthStream ? ReadInt(widthStream, "width") : 0;
58 var height = videoStream is { } heightStream ? ReadInt(heightStream, "height") : 0;
59 var codec = videoStream is { } codecStream ? ReadString(codecStream, "codec_name") : "未知编码";
60 var frameRate = videoStream is { } rateStream
61 ? ParseFrameRate(ReadString(rateStream, "avg_frame_rate"), ReadString(rateStream, "r_frame_rate"))
62 : 0;
63 return new MediaProbeResult(duration, width, height, frameRate, codec, hasAudio, formatName);
64 }
65
66 public async Task ExportTimelineAsync(
67 string ffmpegPath,
68 string sourcePath,
69 IReadOnlyList<TimelineClip> clips,
70 string outputPath,
71 IProgress<ExportProgress>? progress,
72 CancellationToken cancellationToken,
73 string? ffprobePath = null)
74 {
75 cancellationToken.ThrowIfCancellationRequested();
76 var enabledClips = clips.Where(clip => clip.IsEnabled).Select(c => c.Copy()).ToArray();
77 if (enabledClips.Length == 0)
78 throw new InvalidOperationException("时间轴中没有可导出的有效片段。");
79 if (Path.GetFullPath(sourcePath).Equals(Path.GetFullPath(outputPath), StringComparison.OrdinalIgnoreCase))
80 throw new InvalidOperationException("输出文件不能覆盖正在读取的源视频。");
81 var ffmpeg = ProcessRunner.ResolveExecutable(ffmpegPath);
82 var probe = await ProbeAsync(string.IsNullOrWhiteSpace(ffprobePath) ? Path.Combine(Path.GetDirectoryName(ffmpeg)!, "ffprobe.exe") : ffprobePath, sourcePath, cancellationToken);
83 if (probe.Width <= 0 || probe.Height <= 0 || !double.IsFinite(probe.DurationSeconds) || probe.DurationSeconds <= 0)
84 throw new InvalidOperationException("源视频没有有效的画面或时长。");
85 var fps = double.IsFinite(probe.FramesPerSecond) && probe.FramesPerSecond is >= 1 and <= 240 ? probe.FramesPerSecond : 30;
86 if (enabledClips.Any(c => !double.IsFinite(c.StartSeconds) || !double.IsFinite(c.EndSeconds) || c.StartSeconds < 0 || c.EndSeconds > probe.DurationSeconds + .001 || c.DurationSeconds < .99 / fps || !double.IsFinite(c.AudioVolume) || c.AudioVolume is < 0 or > 100))
87 throw new InvalidOperationException("片段边界、帧长度或音量无效,请检查时间轴。");
88 if (!Path.GetExtension(outputPath).Equals(".mp4", StringComparison.OrdinalIgnoreCase))
89 throw new InvalidOperationException("此剪辑预设输出 MP4,请选择 .mp4 文件。");
90 var outputDirectory = Path.GetDirectoryName(Path.GetFullPath(outputPath))!;
91 Directory.CreateDirectory(outputDirectory);
92 var temporaryRoot = Path.Combine(outputDirectory, ".xfe-video-" + Guid.NewGuid().ToString("N"));
93 Directory.CreateDirectory(temporaryRoot);
94
95 try
96 {
97 var parts = new List<string>(enabledClips.Length);
98 for (var index = 0; index < enabledClips.Length; index++)
99 {
100 cancellationToken.ThrowIfCancellationRequested();
101 var clip = enabledClips[index];
102 var partPath = Path.Combine(temporaryRoot, $"part-{index + 1:0000}.mkv");
103 parts.Add(partPath);
104 progress?.Report(new ExportProgress(
105 index / (double)(enabledClips.Length + 1),
106 $"正在渲染片段 {index + 1}/{enabledClips.Length}:{clip.Name}"));
107 var arguments = new List<string>
108 {
109 "-hide_banner", "-loglevel", "error", "-nostdin", "-n",
110 "-ss", FormatSeconds(clip.StartSeconds),
111 "-i", Path.GetFullPath(sourcePath)
112 };
113 if (!probe.HasAudio) arguments.AddRange(["-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo"]);
114 arguments.AddRange([
115 "-t", FormatSeconds(clip.DurationSeconds), "-map", "0:v:0", "-map", probe.HasAudio ? "0:a:0" : "1:a:0",
116 "-c:v", "libx264", "-preset", "medium", "-crf", "20",
117 "-vf", $"scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1,fps={fps.ToString("0.########", CultureInfo.InvariantCulture)}",
118 "-pix_fmt", "yuv420p", "-c:a", "pcm_s16le", "-ac", "2", "-ar", "48000",
119 "-af", $"aresample=48000:async=1:first_pts=0,apad,atrim=duration={FormatSeconds(clip.DurationSeconds)},volume={(clip.AudioEnabled ? clip.AudioVolume / 100 : 0).ToString("0.####", CultureInfo.InvariantCulture)}",
120 "-threads", "4",
121 "-progress", "pipe:1", "-nostats", partPath
122 ]);
123 var result = await processRunner.RunAsync(
124 ffmpegPath,
125 arguments,
126 temporaryRoot,
127 line => ReportFfmpegProgress(line, clip.DurationSeconds, index, enabledClips.Length + 1, clip.Name, progress),
128 null,
129 cancellationToken);
130 if (!result.Success || !File.Exists(partPath))
131 throw CreateProcessException($"片段“{clip.Name}”渲染失败", result);
132 }
133
134 progress?.Report(new ExportProgress(
135 enabledClips.Length / (double)(enabledClips.Length + 1),
136 "正在拼接时间轴并写入最终文件…"));
137 string finalPath = Path.Combine(temporaryRoot, "final.mp4");
138 var listPath = Path.Combine(temporaryRoot, "concat.txt");
139 var lines = parts.Select(path => $"file '{EscapeConcatPath(path)}'");
140 await File.WriteAllLinesAsync(listPath, lines, new UTF8Encoding(false), cancellationToken);
141 var concatResult = await processRunner.RunAsync(
142 ffmpegPath,
143 ["-hide_banner", "-loglevel", "error", "-nostdin", "-n", "-f", "concat", "-safe", "0", "-i", listPath,
144 "-map", "0:v:0", "-map", "0:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", "192k", "-t", FormatSeconds(enabledClips.Sum(c => c.DurationSeconds)), "-movflags", "+faststart", finalPath],
145 temporaryRoot,
146 null,
147 null,
148 cancellationToken);
149 if (!concatResult.Success || !File.Exists(finalPath) || new FileInfo(finalPath).Length == 0)
150 throw CreateProcessException("时间轴拼接失败", concatResult);
151 cancellationToken.ThrowIfCancellationRequested();
152 File.Move(finalPath, Path.GetFullPath(outputPath), overwrite: true);
153 progress?.Report(new ExportProgress(1, "导出完成。"));
154 }
155 finally
156 {
157 TryDeleteDirectory(temporaryRoot);
158 }
159 }
160
161 private static string ReadString(JsonElement element, string propertyName) =>
162 element.TryGetProperty(propertyName, out var property) && property.ValueKind == JsonValueKind.String
163 ? property.GetString() ?? string.Empty
164 : string.Empty;
165
166 private static int ReadInt(JsonElement element, string propertyName) =>
167 element.TryGetProperty(propertyName, out var property) && property.TryGetInt32(out var value) ? value : 0;
168
169 private static double ReadDouble(JsonElement element, string propertyName)
170 {
171 if (!element.TryGetProperty(propertyName, out var property))
172 return 0;
173 if (property.ValueKind == JsonValueKind.Number && property.TryGetDouble(out var number))
174 return number;
175 return double.TryParse(property.GetString(), NumberStyles.Float, CultureInfo.InvariantCulture, out number) ? number : 0;
176 }
177
178 private static double ParseFrameRate(string average, string raw)
179 {
180 foreach (var value in new[] { average, raw })
181 {
182 var parts = value.Split('/');
183 if (parts.Length == 2
184 && double.TryParse(parts[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var numerator)
185 && double.TryParse(parts[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var denominator)
186 && denominator != 0)
187 return numerator / denominator;
188 if (double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var direct))
189 return direct;
190 }
191 return 0;
192 }
193
194 private static void ReportFfmpegProgress(
195 string line,
196 double clipDuration,
197 int completedClipCount,
198 int totalSteps,
199 string clipName,
200 IProgress<ExportProgress>? progress)
201 {
202 if (!line.StartsWith("out_time=", StringComparison.OrdinalIgnoreCase)
203 || !TimeSpan.TryParse(line[9..], CultureInfo.InvariantCulture, out var position))
204 return;
205 var localProgress = clipDuration <= 0 ? 0 : Math.Clamp(position.TotalSeconds / clipDuration, 0, 1);
206 progress?.Report(new ExportProgress(
207 (completedClipCount + localProgress) / totalSteps,
208 $"正在渲染:{clipName} · {localProgress:P0}"));
209 }
210
211 private static string FormatSeconds(double seconds) => Math.Max(0, seconds).ToString("0.######", CultureInfo.InvariantCulture);
212
213 private static string EscapeConcatPath(string path) => path.Replace('\\', '/').Replace("'", "'\\''");
214
215 private static string NormalizeLanguage(string language) => string.IsNullOrWhiteSpace(language) ? "zh" : language.Trim();
216
217 private static string TrimStatusLine(string line, string fallback)
218 {
219 var value = line.Trim();
220 if (value.Length == 0)
221 return fallback;
222 return value.Length <= 140 ? value : value[..140] + "…";
223 }
224
225 private static InvalidOperationException CreateProcessException(string title, ProcessRunResult result)
226 {
227 var detail = result.CombinedOutput;
228 if (detail.Length > 2000)
229 detail = detail[^2000..];
230 return new InvalidOperationException($"{title}(退出代码 {result.ExitCode})。{Environment.NewLine}{detail}".Trim());
231 }
232
233 private static void TryDeleteDirectory(string path)
234 {
235 try
236 {
237 if (Directory.Exists(path))
238 Directory.Delete(path, recursive: true);
239 }
240 catch
241 {
242 // 临时媒体文件可能仍被杀毒软件短暂占用,下次系统清理会移除。
243 }
244 }
245 }
Added tests/VideoStudio.Validation/Program.cs +155 -0
@@ -0,0 +1,155 @@
1 using System.Diagnostics;
2 using System.IO;
3 using System.Reflection;
4 using System.Security.Cryptography;
5 using System.Text.Json;
6 using System.Windows;
7 using System.Windows.Controls;
8 using System.Windows.Media;
9 using System.Windows.Media.Imaging;
10 using System.Windows.Threading;
11 using XFEToolBox.Core.Tools;
12 using XFEToolBox.Tools.VideoStudio;
13
14 namespace VideoStudio.Validation;
15 internal static partial class Program
16 {
17 private static readonly string Workspace = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEToolBox", "CrossVersion", "EditorWorkspaces", "VideoStudio");
18 private static readonly string Root = Path.Combine(AppContext.BaseDirectory, "test-artifacts", DateTime.Now.ToString("yyyyMMdd-HHmmss"));
19 private static readonly List<string> Passes = [];
20 private static int exitCode;
21 private static string ffmpeg = "", ffprobe = "";
22 [STAThread] private static int Main(string[] args)
23 {
24 Directory.CreateDirectory(Root); var app = new Application { ShutdownMode = ShutdownMode.OnExplicitShutdown };
25 app.Resources.MergedDictionaries.Add(new ResourceDictionary { Source = new Uri("pack://application:,,,/XFEToolBox.WpfCore;component/Resources/Style/ToolThemeResources.xaml") });
26 app.Startup += async (_, _) => { try { await RunAsync(args); } catch (Exception e) { exitCode = 1; Console.Error.WriteLine(e); } finally { File.WriteAllText(Path.Combine(Root, "results.json"), JsonSerializer.Serialize(new { success = exitCode == 0, checks = Passes }, new JsonSerializerOptions { WriteIndented = true })); Console.WriteLine("Artifacts: " + Root); app.Shutdown(); } }; app.Run(); return exitCode;
27 }
28 private static void Check(bool condition, string name) { if (!condition) throw new InvalidOperationException("FAIL: " + name); Passes.Add(name); Console.WriteLine("PASS: " + name); }
29 private static async Task Reject(Func<Task> action, string name) { bool failed = false; try { await action(); } catch { failed = true; } Check(failed, name); }
30 private static async Task RunAsync(string[] args)
31 {
32 var settings = JsonSerializer.Deserialize<VideoToolSettings>(File.ReadAllText(Path.Combine(Path.GetDirectoryName(Path.GetDirectoryName(Workspace)!)!, "ToolData", "xfestudio.video-studio", "settings.json")), new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
33 ffmpeg = settings.FfmpegPath; ffprobe = settings.FfprobePath;
34 if (args.Contains("--benchmark-only")) { await Benchmark(); return; }
35 string video = Path.Combine(Root, "测试 剪辑素材.mp4"), silent = Path.Combine(Root, "silent.mp4");
36 await Ffmpeg(["-f", "lavfi", "-i", "testsrc2=size=640x360:rate=25:duration=6", "-f", "lavfi", "-i", "sine=frequency=440:duration=6", "-af", "tremolo=f=1:d=0.7", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", "-shortest", video]);
37 await Ffmpeg(["-i", video, "-an", "-c:v", "copy", silent]);
38 var sourceHash = SHA256.HashData(File.ReadAllBytes(video)); var media = new MediaProcessingService();
39 var probe = await media.ProbeAsync(ffprobe, video, default);
40 Check(probe.HasAudio && probe.Width == 640 && Math.Abs(probe.FramesPerSecond - 25) < .001, "actual FFprobe video/audio/frame rate");
41 using var vm = new MainPageViewModel { FfmpegPath = ffmpeg, FfprobePath = ffprobe };
42 int ticks = 0; var timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(15) }; timer.Tick += (_, _) => ticks++; timer.Start();
43 await vm.LoadSourceAsync(video); timer.Stop();
44 Check(!vm.IsBusy && vm.Clips.Count == 1 && vm.HasAudio, "import creates linked video/audio sequence");
45 Check(ticks > 10 && vm.Thumbnails.Count == 8 && vm.Waveform is not null, "responsive import with real thumbnails and waveform");
46 Check(Math.Abs(vm.TimelineDuration - 6) < .01 && vm.ProgressValue == 1, "sequence duration and completed progress");
47 vm.SeekSequence(2); vm.SplitClipCommand.Execute(null);
48 Check(vm.Clips.Count == 2 && Math.Abs(vm.Clips[0].DurationSeconds - 2) < .001 && vm.Clips[1].StartSeconds == 2, "toolbar split keeps linked source intervals");
49 vm.NextFrameCommand.Execute(null); Check(Math.Abs(vm.SequencePosition - 2.04) < .0001 && vm.SequenceTimecode == "00:00:02:01", "next frame advances exactly one 25-fps frame");
50 vm.PreviousFrameCommand.Execute(null); Check(vm.SequencePosition == 2, "previous frame returns to boundary");
51 vm.SeekSequence(0); vm.SplitClipCommand.Execute(null); Check(vm.Clips.Count == 2, "split at sequence edge does not create empty clips");
52 vm.UndoCommand.Execute(null); Check(vm.Clips.Count == 1, "undo restores original clip");
53 vm.RedoCommand.Execute(null); Check(vm.Clips.Count == 2, "redo restores split");
54 var right = vm.Clips[1]; vm.ReorderClip(right, 0);
55 Check(vm.Clips[0].StartSeconds == 2 && vm.AtSequence(0).SourceSeconds == 2, "reorder maps sequence zero to correct source frame");
56 vm.SeekSequence(4.5); Check(Math.Abs(vm.CurrentPositionSeconds - .48) < .05 && vm.SelectedClip == vm.Clips[1], "sequence-to-source mapping after reorder");
57 vm.SeekSequence(0); vm.TrimInText = "3"; vm.TrimOutText = "5"; vm.ApplyTrimCommand.Execute(null);
58 Check(vm.Clips[0].StartSeconds == 3 && vm.Clips[0].EndSeconds == 5 && vm.TimelineDuration == 4, "frame aligned ripple trim");
59 vm.VolumeText = "50"; vm.ApplyVolumeCommand.Execute(null); Check(vm.SelectedClip!.AudioVolume == 50 && vm.PreviewVolume == .5, "clip audio gain changes preview model");
60 vm.ToggleClipAudioCommand.Execute(null); Check(!vm.SelectedClip.AudioEnabled && vm.PreviewVolume == 0, "clip mute");
61 vm.UndoCommand.Execute(null); Check(vm.SelectedClip!.AudioEnabled && vm.SelectedClip.AudioVolume == 50, "undo retains per-clip gain");
62 vm.MuteAudioCommand.Execute(null); Check(vm.AudioMuted && vm.PreviewVolume == 0, "A1 track mute"); vm.UndoCommand.Execute(null);
63 vm.TrimInText = "NaN"; vm.ApplyTrimCommand.Execute(null); Check(vm.Clips[0].StartSeconds == 3, "invalid trim preserves sequence");
64 vm.RemoveClipCommand.Execute(null); Check(vm.Clips.Count == 1 && vm.TimelineDuration == 2, "ripple delete linked pair"); vm.UndoCommand.Execute(null);
65 var previous = vm.SourcePath; await vm.LoadSourceAsync(Path.Combine(Root, "missing.mp4")); Check(vm.SourcePath == previous && vm.Clips.Count == 2, "failed import preserves current edits");
66 vm.ZoomInCommand.Execute(null); Check(vm.Zoom > 1, "timeline zoom"); vm.FitTimelineCommand.Execute(null); Check(vm.Zoom == 1, "timeline fit");
67 vm.IsBusy = true; int count = vm.Clips.Count; vm.RemoveClipCommand.Execute(null); Check(vm.Clips.Count == count && !vm.CanEdit, "busy tasks reject edits"); vm.IsBusy = false;
68 vm.FramesPerSecond = 30000d / 1001; vm.SeekSequence(0); vm.NextFrameCommand.Execute(null);
69 Check(Math.Abs(vm.SequencePosition - 1001d / 30000) < .000001 && vm.SequenceTimecode == "00:00:00:01", "fractional frame rate stepping and non-drop timecode");
70 vm.FramesPerSecond = 25; vm.SeekSequence(0); vm.FollowPlayback(5);
71 Check(vm.SelectedClip == vm.Clips[1] && Math.Abs(vm.CurrentPositionSeconds) < .001, "playback advances from trimmed segment to reordered successor");
72 await ExportTests(media, video, silent);
73 TrimTests(video);
74 await AccelerationTests(media, video);
75 Check(sourceHash.SequenceEqual(SHA256.HashData(File.ReadAllBytes(video))), "source remains bit-identical");
76 var still = await PreviewAssets.FrameAsync(ffmpeg, video, 2.04, default); Check(still is not null && still.Width > 0, "FFmpeg paused-frame extraction");
77 await ViewTests(video);
78 if (!args.Contains("--skip-host")) await Host(args);
79 Console.WriteLine($"ALL {Passes.Count} CHECKS PASSED");
80 }
81 private static async Task Ffmpeg(string[] args)
82 { var result = await new ProcessRunner().RunAsync(ffmpeg, new[] { "-hide_banner", "-loglevel", "error", "-nostdin", "-y" }.Concat(args), Root, null, null, default); if (!result.Success) throw new InvalidOperationException(result.CombinedOutput); }
83 private static async Task ExportTests(MediaProcessingService service, string source, string silent)
84 {
85 var clips = new[] { new TimelineClip("mute", 1, 2) { AudioEnabled = false }, new TimelineClip("gain", 3, 5) { AudioVolume = 50 } };
86 string target = Path.Combine(Root, "edited.mp4");
87 await service.ExportTimelineAsync(ffmpeg, source, clips, target, null, default);
88 var info = await service.ProbeAsync(ffprobe, target, default);
89 Check(info.HasAudio && Math.Abs(info.DurationSeconds - 3) < .09, "real MP4 export duration and audio/video streams");
90 await Ffmpeg(["-i", target, "-f", "null", "-"]); Check(true, "export fully decodes without media errors");
91 Check(await FrameError(source, 1.2, target, .2) < 9 && await FrameError(source, 3.2, target, 1.2) < 9, "exported frames follow trimmed/reordered source mapping");
92 double mute = await Rms(target, .15, .6), gain = await Rms(target, 1.15, .6), original = await Rms(source, 3.15, .6);
93 Check(mute < .00005 && gain > .001, "export mutes only the selected audio segment");
94 Check(gain / original is > .42 and < .58, "exported gain is approximately 50 percent");
95 string silentOut = Path.Combine(Root, "silent-edited.mp4");
96 await service.ExportTimelineAsync(ffmpeg, silent, [new TimelineClip("silent", 0, 1)], silentOut, null, default);
97 Check((await service.ProbeAsync(ffprobe, silentOut, default)).Width == 640 && await Rms(silentOut, .1, .5) < .00005, "silent source exports with valid silent audio track");
98 string one = Path.Combine(Root, "one-frame.mp4"); await service.ExportTimelineAsync(ffmpeg, source, [new TimelineClip("one", 2, 2.04)], one, null, default);
99 Check((await service.ProbeAsync(ffprobe, one, default)).DurationSeconds < .13, "single-frame clip exports");
100 await Reject(() => service.ExportTimelineAsync(ffmpeg, source, clips, source, null, default), "source overwrite rejected");
101 await Reject(() => service.ExportTimelineAsync(ffmpeg, source, [new TimelineClip("bad", 5, 90)], target, null, default), "out-of-source bounds rejected");
102 byte[] before = File.ReadAllBytes(target); using var cancel = new CancellationTokenSource();
103 var cancelProgress = new CancelProgress(cancel);
104 await Reject(() => service.ExportTimelineAsync(ffmpeg, source, clips, target, cancelProgress, cancel.Token), "active export cancellation");
105 Check(cancelProgress.ObservedEncoding, "cancellation occurs during actual FFmpeg encoding progress");
106 Check(before.SequenceEqual(File.ReadAllBytes(target)) && !Directory.EnumerateDirectories(Root, ".xfe-video-*").Any(), "cancel preserves existing output and cleans staging");
107 }
108 private static async Task<double> FrameError(string first, double a, string second, double b)
109 {
110 async Task<byte[]> Pixels(string path, double position)
111 {
112 var image = (BitmapSource)(await PreviewAssets.FrameAsync(ffmpeg, path, position, default))!;
113 var bitmap = new FormatConvertedBitmap(image, PixelFormats.Rgb24, null, 0); byte[] bytes = new byte[bitmap.PixelWidth * bitmap.PixelHeight * 3]; bitmap.CopyPixels(bytes, bitmap.PixelWidth * 3, 0); return bytes;
114 }
115 var left = await Pixels(first, a); var right = await Pixels(second, b);
116 Check(left.Length == right.Length, "exported frame dimensions match source");
117 return left.Select((value, i) => Math.Abs(value - right[i])).Average();
118 }
119 private static async Task<double> Rms(string path, double start, double duration)
120 {
121 string output = Path.Combine(Root, Guid.NewGuid() + ".f32");
122 await Ffmpeg(["-ss", start.ToString(System.Globalization.CultureInfo.InvariantCulture), "-i", path, "-t", duration.ToString(System.Globalization.CultureInfo.InvariantCulture), "-vn", "-ac", "1", "-f", "f32le", output]);
123 byte[] bytes = File.ReadAllBytes(output); double sum = 0; for (int i = 0; i + 4 <= bytes.Length; i += 4) { double v = BitConverter.ToSingle(bytes, i); sum += v * v; } return Math.Sqrt(sum / (bytes.Length / 4));
124 }
125 private static async Task ViewTests(string video)
126 {
127 var trace = new BindingTrace(); PresentationTraceSources.DataBindingSource.Listeners.Add(trace); PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
128 var page = new MainPage(); var vm = (MainPageViewModel)page.DataContext; vm.FfmpegPath = ffmpeg; vm.FfprobePath = ffprobe;
129 var window = new Window { Content = page, Width = 1360, Height = 820, Left = -30000, Top = -30000, ShowInTaskbar = false, WindowStyle = WindowStyle.None }; window.Show();
130 await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); await vm.LoadSourceAsync(video);
131 vm.SeekSequence(2); vm.SplitClipCommand.Execute(null); vm.SeekSequence(4); vm.SplitClipCommand.Execute(null); vm.SeekSequence(2.6);
132 Check(vm.UndoCommand.CanExecute(null), "undo command is enabled in the rendered editor");
133 await Task.Delay(500); await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); Save(page, "editor.png");
134 var timeline = (TimelineSurface)page.FindName("Timeline"); Check(Math.Abs(timeline.TimeAt(timeline.XAt(2)) - 2) < .001, "timeline hit test and drawing share exact scale");
135 await GestureTests(vm, timeline, page);
136 Check(((Image)page.FindName("PausedFrame")).Source is not null, "paused frame is visible in actual WPF view");
137 Check(((TextBlock)page.FindName("PreviewHint")).Visibility == Visibility.Collapsed, "empty-state hint is hidden after splitting clips");
138 window.Width = 1040; window.Height = 740; await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); Save(page, "editor-minimum.png");
139 vm.ActivePage = 1; vm.Subtitles.Add(new SubtitleCue { Index = 1, StartSeconds = 0, EndSeconds = 1, Text = "字幕编辑测试" }); await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); Save(page, "subtitles.png");
140 vm.ActivePage = 2; await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); Save(page, "environment.png");
141 Check(trace.Errors.Count == 0, "WPF bindings including read-only timecodes: " + string.Join(" | ", trace.Errors));
142 vm.IsBusy = true; window.Close(); Check(window.IsVisible, "window close waits for active task cleanup"); vm.IsBusy = false; window.Close(); PresentationTraceSources.DataBindingSource.Listeners.Remove(trace);
143 }
144 private static void Save(FrameworkElement page, string name) { page.UpdateLayout(); var bitmap = new RenderTargetBitmap((int)page.ActualWidth, (int)page.ActualHeight, 96, 96, PixelFormats.Pbgra32); bitmap.Render(page); var encoder = new PngBitmapEncoder(); encoder.Frames.Add(BitmapFrame.Create(bitmap)); using var stream = File.Create(Path.Combine(Root, name)); encoder.Save(stream); }
145 private static async Task Host(string[] args)
146 {
147 var type = typeof(XFEToolBox.Client.Models.LauncherItem).Assembly.GetType("XFEToolBox.Client.Utilities.ToolProjectRunService", true)!;
148 var manifest = JsonSerializer.Deserialize<ToolPackageManifest>(File.ReadAllText(Path.Combine(Workspace, "manifest.json")), new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
149 async Task Build(string path) { var task = (Task)type.GetMethod("BuildAsync", BindingFlags.Public | BindingFlags.Static)!.Invoke(null, [path, manifest, CancellationToken.None, null])!; await task.WaitAsync(TimeSpan.FromMinutes(4)); var result = task.GetType().GetProperty("Result")!.GetValue(task)!; Check((bool)result.GetType().GetProperty("Success")!.GetValue(result)!, "production toolbox compilation: " + result.GetType().GetProperty("Message")!.GetValue(result)); }
150 await Build(Workspace);
151 if (args.Contains("--check-package")) { string package = Path.Combine(Path.GetDirectoryName(Workspace)!, "Packages", $"{manifest.Id}-{manifest.Version}.xfetool"), extracted = Path.Combine(Root, "package"); await (Task<ToolPackageManifest>)type.GetMethod("ExtractAndValidatePackageAsync", BindingFlags.NonPublic | BindingFlags.Static)!.Invoke(null, [package, extracted, manifest.Id, manifest.Version, CancellationToken.None])!; Check(Directory.GetFiles(extracted, "*", SearchOption.AllDirectories).All(p => File.ReadAllBytes(p).SequenceEqual(File.ReadAllBytes(Path.Combine(Workspace, Path.GetRelativePath(extracted, p))))), "package bytes match workspace"); await Build(extracted); }
152 }
153 private sealed class CancelProgress(CancellationTokenSource token) : IProgress<ExportProgress> { public bool ObservedEncoding { get; private set; } public void Report(ExportProgress value) { if (value.Value > 0 && value.Message.Contains("正在渲染:")) { ObservedEncoding = true; token.Cancel(); } } }
154 private sealed class BindingTrace : TraceListener { public List<string> Errors { get; } = []; public override void Write(string? text) { if (!string.IsNullOrEmpty(text)) Errors.Add(text); } public override void WriteLine(string? text) => Write(text); }
155 }
Added tests/VideoStudio.Validation/README.md +56 -0
@@ -0,0 +1,56 @@
1 # VideoStudio editor regression validation
2
3 ## Verified release
4
5 2026-09-24: **96 checks passed**, exit code 0, including source compilation, production package validation and extracted-package compilation for VideoStudio **1.4.0**.
6
7 - Artifacts: `bin/Debug/net10.0-windows10.0.17763.0/test-artifacts/20260924-232559/`.
8 - Package: `xfestudio.video-studio-1.4.0.xfetool`, 89,719 bytes.
9 - SHA-256: `5161C2DF4D1AFF9AB43758867B70B261873278DD7A4790A7F7C4732F3A90F178`.
10 - Previous 1.3.0 package is retained; `LegacyExporter.cs` freezes that release's implementation for comparisons, not production use.
11
12 Uses actual workspace sources from `%LOCALAPPDATA%\XFEToolBox\CrossVersion\EditorWorkspaces\VideoStudio`, WPF toolbox resources, FFmpeg, and FFprobe. User videos and settings are not modified. Synthetic fixtures, exports, PCM samples and rendered screenshots are kept in a timestamped `bin/Debug/net10.0-windows10.0.17763.0/test-artifacts/` directory.
13
14 ## Run
15
16 Requires Windows, .NET 10, and the existing video tool's `ToolData/xfestudio.video-studio/settings.json` containing working FFmpeg / FFprobe paths. This full validation run explicitly asserts NVIDIA hardware use and therefore requires a working NVENC GPU. Production automatic mode also probes QSV/AMF and works CPU-only; those hardware vendors were not independently validated on other machines.
17
18 ```powershell
19 dotnet run --project tests/VideoStudio.Validation/VideoStudio.Validation.csproj -- --skip-host
20 dotnet run --project tests/VideoStudio.Validation/VideoStudio.Validation.csproj -- --check-package
21 dotnet run --project tests/VideoStudio.Validation/VideoStudio.Validation.csproj -- --benchmark-only
22 ```
23
24 Without `--skip-host`, the tool is compiled through production `ToolProjectRunService.BuildAsync`. `--check-package` additionally uses the production package validator, compares package source bytes and compiles the extracted project.
25
26 ## Coverage
27
28 - Actual probe/import, eight source thumbnails, waveform, dispatcher responsiveness, completed progress.
29 - Split, boundary rejection, exact fixed-frame-rate stepping, fractional frame-rate/non-drop timecode, undo/redo, trimmed/reordered sequence-to-source mapping and playback hand-off.
30 - Ripple trim/delete, per-clip and track audio mute, volume, invalid trim, failed import preservation, zoom/fit, busy-state guards.
31 - Both edge handles on both tracks, start/end extension limits, one-frame minimum, frame snapping, frozen drag scale while the timeline ripples, zoomed tail drag, cancellation and redo preservation, forty updates creating only one undo entry.
32 - Actual NVENC encoding, optimized CPU path, one-pass multi-clip output, non-mutating contiguous-clip coalescing, and smart-copy compressed audio/video SHA-256 identity.
33 - Forced FFmpeg GPU failures before encoding and after a completed batch; complete CPU restart avoids mixed H.264 headers. Unrecoverable failure retains existing destination bytes.
34 - Bounded multi-batch export, exact frame counts across batch joins, 29.97fps non-keyframe cuts, single-frame output, muted/gain-adjusted audio.
35 - Actual H.264/AAC MP4 output and full decode, expected duration, single-frame and silent-source output.
36 - Extracted source/output pixel comparison to verify actual cut intervals; decoded audio RMS to verify muted versus 50% gain segments.
37 - Source overwrite/bounds rejection, cancellation triggered by actual encoding progress, preservation of an existing destination, temporary-directory cleanup, unchanged source hash.
38 - Real WPF page/viewmodel, visible still-frame image, common proportional scale for timeline drawing and hit-testing, no error-level binding messages, empty state after split, safe close during active tasks, full/minimum-size/editor/subtitle/environment renders.
39
40 The generated media is synthetic. Drag tests invoke the same gesture methods called by the WPF pointer handlers on an instantiated, laid-out page; they do not claim an OS-level manual mouse/file-picker session. Arbitrary MediaElement codecs or long continuous hardware playback were not exhaustively tested. FFmpeg frame extraction/export is exercised end-to-end. Whisper recognition/download code is preserved, not re-downloaded/re-run for this change. No network download or source-media deletion is performed by this suite.
41
42 `results.json` records each passed assertion and success state. Native decoder `libpng` interlace warnings may appear while WPF renders; assertions also check that images load and binding errors are absent.
43
44 ## Reproducible performance comparison
45
46 `--benchmark-only` creates one 1920x1080 / 30fps / 24-second H.264 source with a sine audio track, then exports the same six reordered/noncontiguous four-second clips (including one 60%-gain clip and one muted clip). The timed export includes probe, staging, encoder selection, encoding, muxing and cleanup, not fixture creation or verification. All exports are fully decoded and duration/dimensions/muted audio are checked. The two passes reverse ordering to reduce cache/order effects. CPU and GPU comparisons disable smart copy.
47
48 Measured on Ryzen 9 9950X3D, RTX 5090 (driver 32.0.16.1692), FFmpeg 9.0.1. Raw output: `bin/Debug/net10.0-windows10.0.17763.0/test-artifacts/20260924-232117/benchmark.json`.
49
50 | Path | Round 1 | Round 2 | Mean | Speedup | Output bytes |
51 | --- | ---: | ---: | ---: | ---: | ---: |
52 | Frozen 1.3.0, x264 medium / 4 threads, per-clip intermediates | 8.3703 s | 7.8796 s | 8.1249 s | 1.00x | 22,414,326 |
53 | 1.4.0 optimized CPU, x264 fast / CRF 20 | 4.2046 s | 4.1795 s | 4.1920 s | 1.94x | 23,952,379 |
54 | 1.4.0 automatic NVENC, p4 / CQ 20 | 3.3939 s | 2.9569 s | 3.1754 s | 2.56x | 40,288,951 |
55
56 Same resolution/frame rate and edit semantics, **not** identical encoding/compression quality or output size. CQ and CRF values are not equivalent across encoders; GPU output is larger in this fixture. Measurements are local synthetic results, not a universal speed guarantee. The benchmark checks are separate from the 96-check release suite.
Added tests/VideoStudio.Validation/VideoStudio.Validation.csproj +4 -0
@@ -0,0 +1,4 @@
1 <Project Sdk="Microsoft.NET.Sdk">
2 <PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net10.0-windows10.0.17763.0</TargetFramework><UseWPF>true</UseWPF><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings><EnableDefaultCompileItems>false</EnableDefaultCompileItems><EnableDefaultPageItems>false</EnableDefaultPageItems><StartupObject>VideoStudio.Validation.Program</StartupObject><ToolWorkspace>$(LOCALAPPDATA)\XFEToolBox\CrossVersion\EditorWorkspaces\VideoStudio</ToolWorkspace></PropertyGroup>
3 <ItemGroup><Compile Include="*.cs"/><Compile Include="$(ToolWorkspace)\Code\**\*.cs" Link="Tool\%(RecursiveDir)%(Filename)%(Extension)"/><Page Include="$(ToolWorkspace)\Code\**\*.xaml" Link="Tool\%(RecursiveDir)%(Filename)%(Extension)"/><ProjectReference Include="..\..\XFEToolBox\XFEToolBox.Client.csproj"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.2"/></ItemGroup>
4 </Project>