生成ウィンドウの隙間を無くしチャンクの網羅を位置で示す

このコミットが含まれているのは:
routersys committed 2026-09-13 17:52:32 +09:00
1 親 b7a293ce31
コミット 3203298bed
10ファイル変更
+291 -12

検索条件に一致するファイルはありません

+120
ファイルの表示
@@ -0,0 +1,120 @@
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using ProxyForge.Encoding;
using ProxyForge.Views;
namespace ProxyForge.Tests;
[Collection("Wpf")]
public sealed class ChunkCoverageBarTests
{
static (double Start, double Length)[] SegmentsOf(ProxyChunkCoverage coverage) => [.. ChunkCoverageBar.Segments(coverage)];
[Fact]
public void NothingIsDrawnWithoutChunks()
{
Assert.Empty(SegmentsOf(ProxyChunkCoverage.Empty));
Assert.Empty(SegmentsOf(new ProxyChunkCoverage(4, [], null, 0d)));
}
[Fact]
public void CoveredChunksAreDrawnAtTheirPositions()
{
var segments = SegmentsOf(new ProxyChunkCoverage(4, [3, 1], null, 0d));
Assert.Equal([(0.25d, 0.25d), (0.75d, 0.25d)], segments);
}
[Fact]
public void AdjacentChunksAreMergedIntoOneSegment()
{
var segments = SegmentsOf(new ProxyChunkCoverage(5, [0, 1, 2, 4], null, 0d));
Assert.Equal([(0d, 0.6d), (0.8d, 0.2d)], segments);
}
[Fact]
public void ChunksOutsideTheLayoutAndDuplicatesAreIgnored()
{
var segments = SegmentsOf(new ProxyChunkCoverage(4, [7, -1, 2, 2], null, 0d));
Assert.Equal([(0.5d, 0.25d)], segments);
}
[Fact]
public void TheChunkBeingGeneratedIsDrawnPartially()
{
var segments = SegmentsOf(new ProxyChunkCoverage(4, [0], 2, 0.5d));
Assert.Equal([(0d, 0.25d), (0.5d, 0.125d)], segments);
}
[Fact]
public void TheCurrentChunkIsNotDrawnTwiceOrWhenNothingIsDone()
{
Assert.Equal([(0.5d, 0.25d)], SegmentsOf(new ProxyChunkCoverage(4, [2], 2, 0.5d)));
Assert.Empty(SegmentsOf(new ProxyChunkCoverage(4, [], 2, 0d)));
Assert.Empty(SegmentsOf(new ProxyChunkCoverage(4, [], 9, 0.5d)));
Assert.Equal([(0.5d, 0.25d)], SegmentsOf(new ProxyChunkCoverage(4, [], 2, 1.5d)));
}
[Fact]
public void RendersGreenWhereChunksExist()
{
var pixels = RunSta(() =>
{
var bar = new ChunkCoverageBar
{
Coverage = new ProxyChunkCoverage(4, [1], 2, 0.5d),
Fill = Brushes.Lime,
};
bar.Measure(new Size(100d, 10d));
bar.Arrange(new Rect(0d, 0d, 100d, 10d));
bar.UpdateLayout();
var bitmap = new RenderTargetBitmap(100, 10, 96d, 96d, PixelFormats.Pbgra32);
bitmap.Render(bar);
var buffer = new byte[100 * 10 * 4];
bitmap.CopyPixels(buffer, 100 * 4, 0);
return buffer;
});
Assert.Equal(0, AlphaAt(pixels, 10));
Assert.Equal(255, AlphaAt(pixels, 30));
Assert.Equal(255, GreenAt(pixels, 30));
Assert.Equal(0, RedAt(pixels, 30));
Assert.Equal(255, AlphaAt(pixels, 55));
Assert.Equal(0, AlphaAt(pixels, 70));
Assert.Equal(0, AlphaAt(pixels, 90));
}
static byte AlphaAt(byte[] pixels, int x) => pixels[5 * 100 * 4 + x * 4 + 3];
static byte GreenAt(byte[] pixels, int x) => pixels[5 * 100 * 4 + x * 4 + 1];
static byte RedAt(byte[] pixels, int x) => pixels[5 * 100 * 4 + x * 4 + 2];
static T RunSta<T>(Func<T> action)
{
var result = default(T)!;
Exception? error = null;
var thread = new Thread(() =>
{
try
{
result = action();
}
catch (Exception exception)
{
error = exception;
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
thread.Join();
if (error is not null)
throw new InvalidOperationException(error.Message, error);
return result;
}
}
+17
ファイルの表示
@@ -149,6 +149,7 @@ public sealed class ProxyGenerationQueueTests : IDisposable
var started = new TaskCompletionSource();
var release = new TaskCompletionSource();
var progressed = new List<double>();
var covered = new List<ProxyChunkCoverage>();
var queue = CreateQueue(async (_, _, output, progress, _) =>
{
started.TrySetResult();
@@ -161,10 +162,13 @@ public sealed class ProxyGenerationQueueTests : IDisposable
queue.TryEnqueue(source, 50);
await started.Task;
var item = TestUiThread.Read(() => Assert.Single(queue.Items));
Assert.Equal(new ProxyChunkCoverage(2, [], 0, 0d), item.Coverage, CoverageComparer.Instance);
item.PropertyChanged += (_, e) =>
{
if (e.PropertyName == nameof(ProxyGenerationItem.Progress))
progressed.Add(item.Progress);
if (e.PropertyName == nameof(ProxyGenerationItem.Coverage))
covered.Add(item.Coverage);
};
Assert.Equal(source.Path, item.SourcePath);
Assert.Equal("source.mp4", item.FileName);
@@ -180,9 +184,22 @@ public sealed class ProxyGenerationQueueTests : IDisposable
Assert.Equal(progressed.OrderBy(value => value), progressed);
Assert.Contains(0.25d, progressed);
Assert.Contains(0.5d, progressed);
Assert.Contains(new ProxyChunkCoverage(2, [], 0, 0.5d), covered, CoverageComparer.Instance);
Assert.Contains(new ProxyChunkCoverage(2, [0], 1, 0.5d), covered, CoverageComparer.Instance);
Assert.Equal(new ProxyChunkCoverage(2, [0, 1], null, 0d), item.Coverage, CoverageComparer.Instance);
await WaitUntilAsync(() => queue.Items.Count == 0);
}
sealed class CoverageComparer : IEqualityComparer<ProxyChunkCoverage>
{
public static CoverageComparer Instance { get; } = new();
public bool Equals(ProxyChunkCoverage? x, ProxyChunkCoverage? y)
=> x is not null && y is not null && x.ChunkCount == y.ChunkCount && x.Chunks.SequenceEqual(y.Chunks) && x.CurrentChunk == y.CurrentChunk && x.CurrentProgress == y.CurrentProgress;
public int GetHashCode(ProxyChunkCoverage coverage) => HashCode.Combine(coverage.ChunkCount, coverage.Chunks.Count, coverage.CurrentChunk, coverage.CurrentProgress);
}
[Fact]
public async Task ChunksStartAtTheFocusAndFinishTheRest()
{
+6
ファイルの表示
@@ -135,6 +135,12 @@ public sealed class GenerationItemViewModelTests
Assert.Equal(25d, viewModel.Percentage);
Assert.Contains(nameof(GenerationItemViewModel.Percentage), raised);
Assert.Same(ProxyChunkCoverage.Empty, viewModel.Coverage);
var coverage = new ProxyChunkCoverage(4, [1], 2, 0.5d);
item.Coverage = coverage;
Assert.Same(coverage, viewModel.Coverage);
Assert.Contains(nameof(GenerationItemViewModel.Coverage), raised);
item.Status = ProxyGenerationStatus.Generating;
Assert.False(viewModel.IsWaiting);
Assert.Equal(Texts.StatusGenerating, viewModel.StatusText);
+8
ファイルの表示
@@ -0,0 +1,8 @@
namespace ProxyForge.Encoding;
internal sealed record ProxyChunkCoverage(int ChunkCount, IReadOnlyList<int> Chunks, int? CurrentChunk, double CurrentProgress)
{
public static ProxyChunkCoverage Empty { get; } = new(0, [], null, 0d);
public bool Contains(int chunk) => Chunks.Contains(chunk);
}
+7
ファイルの表示
@@ -15,6 +15,7 @@ public enum ProxyGenerationStatus
internal sealed class ProxyGenerationItem(string sourcePath, int scale) : Bindable
{
double progress;
ProxyChunkCoverage coverage = ProxyChunkCoverage.Empty;
ProxyGenerationStatus status;
ProxyEncodeFailure? failure;
@@ -30,6 +31,12 @@ internal sealed class ProxyGenerationItem(string sourcePath, int scale) : Bindab
set => Set(ref progress, value);
}
public ProxyChunkCoverage Coverage
{
get => coverage;
set => Set(ref coverage, value);
}
public ProxyGenerationStatus Status
{
get => status;
+21 -5
ファイルの表示
@@ -22,9 +22,17 @@ internal sealed class ProxyGenerationQueue(
readonly record struct Key(SourceIdentity Source, int Scale);
sealed class ChunkProgress(ProxyGenerationItem item, int completedChunks, int chunkCount, Action<Action> onUi) : IProgress<double>
sealed class ChunkProgress(ProxyGenerationItem item, ProxyCacheEntry entry, int chunk, Action<Action> onUi) : IProgress<double>
{
public void Report(double value) => onUi(() => item.Progress = (completedChunks + Math.Clamp(value, 0d, 1d)) / chunkCount);
public void Report(double value)
{
var fraction = Math.Clamp(value, 0d, 1d);
onUi(() =>
{
item.Progress = (entry.Chunks.Count + fraction) / entry.ChunkCount;
item.Coverage = new ProxyChunkCoverage(entry.ChunkCount, entry.Chunks, chunk, fraction);
});
}
}
readonly Lock gate = new();
@@ -199,7 +207,7 @@ internal sealed class ProxyGenerationQueue(
var analysis = session.Analysis;
var entry = cache.Register(Describe(key, analysis, ProxyChunkPlan.LengthFor(analysis.FrameRate, current.ChunkSeconds)));
var chunkCount = entry.ChunkCount;
onUi(() => item.Progress = (double)entry.Chunks.Count / chunkCount);
Publish(item, entry, null);
while (ProxyChunkPlan.Next(entry.Chunks, chunkCount, entry.ChunkLength, focus.Get(key.Source)) is { } chunk)
{
@@ -211,7 +219,8 @@ internal sealed class ProxyGenerationQueue(
ProxyCacheEntry? updated;
try
{
await session.EncodeAsync(firstFrame, frameCount, temporaryPath, new ChunkProgress(item, entry.Chunks.Count, chunkCount, onUi), token).ConfigureAwait(false);
Publish(item, entry, chunk);
await session.EncodeAsync(firstFrame, frameCount, temporaryPath, new ChunkProgress(item, entry, chunk, onUi), token).ConfigureAwait(false);
if (SourceIdentity.Of(key.Source.Path) != key.Source)
throw new ProxyEncodeException(ProxyEncodeFailure.SourceChanged, "The source file changed while the proxy was being generated.");
@@ -227,11 +236,18 @@ internal sealed class ProxyGenerationQueue(
throw new OperationCanceledException();
entry = updated;
onUi(() => item.Progress = (double)entry.Chunks.Count / chunkCount);
Publish(item, entry, null);
ChunkCompleted?.Invoke(key.Source, key.Scale, entry);
}
}
void Publish(ProxyGenerationItem item, ProxyCacheEntry entry, int? chunk)
=> onUi(() =>
{
item.Progress = (double)entry.Chunks.Count / entry.ChunkCount;
item.Coverage = new ProxyChunkCoverage(entry.ChunkCount, entry.Chunks, chunk, 0d);
});
static ProxyCacheEntry Describe(Key key, ProxyAnalysis analysis, int chunkLength) => new()
{
SourcePath = key.Source.Path,
+5
ファイルの表示
@@ -21,6 +21,8 @@ internal sealed class GenerationItemViewModel : Bindable
public double Percentage => Item.Progress * 100d;
public ProxyChunkCoverage Coverage => Item.Coverage;
public bool IsWaiting => Item.Status == ProxyGenerationStatus.Waiting;
public string StatusText => Item.Status switch
@@ -52,6 +54,9 @@ internal sealed class GenerationItemViewModel : Bindable
case nameof(ProxyGenerationItem.Progress):
OnPropertyChanged(nameof(Percentage));
break;
case nameof(ProxyGenerationItem.Coverage):
OnPropertyChanged(nameof(Coverage));
break;
case nameof(ProxyGenerationItem.Status):
case nameof(ProxyGenerationItem.Failure):
OnPropertyChanged(nameof(StatusText));
+62
ファイルの表示
@@ -0,0 +1,62 @@
using System.Windows;
using System.Windows.Media;
using ProxyForge.Encoding;
namespace ProxyForge.Views;
internal sealed class ChunkCoverageBar : FrameworkElement
{
public static readonly DependencyProperty CoverageProperty = DependencyProperty.Register(
nameof(Coverage), typeof(ProxyChunkCoverage), typeof(ChunkCoverageBar),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
public static readonly DependencyProperty FillProperty = DependencyProperty.Register(
nameof(Fill), typeof(Brush), typeof(ChunkCoverageBar),
new FrameworkPropertyMetadata(Brushes.LimeGreen, FrameworkPropertyMetadataOptions.AffectsRender));
public ProxyChunkCoverage? Coverage
{
get => (ProxyChunkCoverage?)GetValue(CoverageProperty);
set => SetValue(CoverageProperty, value);
}
public Brush Fill
{
get => (Brush)GetValue(FillProperty);
set => SetValue(FillProperty, value);
}
public static IEnumerable<(double Start, double Length)> Segments(ProxyChunkCoverage coverage)
{
if (coverage.ChunkCount <= 0)
yield break;
double count = coverage.ChunkCount;
var chunks = coverage.Chunks.Where(chunk => chunk >= 0 && chunk < coverage.ChunkCount).Distinct().Order().ToArray();
var index = 0;
while (index < chunks.Length)
{
var first = chunks[index];
var last = first;
while (index + 1 < chunks.Length && chunks[index + 1] == last + 1)
last = chunks[++index];
yield return (first / count, (last - first + 1) / count);
index++;
}
if (coverage.CurrentChunk is { } current && current >= 0 && current < coverage.ChunkCount && !coverage.Contains(current) && coverage.CurrentProgress > 0d)
yield return (current / count, Math.Min(coverage.CurrentProgress, 1d) / count);
}
protected override void OnRender(DrawingContext drawingContext)
{
if (Coverage is not { } coverage)
return;
var width = RenderSize.Width;
var height = RenderSize.Height;
foreach (var (start, length) in Segments(coverage))
drawingContext.DrawRectangle(Fill, null, new Rect(start * width, 0d, length * width, height));
}
}
+9 -7
ファイルの表示
@@ -5,6 +5,7 @@
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:root="clr-namespace:ProxyForge"
xmlns:vm="clr-namespace:ProxyForge.ViewModels"
xmlns:views="clr-namespace:ProxyForge.Views"
xmlns:host="clr-namespace:YukkuriMovieMaker.Resources.Localization;assembly=YukkuriMovieMaker.Plugin"
mc:Ignorable="d"
d:DataContext="{d:DesignInstance Type={x:Type vm:GenerationProgressViewModel}}"
@@ -15,11 +16,11 @@
<Window.Style>
<Style TargetType="{x:Type Window}" BasedOn="{StaticResource {x:Type Window}}"/>
</Window.Style>
<Grid Margin="8">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="26"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="26"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{x:Static root:Texts.GeneratingProxies}" VerticalAlignment="Center"/>
<ScrollViewer Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled">
@@ -33,7 +34,8 @@
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Text="{Binding FileName}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"/>
<Grid Grid.Row="1">
<ProgressBar Minimum="0" Maximum="100" Value="{Binding Percentage, Mode=OneWay}" IsIndeterminate="{Binding IsWaiting}"/>
<ProgressBar Minimum="0" Maximum="100" Value="0" IsIndeterminate="{Binding IsWaiting}"/>
<views:ChunkCoverageBar Margin="1" Coverage="{Binding Coverage}"/>
<TextBlock Text="{Binding StatusText}" HorizontalAlignment="Center" VerticalAlignment="Center" TextTrimming="CharacterEllipsis"/>
</Grid>
</Grid>
@@ -41,9 +43,9 @@
</ItemsControl.ItemTemplate>
</ItemsControl>
</ScrollViewer>
<StackPanel Grid.Row="2" Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,8,0,0">
<Button Width="100" Content="{x:Static host:Texts.CancelButtonContent}" Command="{Binding CancelCommand}"/>
<Button Width="100" Margin="8,0,0,0" Content="{x:Static host:Texts.CloseButtonContent}" Click="OnCloseClick"/>
</StackPanel>
<UniformGrid Grid.Row="2" Rows="1" Columns="2">
<Button Content="{x:Static host:Texts.CancelButtonContent}" Command="{Binding CancelCommand}"/>
<Button Content="{x:Static host:Texts.CloseButtonContent}" Click="OnCloseClick"/>
</UniformGrid>
</Grid>
</Window>
+36
ファイルの表示
@@ -538,5 +538,41 @@
"file": "ProxyForge/Views/GenerationProgressWindowHost.cs",
"find": "=> itemCount > 0 && enabled && !hiddenByUser;",
"replace": "=> itemCount > 0 && enabled;"
},
{
"name": "網羅の描画で範囲外のチャンクも描く",
"file": "ProxyForge/Views/ChunkCoverageBar.cs",
"find": ".Where(chunk => chunk >= 0 && chunk < coverage.ChunkCount)",
"replace": ""
},
{
"name": "網羅の描画で隣り合うチャンクを繋げない",
"file": "ProxyForge/Views/ChunkCoverageBar.cs",
"find": "while (index + 1 < chunks.Length && chunks[index + 1] == last + 1)",
"replace": "while (false)"
},
{
"name": "網羅の描画で生成中のチャンクを描かない",
"file": "ProxyForge/Views/ChunkCoverageBar.cs",
"find": "&& !coverage.Contains(current) && coverage.CurrentProgress > 0d)",
"replace": "&& false)"
},
{
"name": "網羅の描画で進み具合を上限で切らない",
"file": "ProxyForge/Views/ChunkCoverageBar.cs",
"find": "Math.Min(coverage.CurrentProgress, 1d) / count",
"replace": "coverage.CurrentProgress / count"
},
{
"name": "生成中のチャンクを網羅に載せない",
"file": "ProxyForge/Encoding/ProxyGenerationQueue.cs",
"find": " Publish(item, entry, chunk);\r\n",
"replace": ""
},
{
"name": "チャンクの完了を網羅に載せない",
"file": "ProxyForge/Encoding/ProxyGenerationQueue.cs",
"find": " Publish(item, entry, null);\r\n ChunkCompleted",
"replace": " ChunkCompleted"
}
]