fix: address the phase 5 review

Video trash moves across volumes commit once the verified copy has its
name and leave an undeletable source whole behind a .leftover marker that
the next start settles; deletes rehash under the lease. Restores honour
the names renders are writing, and encoders never overwrite an output.
Routing floors at the stored settings' format, kindless stills read as
stills, star trails restart per loop, and settings the encoder ignored
become render warnings. The Videos section fits beside the player, plays
downloaded server copies, names blocked videos and says why actions are
off; the admin panel offers no download for sequences or missing files
and names a filtered sequence from its record.

Refs #21

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-05 04:11:02 +01:00
1 parent 6d87a1bc6d
commit 1be273d0e4
38 files changed
+958 -160

No files matched your search

+60 -25
View File
@@ -23,6 +23,41 @@
<Setter Property="MaxWidth" Value="170" />
<Setter Property="ItemTemplate" Value="{StaticResource Template.FilterOption}" />
</Style>
<!--
The list's preset, format and date columns: with the player open the list keeps the title, duration, size and state
(the player shows the rest), so the state stays in view beside the pane.
-->
<Style x:Key="Column.Preset" TargetType="ColumnDefinition">
<Setter Property="Width" Value="*" />
<Setter Property="MinWidth" Value="110" />
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Width" Value="0" />
<Setter Property="MinWidth" Value="0" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Column.Format" TargetType="ColumnDefinition" BasedOn="{StaticResource Column.Preset}">
<Setter Property="MinWidth" Value="130" />
</Style>
<Style x:Key="Column.Date" TargetType="ColumnDefinition" BasedOn="{StaticResource Column.Preset}">
<Setter Property="Width" Value="130" />
<Setter Property="MinWidth" Value="0" />
</Style>
<Style x:Key="Text.CellDetail" TargetType="TextBlock" BasedOn="{StaticResource Text.Cell}">
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
<Style x:Key="Text.HeaderDetail" TargetType="TextBlock" BasedOn="{StaticResource Text.Header}">
<Style.Triggers>
<DataTrigger Binding="{Binding DataContext.IsPlayerOpen, RelativeSource={RelativeSource AncestorType=UserControl}}" Value="True">
<Setter Property="Visibility" Value="Collapsed" />
</DataTrigger>
</Style.Triggers>
</Style>
<ItemsPanelTemplate x:Key="Panel.Row">
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
@@ -35,21 +70,21 @@
-->
<ContextMenu x:Key="Menu.Video" x:Shared="False">
<MenuItem Header="{l:Loc Videos.Play}" Command="{Binding PlacementTarget.Tag.PlayCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding PlayToolTip}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuPlayToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.ShowInFolder}" Command="{Binding PlacementTarget.Tag.ShowInFolderCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.Copy}" Command="{Binding PlacementTarget.Tag.CopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.Copy}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuShowInFolderToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{Binding MenuCopyText}" Command="{Binding PlacementTarget.Tag.CopyCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{Binding MenuCopyToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.CopyOnServer}" Command="{Binding PlacementTarget.Tag.CopyOnServerCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.CopyOnServer}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuCopyOnServerToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Videos.OpenInEdit}" Command="{Binding PlacementTarget.Tag.OpenInEditCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.OpenInEdit}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuOpenInEditToolTip}" ToolTipService.ShowOnDisabled="True" />
<MenuItem Header="{l:Loc Editor.Render.SendAgain}" Command="{Binding PlacementTarget.Tag.SendCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.WorkspaceRow}" ToolTipService.ShowOnDisabled="True"
Visibility="{Binding Entry.IsUnsent, Converter={StaticResource BoolToVisibility}}" />
<Separator />
<MenuItem Header="{l:Loc Videos.Delete}" Command="{Binding PlacementTarget.Tag.DeleteCommand, RelativeSource={RelativeSource AncestorType=ContextMenu}}"
CommandParameter="{Binding}" ToolTip="{l:Loc Tooltips.Videos.Delete}" ToolTipService.ShowOnDisabled="True" />
CommandParameter="{Binding}" ToolTip="{Binding MenuDeleteToolTip}" ToolTipService.ShowOnDisabled="True" />
</ContextMenu>
<Style x:Key="ListBoxItem.VideoCard" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Card}">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
@@ -141,10 +176,10 @@
ToolTip="{Binding PlayToolTip}" AutomationProperties.Name="{l:Loc Videos.Play}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.FolderOpen}"
Command="{Binding DataContext.ShowInFolderCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" AutomationProperties.Name="{l:Loc Videos.ShowInFolder}" />
ToolTip="{Binding MenuShowInFolderToolTip}" AutomationProperties.Name="{l:Loc Videos.ShowInFolder}" />
<Button Style="{StaticResource Button.Quick}" ui:ButtonIcon.Glyph="{StaticResource Icon.CopyToFolder}"
Command="{Binding DataContext.CopyCommand, RelativeSource={RelativeSource AncestorType=ListBox}}" CommandParameter="{Binding}"
ToolTip="{l:Loc Tooltips.Videos.Copy}" AutomationProperties.Name="{l:Loc Videos.Copy}" />
ToolTip="{Binding MenuCopyToolTip}" AutomationProperties.Name="{Binding MenuCopyText}" />
</StackPanel>
</v:SequenceCard.ActionsContent>
</v:SequenceCard>
@@ -162,20 +197,20 @@
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,6">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" MinWidth="160" />
<ColumnDefinition Width="*" MinWidth="110" />
<ColumnDefinition Width="*" MinWidth="130" />
<ColumnDefinition Width="2*" MinWidth="120" />
<ColumnDefinition Style="{StaticResource Column.Preset}" />
<ColumnDefinition Style="{StaticResource Column.Format}" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="130" />
<ColumnDefinition Style="{StaticResource Column.Date}" />
<ColumnDefinition Width="*" MinWidth="140" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Preset}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Format}" Margin="10,0,0,0" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Preset}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Format}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Duration}" TextAlignment="Right" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Size}" TextAlignment="Right" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.Date}" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.HeaderDetail}" Text="{l:Loc Videos.Column.Date}" Margin="10,0,0,0" />
<TextBlock Grid.Column="6" Style="{StaticResource Text.Header}" Text="{l:Loc Videos.Column.State}" Margin="16,0,0,0" />
</Grid>
</Border>
@@ -190,20 +225,20 @@
<DataTemplate DataType="{x:Type vid:VideoRowViewModel}">
<Grid ToolTip="{Binding ToolTip}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*" MinWidth="160" />
<ColumnDefinition Width="*" MinWidth="110" />
<ColumnDefinition Width="*" MinWidth="130" />
<ColumnDefinition Width="2*" MinWidth="120" />
<ColumnDefinition Style="{StaticResource Column.Preset}" />
<ColumnDefinition Style="{StaticResource Column.Format}" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="80" />
<ColumnDefinition Width="130" />
<ColumnDefinition Style="{StaticResource Column.Date}" />
<ColumnDefinition Width="*" MinWidth="140" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Subtitle}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Cell}" Text="{Binding FormatText}" Margin="10,0,0,0" FlowDirection="LeftToRight" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.CellDetail}" Text="{Binding Subtitle}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.CellDetail}" Text="{Binding FormatText}" Margin="10,0,0,0" FlowDirection="LeftToRight" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.CellNumber}" Text="{Binding DurationText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.CellNumber}" Text="{Binding SizeText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.Cell}" Text="{Binding DateText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<TextBlock Grid.Column="5" Style="{StaticResource Text.CellDetail}" Text="{Binding DateText}" Margin="10,0,0,0" Foreground="{DynamicResource Brush.TextMuted}" />
<ItemsControl Grid.Column="6" Margin="16,0,0,0" ItemsSource="{Binding States}" ItemTemplate="{StaticResource Template.Status}"
ItemsPanel="{StaticResource Panel.Row}" VerticalAlignment="Center" Focusable="False" ClipToBounds="True" />
</Grid>
@@ -235,10 +270,10 @@
<TextBlock Text="{Binding SelectionText}" FontWeight="SemiBold" VerticalAlignment="Center" Margin="0,0,12,8" Typography.NumeralAlignment="Tabular" />
<Border Width="1" Height="22" Background="{DynamicResource Brush.Stroke}" Margin="0,0,12,8" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.Play}" Command="{Binding PlayCommand}" ToolTip="{Binding PlayToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.ShowInFolder}" Command="{Binding ShowInFolderCommand}" ToolTip="{l:Loc Tooltips.Videos.ShowInFolder}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.ShowInFolder}" Command="{Binding ShowInFolderCommand}" ToolTip="{Binding ShowInFolderToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{Binding CopyText}" Command="{Binding CopyCommand}" ToolTip="{Binding CopyToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.CopyOnServer}" Command="{Binding CopyOnServerCommand}" ToolTip="{Binding CopyOnServerToolTip}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.OpenInEdit}" Command="{Binding OpenInEditCommand}" ToolTip="{l:Loc Tooltips.Videos.OpenInEdit}" />
<Button Style="{StaticResource Button.Bar}" Content="{l:Loc Videos.OpenInEdit}" Command="{Binding OpenInEditCommand}" ToolTip="{Binding OpenInEditToolTip}" />
<Button Style="{StaticResource Button.Subtle}" Height="30" Margin="0,0,8,8" Content="{l:Loc Library.Action.ClearSelection}" Command="{Binding ClearSelectionCommand}"
ToolTip="{l:Loc Tooltips.Library.ClearSelection}" />
</WrapPanel>
+85 -12
View File
@@ -137,6 +137,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
if (!Set(ref _rows, value)) return;
foreach (var row in _rows)
{
row.Section = this;
row.SelectionChanged += OnSelectionChanged;
row.PosterRequested += OnPosterRequested;
}
@@ -308,7 +309,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
public ICommand PlayCommand { get; }
/// <summary>The toolbar's Play tooltip: why the selection does not play here, else what Play does.</summary>
public string PlayToolTip => SelectedRows is [var one] ? one.PlayToolTip : Loc.L("Tooltips.Videos.Play");
public string PlayToolTip => PlayToolTipOf(SelectedRows);
public ICommand ShowInFolderCommand { get; }
public ICommand CopyCommand { get; }
@@ -318,18 +319,62 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
public ICommand SendCommand { get; }
/// <summary>Copy to folder, or Download for the server's videos alone.</summary>
public string CopyText => SelectedRows is { Count: > 0 } rows && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy");
public string CopyText => CopyTextOf(SelectedRows);
public string CopyToolTip => CopyBlocker(SelectedRows) ?? (SelectedRows.All(r => !r.Entry.IsLocal) && SelectedRows.Count > 0
? Loc.L("Tooltips.Videos.Download")
: Loc.L("Tooltips.Videos.Copy"));
public string CopyToolTip => CopyToolTipOf(SelectedRows);
public string CopyOnServerToolTip => CopyOnServerBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.CopyOnServer");
public string CopyOnServerToolTip => CopyOnServerToolTipOf(SelectedRows);
public string DeleteToolTip => DeleteBlocker(SelectedRows) ?? Loc.L("Tooltips.Videos.Delete");
public string DeleteToolTip => DeleteToolTipOf(SelectedRows);
/// <summary>Show in folder's tooltip: why it waits (more than one video, a server's video alone, a file gone), else what it does.</summary>
public string ShowInFolderToolTip => ShowInFolderToolTipOf(SelectedRows);
/// <summary>Open in Edit's tooltip: why it waits (more than one video, a server's video alone), else what it does.</summary>
public string OpenInEditToolTip => OpenInEditToolTipOf(SelectedRows);
/// <summary>The row's Copy to folder or Download tooltip (its context menu).</summary>
public string RowCopyToolTip(VideoRowViewModel row) => CopyBlocker([row]) ?? Loc.L(row.Entry.IsLocal ? "Tooltips.Videos.Copy" : "Tooltips.Videos.Download");
public string RowCopyToolTip(VideoRowViewModel row) => CopyToolTipOf(Targets(row));
/// <summary>What the row's menu acts on: the selection when the row is part of it, else the row alone (as the commands do).</summary>
internal IReadOnlyList<VideoRowViewModel> TargetsOf(VideoRowViewModel row) => Targets(row);
internal static string PlayToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[var one] => one.PlayToolTip,
{ Count: > 1 } => Loc.L("Tooltips.Videos.SelectOne"),
_ => Loc.L("Tooltips.Videos.Play"),
};
internal static string CopyTextOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows is { Count: > 0 } && rows.All(r => !r.Entry.IsLocal && r.Entry.IsOnServer) ? Loc.L("Videos.Download") : Loc.L("Videos.Copy");
internal string CopyToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
CopyBlocker(rows) ?? (rows.Count > 0 && rows.All(r => !r.Entry.IsLocal) ? Loc.L("Tooltips.Videos.Download") : Loc.L("Tooltips.Videos.Copy"));
internal string CopyOnServerToolTipOf(IReadOnlyList<VideoRowViewModel> rows) => CopyOnServerBlocker(rows) ?? Loc.L("Tooltips.Videos.CopyOnServer");
internal string DeleteToolTipOf(IReadOnlyList<VideoRowViewModel> rows) => DeleteBlocker(rows) ?? Loc.L("Tooltips.Videos.Delete");
internal static string ShowInFolderToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[{ Entry.HasLocalFile: true }] or [] => Loc.L("Tooltips.Videos.ShowInFolder"),
[{ Entry.Missing: true }] => Loc.L("Tooltips.Videos.Missing"),
[_] => Loc.L("Tooltips.Videos.ServerOnly"),
_ => Loc.L("Tooltips.Videos.SelectOne"),
};
internal static string OpenInEditToolTipOf(IReadOnlyList<VideoRowViewModel> rows) =>
rows switch
{
[var one] when CanOpen(one.Entry) => Loc.L("Tooltips.Videos.OpenInEdit"),
[{ Entry.IsUnsent: true }] => Loc.L("Tooltips.Videos.WorkspaceRow"),
[_] => Loc.L("Tooltips.Videos.ServerOnly"),
[] => Loc.L("Tooltips.Videos.OpenInEdit"),
_ => Loc.L("Tooltips.Videos.SelectOne"),
};
public ICommand ClosePlayerCommand { get; }
@@ -360,9 +405,10 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
var local = await localTask;
var (remote, state) = await serverTask;
var workspace = await workspaceTask;
var merged = await WithLocalCopiesAsync(VideoSources.Merge(local, remote, workspace));
if (load != _loads) return;
_server = state;
Entries = VideoSources.Merge(local, remote, workspace);
Entries = merged;
OnPropertyChanged(nameof(ServerState));
OnPropertyChanged(nameof(IsServerLimited));
OnPropertyChanged(nameof(ServerStatusText));
@@ -400,6 +446,27 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
}
}
/// <summary>The server's renders this PC downloaded, with their copies here (<see cref="VideoSources.WithLocalCopies"/>).</summary>
private async Task<IReadOnlyList<VideoEntry>> WithLocalCopiesAsync(IReadOnlyList<VideoEntry> entries)
{
List<Guid> serverOnly = [.. entries.Where(e => e.IsOnServer && !e.IsLocal && !e.IsUnsent).Select(e => e.Id)];
if (serverOnly.Count == 0 || LocalLibrary() is not { IsAvailable: true } library) return entries;
try
{
return await Task.Run(async () =>
{
var copies = await library.CopiesAsync(serverOnly);
var paths = copies.ToDictionary(c => c.Key, c => (IReadOnlyList<string>)[.. c.Value.Select(copy => copy.Path)]);
return VideoSources.WithLocalCopies(entries, paths, p => File.Exists(p) || Directory.Exists(p));
});
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("videos", "The copies of the server's videos on this PC could not be read", ex);
return entries;
}
}
private static async Task<(IReadOnlyList<VideoEntry> Entries, VideoServer State)> ReadServerAsync(VideoServer server)
{
if (server is not { State: VideoServerState.Available, Connect: { } connect }) return ([], server);
@@ -549,6 +616,10 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
OnPropertyChanged(nameof(CopyToolTip));
OnPropertyChanged(nameof(CopyOnServerToolTip));
OnPropertyChanged(nameof(DeleteToolTip));
OnPropertyChanged(nameof(ShowInFolderToolTip));
OnPropertyChanged(nameof(OpenInEditToolTip));
// A row's menu acts on the selection it is part of: its words follow the selection too.
foreach (var each in _rows) each.RefreshMenu();
CommandManager.InvalidateRequerySuggested();
}
@@ -735,7 +806,7 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
using var remote = connect();
server = await remote.PlanDeleteAsync(serverIds);
}
plans = new VideoDeletePlans(local, server);
plans = new VideoDeletePlans(local, server, rows.DistinctBy(r => r.Entry.Id).ToDictionary(r => r.Entry.Id, r => VideoDeletePlans.NameOf(r.Entry)));
}
catch (Exception ex) when (ex is ChronosApiException or HttpRequestException or TaskCanceledException or UntrustedCertificateException)
{
@@ -757,15 +828,17 @@ public sealed class VideosViewModel : SectionViewModel, Chronos.App.Editor.IVide
var deleted = 0;
try
{
// Each delete asks for exactly the ids that were planned, blocked ones included: its fingerprint covers them all, and
// what is blocked stays where it is.
if (plans.Local is { Items.Count: > 0 } localPlan)
{
var result = await Task.Run(() => library!.DeleteAsync([.. localPlan.Items.Select(i => i.Render.Id)], localPlan.Fingerprint, Environment.MachineName));
var result = await Task.Run(() => library!.DeleteAsync(localIds, localPlan.Fingerprint, Environment.MachineName));
deleted += result.Deleted.Count;
}
if (plans.Server is { Items.Count: > 0 } serverPlan && _server.Connect is { } connect)
{
using var remote = connect();
var result = await remote.DeleteAsync([.. serverPlan.Items.Select(i => i.Id)], serverPlan.Fingerprint);
var result = await remote.DeleteAsync(serverIds, serverPlan.Fingerprint);
deleted += result.Items.Count;
}
Shell.Notify(Loc.L("Videos.Delete.Done", Formatting.Count(deleted)));
+50 -6
View File
@@ -42,12 +42,11 @@ public static class VideoText
return size.Length == 0 ? codec : codec.Length == 0 ? size : size + Loc.Separator + codec;
}
/// <summary>"3840×2160 · HEVC · 0:42 · 1.2 GB" (<c>Videos.Details</c>).</summary>
/// <summary>"3840×2160 · HEVC · 0:42 · 1.2 GB": the parts a render has (a still has no duration), joined by the separator.</summary>
public static string Details(VideoEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return Loc.L("Videos.Details", entry.Width.ToString(CultureInfo.InvariantCulture), entry.Height.ToString(CultureInfo.InvariantCulture),
VideoSources.CodecText(entry.Codec), Duration(entry), Formatting.Bytes(entry.Bytes));
return string.Join(Loc.Separator, new[] { Format(entry), Duration(entry), Formatting.Bytes(entry.Bytes) }.Where(p => p.Length > 0));
}
/// <summary>The state chips of a render: where its file is, whether it was copied, and a missing file.</summary>
@@ -137,6 +136,39 @@ public sealed class VideoRowViewModel(VideoEntry entry) : ObservableObject
/// </summary>
public string PlayToolTip => VideoText.PlayToolTip(Entry);
/// <summary>The section listing the row: its menu's words are those of the commands it runs, on what they act on.</summary>
internal Sections.VideosViewModel? Section { get; set; }
private IReadOnlyList<VideoRowViewModel> MenuTargets => Section?.TargetsOf(this) ?? [this];
/// <summary>The menu's Play tooltip: why it waits, else what it does.</summary>
public string MenuPlayToolTip => Sections.VideosViewModel.PlayToolTipOf(MenuTargets);
public string MenuShowInFolderToolTip => Sections.VideosViewModel.ShowInFolderToolTipOf(MenuTargets);
/// <summary>Copy to folder, or Download for the server's videos alone.</summary>
public string MenuCopyText => Sections.VideosViewModel.CopyTextOf(MenuTargets);
public string MenuCopyToolTip => Section?.CopyToolTipOf(MenuTargets) ?? Loc.L("Tooltips.Videos.Copy");
public string MenuCopyOnServerToolTip => Section?.CopyOnServerToolTipOf(MenuTargets) ?? Loc.L("Tooltips.Videos.CopyOnServer");
public string MenuOpenInEditToolTip => Sections.VideosViewModel.OpenInEditToolTipOf(MenuTargets);
public string MenuDeleteToolTip => Section?.DeleteToolTipOf(MenuTargets) ?? Loc.L("Tooltips.Videos.Delete");
/// <summary>The selection or the section's state changed: the menu's words are read again.</summary>
internal void RefreshMenu()
{
OnPropertyChanged(nameof(MenuPlayToolTip));
OnPropertyChanged(nameof(MenuShowInFolderToolTip));
OnPropertyChanged(nameof(MenuCopyText));
OnPropertyChanged(nameof(MenuCopyToolTip));
OnPropertyChanged(nameof(MenuCopyOnServerToolTip));
OnPropertyChanged(nameof(MenuOpenInEditToolTip));
OnPropertyChanged(nameof(MenuDeleteToolTip));
}
/// <summary>The file name, left to right in every language.</summary>
public string FileNameText => Formatting.LeftToRight(Entry.FileName);
@@ -174,8 +206,17 @@ public sealed class VideoRowViewModel(VideoEntry entry) : ObservableObject
/// many bytes), the renders whose file is missing (only their entry goes), the renders left where they are and why, and
/// that copies in the videos folder stay. This PC's renders and the server's are planned apart and confirmed together.
/// </summary>
public sealed record VideoDeletePlans(VideoDeletePlan? Local, VideoDeletePlanDto? Server)
/// <param name="Names">What the section shows of each selected render ("title · file"), which names a render that stays
/// (the server's plan gives only its id); a render not among them is named by its id.</param>
public sealed record VideoDeletePlans(VideoDeletePlan? Local, VideoDeletePlanDto? Server, IReadOnlyDictionary<Guid, string>? Names = null)
{
/// <summary>"Harbour sunset · harbour-4k.mp4": how a render that stays is named in the confirmation.</summary>
public static string NameOf(VideoEntry entry)
{
ArgumentNullException.ThrowIfNull(entry);
return entry.Title + Loc.Separator + Formatting.LeftToRight(entry.FileName);
}
/// <summary>The renders that go.</summary>
public int Count => (Local?.Items.Count ?? 0) + (Server?.Items.Count ?? 0);
@@ -200,14 +241,17 @@ public sealed record VideoDeletePlans(VideoDeletePlan? Local, VideoDeletePlanDto
missing ? Loc.L("Videos.State.Missing") : Formatting.Bytes(bytes)));
}
if (goes.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", goes.Count - DeletePlans.ListedLines));
var stays = (Local?.Blocked.Select(b => (b.Video?.SequenceTitle ?? b.RenderId.ToString("D"), b.Reason)) ?? [])
.Concat(Server?.Blocked.Select(b => (b.Id.ToString("D"), b.Reason)) ?? []).ToList();
var stays = (Local?.Blocked.Select(b => (Named(b.RenderId, b.Video is { } video ? video.SequenceTitle + Loc.Separator + Formatting.LeftToRight(video.FileName) : null), b.Reason)) ?? [])
.Concat(Server?.Blocked.Select(b => (Named(b.Id, null), b.Reason)) ?? []).ToList();
if (stays.Count > 0) lines.Add(Loc.L("Videos.Delete.Blocked", Formatting.Count(stays.Count)));
foreach (var (name, reason) in stays.Take(DeletePlans.ListedLines)) lines.Add(name + Loc.Separator + VideoText.BlockReason(reason));
if (stays.Count > DeletePlans.ListedLines) lines.Add(Loc.Plural("Archive.Delete.More", stays.Count - DeletePlans.ListedLines));
return lines;
}
/// <summary>The render's name in the section, else <paramref name="fallback"/>, else its id.</summary>
private string Named(Guid id, string? fallback) => Names?.GetValueOrDefault(id) ?? fallback ?? id.ToString("D");
/// <summary>The confirmation of moving the planned renders into the trash; null when nothing would go.</summary>
public ConfirmRequest? Request()
{
+24 -1
View File
@@ -308,7 +308,7 @@ public static class VideoSources
DurationSeconds = render.DurationSeconds,
Bytes = render.Size,
Created = render.Rendered,
Kind = RenderKind.Of(null, render.Codec),
Kind = RenderKind.Of(null, render.Codec, render.Fps, render.DurationSeconds),
FileName = Path.GetFileName(path.TrimEnd('/', '\\')),
LocalPath = path,
IsUnsent = true,
@@ -353,6 +353,29 @@ public static class VideoSources
return [.. order.Select(id => merged[id])];
}
/// <summary>
/// The renders the server alone holds that this PC downloaded (a verified copy in its videos folder, <paramref name="copies"/>
/// by render id): the copies listed with theirs ("Copied"), and the first one still on disk (<paramref name="exists"/>)
/// as the file Play and Show in folder use here. Every other entry as it is.
/// </summary>
public static IReadOnlyList<VideoEntry> WithLocalCopies(IReadOnlyList<VideoEntry> entries, IReadOnlyDictionary<Guid, IReadOnlyList<string>> copies,
Func<string, bool> exists)
{
ArgumentNullException.ThrowIfNull(entries);
ArgumentNullException.ThrowIfNull(copies);
ArgumentNullException.ThrowIfNull(exists);
return
[
.. entries.Select(e => !e.IsLocal && !e.IsUnsent && e.LocalPath is null && copies.TryGetValue(e.Id, out var paths) && paths.Count > 0
? e with
{
LocalPath = paths.FirstOrDefault(exists),
Copies = [.. e.Copies.Concat(paths).Distinct(StringComparer.OrdinalIgnoreCase)],
}
: e),
];
}
/// <summary>Every render of this PC's index (<see cref="MaxPages"/> pages at most); none while the library is not there.</summary>
public static async Task<IReadOnlyList<VideoEntry>> ReadLocalAsync(IVideoLibrary? library, CancellationToken cancellationToken = default)
{
@@ -33,6 +33,7 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession
private readonly Dictionary<long, long> _ticksByHns = [];
private readonly Dictionary<long, long> _durationByTicks = [];
private readonly Queue<long> _inputStarts = new();
private readonly List<EncoderSetting> _ignored = [];
private bool _providesSamples;
private uint _outputBufferSize;
private int _needInput;
@@ -58,6 +59,7 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession
if (UnlockAsync(transform))
_events = transform as IMFMediaEventGenerator ?? throw new NotSupportedException("Asynchronous MFT without an event generator");
if (transform as ICodecAPI is { } codecApi) ApplyCodecSettings(codecApi);
else _ignored.AddRange(Asked());
SetOutputType();
SetInputType();
ReadOutputStreamInfo();
@@ -157,7 +159,8 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession
_muxer.Complete();
_file.Flush(flushToDisk: true);
_file.Dispose();
AtomicFile.Commit(_tempPath, _settings.OutputPath);
// The render picked a free name: something that took it meanwhile (a restore) is never overwritten.
AtomicFile.CommitNew(_tempPath, _settings.OutputPath);
_completed = true;
Log.Info(LogCategory, $"\"{EncoderName}\" encoded {_framesIn} frames into {_framesOut} samples: {_settings.OutputPath}");
}
@@ -208,27 +211,51 @@ public sealed class MediaFoundationEncoderSession : IVideoEncoderSession
RateControl.Quality => MfNative.RateControlQuality,
_ => MfNative.RateControlUnconstrainedVbr,
};
SetCodecValue(api, MfGuids.CodecRateControlMode, ComVariant.Create(mode), "RateControlMode");
var asked = Asked().ToHashSet();
void Set(in Guid property, ComVariant value, string name, EncoderSetting setting)
{
if (!SetCodecValue(api, property, value, name) && asked.Contains(setting) && !_ignored.Contains(setting)) _ignored.Add(setting);
}
Set(MfGuids.CodecRateControlMode, ComVariant.Create(mode), "RateControlMode", EncoderSetting.RateControl);
if (_settings.RateControl == RateControl.Quality)
SetCodecValue(api, MfGuids.CodecQuality, ComVariant.Create((uint)Math.Clamp(_settings.Quality, 1, 100)), "Quality");
Set(MfGuids.CodecQuality, ComVariant.Create((uint)Math.Clamp(_settings.Quality, 1, 100)), "Quality", EncoderSetting.Quality);
else
SetCodecValue(api, MfGuids.CodecMeanBitRate, ComVariant.Create(BitRate), "MeanBitRate");
Set(MfGuids.CodecMeanBitRate, ComVariant.Create(BitRate), "MeanBitRate", EncoderSetting.BitRate);
var gop = _settings.GopLength > 0 ? _settings.GopLength : (int)Math.Max(1, Math.Round(_settings.FrameRate.Value));
SetCodecValue(api, MfGuids.CodecGopSize, ComVariant.Create((uint)gop), "GOPSize");
Set(MfGuids.CodecGopSize, ComVariant.Create((uint)gop), "GOPSize", EncoderSetting.KeyframeInterval);
var bFrames = _settings.Profile == CodecProfile.H264Baseline ? 0 : Math.Max(0, _settings.BFrames);
SetCodecValue(api, MfGuids.CodecBPictureCount, ComVariant.Create((uint)bFrames), "BPictureCount");
Set(MfGuids.CodecBPictureCount, ComVariant.Create((uint)bFrames), "BPictureCount", EncoderSetting.BFrames);
SetCodecValue(api, MfGuids.CodecLowLatencyMode, ComVariant.Create(false), "LowLatencyMode");
}
private static unsafe void SetCodecValue(ICodecAPI api, in Guid property, ComVariant value, string name)
/// <inheritdoc />
public IReadOnlyList<EncoderSetting> Ignored => _ignored;
/// <summary>
/// The settings that name a value of their own rather than the encoder's default, whose refusal the render reports: a rate
/// control other than VBR, its quality, a bit rate given, a keyframe interval given, a B-frame count other than the default.
/// </summary>
private IEnumerable<EncoderSetting> Asked()
{
if (_settings.RateControl != RateControl.Vbr) yield return EncoderSetting.RateControl;
if (_settings.RateControl == RateControl.Quality) yield return EncoderSetting.Quality;
else if (_settings.BitRate > 0) yield return EncoderSetting.BitRate;
if (_settings.GopLength > 0) yield return EncoderSetting.KeyframeInterval;
if (_settings.Profile != CodecProfile.H264Baseline && _settings.BFrames != EncodeSettings.DefaultBFrames) yield return EncoderSetting.BFrames;
}
/// <summary>Sets an ICodecAPI property; false (logged) when the encoder does not support it or refuses the value.</summary>
private static unsafe bool SetCodecValue(ICodecAPI api, in Guid property, ComVariant value, string name)
{
if (api.IsSupported(property) != 0)
{
Log.Debug(LogCategory, $"ICodecAPI {name} not supported by the encoder");
return;
return false;
}
var hr = api.SetValue(property, (nint)(&value));
if (hr < 0) Log.Debug(LogCategory, $"ICodecAPI {name} rejected (0x{hr:X8})");
return hr >= 0;
}
/// <summary>Requested bit rate, or the preset density (§11.4: 0.10/0.07/0.05 bits per pixel per frame) when unset.</summary>
+12
View File
@@ -93,6 +93,18 @@ public static class AtomicFile
Replace(tempPath, path);
}
/// <summary>
/// Commits an already-written temporary file as <paramref name="path"/>, which must not exist: an output whose free name
/// something else took meanwhile (a restore, another program) is never overwritten.
/// </summary>
/// <exception cref="IOException"><paramref name="path"/> exists (the temporary file stays for the caller to discard).</exception>
public static void CommitNew(string tempPath, string path)
{
using (var fs = new FileStream(tempPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
fs.Flush(flushToDisk: true);
File.Move(tempPath, path, overwrite: false);
}
public static string TempPathFor(string path)
{
var dir = Path.GetDirectoryName(Path.GetFullPath(path)) ?? ".";
+13 -2
View File
@@ -201,11 +201,22 @@ public static class RenderKind
: codec is { } c && c.EndsWith("sequence", StringComparison.OrdinalIgnoreCase) ? Sequence
: Video;
/// <inheritdoc cref="Of(string?, string?)"/>
/// <summary>
/// <see cref="Of(string?, string?)"/>, telling a still apart when its kind was lost (one uploaded to a server of before
/// phase 5, which does not record it): an image-sequence codec with fps 0 and duration 0, which every still records and
/// no image sequence has.
/// </summary>
public static string Of(string? kind, string? codec, double fps, double durationSeconds)
{
var of = Of(kind, codec);
return of == Sequence && fps <= 0 && durationSeconds <= 0 ? Still : of;
}
/// <inheritdoc cref="Of(string?, string?, double, double)"/>
public static string Of(Render render)
{
ArgumentNullException.ThrowIfNull(render);
return Of(render.Kind, render.Codec);
return Of(render.Kind, render.Codec, render.Fps, render.DurationSeconds);
}
}
+8 -6
View File
@@ -11,7 +11,9 @@ namespace Chronos.Core.Render;
/// <param name="Gain">The linear-light multiplier of the fade to and from black, applied after the look and the knee
/// (<c>FrameFinish</c>): 1 leaves the frame as it is, 0 is black. Already in linear light (the sRGB ramp converted), so a
/// fade looks even.</param>
public readonly record struct ProgramEntry(int PlanIndex, long Duration90k, double Gain);
/// <param name="Pass">The pass of the playback it belongs to (0 for the first; each loop is one more): a star-trail stack
/// starts again at each pass, so every loop plays the trails growing.</param>
public readonly record struct ProgramEntry(int PlanIndex, long Duration90k, double Gain, int Pass = 0);
/// <summary>
/// The output program of a render (owner review 1, R8): the plan's frames in the order and for the time they are emitted,
@@ -87,15 +89,15 @@ public sealed class OutputProgram
switch (direction)
{
case PlaybackDirection.Reverse:
for (var i = frames.Count - 1; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
for (var i = frames.Count - 1; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
case PlaybackDirection.Boomerang:
// The turning frame plays once, and a later pass starts after the first frame the previous one ended on.
for (var i = pass == 0 ? 0 : 1; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
for (var i = frames.Count - 2; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
for (var i = pass == 0 ? 0 : 1; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
for (var i = frames.Count - 2; i >= 0; i--) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
default:
for (var i = 0; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1));
for (var i = 0; i < frames.Count; i++) entries.Add(new ProgramEntry(i, frames[i].Duration90k, 1, pass));
break;
}
}
@@ -148,7 +150,7 @@ public sealed class OutputProgram
{
var boundary = (long)double.Round((double)entry.Duration90k * part / parts);
if (boundary == previous) continue;
faded.Add(new ProgramEntry(entry.PlanIndex, boundary - previous, Gain(start + previous, start + boundary, total, fadeIn, fadeOut)));
faded.Add(entry with { Duration90k = boundary - previous, Gain = Gain(start + previous, start + boundary, total, fadeIn, fadeOut) });
previous = boundary;
}
start = end;
+33 -11
View File
@@ -100,6 +100,9 @@ internal sealed class RenderRun : IDisposable
/// <summary>Largest speed (source frames per output period) that scales motion blur; faster plans blur no further.</summary>
private const double MaxBlurSpeed = 4;
/// <summary>Warning key prefix of a setting the encoder refused (<see cref="IVideoEncoderSession.Ignored"/>), followed by its <see cref="EncoderSetting"/>.</summary>
internal const string IgnoredWarningPrefix = "Export.Encoder.Ignored.";
private readonly RenderInput _input;
private readonly RenderCorrections _corrections;
private readonly RenderSetup _setup;
@@ -157,12 +160,14 @@ internal sealed class RenderRun : IDisposable
else
Log.Info(RenderPipeline.LogCategory, $"Rendering {_program.Count} frames of a {_plan.Frames.Count}-frame plan ({_plan.SlotCount} periods) to {settings.Codec} {settings.Width}×{settings.Height} @ {settings.FrameRate}: {settings.OutputPath}");
var session = _session = _setup.Encoder.Open();
IReadOnlyList<EncoderSetting> ignored;
try
{
await RenderFramesAsync(cancellationToken).ConfigureAwait(false);
await FlushEncodingAsync().ConfigureAwait(false);
_progress?.Report(new RenderProgress(RenderStage.Finishing, _done, _program.Count, Fps(), _clock.Elapsed, TimeSpan.Zero));
session.Complete();
ignored = [.. session.Ignored];
}
catch
{
@@ -177,6 +182,8 @@ internal sealed class RenderRun : IDisposable
var warnings = new List<RenderWarning>(_setup.Warnings);
warnings.AddRange(_corrections.Report.Warnings);
warnings.AddRange(_warnings);
// What the encoder did not take: the output was encoded with its own value, which the job's log says.
warnings.AddRange(ignored.Select(s => new RenderWarning(IgnoredWarningPrefix + s)));
var result = new RenderResult
{
OutputPath = settings.OutputPath,
@@ -221,28 +228,42 @@ internal sealed class RenderRun : IDisposable
await RenderWindowStackAsync(stack, cancellationToken).ConfigureAwait(false);
break;
case StackSetting.StarTrails:
// The trails accumulate in program order: a reversed video grows its trails from the end.
using (var trails = new StarTrailStacker(StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity)))
// The trails accumulate in program order: a reversed video grows its trails from the end, and each loop grows
// them again from nothing (a stacker carried over would freeze on the trails the first pass finished).
var decay = StarTrailStacker.DecayForTrailLength(stack.Length > 0 ? stack.Length : double.PositiveInfinity);
StarTrailStacker? trails = null;
var pass = -1;
try
{
await RenderProgramAsync(async (index, token) =>
await RenderProgramAsync(async (entry, token) =>
{
using (var frame = await RenderFrameAsync(_plan.Frames[index], blur: false, token).ConfigureAwait(false)) trails.Add(frame);
if (entry.Pass != pass || trails is null)
{
trails?.Dispose();
trails = new StarTrailStacker(decay);
pass = entry.Pass;
}
using (var frame = await RenderFrameAsync(_plan.Frames[entry.PlanIndex], blur: false, token).ConfigureAwait(false)) trails.Add(frame);
return trails.Result!.Clone();
}, cancellationToken).ConfigureAwait(false);
}
finally
{
trails?.Dispose();
}
break;
default:
await RenderProgramAsync((index, token) => RenderFrameAsync(_plan.Frames[index], _setup.MotionBlur, token), cancellationToken).ConfigureAwait(false);
await RenderProgramAsync((entry, token) => RenderFrameAsync(_plan.Frames[entry.PlanIndex], _setup.MotionBlur, token), cancellationToken).ConfigureAwait(false);
break;
}
}
/// <summary>
/// Emits the program's entries in order, each rendered by <paramref name="render"/> from its plan index. Consecutive
/// entries of one plan frame (a held frame split over the periods of a fade) share one rendering, so a stack folds it
/// in once; every other entry is rendered again (a boomerang's way back, each loop).
/// entries of one plan frame and one pass (a held frame split over the periods of a fade) share one rendering, so a
/// stack folds it in once; every other entry is rendered again (a boomerang's way back, each loop).
/// </summary>
private async Task RenderProgramAsync(Func<int, CancellationToken, Task<ImageBuffer>> render, CancellationToken cancellationToken)
private async Task RenderProgramAsync(Func<ProgramEntry, CancellationToken, Task<ImageBuffer>> render, CancellationToken cancellationToken)
{
var entries = _program.Entries;
ImageBuffer? kept = null;
@@ -252,9 +273,9 @@ internal sealed class RenderRun : IDisposable
{
cancellationToken.ThrowIfCancellationRequested();
var entry = entries[i];
var frame = kept ?? await render(entry.PlanIndex, cancellationToken).ConfigureAwait(false);
var frame = kept ?? await render(entry, cancellationToken).ConfigureAwait(false);
kept = null;
if (i + 1 < entries.Count && entries[i + 1].PlanIndex == entry.PlanIndex)
if (i + 1 < entries.Count && entries[i + 1].PlanIndex == entry.PlanIndex && entries[i + 1].Pass == entry.Pass)
{
try
{
@@ -290,8 +311,9 @@ internal sealed class RenderRun : IDisposable
// Plan indices in the stacker, oldest (the next evicted) first.
var held = new List<int>(window + 1);
var previous = -1;
await RenderProgramAsync(async (index, token) =>
await RenderProgramAsync(async (entry, token) =>
{
var index = entry.PlanIndex;
var hi = int.Min(index + half, last);
var lo = int.Max(0, hi - window + 1);
await WindowAsync(stacker, held, lo, hi, index >= previous, token).ConfigureAwait(false);
+21 -1
View File
@@ -102,7 +102,11 @@ public sealed record EncodeSettings
/// <summary>Distance between key frames in frames; 0 = encoder default (≈ 1 s).</summary>
public int GopLength { get; init; }
public int BFrames { get; init; } = 2;
public int BFrames { get; init; } = DefaultBFrames;
/// <summary>The B-frames an encode asks for unless told otherwise.</summary>
public const int DefaultBFrames = 2;
public bool PreferHardware { get; init; } = true;
/// <summary>Optional specific encoder name from <see cref="EncoderCapability.Name"/>.</summary>
@@ -128,6 +132,22 @@ public interface IVideoEncoderSession : IDisposable
/// <summary>Flushes and closes the output. Without it, <see cref="IDisposable.Dispose"/> deletes the partial file.</summary>
void Complete();
/// <summary>
/// The settings asked for that the encoder does not support or refused, so the output was encoded with its own instead;
/// empty when it took every one (the managed encoders, which have none of them to refuse).
/// </summary>
IReadOnlyList<EncoderSetting> Ignored => [];
}
/// <summary>An encoding setting an encoder may refuse (<see cref="IVideoEncoderSession.Ignored"/>).</summary>
public enum EncoderSetting
{
RateControl,
Quality,
BitRate,
KeyframeInterval,
BFrames,
}
/// <summary>A family of encoders (Media Foundation on Windows, managed everywhere).</summary>
@@ -108,7 +108,8 @@ internal abstract class SingleFileSession : ManagedSession
Finish();
File.Flush(flushToDisk: true);
File.Dispose();
AtomicFile.Commit(_tempPath, Settings.OutputPath);
// The render picked a free name: something that took it meanwhile (a restore) is never overwritten.
AtomicFile.CommitNew(_tempPath, Settings.OutputPath);
}
protected override void Discard()
+13 -5
View File
@@ -153,12 +153,19 @@ public static class ProcessingJobs
{
Width = width,
Height = height,
// The job's own export (playback included) is what renders, not the export the settings carry.
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat,
RequiredFormat(settings with { Export = ReadExport(parameters.PresetJson) }, resolved, sourceWidth, sourceHeight)),
// The job's own export (playback included) is what renders, not the export the settings carry; but a node parses
// the settings text as it is, so never less than the format that text is written in.
RequiredSettingsFormat = int.Max(parameters.RequiredSettingsFormat, int.Max(TextFormat(settings),
RequiredFormat(settings with { Export = ReadExport(parameters.PresetJson) }, resolved, sourceWidth, sourceHeight))),
};
}
/// <summary>
/// The format of the settings text a node parses: the version it was read with, or the one <see cref="ProjectSettings.ToJson"/>
/// writes for it. A node that reads less refuses that text, whatever export the job renders.
/// </summary>
private static int TextFormat(ProjectSettings settings) => int.Max(settings.Version, settings.WrittenFormat);
/// <summary>
/// The settings format a render of <paramref name="settings"/> with <paramref name="export"/> and each of its batch
/// presets needs (the highest <see cref="RenderRules.RequiredFormat"/> of them): what a server or a render node must read
@@ -227,10 +234,11 @@ public static class ProcessingJobs
settings ??= ReadSettings(settingsJson);
var (width, height) = (settings is null ? null : Size(settings, resolved, sourceWidth, sourceHeight))
?? (resolved.Width > 0 ? resolved.Width : sourceWidth, resolved.Height > 0 ? resolved.Height : sourceHeight);
// The format of what renders: the settings with this export in place of their own (its playback raises it to 3).
// The format of what renders: the settings with this export in place of their own (its playback raises it to 3), and
// never less than the format of the settings text the node parses.
var format = settings is null
? new ProjectSettings { Export = export }.RequiredFormat
: RequiredFormat(settings with { Export = export }, resolved, sourceWidth, sourceHeight);
: int.Max(TextFormat(settings), RequiredFormat(settings with { Export = export }, resolved, sourceWidth, sourceHeight));
return new RenderJobParameters(PresetName(resolved), JsonSerializer.Serialize(export, ProcessingJson.Default.ExportSettings), CodecName(resolved.Codec),
width, height, useProxies, settingsJson, RequiredSettingsFormat: format);
}
@@ -183,8 +183,9 @@ internal sealed class SequenceRender : IAsyncDisposable
/// <summary>
/// The frame a still job saves (<see cref="Protocol.RenderJobParameters.StillFrame"/>, <see cref="Protocol.RenderJobParameters.StillPhoto"/>):
/// the frame holding the photo when its SHA-256 is given and found (the frames may have moved since), else the index;
/// null when neither names a frame of the sequence.
/// the frame holding the photo when its SHA-256 is given (the frames may have moved since), null when that photo is no
/// longer in the sequence (the index would name another photo now); without a hash (a photo not hashed yet) the index.
/// Null when neither names a frame of the sequence.
/// </summary>
public static int? StillIndex(SequenceFrames frames, int? frameIndex, string? photoSha256)
{
@@ -195,6 +196,7 @@ internal sealed class SequenceRender : IAsyncDisposable
{
if (string.Equals(frames.Frames[i].Sha256, sha, StringComparison.OrdinalIgnoreCase)) return i;
}
return null;
}
return frameIndex is { } index && (uint)index < (uint)frames.Frames.Count ? index : null;
}
@@ -180,17 +180,22 @@ public sealed class RenderRepository
var from = new DateTimeOffset(year, 1, 1, 0, 0, 0, TimeSpan.Zero);
where.Add($"r.created >= {p.Add(from)} AND r.created < {p.Add(from.AddYears(1))}");
}
// A sequence's codec names end in "sequence" (pngsequence, tiff16sequence…).
const string Sequence = "(r.kind IS NULL AND lower(coalesce(r.codec, '')) LIKE '%sequence')";
// A sequence's codec names end in "sequence" (pngsequence, tiff16sequence…). A still whose kind was lost (uploaded to
// a server of before phase 5) has such a codec with fps 0 and duration 0, as RenderKind.Of tells it apart.
const string ImageCodec = "lower(coalesce(r.codec, '')) LIKE '%sequence'";
const string KindlessStill = $"(r.kind IS NULL AND {ImageCodec} AND coalesce(r.fps, 0) <= 0 AND coalesce(r.duration_seconds, 0) <= 0)";
switch (query.Kind?.Trim().ToLowerInvariant())
{
case null or "":
break;
case RenderKind.Video:
where.Add($"(r.kind IS NULL AND NOT {Sequence})");
where.Add($"(r.kind IS NULL AND NOT {ImageCodec})");
break;
case RenderKind.Sequence:
where.Add(Sequence);
where.Add($"(r.kind IS NULL AND {ImageCodec} AND NOT {KindlessStill})");
break;
case RenderKind.Still:
where.Add($"(r.kind = {p.Add(RenderKind.Still)} OR {KindlessStill})");
break;
case var kind:
where.Add($"r.kind = {p.Add(kind)}");
+7
View File
@@ -230,6 +230,13 @@ public interface IVideoLibrary
/// <summary>One render; null when the index has no such render.</summary>
Task<VideoItem?> GetAsync(Guid renderId, CancellationToken cancellationToken = default);
/// <summary>
/// The verified copies this host made of <paramref name="renderIds"/>, renders of its index or not (a server's render
/// downloaded into the videos folder); none for a render it never copied.
/// </summary>
Task<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>> CopiesAsync(IReadOnlyCollection<Guid> renderIds, CancellationToken cancellationToken = default) =>
Task.FromResult<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>>(new Dictionary<Guid, IReadOnlyList<RenderCopy>>());
/// <summary>The dry run of deleting <paramref name="renderIds"/> into the trash; nothing moves.</summary>
Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default);
@@ -154,19 +154,20 @@ internal sealed class VideoCopyJobHandler(ChronosDatabase db, VideoLibrary libra
await VideoTrash.CopyFileAsync(source.Path!, part, ct).ConfigureAwait(false);
sha = await Verified(part, source.Sha256, context, ct).ConfigureAwait(false);
}
if (sha is null)
{
Mismatch(context, source, part);
return false;
}
// Inside the try: a rename the folder refuses (an antivirus, a permission changed) leaves no part copy behind.
await Commit(context, parameters, source, part, sha).ConfigureAwait(false);
return true;
}
catch
{
Remove(part);
throw;
}
if (sha is null)
{
Mismatch(context, source, part);
return false;
}
await Commit(context, parameters, source, part, sha).ConfigureAwait(false);
return true;
}
/// <summary>The copy takes its name (never overwriting: another free name when one appeared meanwhile) and is recorded.</summary>
+6
View File
@@ -57,6 +57,12 @@ public sealed class VideoLibrary : IVideoLibrary
? (await ItemsAsync([render], cancellationToken).ConfigureAwait(false)).FirstOrDefault()
: null;
public Task<IReadOnlyDictionary<Guid, IReadOnlyList<RenderCopy>>> CopiesAsync(IReadOnlyCollection<Guid> renderIds, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(renderIds);
return _db.RenderCopies.ListByRendersAsync(renderIds, cancellationToken);
}
public async Task<VideoDeletePlan> PlanDeleteAsync(IReadOnlyList<Guid> renderIds, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(renderIds);
+207 -41
View File
@@ -6,6 +6,7 @@ using Chronos.Core.IO;
using Chronos.Core.Localization;
using Chronos.Core.Model;
using Chronos.Data.Archiving;
using Chronos.Data.Processing;
namespace Chronos.Data.Videos;
@@ -40,6 +41,12 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
private const string PartSuffix = ".part";
/// <summary>
/// The suffix of a marker next to an entry's folder naming a source a copy could not remove after it verified (a file
/// held open): settled by <see cref="RecoverAsync"/>.
/// </summary>
internal const string LeftoverSuffix = ".leftover";
/// <summary>Tests: move as if the trash were on another volume (copy, verify, delete).</summary>
internal bool ForceCopy { get; set; }
@@ -105,9 +112,15 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
long bytes;
if (isFile)
{
// Hashed now when it never was (a render of before migration 0010), and remembered.
sha = row.Sha256 ?? await ContentHash.Sha256Async(source, cancellationToken: cancellationToken).ConfigureAwait(false);
if (row.Sha256 is null) await db.Renders.SetSha256Async(row.Id, sha, CancellationToken.None).ConfigureAwait(false);
// Hashed now, under the lease, whatever the row says: the record keeps the bytes that go into the trash, which a
// restore checks. A file changed in place since it was recorded (or never hashed, before migration 0010) has its
// row brought up to date, so it is never trashed under a hash it can no longer be restored against.
sha = await ContentHash.Sha256Async(source, cancellationToken: cancellationToken).ConfigureAwait(false);
if (!string.Equals(sha, row.Sha256, StringComparison.OrdinalIgnoreCase))
{
if (row.Sha256 is not null) Log.Warning("videos", $"{source} changed since it was recorded; it goes to the trash as it is now");
await db.Renders.SetSha256Async(row.Id, sha, CancellationToken.None).ConfigureAwait(false);
}
bytes = new FileInfo(source).Length;
}
else
@@ -129,20 +142,24 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
// The journal first: a crash from here on is settled by RecoverAsync.
AtomicFile.WriteAllText(recordPath + PendingSuffix, JsonSerializer.Serialize(record, VideoTrashJson.Default.VideoTrashRecord));
var target = Path.Combine(entryFolder, fileName);
bool removed;
try
{
await MoveAsync(source, target, record, cancellationToken).ConfigureAwait(false);
removed = await MoveAsync(source, target, record, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex)
{
// A file is open elsewhere, the copy did not verify, or the move was cancelled: the render stays where it was.
// A file is open elsewhere, the copy did not verify, or the move was cancelled before the verified copy took
// its name in the trash: nothing moved, the render stays where it was.
Log.Warning("videos", $"{source} could not move to the trash; it stays where it is", ex);
Undo(target, entryFolder, recordPath);
throw;
}
if (CrashAfterMove) throw new IOException("Simulated crash after the move.");
// The file has moved: its row goes too, to the end, whatever the caller cancels meanwhile.
// The file is in the trash (verified, when copied): the delete is done, its row goes too, to the end, whatever
// the caller cancels meanwhile. A source a copy could not remove stays whole and is left for RecoverAsync.
await db.Renders.DeleteAsync(row.Id, CancellationToken.None).ConfigureAwait(false);
if (!removed) MarkLeftover(entryFolder, source);
Publish(recordPath);
}
Log.Info("videos", $"{source} moved to the trash ({name}, {bytes} bytes)");
@@ -179,12 +196,19 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
if (!await MatchesAsync(trashed, record, cancellationToken).ConfigureAwait(false))
throw new VideoLibraryException(VideoErrors.HashMismatch, Loc.L("Errors.Videos.TrashMismatch"));
Render restored;
bool removed;
await using (await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
var target = Destination(paths, record, sequence);
// The original this entry's delete could not remove goes first (still what went into the trash), so the
// render takes its own name back.
await SettleLeftoverAsync(paths, entryFolder, cancellationToken).ConfigureAwait(false);
// A name a render of this process is writing counts as taken, and stays reserved until the move is done: the
// render's commit would otherwise land on the restored file (and commits never overwrite, for other processes).
using var names = new OutputNames();
var target = names.Reserve(taken => Destination(paths, record, sequence, taken));
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
cancellationToken.ThrowIfCancellationRequested();
await MoveAsync(trashed, target, record, cancellationToken).ConfigureAwait(false);
removed = await MoveAsync(trashed, target, record, cancellationToken).ConfigureAwait(false);
restored = record.Render with { SequenceId = sequence.Id, OutputPath = Stored(paths, target), Sha256 = record.Sha256 };
try
{
@@ -193,12 +217,17 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
catch (Exception ex)
{
Log.Warning("videos", $"{target} could not be indexed again; it goes back into the trash", ex);
await MoveAsync(target, trashed, record, CancellationToken.None).ConfigureAwait(false);
// A copy that could not remove the trashed one left it whole: the copy alone goes.
if (!removed) RemoveSource(target);
else if (!await MoveAsync(target, trashed, record, CancellationToken.None).ConfigureAwait(false))
Log.Warning("videos", $"{target} went back into the trash but is left over where it was restored to");
throw;
}
}
// The render is back: its trash copy goes (left for RecoverAsync when a copy could not remove it), then its record.
if (!removed) MarkLeftover(entryFolder, trashed);
File.Delete(recordPath);
RemoveEmpty(entryFolder);
if (removed) RemoveEmpty(entryFolder);
Log.Info("videos", $"{name} restored to {restored.OutputPath}");
return restored;
}
@@ -234,11 +263,21 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
{
// The file reached the trash (a copy only takes its name once verified): the delete completes. A source still
// there is the original a copy left behind, unless something new took its name since.
if ((File.Exists(record.OriginalPath) || System.IO.Directory.Exists(record.OriginalPath))
&& await MatchesAsync(record.OriginalPath, record, cancellationToken).ConfigureAwait(false))
DeletePath(record.OriginalPath);
if (await db.Renders.GetAsync(record.Render.Id, cancellationToken).ConfigureAwait(false) is not null)
await db.Renders.DeleteAsync(record.Render.Id, CancellationToken.None).ConfigureAwait(false);
if ((File.Exists(record.OriginalPath) || System.IO.Directory.Exists(record.OriginalPath))
&& await MatchesAsync(record.OriginalPath, record, cancellationToken).ConfigureAwait(false))
{
try
{
RemoveSource(record.OriginalPath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"{record.OriginalPath} is still in use; it is removed at the next start", ex);
MarkLeftover(entryFolder, record.OriginalPath);
}
}
Publish(recordPath);
Log.Info("videos", $"An interrupted delete of {record.OriginalPath} completed");
}
@@ -251,9 +290,82 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
settled++;
}
}
foreach (var marker in System.IO.Directory.EnumerateFiles(folder, "*" + LeftoverSuffix).ToList())
{
cancellationToken.ThrowIfCancellationRequested();
if (!marker.EndsWith(LeftoverSuffix, StringComparison.OrdinalIgnoreCase)) continue;
var entryFolder = marker[..^LeftoverSuffix.Length];
var sequence = ReadRecord(entryFolder + RecordExtension) is { } record
? await db.Sequences.GetAsync(record.SequenceId, cancellationToken).ConfigureAwait(false)
: null;
await using (sequence is null ? null : await writer.LockAsync(paths, sequence.Id, cancellationToken).ConfigureAwait(false))
{
if (await SettleLeftoverAsync(paths, entryFolder, cancellationToken).ConfigureAwait(false)) settled++;
}
}
return settled;
}
/// <summary>
/// Settles what a move that copied left at its source because it could not remove it (a file held open): the original of
/// a delete, removed once it still holds what went into the trash and no render was recorded there since; the trash copy
/// of a restore, removed once the render is back in the index. Its marker goes either way, unless removing fails again
/// (the next start tries again). True when the marker was settled.
/// </summary>
private async Task<bool> SettleLeftoverAsync(ArchivePaths paths, string entryFolder, CancellationToken cancellationToken)
{
var marker = entryFolder + LeftoverSuffix;
if (!File.Exists(marker)) return false;
try
{
var path = File.ReadAllText(marker).Trim();
var record = ReadRecord(entryFolder + RecordExtension);
var indexed = record is not null && await db.Renders.GetAsync(record.Render.Id, cancellationToken).ConfigureAwait(false) is not null;
var inside = path.Length > 0 && Path.GetFullPath(path).StartsWith(Path.GetFullPath(entryFolder) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase);
if (path.Length > 0 && (File.Exists(path) || System.IO.Directory.Exists(path)))
{
if (inside && (record is null || indexed))
{
// A restored render's trash copy: the render is back, the copy goes, and a record a crash left with it.
RemoveSource(path);
if (record is not null) File.Delete(entryFolder + RecordExtension);
RemoveEmpty(entryFolder);
}
else if (!inside && record is not null && !indexed)
{
var stored = Stored(paths, path);
var recorded = await db.Renders.ListBySequenceAsync(record.SequenceId, cancellationToken).ConfigureAwait(false);
if (recorded.All(r => r.OutputPath != stored) && await MatchesAsync(path, record, cancellationToken).ConfigureAwait(false))
{
RemoveSource(path);
Log.Info("videos", $"{path}, left over by a delete, removed");
}
}
}
File.Delete(marker);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"What {marker} names could not be removed yet; the next start tries again", ex);
return false;
}
}
/// <summary>Records that a move's source stays at <paramref name="path"/> for <see cref="SettleLeftoverAsync"/>; a failure is logged.</summary>
private static void MarkLeftover(string entryFolder, string path)
{
try
{
AtomicFile.WriteAllText(entryFolder + LeftoverSuffix, path);
Log.Warning("videos", $"{path} could not be removed after it was copied; it is removed at the next start");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"{path} is left over and could not be recorded as such", ex);
}
}
/// <summary>
/// The SHA-256 of every file of an image sequence's folder (paths inside it, forward slashes, in order); the folder's
/// own render records no hash (decision 14).
@@ -287,9 +399,13 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
/// <summary>
/// Moves a render's file or folder from <paramref name="from"/> to <paramref name="to"/>: renamed on one volume; copied
/// under a part name, verified against <paramref name="record"/>, renamed and the source deleted across volumes.
/// under a part name, verified against <paramref name="record"/>, renamed and the source removed across volumes. Once the
/// verified copy took its name the move is done: a source that cannot be removed then (a file held open) stays whole
/// (<see cref="RemoveSource"/>) and the move returns false, for the caller to record it as left over.
/// </summary>
private async Task MoveAsync(string from, string to, VideoTrashRecord record, CancellationToken cancellationToken)
/// <returns>True when the source is gone; false when the copy is in place and the source left over.</returns>
/// <exception cref="IOException">The move failed before it took its name (nothing moved, no part copy left), the copy not verifying among others.</exception>
private async Task<bool> MoveAsync(string from, string to, VideoTrashRecord record, CancellationToken cancellationToken)
{
var folder = System.IO.Directory.Exists(from);
if (!ForceCopy && SameVolume(from, to))
@@ -298,37 +414,84 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
{
if (folder) System.IO.Directory.Move(from, to);
else File.Move(from, to, overwrite: false);
return;
return true;
}
catch (IOException) when (folder && !System.IO.Directory.Exists(to) && System.IO.Directory.Exists(from))
{
// Another mount on the same root (Linux): copied instead.
// Another mount on the same root (Linux), or a file of the folder held open (Windows): copied instead.
}
}
var part = to + PartSuffix;
DeletePath(part);
if (folder)
{
foreach (var file in System.IO.Directory.EnumerateFiles(from, "*", SearchOption.AllDirectories))
{
var target = Path.Combine(part, Path.GetRelativePath(from, file));
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await CopyFileAsync(file, target, cancellationToken).ConfigureAwait(false);
}
System.IO.Directory.CreateDirectory(part);
}
else
{
await CopyFileAsync(from, part, cancellationToken).ConfigureAwait(false);
}
if (!await MatchesAsync(part, record, cancellationToken).ConfigureAwait(false))
try
{
DeletePath(part);
throw new IOException(Loc.L("Errors.Videos.TrashMismatch"));
if (folder)
{
foreach (var file in System.IO.Directory.EnumerateFiles(from, "*", SearchOption.AllDirectories))
{
var target = Path.Combine(part, Path.GetRelativePath(from, file));
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(target)!);
await CopyFileAsync(file, target, cancellationToken).ConfigureAwait(false);
}
System.IO.Directory.CreateDirectory(part);
}
else
{
await CopyFileAsync(from, part, cancellationToken).ConfigureAwait(false);
}
if (!await MatchesAsync(part, record, cancellationToken).ConfigureAwait(false)) throw new IOException(Loc.L("Errors.Videos.TrashMismatch"));
if (folder) System.IO.Directory.Move(part, to);
else File.Move(part, to, overwrite: false);
}
catch
{
try
{
DeletePath(part);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"The part copy {part} could not be removed", ex);
}
throw;
}
try
{
RemoveSource(from);
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("videos", $"{from} was copied to {to} but could not be removed: it stays whole", ex);
return false;
}
}
/// <summary>
/// Removes the source of a verified copy all or nothing: a file is deleted; a folder is renamed aside first (which fails
/// at once while any of its files is open on Windows, leaving it whole), then erased.
/// </summary>
private static void RemoveSource(string path)
{
if (System.IO.Directory.Exists(path))
{
var full = Path.GetFullPath(path).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
var aside = Path.Combine(Path.GetDirectoryName(full)!, "." + Path.GetFileName(full) + ".removing-" + Guid.NewGuid().ToString("N")[..8]);
System.IO.Directory.Move(full, aside);
try
{
SequenceTrash.Erase(aside);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Its name is free and its content is in the trash already: what could not be erased is only left over.
Log.Warning("videos", $"{aside} could not be erased whole; it is left over", ex);
}
}
else if (File.Exists(path))
{
File.Delete(path);
}
if (folder) System.IO.Directory.Move(part, to);
else File.Move(part, to, overwrite: false);
DeletePath(from);
}
/// <summary>Copies a file, flushed to the disk.</summary>
@@ -340,8 +503,11 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
to.Flush(flushToDisk: true);
}
/// <summary>Where a restored render goes: where it was (in its sequence's folder as the index has it now), or a free name next to it.</summary>
private static string Destination(ArchivePaths paths, VideoTrashRecord record, Sequence sequence)
/// <summary>
/// Where a restored render goes: where it was (in its sequence's folder as the index has it now), or a free name next to
/// it when that one is on disk or <paramref name="taken"/> (an output a render of this process is writing).
/// </summary>
private static string Destination(ArchivePaths paths, VideoTrashRecord record, Sequence sequence, Func<string, bool> taken)
{
var stored = record.Render.OutputPath;
string full;
@@ -354,8 +520,8 @@ internal sealed class VideoTrash(ChronosDatabase db, SequenceWriter writer)
: stored;
full = paths.FromRelative(rebased);
}
return File.Exists(full) || System.IO.Directory.Exists(full)
? VideosFolder.FreeName(Path.GetDirectoryName(full)!, Path.GetFileName(full), record.Files is not null)
return File.Exists(full) || System.IO.Directory.Exists(full) || taken(full)
? VideosFolder.FreeName(Path.GetDirectoryName(full)!, Path.GetFileName(full), record.Files is not null, taken)
: full;
}
+3 -2
View File
@@ -64,7 +64,8 @@ public static class VideosFolder
/// "name (2).ext", "name (3).ext"… (a folder's name, an image sequence, has no extension to keep).
/// </summary>
/// <param name="isFolder">The copy is an image sequence's folder: its whole name is the stem.</param>
public static string FreeName(string folder, string fileName, bool isFolder = false)
/// <param name="taken">Names in use besides those on disk (outputs a render of this process is writing).</param>
public static string FreeName(string folder, string fileName, bool isFolder = false, Func<string, bool>? taken = null)
{
ArgumentException.ThrowIfNullOrWhiteSpace(folder);
ArgumentException.ThrowIfNullOrWhiteSpace(fileName);
@@ -73,7 +74,7 @@ public static class VideosFolder
for (var n = 1; ; n++)
{
var candidate = Path.Combine(folder, (n == 1 ? stem : string.Create(CultureInfo.InvariantCulture, $"{stem} ({n})")) + extension);
if (!File.Exists(candidate) && !Directory.Exists(candidate)) return candidate;
if (!File.Exists(candidate) && !Directory.Exists(candidate) && taken?.Invoke(candidate) != true) return candidate;
}
}
+33 -5
View File
@@ -38,6 +38,8 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
const codecs = new Set();
const years = new Set();
const selection = new Selection();
/** Sequence titles read for the sequence filter, by id. */
const titles = new Map();
const user = api.user();
const may = (bit) => (Number(user?.permissions ?? 0) & bit) !== 0;
/** The server's videos folder: "" when none is set (Copy is off), null while unknown (the server decides). */
@@ -232,7 +234,7 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
root.querySelector("#clear").hidden = !isFiltered();
// One sequence's videos ("All videos" of a sequence page): its title, which opens it, and × for every sequence's
// videos again (the other filters stay).
const title = filters.sequence ? rows.find((v) => v.sequenceId === filters.sequence)?.sequenceTitle : null;
const title = filters.sequence ? rows.find((v) => v.sequenceId === filters.sequence)?.sequenceTitle ?? sequenceTitle(filters.sequence) : null;
const chip = root.querySelector("#sequence-filter");
chip.innerHTML = filters.sequence ? `<a class="pill" href="#/library?id=${attr(encodeURIComponent(filters.sequence))}" dir="auto"
title="${attr(t("Admin.Library.Open.Tip"))}">${escapeHtml(title ?? "…")}</a>
@@ -243,6 +245,20 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
setMeta(title ?? "");
}
/**
* The title of a sequence none of whose videos is on the page (a filter that matches nothing, or its videos further
* down): read once from the sequence's own record, and the chip redrawn when it comes; undefined until then.
*/
function sequenceTitle(id) {
if (titles.has(id)) return titles.get(id);
titles.set(id, undefined);
api.get(`/api/v1/sequences/${encodeURIComponent(id)}`).then((s) => {
titles.set(id, s.title ?? "");
if (root.isConnected && filters.sequence === id) drawFilters();
}, () => {});
return undefined;
}
function draw() {
itemsHost.className = `seq-items video-items ${view === "list" ? "rows" : "cards"}`;
itemsHost.setAttribute("role", "listbox");
@@ -330,6 +346,8 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
return;
}
const one = n === 1;
const [only] = selection.ids;
const downloadWhy = one ? downloadBlock(rows.find((v) => v.id === only)) : "Admin.Videos.Download.One.Tip";
const copyWhy = !may(EDIT) ? "Admin.Videos.Copy.NoRight.Tip" : folder === "" ? "Admin.Videos.Copy.NoFolder.Tip" : null;
const deleteWhy = may(DELETE) ? null : "Admin.Videos.Delete.NoRight.Tip";
mass.hidden = false;
@@ -340,8 +358,8 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
<span class="spacer"></span>
<button class="btn small" id="mass-play" data-mass="play" data-i18n-title="${one ? "Admin.Videos.Play.Tip" : "Admin.Videos.Play.One.Tip"}"
${one ? "" : "disabled"}>${icons.play}<span data-i18n="Admin.Videos.Play"></span></button>
<button class="btn small" id="mass-download" data-mass="download" data-i18n-title="${one ? "Admin.Videos.Download.Tip" : "Admin.Videos.Download.One.Tip"}"
${one ? "" : "disabled"}>${icons.download}<span data-i18n="Admin.Videos.Download"></span></button>
<button class="btn small" id="mass-download" data-mass="download" data-i18n-title="${downloadWhy ?? "Admin.Videos.Download.Tip"}"
${downloadWhy ? "disabled" : ""}>${icons.download}<span data-i18n="Admin.Videos.Download"></span></button>
<button class="btn small" id="mass-copy" data-mass="copy" data-i18n-title="${copyWhy ?? "Admin.Videos.Copy.Tip"}"
${copyWhy ? "disabled" : ""}>${icons.copyToFolder}<span data-i18n="Admin.Videos.Copy"></span></button>
<button class="btn small destructive" id="mass-delete" data-mass="delete" data-i18n="Admin.Videos.Delete"
@@ -377,7 +395,7 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
}
function download(v) {
if (!v) return;
if (!v || downloadBlock(v)) return;
const a = document.createElement("a");
a.href = fileUrl(v);
a.download = v.fileName ?? "";
@@ -470,7 +488,9 @@ export async function render(root, { api, setMeta, actions, onEvent }) {
dialog.innerHTML = `
<div class="viewer-head"><h2 id="player-title" class="ellipsis" dir="auto">${escapeHtml(v.sequenceTitle)}</h2>
<span class="muted ellipsis" dir="ltr">${escapeHtml(v.fileName ?? "")}</span><span class="spacer"></span>
<a class="btn icon" href="${attr(fileUrl(v))}" download="${attr(v.fileName ?? "")}" data-i18n-title="Admin.Videos.Download.Tip">${icons.download}</a>
${downloadBlock(v)
? `<button class="btn icon" type="button" disabled data-i18n-title="${downloadBlock(v)}">${icons.download}</button>`
: `<a class="btn icon" href="${attr(fileUrl(v))}" download="${attr(v.fileName ?? "")}" data-i18n-title="Admin.Videos.Download.Tip">${icons.download}</a>`}
<button class="btn icon" type="button" data-close data-i18n-title="Admin.Videos.Player.Close.Tip">${icons.close}</button></div>
<div class="viewer-stage" dir="ltr">${media}<p class="player-note" ${media ? "hidden" : ""}>${escapeHtml(v.state === "missing"
? t("Admin.Videos.State.Missing.Tip") : t("Admin.Videos.Player.NoPlay"))}</p></div>
@@ -524,6 +544,14 @@ export function videoKind(v) {
return String(v.codec ?? "").toLowerCase().endsWith("sequence") ? "sequence" : "video";
}
/** Why a video has no download: an image sequence is a folder, not one file, and a missing file is gone; null when it has. */
export function downloadBlock(v) {
if (!v) return null;
if (videoKind(v) === "sequence") return "Admin.Videos.Download.Folder.Tip";
if (v.state === "missing") return "Admin.Videos.Download.Missing.Tip";
return null;
}
/** A kind in words; a newer server's kind as it is. */
export function kindText(kind) {
if (kind === "still") return t("Admin.Videos.Kind.Still.Label");