using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text.Json;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using XFEToolBox.Tools.VideoStudio;
namespace VideoStudio.Validation;
internal static partial class Program
{
private sealed record LargeMetric(string Stage, double ElapsedMs, int UiTicks, double MaximumUiGapMs, double PeakPrivateMiB);
private static async Task LargeMediaTests()
{
const long target = 3L * 1024 * 1024 * 1024;
Check(new DriveInfo(Path.GetPathRoot(Root)!).AvailableFreeSpace > 12L * 1024 * 1024 * 1024, "enough free space for two owned 3 GiB media fixtures");
string seed = Path.Combine(Root, "large-seed.mp4"), first = Path.Combine(Root, "大素材 A.mp4"), second = Path.Combine(Root, "大素材 B.mp4");
Console.WriteLine("Generating actual indexed H.264/AAC media; no sparse/padded dummy files.");
await Ffmpeg(["-f","lavfi","-i","testsrc2=s=1280x720:r=30:d=6","-f","lavfi","-i","sine=frequency=440:duration=6","-c:v","libx264","-preset","ultrafast","-pix_fmt","yuv420p","-b:v","64M","-minrate","64M","-maxrate","64M","-bufsize","128M","-x264-params","nal-hrd=cbr:force-cfr=1:keyint=30","-c:a","aac","-shortest","-movflags","+faststart",seed]);
int repeats = (int)Math.Ceiling((double)target / new FileInfo(seed).Length) + 1;
await Ffmpeg(["-stream_loop",(repeats - 1).ToString(),"-i",seed,"-map","0","-c","copy","-movflags","+faststart",first]);
await Task.Run(() => File.Copy(first, second));
long sizeA = new FileInfo(first).Length, sizeB = new FileInfo(second).Length;
Check(sizeA >= target && sizeB >= target, $"two real media files each exceed 3 GiB ({sizeA:N0} / {sizeB:N0} bytes)");
var page = new MainPage(); var vm = (MainPageViewModel)page.DataContext; vm.FfmpegPath = ffmpeg; vm.FfprobePath = ffprobe;
page.Playback.IsMuted = true; var window = TestWindow(page); window.Show();
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); await Task.Delay(300);
var metrics = new List<LargeMetric>(); var process = Process.GetCurrentProcess(); process.Refresh(); double baseline = process.PrivateMemorySize64 / 1048576d;
async Task Measure(string stage, Func<Task> action)
{
int ticks = 0; double last = 0, gap = 0, peak = baseline; var watch = Stopwatch.StartNew();
var heartbeat = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(20) };
heartbeat.Tick += (_, _) => { double now = watch.Elapsed.TotalMilliseconds; gap = Math.Max(gap, now - last); last = now; ticks++; process.Refresh(); peak = Math.Max(peak, process.PrivateMemorySize64 / 1048576d); };
heartbeat.Start();
try { await action(); }
finally { heartbeat.Stop(); gap = Math.Max(gap, watch.Elapsed.TotalMilliseconds - last); metrics.Add(new(stage, Math.Round(watch.Elapsed.TotalMilliseconds,2),ticks,Math.Round(gap,2),Math.Round(peak,2))); }
Console.WriteLine(JsonSerializer.Serialize(metrics[^1], Json));
}
try
{
await Measure("Import two 3 GiB videos", async () => { await vm.ImportAssetsAsync([first,second]); await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); });
Check(vm.Assets.Count == 2 && vm.Clips.Count == 2 && vm.Clips.All(c => c.AssetId == vm.Assets[0].Id), "large import adds only the first video's V1/A1 clips");
await vm.WaitForAssetPreviewsAsync();
Check(vm.Assets.All(a => a.Waveform is null && a.Frames.Count <= 1), "large media never scans complete audio or creates a full thumbnail strip");
vm.InsertAsset(vm.Assets[1], vm.TimelineDuration, vm.Tracks.First(t => t.Kind == MediaKind.Video));
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
Check(vm.Clips.Count == 4, "second large video explicitly inserts independent V1/A1 clips");
vm.FfmpegPath = Path.Combine(Root, "ffmpeg-intentionally-unavailable.exe"); vm.FfprobePath = Path.Combine(Root,"ffprobe-intentionally-unavailable.exe");
var surface = (SourcePreviewSurface)page.FindName("SourcePreview");
byte[] FrameHash()
{
var image = new RenderTargetBitmap((int)surface.ActualWidth,(int)surface.ActualHeight,96,96,PixelFormats.Pbgra32); image.Render(surface);
byte[] pixels = new byte[image.PixelWidth * image.PixelHeight * 4]; image.CopyPixels(pixels,image.PixelWidth * 4,0); return SHA256.HashData(pixels);
}
await Measure("Direct play and random seek (FFmpeg unavailable)", async () =>
{
double start = vm.Assets[0].Duration * .6; vm.SeekSequence(start);
var click = Stopwatch.StartNew(); vm.TogglePlaybackCommand.Execute(null); click.Stop();
Check(click.ElapsedMilliseconds < 500 && !vm.IsBusy, $"large-source Play returns in {click.Elapsed.TotalMilliseconds:F1} ms without a render task");
await WaitUntil(() => page.Playback.ReadySourceCount > 0 && vm.SequencePosition > start + .8, "large original video starts and advances without FFmpeg");
byte[] before = FrameHash(); await Task.Delay(550); byte[] after = FrameHash();
Check(!before.SequenceEqual(after), "large source decodes changing video pixels, not a frozen poster or clock-only playback");
var layer = page.Playback.ActiveLayers.First(l => l.Clip.Kind == MediaKind.Video);
Check(Math.Abs((page.Playback.SourcePosition(layer) ?? -1) - layer.SourceTime(page.Playback.Position)) < .6, "native large-video position follows random seek source offset");
Check(page.Playback.OpenSources.All(u => u.LocalPath == first || u.LocalPath == second), "large playback opens only original media, no composite/proxy paths");
page.Playback.Pause();
});
await Measure("Cross large-file boundary", async () =>
{
double boundary = vm.Clips.Where(c => c.AssetId == vm.Assets[1].Id).Min(c => c.TimelineStart);
vm.SeekSequence(boundary - .45); vm.TogglePlaybackCommand.Execute(null);
await WaitUntil(() => vm.SequencePosition > boundary + .65 && page.Playback.ActiveLayers.Any(l => l.Asset.FilePath == second) && page.Playback.ReadySourceCount > 0, "large source boundary switches to second original decoder", 12);
Check(page.Playback.DecoderCount == 1 && page.Playback.OpenSources.Single().LocalPath == second, "expired 3 GiB source decoder is released, linked video/audio shares new decoder");
page.Playback.Pause(); Save(page,"large-original-playback.png");
});
await Measure("Two large sources playing concurrently", async () =>
{
vm.AddVideoTrackCommand.Execute(null); vm.InsertAsset(vm.Assets[1], 0, vm.SelectedTrack);
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
vm.SeekSequence(2); vm.TogglePlaybackCommand.Execute(null);
await WaitUntil(() => page.Playback.ReadySourceCount == 2 && page.Playback.Position > 3, "both 3 GiB sources decode simultaneously on independent video/audio tracks");
Check(page.Playback.OpenSources.Select(u => u.LocalPath).Distinct().Count() == 2 && page.Playback.DecoderCount == 2, "concurrent large preview keeps exactly two source decoders, no rendered movie");
page.Playback.Pause();
});
Check(metrics.All(m => m.UiTicks > 0 && m.MaximumUiGapMs < 1000), "dispatcher stays responsive during large import/play/seek/boundary/concurrent playback (no one-second stalls)");
Check(metrics.Max(m => m.PeakPrivateMiB) - baseline < 1024, "large-media private-memory growth stays below 1 GiB instead of loading two full files");
Check(new FileInfo(first).Length == sizeA && new FileInfo(second).Length == sizeB, "large original files remain unchanged in size");
}
finally
{
vm.HasUnsavedChanges = false; window.Close(); page.Playback.Dispose(); await Task.Delay(300);
await File.WriteAllTextAsync(Path.Combine(Root,"large-metrics.json"), JsonSerializer.Serialize(new { sizeA,sizeB,baselinePrivateMiB=baseline,metrics },Json));
// Only delete exact synthetic paths created by this test, beneath this run's private artifact directory.
foreach (string path in new[] { first,second,seed })
{
if (!Path.GetFullPath(path).StartsWith(Path.GetFullPath(Root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Fixture cleanup escaped private artifact directory");
for (int attempt = 0; ; attempt++) { try { File.Delete(path); break; } catch (IOException) when (attempt < 10) { await Task.Delay(200); } }
}
Console.WriteLine("Removed only this run's large synthetic media; metrics and screenshot retained.");
}
}
}
using System.Diagnostics;
using System.IO;
using System.Security.Cryptography;
using System.Text.Json;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Threading;
using XFEToolBox.Tools.VideoStudio;
namespace VideoStudio.Validation;
internal static partial class Program
{
private sealed record LargeMetric(string Stage, double ElapsedMs, int UiTicks, double MaximumUiGapMs, double PeakPrivateMiB);
private static async Task LargeMediaTests()
{
const long target = 3L * 1024 * 1024 * 1024;
Check(new DriveInfo(Path.GetPathRoot(Root)!).AvailableFreeSpace > 12L * 1024 * 1024 * 1024, "enough free space for two owned 3 GiB media fixtures");
string seed = Path.Combine(Root, "large-seed.mp4"), first = Path.Combine(Root, "大素材 A.mp4"), second = Path.Combine(Root, "大素材 B.mp4");
Console.WriteLine("Generating actual indexed H.264/AAC media; no sparse/padded dummy files.");
await Ffmpeg(["-f","lavfi","-i","testsrc2=s=1280x720:r=30:d=6","-f","lavfi","-i","sine=frequency=440:duration=6","-c:v","libx264","-preset","ultrafast","-pix_fmt","yuv420p","-b:v","64M","-minrate","64M","-maxrate","64M","-bufsize","128M","-x264-params","nal-hrd=cbr:force-cfr=1:keyint=30","-c:a","aac","-shortest","-movflags","+faststart",seed]);
int repeats = (int)Math.Ceiling((double)target / new FileInfo(seed).Length) + 1;
await Ffmpeg(["-stream_loop",(repeats - 1).ToString(),"-i",seed,"-map","0","-c","copy","-movflags","+faststart",first]);
await Task.Run(() => File.Copy(first, second));
long sizeA = new FileInfo(first).Length, sizeB = new FileInfo(second).Length;
Check(sizeA >= target && sizeB >= target, $"two real media files each exceed 3 GiB ({sizeA:N0} / {sizeB:N0} bytes)");
var page = new MainPage(); var vm = (MainPageViewModel)page.DataContext; vm.FfmpegPath = ffmpeg; vm.FfprobePath = ffprobe;
page.Playback.IsMuted = true; var window = TestWindow(page); window.Show();
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); await Task.Delay(300);
var metrics = new List<LargeMetric>(); var process = Process.GetCurrentProcess(); process.Refresh(); double baseline = process.PrivateMemorySize64 / 1048576d;
async Task Measure(string stage, Func<Task> action)
{
int ticks = 0; double last = 0, gap = 0, peak = baseline; var watch = Stopwatch.StartNew();
var heartbeat = new DispatcherTimer(DispatcherPriority.Background) { Interval = TimeSpan.FromMilliseconds(20) };
heartbeat.Tick += (_, _) => { double now = watch.Elapsed.TotalMilliseconds; gap = Math.Max(gap, now - last); last = now; ticks++; process.Refresh(); peak = Math.Max(peak, process.PrivateMemorySize64 / 1048576d); };
heartbeat.Start();
try { await action(); }
finally { heartbeat.Stop(); gap = Math.Max(gap, watch.Elapsed.TotalMilliseconds - last); metrics.Add(new(stage, Math.Round(watch.Elapsed.TotalMilliseconds,2),ticks,Math.Round(gap,2),Math.Round(peak,2))); }
Console.WriteLine(JsonSerializer.Serialize(metrics[^1], Json));
}
try
{
await Measure("Import two 3 GiB videos", async () => { await vm.ImportAssetsAsync([first,second]); await Dispatcher.Yield(DispatcherPriority.ApplicationIdle); });
Check(vm.Assets.Count == 2 && vm.Clips.Count == 2 && vm.Clips.All(c => c.AssetId == vm.Assets[0].Id), "large import adds only the first video's V1/A1 clips");
await vm.WaitForAssetPreviewsAsync();
Check(vm.Assets.All(a => a.Waveform is null && a.Frames.Count <= 1), "large media never scans complete audio or creates a full thumbnail strip");
vm.InsertAsset(vm.Assets[1], vm.TimelineDuration, vm.Tracks.First(t => t.Kind == MediaKind.Video));
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
Check(vm.Clips.Count == 4, "second large video explicitly inserts independent V1/A1 clips");
vm.FfmpegPath = Path.Combine(Root, "ffmpeg-intentionally-unavailable.exe"); vm.FfprobePath = Path.Combine(Root,"ffprobe-intentionally-unavailable.exe");
var surface = (SourcePreviewSurface)page.FindName("SourcePreview");
byte[] FrameHash()
{
var image = new RenderTargetBitmap((int)surface.ActualWidth,(int)surface.ActualHeight,96,96,PixelFormats.Pbgra32); image.Render(surface);
byte[] pixels = new byte[image.PixelWidth * image.PixelHeight * 4]; image.CopyPixels(pixels,image.PixelWidth * 4,0); return SHA256.HashData(pixels);
}
await Measure("Direct play and random seek (FFmpeg unavailable)", async () =>
{
double start = vm.Assets[0].Duration * .6; vm.SeekSequence(start);
var click = Stopwatch.StartNew(); vm.TogglePlaybackCommand.Execute(null); click.Stop();
Check(click.ElapsedMilliseconds < 500 && !vm.IsBusy, $"large-source Play returns in {click.Elapsed.TotalMilliseconds:F1} ms without a render task");
await WaitUntil(() => page.Playback.ReadySourceCount > 0 && vm.SequencePosition > start + .8, "large original video starts and advances without FFmpeg");
byte[] before = FrameHash(); await Task.Delay(550); byte[] after = FrameHash();
Check(!before.SequenceEqual(after), "large source decodes changing video pixels, not a frozen poster or clock-only playback");
var layer = page.Playback.ActiveLayers.First(l => l.Clip.Kind == MediaKind.Video);
Check(Math.Abs((page.Playback.SourcePosition(layer) ?? -1) - layer.SourceTime(page.Playback.Position)) < .6, "native large-video position follows random seek source offset");
Check(page.Playback.OpenSources.All(u => u.LocalPath == first || u.LocalPath == second), "large playback opens only original media, no composite/proxy paths");
page.Playback.Pause();
});
await Measure("Cross large-file boundary", async () =>
{
double boundary = vm.Clips.Where(c => c.AssetId == vm.Assets[1].Id).Min(c => c.TimelineStart);
vm.SeekSequence(boundary - .45); vm.TogglePlaybackCommand.Execute(null);
await WaitUntil(() => vm.SequencePosition > boundary + .65 && page.Playback.ActiveLayers.Any(l => l.Asset.FilePath == second) && page.Playback.ReadySourceCount > 0, "large source boundary switches to second original decoder", 12);
Check(page.Playback.DecoderCount == 1 && page.Playback.OpenSources.Single().LocalPath == second, "expired 3 GiB source decoder is released, linked video/audio shares new decoder");
page.Playback.Pause(); Save(page,"large-original-playback.png");
});
await Measure("Two large sources playing concurrently", async () =>
{
vm.AddVideoTrackCommand.Execute(null); vm.InsertAsset(vm.Assets[1], 0, vm.SelectedTrack);
await Dispatcher.Yield(DispatcherPriority.ApplicationIdle);
vm.SeekSequence(2); vm.TogglePlaybackCommand.Execute(null);
await WaitUntil(() => page.Playback.ReadySourceCount == 2 && page.Playback.Position > 3, "both 3 GiB sources decode simultaneously on independent video/audio tracks");
Check(page.Playback.OpenSources.Select(u => u.LocalPath).Distinct().Count() == 2 && page.Playback.DecoderCount == 2, "concurrent large preview keeps exactly two source decoders, no rendered movie");
page.Playback.Pause();
});
Check(metrics.All(m => m.UiTicks > 0 && m.MaximumUiGapMs < 1000), "dispatcher stays responsive during large import/play/seek/boundary/concurrent playback (no one-second stalls)");
Check(metrics.Max(m => m.PeakPrivateMiB) - baseline < 1024, "large-media private-memory growth stays below 1 GiB instead of loading two full files");
Check(new FileInfo(first).Length == sizeA && new FileInfo(second).Length == sizeB, "large original files remain unchanged in size");
}
finally
{
vm.HasUnsavedChanges = false; window.Close(); page.Playback.Dispose(); await Task.Delay(300);
await File.WriteAllTextAsync(Path.Combine(Root,"large-metrics.json"), JsonSerializer.Serialize(new { sizeA,sizeB,baselinePrivateMiB=baseline,metrics },Json));
// Only delete exact synthetic paths created by this test, beneath this run's private artifact directory.
foreach (string path in new[] { first,second,seed })
{
if (!Path.GetFullPath(path).StartsWith(Path.GetFullPath(Root) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException("Fixture cleanup escaped private artifact directory");
for (int attempt = 0; ; attempt++) { try { File.Delete(path); break; } catch (IOException) when (attempt < 10) { await Task.Delay(200); } }
}
Console.WriteLine("Removed only this run's large synthetic media; metrics and screenshot retained.");
}
}
}